This is an automated email from the ASF dual-hosted git repository. steFaiz pushed a commit to branch comm_optim in repository https://gitbox.apache.org/repos/asf/paimon-full-text.git
commit c2e764e8624b96aced6faaca43cce00c0a51d4ff Author: Xinyu Wang <[email protected]> AuthorDate: Tue Nov 24 11:14:13 2026 +0800 [core][java] optimize fts build & search performance --- core/src/archive_directory.rs | 108 ++++++++++- core/src/build.rs | 211 +++++++++++++++++++++ core/src/config.rs | 16 +- core/src/index.rs | 7 +- core/src/lib.rs | 2 + core/tests/core_roundtrip.rs | 53 ++++++ docs/paimon-integration.md | 11 ++ .../fulltext/FullTextNativeRoundTripTest.java | 77 ++++++++ jni/src/lib.rs | 24 ++- 9 files changed, 493 insertions(+), 16 deletions(-) diff --git a/core/src/archive_directory.rs b/core/src/archive_directory.rs index 717b283..d80af6d 100644 --- a/core/src/archive_directory.rs +++ b/core/src/archive_directory.rs @@ -23,7 +23,7 @@ use std::fmt; use std::io; use std::ops::Range; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, Weak}; use tantivy::directory::error::{DeleteError, LockError, OpenReadError, OpenWriteError}; use tantivy::directory::WritePtr; use tantivy::directory::{ @@ -33,6 +33,8 @@ use tantivy_common::HasLen; const READ_CACHE_BLOCK_BYTES: usize = 64 * 1024; const READ_CACHE_MAX_BLOCKS: usize = 256; +/// Dead entries of the shared-read table are swept whenever it grows past this many entries. +const SHARED_READS_SWEEP_LEN: usize = 1024; pub(crate) struct ArchiveDirectory<R> { input: Arc<R>, @@ -224,8 +226,7 @@ impl<R: SeekRead + 'static> FileHandle for ArchiveFileHandle<R> { .start .checked_add(relative_start) .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "offset overflow"))?; - let data = vec![0u8; range.len()]; - self.read_direct(pos, data) + self.read_shared(pos, range.len()) } } @@ -258,6 +259,29 @@ impl<R: SeekRead + 'static> ArchiveFileHandle<R> { Ok(Some(block.slice(start..start + range.len()))) } + /// Reads a range that is too large for the block cache, sharing the bytes with every other + /// read of the same range that is still alive. + /// + /// Tantivy assumes that reading a range is free, as it is with mmap. A phrase query reads the + /// positions of a term once per occurrence of the term in the phrase and keeps all of them + /// until the segment is scored, so without sharing a frequent repeated token costs its whole + /// position list in I/O and memory for every occurrence. + /// + /// Only a weak reference is kept here: the bytes are freed as soon as Tantivy drops them, so + /// this never holds memory that is not in use. + fn read_shared(&self, pos: u64, len: usize) -> io::Result<OwnedBytes> { + let key = (pos, len); + if let Some(data) = self.cache.get_shared(key)? { + return Ok(OwnedBytes::new(data)); + } + // Allocated as `Arc<[u8]>` up front so that sharing it needs no copy. + let mut data: Arc<[u8]> = std::iter::repeat_n(0u8, len).collect(); + let buf = Arc::get_mut(&mut data).expect("newly created buffer is not shared"); + self.input.pread(&mut [ReadRequest::new(pos, buf)])?; + self.cache.insert_shared(key, &data)?; + Ok(OwnedBytes::new(data)) + } + fn read_direct(&self, pos: u64, mut data: Vec<u8>) -> io::Result<OwnedBytes> { let mut request = [ReadRequest::new(pos, data.as_mut_slice())]; self.input.pread(&mut request)?; @@ -274,6 +298,8 @@ struct ArchiveReadCache { struct ArchiveReadCacheInner { blocks: HashMap<u64, OwnedBytes>, order: VecDeque<u64>, + /// Large reads currently held by Tantivy, by archive position and length. + shared: HashMap<(u64, usize), Weak<[u8]>>, } impl ArchiveReadCache { @@ -296,6 +322,32 @@ impl ArchiveReadCache { Ok(block) } + fn get_shared(&self, key: (u64, usize)) -> io::Result<Option<Arc<[u8]>>> { + let mut inner = self + .inner + .lock() + .map_err(|_| io::Error::other("archive read cache lock poisoned"))?; + let data = inner.shared.get(&key).and_then(Weak::upgrade); + if data.is_some() { + self.metrics.record_cache_hit(); + } else { + inner.shared.remove(&key); + } + Ok(data) + } + + fn insert_shared(&self, key: (u64, usize), data: &Arc<[u8]>) -> io::Result<()> { + let mut inner = self + .inner + .lock() + .map_err(|_| io::Error::other("archive read cache lock poisoned"))?; + if inner.shared.len() >= SHARED_READS_SWEEP_LEN { + inner.shared.retain(|_, data| data.strong_count() > 0); + } + inner.shared.insert(key, Arc::downgrade(data)); + Ok(()) + } + fn record_miss(&self) { self.metrics.record_cache_miss(); } @@ -511,4 +563,54 @@ mod tests { assert_eq!(metrics.cache_misses, 1); assert_eq!(metrics.cached_blocks, 1); } + #[test] + fn archive_directory_shares_large_reads_while_they_are_alive() { + let len = READ_CACHE_BLOCK_BYTES * 4; + let data: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect(); + let metrics = Arc::new(ReadMetrics::default()); + let input = Arc::new(CountingDataReader { + data: data.clone(), + read_calls: AtomicUsize::new(0), + }); + let directory = ArchiveDirectory::new_with_metrics( + Arc::clone(&input), + 0, + &[ArchiveFileEntry { + name: "segment.pos".to_string(), + offset: 0, + length: len as u64, + }], + Arc::clone(&metrics), + ) + .expect("archive directory"); + let file = directory.open_read(Path::new("segment.pos")).expect("file"); + let range = 100..READ_CACHE_BLOCK_BYTES * 3; + let reads = || input.read_calls.load(Ordering::SeqCst); + + let first = file.read_bytes_slice(range.clone()).expect("first"); + let second = file.read_bytes_slice(range.clone()).expect("second"); + assert_eq!(first.as_slice(), &data[range.clone()]); + assert_eq!(second.as_slice(), &data[range.clone()]); + assert_eq!(first.as_slice().as_ptr(), second.as_slice().as_ptr()); + assert_eq!(reads(), 1); + assert_eq!(metrics.snapshot().cache_hits, 1); + + // A different range is not shared, even when it overlaps. + let other = file + .read_bytes_slice(101..READ_CACHE_BLOCK_BYTES * 3) + .expect("other"); + assert_eq!(other.as_slice(), &data[101..READ_CACHE_BLOCK_BYTES * 3]); + assert_eq!(reads(), 2); + + // One live holder is enough to keep sharing. + drop(first); + let third = file.read_bytes_slice(range.clone()).expect("third"); + assert_eq!(reads(), 2); + + // Nothing is retained once every holder is gone. + drop((second, third)); + let again = file.read_bytes_slice(range.clone()).expect("again"); + assert_eq!(again.as_slice(), &data[range]); + assert_eq!(reads(), 3); + } } diff --git a/core/src/build.rs b/core/src/build.rs new file mode 100644 index 0000000..41a0832 --- /dev/null +++ b/core/src/build.rs @@ -0,0 +1,211 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Options that tune how a writer builds an index. +//! +//! They only affect the resources used while building. They never change tokenization or the +//! archive format, and they are not persisted in the index metadata. They are passed together +//! with the other writer options, with the same optional `fulltext.` prefix: +//! +//! | Option | Default | Meaning | +//! |----------------------------|------------|-------------------------------------------------| +//! | `build.writer-threads` | `1` | Tantivy indexing threads per writer | +//! | `build.writer-memory-size` | `50000000` | Tantivy memory budget shared by those threads | +//! +//! Sizes are bytes with an optional `k`/`kb`, `m`/`mb` or `g`/`gb` suffix (powers of 1024). +//! +//! Each thread indexes into its own segment and flushes it when its share of the budget is full, +//! so more threads build faster and produce more segments. Document order within the archive is +//! not affected: results are identified by row id. + +use crate::config::normalize_option_key; +use crate::error::{FtIndexError, Result}; +use std::collections::HashMap; + +const WRITER_THREADS: &str = "build.writer-threads"; +const WRITER_MEMORY_SIZE: &str = "build.writer-memory-size"; + +/// Bounds Tantivy puts on the memory budget of one indexing thread. Tantivy does not export them. +const MIN_MEMORY_BYTES_PER_THREAD: usize = 15_000_000; +const MAX_MEMORY_BYTES_PER_THREAD: usize = u32::MAX as usize - 1_000_000; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IndexBuildConfig { + /// Number of Tantivy indexing threads. + pub writer_threads: usize, + /// Memory budget in bytes, split evenly between the indexing threads. + pub writer_memory_bytes: usize, +} + +impl Default for IndexBuildConfig { + fn default() -> Self { + Self { + writer_threads: 1, + writer_memory_bytes: 50_000_000, + } + } +} + +impl IndexBuildConfig { + /// Parses the `build.*` options; other keys are ignored. + pub fn from_options(options: &HashMap<String, String>) -> Result<Self> { + let mut config = Self::default(); + for (raw_key, value) in options { + let key = normalize_option_key(raw_key); + match key.as_str() { + WRITER_THREADS => config.writer_threads = parse_count(&key, value)?, + WRITER_MEMORY_SIZE => config.writer_memory_bytes = parse_size(&key, value)?, + _ => {} + } + } + config.validate()?; + Ok(config) + } + + pub fn validate(&self) -> Result<()> { + if self.writer_threads == 0 { + return Err(FtIndexError::InvalidOption { + key: WRITER_THREADS.to_string(), + message: "must be greater than 0".to_string(), + }); + } + let per_thread = self.writer_memory_bytes / self.writer_threads; + if !(MIN_MEMORY_BYTES_PER_THREAD..MAX_MEMORY_BYTES_PER_THREAD).contains(&per_thread) { + return Err(FtIndexError::InvalidOption { + key: WRITER_MEMORY_SIZE.to_string(), + message: format!( + "must be at least {MIN_MEMORY_BYTES_PER_THREAD} and less than \ + {MAX_MEMORY_BYTES_PER_THREAD} bytes per writer thread, got {per_thread} \ + ({} bytes for {} threads)", + self.writer_memory_bytes, self.writer_threads + ), + }); + } + Ok(()) + } +} + +fn invalid(key: &str, expected: &str, value: &str) -> FtIndexError { + FtIndexError::InvalidOption { + key: key.to_string(), + message: format!("expected {expected}, got '{value}'"), + } +} + +fn parse_count(key: &str, value: &str) -> Result<usize> { + value + .trim() + .parse() + .map_err(|_| invalid(key, "unsigned integer", value)) +} + +fn parse_size(key: &str, value: &str) -> Result<usize> { + let v = value.trim().to_ascii_lowercase(); + let unit_start = v.find(|c: char| !c.is_ascii_digit()).unwrap_or(v.len()); + let (digits, unit) = v.split_at(unit_start); + let shift = match unit.trim_start() { + "" | "b" => 0, + "k" | "kb" => 10, + "m" | "mb" => 20, + "g" | "gb" => 30, + _ => return Err(invalid(key, "size such as 256mb", value)), + }; + digits + .parse::<usize>() + .ok() + .and_then(|n| n.checked_mul(1usize << shift)) + .ok_or_else(|| invalid(key, "size such as 256mb", value)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(pairs: &[(&str, &str)]) -> Result<IndexBuildConfig> { + let options = pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + IndexBuildConfig::from_options(&options) + } + + #[test] + fn parses_overrides() { + assert_eq!(parse(&[]).unwrap(), IndexBuildConfig::default()); + assert_eq!( + parse(&[ + ("fulltext.build.writer_threads", " 4 "), + ("build.writer-memory-size", "1 GB"), + ("tokenizer", "jieba"), + ]) + .unwrap(), + IndexBuildConfig { + writer_threads: 4, + writer_memory_bytes: 1 << 30, + } + ); + } + + #[test] + fn parses_sizes() { + for (value, expected) in [ + ("50000000", 50_000_000), + ("20000000b", 20_000_000), + ("32768k", 32 << 20), + ("64m", 64 << 20), + (" 64 MB ", 64 << 20), + ("2g", 2 << 30), + ] { + let config = parse(&[("build.writer-memory-size", value)]).unwrap(); + assert_eq!(config.writer_memory_bytes, expected, "{value}"); + } + } + + #[test] + fn rejects_invalid_values() { + for (key, value) in [ + ("build.writer-threads", "x"), + ("build.writer-threads", "-1"), + ("build.writer-threads", "0"), + ("build.writer-memory-size", "64x"), + ("build.writer-memory-size", "mb"), + ("build.writer-memory-size", "0"), + ("build.writer-memory-size", "14mb"), + ("build.writer-memory-size", "4gb"), + ("build.writer-memory-size", "99999999999gb"), + ] { + let err = parse(&[(key, value)]).unwrap_err(); + assert!(err.to_string().contains(key), "{key}={value}: {err}"); + } + } + + #[test] + fn memory_budget_is_checked_per_thread() { + // The default budget is enough for three threads, not for four. + assert!(parse(&[("build.writer-threads", "3")]).is_ok()); + let err = parse(&[("build.writer-threads", "4")]).unwrap_err(); + assert!( + err.to_string().contains("build.writer-memory-size"), + "{err}" + ); + assert!(parse(&[ + ("build.writer-threads", "4"), + ("build.writer-memory-size", "8gb") + ]) + .is_ok()); + } +} diff --git a/core/src/config.rs b/core/src/config.rs index 425e8b1..b6f76c6 100644 --- a/core/src/config.rs +++ b/core/src/config.rs @@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. +use crate::build::IndexBuildConfig; use crate::tokenizer::TokenizerConfig; use crate::{FtIndexError, Result}; use serde::{Deserialize, Serialize}; @@ -28,6 +29,10 @@ pub struct FullTextIndexConfig { pub text_fields: Vec<String>, #[serde(default)] pub tokenizer: TokenizerConfig, + /// Resources a writer uses to build the index. Not part of the index itself, so it is never + /// persisted in the index metadata; readers always see the default. + #[serde(skip)] + pub build: IndexBuildConfig, } impl Default for FullTextIndexConfig { @@ -36,6 +41,7 @@ impl Default for FullTextIndexConfig { row_id_field: default_row_id_field(), text_fields: default_text_fields(), tokenizer: TokenizerConfig::default(), + build: IndexBuildConfig::default(), } } } @@ -55,6 +61,7 @@ impl FullTextIndexConfig { pub fn from_options(options: &HashMap<String, String>) -> Result<Self> { let tokenizer = TokenizerConfig::from_options(options)?; + let build = IndexBuildConfig::from_options(options)?; let mut row_id_field = None; let mut text_field = None; let mut text_fields = None; @@ -80,6 +87,7 @@ impl FullTextIndexConfig { row_id_field: row_id_field.unwrap_or_else(default_row_id_field), text_fields: fields, tokenizer, + build, }; config.validate()?; Ok(config) @@ -99,6 +107,11 @@ impl FullTextIndexConfig { self } + pub fn with_build(mut self, build: IndexBuildConfig) -> Self { + self.build = build; + self + } + pub fn with_positions(mut self, with_positions: bool) -> Self { self.tokenizer.with_position = with_positions; self @@ -133,6 +146,7 @@ impl FullTextIndexConfig { return invalid("text-fields", "must not contain the row id field"); } } + self.build.validate()?; self.tokenizer.validate() } } @@ -147,7 +161,7 @@ pub struct FullTextIndexMetadata { pub tantivy_version: String, } -fn normalize_option_key(raw_key: &str) -> String { +pub(crate) fn normalize_option_key(raw_key: &str) -> String { raw_key .strip_prefix("fulltext.") .or_else(|| raw_key.strip_prefix("tantivy.")) diff --git a/core/src/index.rs b/core/src/index.rs index d76565a..609f0c8 100644 --- a/core/src/index.rs +++ b/core/src/index.rs @@ -47,8 +47,6 @@ use tantivy_fst::Automaton; use tantivy_jieba::JiebaTokenizer; use tempfile::TempDir; -const INDEX_WRITER_MEMORY_BUDGET_BYTES: usize = 50_000_000; - #[derive(Clone, Debug, PartialEq)] pub struct FullTextSearchResult { pub row_ids: Vec<i64>, @@ -85,7 +83,10 @@ impl FullTextIndexWriter { .get_field(&config.row_id_field) .map_err(|_| FtIndexError::InvalidStorage("missing row_id field".to_string()))?; let text_fields = text_field_map(&schema, &config)?; - let index_writer = index.writer_with_num_threads(1, INDEX_WRITER_MEMORY_BUDGET_BYTES)?; + let index_writer = index.writer_with_num_threads( + config.build.writer_threads, + config.build.writer_memory_bytes, + )?; Ok(Self { config, state: Some(FullTextIndexWriterState { diff --git a/core/src/lib.rs b/core/src/lib.rs index 291aac3..2359553 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -16,6 +16,7 @@ // under the License. mod archive_directory; +pub mod build; pub mod config; pub mod error; pub mod index; @@ -24,6 +25,7 @@ mod query; pub mod storage; pub mod tokenizer; +pub use build::IndexBuildConfig; pub use config::{FullTextIndexConfig, FullTextIndexMetadata}; pub use error::{FtIndexError, Result}; pub use index::{FullTextDocument, FullTextIndexReader, FullTextIndexWriter, FullTextSearchResult}; diff --git a/core/tests/core_roundtrip.rs b/core/tests/core_roundtrip.rs index 1b71da9..d802a4f 100644 --- a/core/tests/core_roundtrip.rs +++ b/core/tests/core_roundtrip.rs @@ -994,3 +994,56 @@ fn boolean_query_rejects_only_must_not() -> anyhow::Result<()> { .contains("at least one should or must clause")); Ok(()) } + +#[test] +fn build_options_are_applied_but_not_persisted() -> anyhow::Result<()> { + let options: HashMap<String, String> = [ + ("fulltext.build.writer-threads", "2"), + ("fulltext.build.writer-memory-size", "40mb"), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + let config = FullTextIndexConfig::from_options(&options)?; + assert_eq!(config.build.writer_threads, 2); + assert_eq!(config.build.writer_memory_bytes, 40 << 20); + + let mut writer = FullTextIndexWriter::new(config)?; + for row_id in 0..5000 { + writer.add_document(row_id, format!("shared marker{row_id}"))?; + } + let mut output = PosWriter::new(Vec::new()); + writer.write(&mut output)?; + let bytes = output.into_inner(); + + let (header, _) = read_header(&SliceReader::new(bytes.clone()))?; + let header_json = serde_json::to_value(&header)?; + assert!(header_json["metadata"]["config"].get("build").is_none()); + + let reader = FullTextIndexReader::open(SliceReader::new(bytes))?; + assert_eq!(reader.metadata().config, FullTextIndexConfig::new()); + assert_eq!(reader.metadata().document_count, 5000); + let result = reader.search(match_query("marker4242", "text"), 10)?; + assert_eq!(result.row_ids, vec![4242]); + Ok(()) +} + +#[test] +fn invalid_build_options_are_rejected() { + let options = |key: &str, value: &str| -> HashMap<String, String> { + [(key.to_string(), value.to_string())].into_iter().collect() + }; + let err = FullTextIndexConfig::from_options(&options("build.writer-threads", "0")).unwrap_err(); + assert!(err.to_string().contains("build.writer-threads"), "{err}"); + let err = + FullTextIndexConfig::from_options(&options("build.writer-memory-size", "1mb")).unwrap_err(); + assert!( + err.to_string().contains("build.writer-memory-size"), + "{err}" + ); + + // A config assembled in code is validated by the writer too, instead of panicking in Tantivy. + let mut config = FullTextIndexConfig::new(); + config.build.writer_threads = 0; + assert!(FullTextIndexWriter::new(config).is_err()); +} diff --git a/docs/paimon-integration.md b/docs/paimon-integration.md index 650723d..141f31a 100644 --- a/docs/paimon-integration.md +++ b/docs/paimon-integration.md @@ -53,11 +53,22 @@ fulltext.language fulltext.remove-stop-words fulltext.stop-words fulltext.with-position +fulltext.build.writer-threads +fulltext.build.writer-memory-size ``` The standalone library accepts both unprefixed keys and `fulltext.` prefixed keys. +`fulltext.build.*` options only tune how a writer builds an index; they are not +persisted in the index metadata and do not affect readers. +`build.writer-threads` (default `1`) is the number of Tantivy indexing threads +of one writer, and `build.writer-memory-size` (default `50000000`) is the +memory budget those threads share. Sizes accept `k`/`kb`, `m`/`mb` and +`g`/`gb` suffixes. Tantivy requires at least 15,000,000 bytes and less than +4GB of budget per thread, so raise the budget together with the thread count. +More threads build faster and leave more segments in the archive. + `fulltext.tokenizer` accepts `default`, `simple`, `whitespace`, `raw`, `ngram`, `jieba`, `icu`, and `icu/split`. ICU uses built-in dictionaries for mixed-language word segmentation. `icu/split` additionally splits each word diff --git a/java/src/test/java/org/apache/paimon/index/fulltext/FullTextNativeRoundTripTest.java b/java/src/test/java/org/apache/paimon/index/fulltext/FullTextNativeRoundTripTest.java index e7f3b3b..e0cb4bd 100644 --- a/java/src/test/java/org/apache/paimon/index/fulltext/FullTextNativeRoundTripTest.java +++ b/java/src/test/java/org/apache/paimon/index/fulltext/FullTextNativeRoundTripTest.java @@ -24,9 +24,12 @@ import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; +import java.lang.ref.WeakReference; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; @@ -173,6 +176,80 @@ public class FullTextNativeRoundTripTest { return options; } + @Test + public void testCallbackBuffersAreReleasedDuringNativeCall() throws Exception { + assumeTrue( + "PAIMON_FTINDEX_JNI_LIB_PATH must point to the built JNI library " + + "or the native library must be present in classpath resources", + nativeLibraryAvailable()); + + // The native side allocates one byte[] per callback. Each must become collectable as + // soon as its callback returns, not only when the enclosing native call returns: + // otherwise a single write or search pins every byte it transfers on the Java heap. + ByteArrayOutputStream output = new ByteArrayOutputStream(); + List<WeakReference<byte[]>> written = new ArrayList<>(); + AtomicInteger writtenStillReachable = new AtomicInteger(); + Map<String, String> options = new LinkedHashMap<>(); + options.put("build.writer-threads", "2"); + options.put("build.writer-memory-size", "40mb"); + try (FullTextIndexWriter writer = FullTextIndexWriter.create(options)) { + StringBuilder text = new StringBuilder(); + for (int i = 0; i < 20000; i++) { + text.setLength(0); + for (int j = 0; j < 20; j++) { + text.append("term").append((i * 31 + j * 7919) % 50000).append(' '); + } + writer.addDocument(i, text.toString()); + } + writer.writeIndex( + (buffer, offset, length) -> { + if (written.size() == 20) { + writtenStillReachable.set(countReachableAfterGc(written)); + } + output.write(buffer, offset, length); + written.add(new WeakReference<>(buffer)); + }); + } + assertTrue("expected more than 20 write callbacks", written.size() > 20); + assertEquals(0, writtenStillReachable.get()); + + byte[] indexBytes = output.toByteArray(); + List<WeakReference<byte[]>> read = new ArrayList<>(); + AtomicInteger maxReadStillReachable = new AtomicInteger(); + FullTextIndexInput input = + (position, buffer, offset, length) -> { + if (read.size() % 8 == 7) { + maxReadStillReachable.accumulateAndGet( + countReachableAfterGc(read), Math::max); + } + preadBytes(indexBytes, position, buffer, offset, length); + read.add(new WeakReference<>(buffer)); + }; + try (FullTextIndexReader reader = new FullTextIndexReader(input)) { + read.clear(); + FullTextSearchResult result = + reader.search(matchQuery("term1 term2 term3 term4 term5 term6", "text"), 10); + assertTrue(result.size() > 0); + assertTrue("expected at least 8 reads in one search", read.size() >= 8); + assertEquals(0, maxReadStillReachable.get()); + } + } + + private static int countReachableAfterGc(List<WeakReference<byte[]>> references) { + int reachable = references.size(); + for (int attempt = 0; attempt < 20 && reachable > 0; attempt++) { + System.gc(); + System.runFinalization(); + reachable = 0; + for (WeakReference<byte[]> reference : references) { + if (reference.get() != null) { + reachable++; + } + } + } + return reachable; + } + private static boolean nativeLibraryAvailable() { String path = System.getenv("PAIMON_FTINDEX_JNI_LIB_PATH"); if (path != null && !path.isEmpty() && new File(path).isFile()) { diff --git a/jni/src/lib.rs b/jni/src/lib.rs index 3df3772..e29f5a0 100644 --- a/jni/src/lib.rs +++ b/jni/src/lib.rs @@ -40,16 +40,17 @@ impl SeekWrite for JavaOutput { let array = env .new_byte_array(buf.len() as i32) .map_err(|e| io::Error::other(format!("new_byte_array failed: {e}")))?; + // See `JavaInput::pread`: release the array as soon as this call is done with it. + let array = env.auto_local(array); let signed: Vec<i8> = buf.iter().map(|b| *b as i8).collect(); - env.set_byte_array_region(&array, 0, &signed) + env.set_byte_array_region(&*array, 0, &signed) .map_err(|e| io::Error::other(format!("set_byte_array_region failed: {e}")))?; - let array_obj = JObject::from(array); env.call_method( self.output.as_obj(), "write", "([BII)V", &[ - JValue::Object(&array_obj), + JValue::Object(&array), JValue::Int(0), JValue::Int(buf.len() as i32), ], @@ -92,20 +93,25 @@ impl SeekRead for JavaInput { let buffer = env .new_byte_array(length) .map_err(|e| io::Error::other(format!("new_byte_array failed: {e}")))?; - let buffer_obj = JObject::from(buffer); + // Searches run on a Java thread, so a local reference would otherwise live until the + // enclosing native method (a whole `search`) returns, pinning every array read so far + // on the Java heap. `AutoLocal` deletes the reference at the end of this iteration, on + // success and on error. By then the bytes have been copied into `range.buf`, which is + // Rust memory, and nothing below keeps the array. + let buffer = env.auto_local(buffer); env.call_method( self.input.as_obj(), "pread", "(J[BII)V", &[ JValue::Long(position), - JValue::Object(&buffer_obj), + JValue::Object(&buffer), JValue::Int(0), JValue::Int(length), ], ) .map_err(|e| io::Error::other(format!("Java input pread failed: {e}")))?; - copy_java_buffer(&mut env, JByteArray::from(buffer_obj), range.buf)?; + copy_java_buffer(&mut env, &buffer, range.buf)?; } Ok(()) } @@ -113,11 +119,11 @@ impl SeekRead for JavaInput { fn copy_java_buffer( env: &mut JNIEnv<'_>, - buffer: JByteArray<'_>, + buffer: &JByteArray<'_>, output: &mut [u8], ) -> io::Result<()> { let length = env - .get_array_length(&buffer) + .get_array_length(buffer) .map_err(|e| io::Error::other(format!("get_array_length failed: {e}")))? as usize; if length != output.len() { @@ -132,7 +138,7 @@ fn copy_java_buffer( } if length > 0 { let mut signed = vec![0i8; output.len()]; - env.get_byte_array_region(&buffer, 0, &mut signed) + env.get_byte_array_region(buffer, 0, &mut signed) .map_err(|e| io::Error::other(format!("get_byte_array_region failed: {e}")))?; for (dst, src) in output.iter_mut().zip(signed) { *dst = src as u8;
