mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
feat(mito2): add shared SST scan prerequisites
This commit is contained in:
@@ -15,6 +15,18 @@ headerPath = "licenses/enterprise-header.txt"
|
||||
# with the "# enterprise" block in `licenserc.toml`'s `excludes` — both are
|
||||
# enforced by `make check-enterprise-license`.
|
||||
includes = [
|
||||
"src/mito2/src/compaction/scheduler/hybrid.rs",
|
||||
"src/mito2/src/compaction/compactor/experiment/parallelism.rs",
|
||||
"src/mito2/src/compaction/multi_region/worker.rs",
|
||||
"src/mito2/src/compaction/multi_region/spill.rs",
|
||||
"src/mito2/src/compaction/multi_region/source.rs",
|
||||
"src/mito2/src/compaction/multi_region/streaming.rs",
|
||||
"src/mito2/src/compaction/multi_region/tests.rs",
|
||||
"src/mito2/src/compaction/multi_region/writer.rs",
|
||||
"src/mito2/src/compaction/multi_region/streaming/writer_block.rs",
|
||||
"src/mito2/src/compaction/multi_region.rs",
|
||||
"src/mito2/src/compaction/compactor/experiment.rs",
|
||||
"src/mito2/src/compaction/compactor/experiment/batch_window.rs",
|
||||
"src/common/meta/src/rpc/ddl/trigger.rs",
|
||||
"src/operator/src/expr_helper/trigger.rs",
|
||||
"src/sql/src/statements/alter/trigger.rs",
|
||||
|
||||
@@ -21,6 +21,18 @@ includes = [
|
||||
]
|
||||
|
||||
excludes = [
|
||||
"src/mito2/src/compaction/scheduler/hybrid.rs",
|
||||
"src/mito2/src/compaction/compactor/experiment/parallelism.rs",
|
||||
"src/mito2/src/compaction/multi_region/worker.rs",
|
||||
"src/mito2/src/compaction/multi_region/spill.rs",
|
||||
"src/mito2/src/compaction/multi_region/source.rs",
|
||||
"src/mito2/src/compaction/multi_region/streaming.rs",
|
||||
"src/mito2/src/compaction/multi_region/tests.rs",
|
||||
"src/mito2/src/compaction/multi_region/writer.rs",
|
||||
"src/mito2/src/compaction/multi_region/streaming/writer_block.rs",
|
||||
"src/mito2/src/compaction/multi_region.rs",
|
||||
"src/mito2/src/compaction/compactor/experiment.rs",
|
||||
"src/mito2/src/compaction/compactor/experiment/batch_window.rs",
|
||||
# copied sources
|
||||
"src/common/base/src/readable_size.rs",
|
||||
"src/common/base/src/secrets.rs",
|
||||
|
||||
@@ -14,9 +14,12 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use common_error::ext::BoxedError;
|
||||
use common_telemetry::warn;
|
||||
use puffin::puffin_manager::{PuffinWriter, PutOptions};
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use tantivy::indexer::NoMergePolicy;
|
||||
@@ -37,6 +40,8 @@ pub const ROWID_FIELD_NAME: &str = "greptime_fulltext_rowid";
|
||||
pub struct TantivyFulltextIndexCreator {
|
||||
/// The tantivy index writer.
|
||||
writer: Option<IndexWriter>,
|
||||
/// Retained across awaits so abort can join a cancelled finish operation.
|
||||
finishing: Option<common_runtime::JoinHandle<Result<()>>>,
|
||||
|
||||
/// The field for the text.
|
||||
text_field: tantivy::schema::Field,
|
||||
@@ -47,28 +52,94 @@ pub struct TantivyFulltextIndexCreator {
|
||||
/// The current max row id.
|
||||
max_rowid: u64,
|
||||
|
||||
/// The directory path in filesystem to store the index.
|
||||
path: PathBuf,
|
||||
/// Shared with blocking work so cancellation cannot unlink an active index.
|
||||
directory: Arc<TempIndexDirectory>,
|
||||
|
||||
/// The configuration of the fulltext index.
|
||||
config: Config,
|
||||
}
|
||||
|
||||
/// Owns an empty temporary directory, never a pre-existing index.
|
||||
struct TempIndexDirectory {
|
||||
path: PathBuf,
|
||||
removed: AtomicBool,
|
||||
}
|
||||
|
||||
impl TempIndexDirectory {
|
||||
fn create(path: PathBuf) -> Result<Arc<Self>> {
|
||||
std::fs::create_dir_all(&path).context(IoSnafu)?;
|
||||
if std::fs::read_dir(&path)
|
||||
.context(IoSnafu)?
|
||||
.next()
|
||||
.transpose()
|
||||
.context(IoSnafu)?
|
||||
.is_some()
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::AlreadyExists,
|
||||
"Tantivy temporary directory must be empty",
|
||||
))
|
||||
.context(IoSnafu);
|
||||
}
|
||||
Ok(Arc::new(Self {
|
||||
path,
|
||||
removed: AtomicBool::new(false),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempIndexDirectory {
|
||||
fn drop(&mut self) {
|
||||
if self.removed.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let path = self.path.clone();
|
||||
common_runtime::spawn_blocking_global(move || {
|
||||
if let Err(error) = std::fs::remove_dir_all(&path)
|
||||
&& error.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
warn!(error; "Failed to remove temporary Tantivy directory: {}", path.display());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TantivyFulltextIndexCreator {
|
||||
fn drop(&mut self) {
|
||||
if let Some(writer) = self.writer.take() {
|
||||
let directory = self.directory.clone();
|
||||
// IndexWriter::drop joins its threads; neither that nor directory
|
||||
// removal may block the async task cancelling this creator.
|
||||
common_runtime::spawn_blocking_global(move || {
|
||||
drop(writer);
|
||||
drop(directory);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TantivyFulltextIndexCreator {
|
||||
/// Creates a new `TantivyFulltextIndexCreator`.
|
||||
///
|
||||
/// The `path` is the directory path in filesystem to store the index.
|
||||
/// `path` must be an empty temporary directory. It is removed after the
|
||||
/// creator and any in-flight blocking work release it.
|
||||
pub async fn new(path: impl AsRef<Path>, config: Config, memory_limit: usize) -> Result<Self> {
|
||||
tokio::fs::create_dir_all(path.as_ref())
|
||||
let path = path.as_ref().to_path_buf();
|
||||
// Keep creation and its guard in the same task: dropping the awaiting
|
||||
// future must not race mkdir against cleanup.
|
||||
common_runtime::spawn_blocking_global(move || Self::create(path, config, memory_limit))
|
||||
.await
|
||||
.context(IoSnafu)?;
|
||||
.context(JoinSnafu)?
|
||||
}
|
||||
|
||||
fn create(path: PathBuf, config: Config, memory_limit: usize) -> Result<Self> {
|
||||
let directory = TempIndexDirectory::create(path)?;
|
||||
let mut schema_builder = Schema::builder();
|
||||
let text_field = schema_builder.add_text_field(TEXT_FIELD_NAME, TEXT);
|
||||
let rowid_field = schema_builder.add_u64_field(ROWID_FIELD_NAME, STORED);
|
||||
let schema = schema_builder.build();
|
||||
|
||||
let mut index = Index::create_in_dir(&path, schema).context(TantivySnafu)?;
|
||||
let mut index = Index::create_in_dir(&directory.path, schema).context(TantivySnafu)?;
|
||||
index.settings_mut().docstore_compression = Compressor::Zstd(ZstdCompressor::default());
|
||||
index.set_tokenizers(config.build_tantivy_tokenizer());
|
||||
|
||||
@@ -82,14 +153,33 @@ impl TantivyFulltextIndexCreator {
|
||||
|
||||
Ok(Self {
|
||||
writer: Some(writer),
|
||||
finishing: None,
|
||||
text_field,
|
||||
rowid_field,
|
||||
max_rowid: 0,
|
||||
path: path.as_ref().to_path_buf(),
|
||||
directory,
|
||||
config,
|
||||
})
|
||||
}
|
||||
|
||||
async fn finish_writer(&mut self) -> Result<()> {
|
||||
if self.finishing.is_none() {
|
||||
let writer = self.writer.take().context(FinishedSnafu)?;
|
||||
let directory = self.directory.clone();
|
||||
self.finishing = Some(common_runtime::spawn_blocking_global(move || {
|
||||
let _directory = directory;
|
||||
// Declare the writer after the lease so error unwinding also
|
||||
// drops/joins it before releasing the directory.
|
||||
let mut writer = writer;
|
||||
writer.commit().context(TantivySnafu)?;
|
||||
writer.wait_merging_threads().context(TantivySnafu)
|
||||
}));
|
||||
}
|
||||
let completed = self.finishing.as_mut().context(FinishedSnafu)?.await;
|
||||
self.finishing.take();
|
||||
completed.context(JoinSnafu)?
|
||||
}
|
||||
|
||||
fn sanitize_memory_limit(memory_limit: usize) -> usize {
|
||||
// Port from tantivy::indexer::index_writer::{MEMORY_BUDGET_NUM_BYTES_MIN, MEMORY_BUDGET_NUM_BYTES_MAX}
|
||||
const MARGIN_IN_BYTES: usize = 1_000_000;
|
||||
@@ -116,13 +206,7 @@ impl FulltextIndexCreator for TantivyFulltextIndexCreator {
|
||||
blob_key: &str,
|
||||
put_options: PutOptions,
|
||||
) -> Result<u64> {
|
||||
let mut writer = self.writer.take().context(FinishedSnafu)?;
|
||||
common_runtime::spawn_blocking_global(move || {
|
||||
writer.commit().context(TantivySnafu)?;
|
||||
writer.wait_merging_threads().context(TantivySnafu)
|
||||
})
|
||||
.await
|
||||
.context(JoinSnafu)??;
|
||||
self.finish_writer().await?;
|
||||
|
||||
let property_key = KEY_FULLTEXT_CONFIG.to_string();
|
||||
let property_value = serde_json::to_string(&self.config).context(SerializeToJsonSnafu)?;
|
||||
@@ -130,7 +214,7 @@ impl FulltextIndexCreator for TantivyFulltextIndexCreator {
|
||||
puffin_writer
|
||||
.put_dir(
|
||||
blob_key,
|
||||
self.path.clone(),
|
||||
self.directory.path.clone(),
|
||||
put_options,
|
||||
HashMap::from([(property_key, property_value)]),
|
||||
)
|
||||
@@ -140,15 +224,15 @@ impl FulltextIndexCreator for TantivyFulltextIndexCreator {
|
||||
}
|
||||
|
||||
async fn abort(&mut self) -> Result<()> {
|
||||
let mut writer = self.writer.take().context(FinishedSnafu)?;
|
||||
common_runtime::spawn_blocking_global(move || {
|
||||
writer.commit().context(TantivySnafu)?;
|
||||
writer.wait_merging_threads().context(TantivySnafu)
|
||||
})
|
||||
.await
|
||||
.context(JoinSnafu)??;
|
||||
|
||||
tokio::fs::remove_dir_all(&self.path).await.context(IoSnafu)
|
||||
if self.writer.is_some() || self.finishing.is_some() {
|
||||
self.finish_writer().await?;
|
||||
}
|
||||
match tokio::fs::remove_dir_all(&self.directory.path).await {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
removed => removed.context(IoSnafu)?,
|
||||
}
|
||||
self.directory.removed.store(true, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn memory_usage(&self) -> usize {
|
||||
@@ -171,7 +255,10 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::fulltext_index::Analyzer;
|
||||
|
||||
struct MockPuffinWriter;
|
||||
#[derive(Default)]
|
||||
struct MockPuffinWriter {
|
||||
blocked: Option<Arc<tokio::sync::Notify>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PuffinWriter for MockPuffinWriter {
|
||||
@@ -191,10 +278,15 @@ mod tests {
|
||||
async fn put_dir(
|
||||
&mut self,
|
||||
_key: &str,
|
||||
_dir: PathBuf,
|
||||
dir: PathBuf,
|
||||
_options: PutOptions,
|
||||
_properties: HashMap<String, String>,
|
||||
) -> puffin::error::Result<u64> {
|
||||
if let Some(blocked) = &self.blocked {
|
||||
assert!(dir.join("meta.json").exists());
|
||||
blocked.notify_one();
|
||||
futures::future::pending::<()>().await;
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
fn set_footer_lz4_compressed(&mut self, _lz4_compressed: bool) {
|
||||
@@ -206,6 +298,116 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_directory_removed(path: &Path) {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
while tokio::fs::try_exists(path).await.unwrap() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("temporary Tantivy directory leaked");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_creator_drop_cleans_temporary_files() {
|
||||
for stage in ["active", "finished", "aborted"] {
|
||||
let root = create_temp_dir("tantivy-drop-");
|
||||
let path = root.path().join("index");
|
||||
let mut creator = TantivyFulltextIndexCreator::new(&path, Config::default(), 1)
|
||||
.await
|
||||
.unwrap();
|
||||
creator.push_text("indexed text").await.unwrap();
|
||||
assert!(path.join("meta.json").exists());
|
||||
match stage {
|
||||
"finished" => {
|
||||
creator
|
||||
.finish(
|
||||
&mut MockPuffinWriter::default(),
|
||||
"index",
|
||||
PutOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
"aborted" => {
|
||||
creator.abort().await.unwrap();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
drop(creator);
|
||||
assert_directory_removed(&path).await;
|
||||
assert!(root.path().exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_abort_after_cancelled_finish_cleans_temporary_files() {
|
||||
let root = create_temp_dir("tantivy-cancel-finish-");
|
||||
let path = root.path().join("index");
|
||||
let mut creator = TantivyFulltextIndexCreator::new(&path, Config::default(), 1)
|
||||
.await
|
||||
.unwrap();
|
||||
creator.push_text("indexed text").await.unwrap();
|
||||
let blocked = Arc::new(tokio::sync::Notify::new());
|
||||
let mut writer = MockPuffinWriter {
|
||||
blocked: Some(blocked.clone()),
|
||||
};
|
||||
{
|
||||
let finishing = creator.finish(&mut writer, "index", PutOptions::default());
|
||||
tokio::pin!(finishing);
|
||||
tokio::select! {
|
||||
_ = blocked.notified() => {}
|
||||
result = &mut finishing => panic!("finish did not reach the blocked upload: {result:?}"),
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(10)) => panic!("finish stalled"),
|
||||
}
|
||||
}
|
||||
creator.abort().await.unwrap();
|
||||
creator.abort().await.unwrap();
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_detached_initialization_cleans_its_result() {
|
||||
let root = create_temp_dir("tantivy-detached-init-");
|
||||
let path = root.path().join("index");
|
||||
let creating_path = path.clone();
|
||||
let (ready, initialized) = tokio::sync::oneshot::channel();
|
||||
let (release, released) = std::sync::mpsc::channel();
|
||||
// The real constructor runs on the blocking pool. Detaching its handle
|
||||
// must clean even if cancellation happens before the result is delivered.
|
||||
let creating = common_runtime::spawn_blocking_global(move || {
|
||||
let creator =
|
||||
TantivyFulltextIndexCreator::create(creating_path, Config::default(), 1).unwrap();
|
||||
ready.send(()).unwrap();
|
||||
released.recv().unwrap();
|
||||
creator
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), initialized)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(path.join("meta.json").exists());
|
||||
drop(creating);
|
||||
release.send(()).unwrap();
|
||||
assert_directory_removed(&path).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_initialization_preserves_nonempty_directory() {
|
||||
let root = create_temp_dir("tantivy-existing-");
|
||||
let sentinel = root.path().join("existing");
|
||||
tokio::fs::write(&sentinel, "must survive").await.unwrap();
|
||||
assert!(
|
||||
TantivyFulltextIndexCreator::new(root.path(), Config::default(), 1)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
"must survive",
|
||||
tokio::fs::read_to_string(&sentinel).await.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_creator_basic() {
|
||||
let memory_limits = [1, 64_000_000, usize::MAX];
|
||||
@@ -215,7 +417,7 @@ mod tests {
|
||||
|
||||
let texts = vec!["hello", "world", "hello, world", "foo!", "Bar"];
|
||||
let config = Config::default();
|
||||
build_index(&texts, temp_dir.path(), config, memory_limit).await;
|
||||
let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
|
||||
|
||||
let cases = [
|
||||
("hello", vec![0u32, 2]),
|
||||
@@ -239,7 +441,7 @@ mod tests {
|
||||
case_sensitive: true,
|
||||
..Config::default()
|
||||
};
|
||||
build_index(&texts, temp_dir.path(), config, memory_limit).await;
|
||||
let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
|
||||
|
||||
let cases = [
|
||||
("hello", vec![0u32, 2]),
|
||||
@@ -267,7 +469,7 @@ mod tests {
|
||||
analyzer: Analyzer::Chinese,
|
||||
..Config::default()
|
||||
};
|
||||
build_index(&texts, temp_dir.path(), config, memory_limit).await;
|
||||
let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
|
||||
|
||||
let cases = [
|
||||
("你好", vec![0u32, 2, 3]),
|
||||
@@ -291,7 +493,7 @@ mod tests {
|
||||
case_sensitive: true,
|
||||
analyzer: Analyzer::Chinese,
|
||||
};
|
||||
build_index(&texts, temp_dir.path(), config, memory_limit).await;
|
||||
let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
|
||||
|
||||
let cases = [
|
||||
("你好", vec![0u32, 2, 3]),
|
||||
@@ -307,7 +509,12 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
async fn build_index(texts: &[&str], path: &Path, config: Config, memory_limit: usize) {
|
||||
async fn build_index(
|
||||
texts: &[&str],
|
||||
path: &Path,
|
||||
config: Config,
|
||||
memory_limit: usize,
|
||||
) -> TantivyFulltextIndexCreator {
|
||||
let mut creator = TantivyFulltextIndexCreator::new(path, config, memory_limit)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -315,9 +522,10 @@ mod tests {
|
||||
creator.push_text(text).await.unwrap();
|
||||
}
|
||||
creator
|
||||
.finish(&mut MockPuffinWriter, "", PutOptions::default())
|
||||
.finish(&mut MockPuffinWriter::default(), "", PutOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
creator
|
||||
}
|
||||
|
||||
async fn query_and_check(path: &Path, config: Config, cases: &[(&str, Vec<u32>)]) {
|
||||
|
||||
@@ -348,6 +348,29 @@ impl AccessLayer {
|
||||
request: SstWriteRequest,
|
||||
write_opts: &WriteOptions,
|
||||
metrics: &mut Metrics,
|
||||
) -> Result<SstInfoArray> {
|
||||
self.write_sst_inner(request, write_opts, metrics, None)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub(crate) async fn write_sst_with_guard(
|
||||
&self,
|
||||
request: SstWriteRequest,
|
||||
write_opts: &WriteOptions,
|
||||
metrics: &mut Metrics,
|
||||
guard: Arc<dyn crate::sst::parquet::writer::SstWriteGuard>,
|
||||
) -> Result<SstInfoArray> {
|
||||
self.write_sst_inner(request, write_opts, metrics, Some(guard))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn write_sst_inner(
|
||||
&self,
|
||||
request: SstWriteRequest,
|
||||
write_opts: &WriteOptions,
|
||||
metrics: &mut Metrics,
|
||||
guard: Option<Arc<dyn crate::sst::parquet::writer::SstWriteGuard>>,
|
||||
) -> Result<SstInfoArray> {
|
||||
let op_type = request.op_type;
|
||||
let region_id = request.metadata.region_id;
|
||||
@@ -359,7 +382,9 @@ impl AccessLayer {
|
||||
request.max_sequence
|
||||
};
|
||||
|
||||
let sst_info = if let Some(write_cache) = cache_manager.write_cache() {
|
||||
let sst_info = if let Some(write_cache) = cache_manager.write_cache()
|
||||
&& guard.is_none()
|
||||
{
|
||||
// Write to the write cache.
|
||||
write_cache
|
||||
.write_and_upload_sst(
|
||||
@@ -405,7 +430,13 @@ impl AccessLayer {
|
||||
metrics,
|
||||
)
|
||||
.await
|
||||
.with_file_cleaner(cleaner);
|
||||
.with_file_cleaner(cleaner)
|
||||
.with_write_concurrency(if guard.is_some() {
|
||||
1
|
||||
} else {
|
||||
crate::sst::DEFAULT_WRITE_CONCURRENCY
|
||||
})
|
||||
.with_write_guard(guard);
|
||||
match request.sst_write_format {
|
||||
FormatType::PrimaryKey => {
|
||||
writer
|
||||
|
||||
@@ -17,6 +17,8 @@ pub mod compactor;
|
||||
mod json2;
|
||||
mod last_non_null;
|
||||
pub mod memory_manager;
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub mod multi_region;
|
||||
mod overlap;
|
||||
pub mod picker;
|
||||
mod reader;
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub(crate) mod experiment;
|
||||
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -434,6 +437,26 @@ impl CompactionContext {
|
||||
&self,
|
||||
merge_output: MergeOutput,
|
||||
) -> Result<(RegionEdit, ManifestVersion)> {
|
||||
#[cfg(feature = "enterprise")]
|
||||
let shared_stats = if experiment::enabled(self.region_id)
|
||||
&& experiment::shared_inputs(merge_output.files_to_remove.iter())
|
||||
{
|
||||
Some((
|
||||
merge_output.files_to_add.len(),
|
||||
merge_output
|
||||
.files_to_add
|
||||
.iter()
|
||||
.map(|f| f.num_rows)
|
||||
.sum::<u64>(),
|
||||
merge_output
|
||||
.files_to_add
|
||||
.iter()
|
||||
.map(|f| f.file_size)
|
||||
.sum::<u64>(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let edit = RegionEdit {
|
||||
files_to_add: merge_output.files_to_add,
|
||||
files_to_remove: merge_output.files_to_remove,
|
||||
@@ -452,6 +475,18 @@ impl CompactionContext {
|
||||
.update_manifest_for_compaction(action_list)
|
||||
.await?;
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
if let Some((files, rows, bytes)) = shared_stats {
|
||||
experiment::record_publication(self, &edit.files_to_remove).await?;
|
||||
common_telemetry::info!(
|
||||
"hybrid_shared_published region={} files={} rows={} bytes={} manifest={}",
|
||||
self.region_id,
|
||||
files,
|
||||
rows,
|
||||
bytes,
|
||||
manifest_version
|
||||
);
|
||||
}
|
||||
Ok((edit, manifest_version))
|
||||
}
|
||||
}
|
||||
@@ -772,6 +807,12 @@ impl<M: SstMerger> DefaultCompactor<M> {
|
||||
context: &CompactionContext,
|
||||
unit: &CompactionUnit,
|
||||
) -> Result<MergeOutput> {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if experiment::enabled(context.region_id)
|
||||
&& experiment::shared_inputs(unit.inputs.iter().map(|f| f.meta_ref()))
|
||||
{
|
||||
return experiment::merge(context, unit, self.cancel_handle.clone()).await;
|
||||
}
|
||||
let mut result = MergeOutput {
|
||||
files_to_remove: unit.inputs.iter().map(|f| f.meta_ref().clone()).collect(),
|
||||
compaction_time_window: Some(unit.time_window_size),
|
||||
@@ -857,9 +898,36 @@ where
|
||||
let context = context.clone();
|
||||
let uncommitted = self.uncommitted.clone();
|
||||
let fut = async move {
|
||||
let region_id = context.region_id;
|
||||
let group = output
|
||||
.inputs
|
||||
.first()
|
||||
.map(|f| f.file_id().to_string())
|
||||
.unwrap_or_default();
|
||||
let rows = output
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|f| f.meta_ref().num_rows)
|
||||
.sum::<u64>();
|
||||
let started = std::time::Instant::now();
|
||||
common_telemetry::info!(
|
||||
"testbed_l1_group_start region={} group={} files={} rows={} encode_parallelism={}",
|
||||
region_id.as_u64(),
|
||||
group,
|
||||
output.inputs.len(),
|
||||
rows,
|
||||
write_opts.encode_parallelism
|
||||
);
|
||||
let result = merger
|
||||
.merge_single_output(context, output, write_opts)
|
||||
.await;
|
||||
common_telemetry::info!(
|
||||
"testbed_l1_group_end region={} group={} elapsed_us={} success={}",
|
||||
region_id.as_u64(),
|
||||
group,
|
||||
started.elapsed().as_micros(),
|
||||
result.is_ok()
|
||||
);
|
||||
if let (Some(uncommitted), Ok((_, infos))) = (&uncommitted, &result) {
|
||||
uncommitted.track(infos);
|
||||
}
|
||||
@@ -1599,14 +1667,26 @@ mod tests {
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::successful_outputs(false)]
|
||||
#[case::join_error(true)]
|
||||
#[case::successful_outputs(false, 2)]
|
||||
#[case::join_error(true, 2)]
|
||||
#[case::ordinary_eight(false, 8)]
|
||||
#[case::scanner_sixteen(false, 16)]
|
||||
#[case::scanner_twenty_four(false, 24)]
|
||||
#[tokio::test]
|
||||
async fn test_merge_ssts_cancellation_waits_for_encoders(#[case] panic_merge: bool) {
|
||||
async fn test_merge_ssts_cancellation_waits_for_encoders(
|
||||
#[case] panic_merge: bool,
|
||||
#[case] parallelism: usize,
|
||||
) {
|
||||
// The fixture blocks every encoder before release; all cases need
|
||||
// enough threads to reach their gates concurrently.
|
||||
common_runtime::init_global_runtimes(&common_runtime::global::RuntimeOptions {
|
||||
compact_rt_max_blocking_threads: 32,
|
||||
..Default::default()
|
||||
});
|
||||
let mut region = new_test_compaction_region().await;
|
||||
region.max_parallelism = 2;
|
||||
region.max_parallelism = parallelism;
|
||||
region.region_options.compaction_output_parallelism = Some(2);
|
||||
let inputs: Vec<_> = (0..3).map(|_| dummy_file_meta()).collect();
|
||||
let inputs: Vec<_> = (0..parallelism + 1).map(|_| dummy_file_meta()).collect();
|
||||
let picker_output = PickerOutput {
|
||||
outputs: inputs
|
||||
.iter()
|
||||
@@ -1638,7 +1718,7 @@ mod tests {
|
||||
});
|
||||
assert!(futures::poll!(merge.as_mut()).is_pending());
|
||||
let mut encoders = Vec::new();
|
||||
for _ in 0..2 {
|
||||
for _ in 0..parallelism {
|
||||
encoders.push(
|
||||
timeout(Duration::from_secs(10), started_rx.recv())
|
||||
.await
|
||||
|
||||
@@ -0,0 +1,658 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! Fixed-topology two-stage experiment: local shared L0 routing, remote per-region L1.
|
||||
//! Round objects are immutable; each leader publishes only its own region manifest.
|
||||
mod batch_window;
|
||||
mod parallelism;
|
||||
pub(crate) use parallelism::{automatic_parallelism, merge_parallelism};
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use common_base::cancellation::CancellationHandle;
|
||||
use object_store::{ErrorKind, ObjectStore};
|
||||
use partition::multi_dim::MultiDimPartitionRule;
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use snafu::{ResultExt, ensure};
|
||||
use store_api::metadata::RegionMetadata;
|
||||
use store_api::region_request::PathType;
|
||||
use store_api::storage::{FileId, RegionId};
|
||||
|
||||
use super::{CompactionContext, CompactionRegion, MergeOutput};
|
||||
use crate::compaction::CompactionOutput;
|
||||
use crate::compaction::multi_region::{
|
||||
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, compact_regions,
|
||||
};
|
||||
use crate::compaction::picker::PickerOutput;
|
||||
use crate::compaction::unit::CompactionUnit;
|
||||
use crate::error::{
|
||||
InvalidMultiRegionCompactionSnafu as Invalid, OpenDalSnafu, Result, SerdeJsonSnafu,
|
||||
};
|
||||
use crate::region::options::RegionOptions;
|
||||
use crate::sst::file::{FileMeta, RegionFileId};
|
||||
use crate::sst::parquet::writer::SstWriteGuard;
|
||||
|
||||
static WIDTH: LazyLock<usize> = LazyLock::new(|| {
|
||||
std::env::var("TESTBED_SHARED_BATCH_FILES")
|
||||
.unwrap_or_else(|_| "32".into())
|
||||
.parse::<std::num::NonZeroUsize>()
|
||||
.expect("invalid TESTBED_SHARED_BATCH_FILES")
|
||||
.get()
|
||||
});
|
||||
static REGIONS: LazyLock<u32> = LazyLock::new(|| {
|
||||
std::env::var("TESTBED_SHARED_TABLE_REGIONS")
|
||||
.unwrap_or_else(|_| "12".into())
|
||||
.parse::<std::num::NonZeroU32>()
|
||||
.expect("invalid TESTBED_SHARED_TABLE_REGIONS")
|
||||
.get()
|
||||
});
|
||||
static REGION_COUNTS: LazyLock<HashMap<u32, u32>> = LazyLock::new(|| {
|
||||
std::env::var("TESTBED_SHARED_TABLE_LAYOUT")
|
||||
.unwrap_or_default()
|
||||
.split(',')
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.map(|s| {
|
||||
let (table, count) = s.split_once(':').expect("expected table_id:region_count");
|
||||
(
|
||||
table.trim().parse().expect("invalid table id"),
|
||||
count
|
||||
.trim()
|
||||
.parse::<std::num::NonZeroU32>()
|
||||
.expect("invalid region count")
|
||||
.get(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
|
||||
fn region_count(id: RegionId) -> u32 {
|
||||
REGION_COUNTS
|
||||
.get(&id.table_id())
|
||||
.copied()
|
||||
.unwrap_or(*REGIONS)
|
||||
}
|
||||
const DAY: i64 = 86400;
|
||||
static TABLES: LazyLock<Vec<u32>> = LazyLock::new(|| {
|
||||
std::env::var("TESTBED_SHARED_TABLE_ID")
|
||||
.ok()
|
||||
.map(|s| {
|
||||
s.split(',')
|
||||
.map(|id| id.trim().parse().expect("invalid TESTBED_SHARED_TABLE_ID"))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
});
|
||||
static BATCHES: LazyLock<std::num::NonZeroUsize> = LazyLock::new(|| {
|
||||
std::env::var("TESTBED_SHARED_TABLE_BATCHES")
|
||||
.unwrap_or_else(|_| "1".into())
|
||||
.parse()
|
||||
.expect("TESTBED_SHARED_TABLE_BATCHES must be a positive integer")
|
||||
});
|
||||
|
||||
pub(crate) fn batch_limit() -> usize {
|
||||
BATCHES.get()
|
||||
}
|
||||
|
||||
// Single-batch rounds keep the original object layout for replay.
|
||||
fn batch_root(root: &str, files: usize, index: usize) -> String {
|
||||
if files == *WIDTH {
|
||||
root.into()
|
||||
} else {
|
||||
format!("{root}/batch-{index}")
|
||||
}
|
||||
}
|
||||
|
||||
static CURSORS: LazyLock<Mutex<HashMap<RegionId, u64>>> = LazyLock::new(Default::default);
|
||||
pub(crate) fn enabled(id: RegionId) -> bool {
|
||||
uses_shared_compaction(id, &TABLES, region_count(id))
|
||||
}
|
||||
|
||||
// A single target has no duplicated scan to share. Keep its picker, merge and
|
||||
// file lifecycle on the ordinary path, including unpartitioned metric tables.
|
||||
fn uses_shared_compaction(id: RegionId, tables: &[u32], regions: u32) -> bool {
|
||||
regions > 1 && id.region_number() < regions && tables.contains(&id.table_id())
|
||||
}
|
||||
|
||||
/// Only mixed bulk L0s belong to the shared scan. Routed L1s keep the regular picker.
|
||||
pub(crate) fn is_shared(file: &FileMeta) -> bool {
|
||||
file.level == 0 && file.region_id.region_number() == 0 && file.partition_expr.is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn shared_inputs<'a>(files: impl Iterator<Item = &'a FileMeta>) -> bool {
|
||||
let mut found = false;
|
||||
for file in files {
|
||||
if !is_shared(file) {
|
||||
return false;
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn single_region_uses_ordinary_compaction() {
|
||||
assert!(!uses_shared_compaction(RegionId::new(42, 0), &[42], 1));
|
||||
assert!(!uses_shared_compaction(RegionId::new(42, 1), &[42], 1));
|
||||
assert!(!uses_shared_compaction(RegionId::new(42, 0), &[42], 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_compaction_only_matches_selected_data_regions() {
|
||||
for n in 0..12 {
|
||||
assert!(uses_shared_compaction(RegionId::new(42, n), &[42], 12));
|
||||
}
|
||||
assert!(!uses_shared_compaction(RegionId::new(42, 12), &[42], 12));
|
||||
assert!(!uses_shared_compaction(
|
||||
RegionId::new(42, 1 << 24),
|
||||
&[42],
|
||||
12
|
||||
));
|
||||
assert!(!uses_shared_compaction(RegionId::new(43, 0), &[42], 12));
|
||||
assert!(!uses_shared_compaction(RegionId::new(42, 0), &[], 12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routed_l1_never_reenters_the_shared_scan() {
|
||||
use crate::compaction::test_util::new_file_handle;
|
||||
let input = new_file_handle(FileId::random(), 0, 100, 0);
|
||||
let mut l0 = input.meta_ref().clone();
|
||||
l0.region_id = RegionId::new(42, 0);
|
||||
l0.partition_expr = None;
|
||||
assert!(shared_inputs([&l0].into_iter()));
|
||||
let mut l1 = l0.clone();
|
||||
l1.level = 1;
|
||||
assert!(!shared_inputs([&l1].into_iter()));
|
||||
assert!(!shared_inputs([&l0, &l1].into_iter()));
|
||||
assert!(!shared_inputs(std::iter::empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn l1_picker_view_preserves_live_reservations_without_deleting_l0() {
|
||||
use crate::compaction::test_util::{new_file_handle, primary_key_metadata_for_test};
|
||||
use crate::sst::file_purger::NoopFilePurger;
|
||||
use crate::sst::version::SstVersion;
|
||||
let l0 = new_file_handle(FileId::random(), 0, 100, 0)
|
||||
.meta_ref()
|
||||
.clone();
|
||||
let l1 = new_file_handle(FileId::random(), 0, 100, 1)
|
||||
.meta_ref()
|
||||
.clone();
|
||||
let mut version = SstVersion::new(primary_key_metadata_for_test());
|
||||
version.add_files(Arc::new(NoopFilePurger), [l0, l1].into_iter());
|
||||
let live_l0 = version.levels()[0].files().next().unwrap().clone();
|
||||
let live_l1 = version.levels()[1].files().next().unwrap().clone();
|
||||
let filtered = version.without_shared_l0();
|
||||
assert_eq!(0, filtered.levels()[0].files().count());
|
||||
let selected = filtered.levels()[1].files().next().unwrap();
|
||||
assert!(selected.try_set_compacting());
|
||||
assert!(live_l1.compacting());
|
||||
assert!(!live_l0.is_deleted());
|
||||
selected.set_compacting(false);
|
||||
assert_eq!(1, version.levels()[0].files().count());
|
||||
}
|
||||
}
|
||||
fn cursor(id: RegionId) -> u64 {
|
||||
*CURSORS.lock().unwrap().get(&id).unwrap_or(&0)
|
||||
}
|
||||
fn prefix(id: RegionId, round: u64) -> String {
|
||||
format!("_testbed_table_jobs/{}/{round}", id.table_id())
|
||||
}
|
||||
|
||||
async fn read<T: DeserializeOwned>(store: &ObjectStore, key: &str) -> Result<Option<T>> {
|
||||
match store.read(key).await {
|
||||
Ok(buf) => serde_json::from_slice(&buf.to_bytes())
|
||||
.map(Some)
|
||||
.context(SerdeJsonSnafu),
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(e).context(OpenDalSnafu),
|
||||
}
|
||||
}
|
||||
|
||||
async fn create<T: Serialize>(store: &ObjectStore, key: &str, value: &T) -> Result<()> {
|
||||
let bytes = serde_json::to_vec(&serde_json::to_value(value).context(SerdeJsonSnafu)?)
|
||||
.context(SerdeJsonSnafu)?;
|
||||
match store
|
||||
.write_with(key, bytes.clone())
|
||||
.if_not_exists(true)
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => {
|
||||
// OSS reports FileAlreadyExists as a conflict. Verify the exact payload
|
||||
// also for an ambiguous response to our own successful first write.
|
||||
if let Ok(buf) = store.read(key).await
|
||||
&& buf.to_bytes().as_ref() == bytes
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
Err(e).context(OpenDalSnafu)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Reservation {
|
||||
metadata: RegionMetadata,
|
||||
options: RegionOptions,
|
||||
inputs: Vec<FileMeta>,
|
||||
}
|
||||
|
||||
type Outputs = BTreeMap<RegionId, Vec<FileMeta>>;
|
||||
|
||||
/// Only a complete, registered shared batch needs a readiness retry.
|
||||
/// Routed L1, unsequenced files and an undersized tail do not keep polling.
|
||||
pub(crate) fn has_pending_shared_batch(ssts: &crate::sst::version::SstVersion) -> bool {
|
||||
ssts.levels()[0]
|
||||
.files()
|
||||
.filter(|f| is_shared(f.meta_ref()) && f.meta_ref().sequence.is_some())
|
||||
.take(*WIDTH)
|
||||
.count()
|
||||
== *WIDTH
|
||||
}
|
||||
|
||||
pub(crate) async fn pick(region: &CompactionRegion) -> Result<Option<PickerOutput>> {
|
||||
let id = region.region_id;
|
||||
ensure!(
|
||||
region.access_layer.path_type() == PathType::Data && id.region_number() < region_count(id),
|
||||
Invalid {
|
||||
reason: "expected a fixed physical metric data region"
|
||||
}
|
||||
);
|
||||
let store = region.access_layer.object_store();
|
||||
let handles: HashMap<_, _> = region.current_version.ssts.levels()[0]
|
||||
.files()
|
||||
.filter(|f| is_shared(f.meta_ref()) && f.meta_ref().sequence.is_some())
|
||||
.map(|f| (f.meta_ref().file_id, f))
|
||||
.collect();
|
||||
let mut round = cursor(id);
|
||||
loop {
|
||||
let root = prefix(id, round);
|
||||
let key = format!("{root}/sources");
|
||||
let ids: Vec<FileId> = if let Some(ids) = read(store, &key).await? {
|
||||
ids
|
||||
} else {
|
||||
if id.region_number() != 0 || handles.len() < *WIDTH {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut files: Vec<_> = handles.values().map(|f| f.meta_ref()).collect();
|
||||
files.sort_by(|a, b| {
|
||||
(a.sequence, a.file_id.as_bytes()).cmp(&(b.sequence, b.file_id.as_bytes()))
|
||||
});
|
||||
let ids =
|
||||
batch_window::new_roster(files.iter().map(|f| f.file_id), *WIDTH, batch_limit());
|
||||
create(store, &key, &ids).await?;
|
||||
ids
|
||||
};
|
||||
ensure!(
|
||||
batch_window::valid_roster(&ids, *WIDTH),
|
||||
Invalid {
|
||||
reason: "invalid immutable round roster"
|
||||
}
|
||||
);
|
||||
let mut pending = Vec::new();
|
||||
let mut waiting = false;
|
||||
for (index, batch) in ids.chunks_exact(*WIDTH).enumerate() {
|
||||
let job = batch_root(&root, ids.len(), index);
|
||||
// Record successful local publication before allowing L1 compaction.
|
||||
// Its output may later be replaced by a remote merge, so checking
|
||||
// the original L1 IDs on every restart would be incorrect.
|
||||
let applied_key = format!("{job}/applied-{}", id.region_number());
|
||||
if read::<bool>(store, &applied_key).await? == Some(true) {
|
||||
continue;
|
||||
}
|
||||
let inputs: Vec<_> = batch
|
||||
.iter()
|
||||
.filter_map(|k| handles.get(k).map(|f| (**f).clone()))
|
||||
.collect();
|
||||
if inputs.len() == *WIDTH {
|
||||
pending.push(CompactionOutput {
|
||||
output_level: 1,
|
||||
inputs,
|
||||
filter_deleted: false,
|
||||
output_time_range: None,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let Some(result): Option<Outputs> = read(store, &format!("{job}/result")).await? else {
|
||||
waiting = true;
|
||||
continue;
|
||||
};
|
||||
let expected = result.get(&id).ok_or_else(|| {
|
||||
Invalid {
|
||||
reason: "region missing from table result",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let live: HashMap<_, _> = region.current_version.ssts.levels()[1]
|
||||
.files()
|
||||
.map(|f| (f.meta_ref().file_id, f.meta_ref()))
|
||||
.collect();
|
||||
ensure!(
|
||||
inputs.is_empty() && expected.iter().all(|f| live.get(&f.file_id) == Some(&f)),
|
||||
Invalid {
|
||||
reason: "partial or conflicting region publication"
|
||||
}
|
||||
);
|
||||
create(store, &applied_key, &true).await?;
|
||||
}
|
||||
if !pending.is_empty() {
|
||||
return Ok(Some(PickerOutput {
|
||||
outputs: pending,
|
||||
expired_ssts: vec![],
|
||||
time_window_size: DAY,
|
||||
max_file_size: Some(256 << 20),
|
||||
}));
|
||||
}
|
||||
if waiting {
|
||||
return Ok(None);
|
||||
}
|
||||
round += 1;
|
||||
CURSORS.lock().unwrap().insert(id, round);
|
||||
// L1 has its own scheduling state and no longer needs a turn here.
|
||||
}
|
||||
}
|
||||
|
||||
struct Guard {
|
||||
store: ObjectStore,
|
||||
root: String,
|
||||
}
|
||||
#[async_trait::async_trait]
|
||||
impl SstWriteGuard for Guard {
|
||||
async fn before_create(&self, id: RegionFileId) -> Result<()> {
|
||||
create(
|
||||
&self.store,
|
||||
&format!(
|
||||
"{}/protected/{}/{}",
|
||||
self.root,
|
||||
id.region_id().as_u64(),
|
||||
id.file_id()
|
||||
),
|
||||
&true,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn merge(
|
||||
ctx: &CompactionContext,
|
||||
unit: &CompactionUnit,
|
||||
cancel: Arc<CancellationHandle>,
|
||||
) -> Result<MergeOutput> {
|
||||
let id = ctx.region_id;
|
||||
let round = cursor(id);
|
||||
let root = prefix(id, round);
|
||||
let store = ctx.access_layer.object_store();
|
||||
let ids: Vec<FileId> = read(store, &format!("{root}/sources"))
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
Invalid {
|
||||
reason: "missing round sources",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let by_id: HashMap<_, _> = unit
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|f| (f.meta_ref().file_id, f.meta_ref()))
|
||||
.collect();
|
||||
let (index, batch) = batch_window::batch_for_unit(&ids, *WIDTH, &by_id.keys().collect())
|
||||
.ok_or_else(|| {
|
||||
Invalid {
|
||||
reason: "unit does not own exactly one complete batch",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let root = batch_root(&root, ids.len(), index);
|
||||
let ids = batch;
|
||||
let wait_start = Instant::now();
|
||||
let inputs: Vec<_> = ids.iter().map(|k| by_id[k].clone()).collect();
|
||||
let reservation = Reservation {
|
||||
metadata: (*ctx.region_metadata).clone(),
|
||||
options: ctx.region_options.clone(),
|
||||
inputs: inputs.clone(),
|
||||
};
|
||||
create(
|
||||
store,
|
||||
&format!("{root}/ready-{}", id.region_number()),
|
||||
&reservation,
|
||||
)
|
||||
.await?;
|
||||
let result_key = format!("{root}/result");
|
||||
let start = Instant::now();
|
||||
let mut ready = BTreeMap::new();
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
return crate::error::CompactionCancelledSnafu.fail();
|
||||
}
|
||||
ensure!(
|
||||
start.elapsed() < Duration::from_secs(900),
|
||||
Invalid {
|
||||
reason: "timed out waiting for table result"
|
||||
}
|
||||
);
|
||||
if let Some(outputs) = read::<Outputs>(store, &result_key).await? {
|
||||
let files = outputs.get(&id).ok_or_else(|| {
|
||||
Invalid {
|
||||
reason: "missing region result",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
ensure!(
|
||||
files.iter().all(|f| f.region_id == id && f.level == 1),
|
||||
Invalid {
|
||||
reason: "misrouted region result"
|
||||
}
|
||||
);
|
||||
return Ok(MergeOutput {
|
||||
files_to_add: files.clone(),
|
||||
files_to_remove: inputs,
|
||||
compaction_time_window: Some(DAY),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if id.region_number() == 0 {
|
||||
for n in 0..region_count(id) {
|
||||
if !ready.contains_key(&n)
|
||||
&& let Some(r) =
|
||||
read::<Reservation>(store, &format!("{root}/ready-{n}")).await?
|
||||
{
|
||||
ready.insert(n, r);
|
||||
}
|
||||
}
|
||||
if ready.len() == region_count(id) as usize {
|
||||
let ready_wait = wait_start.elapsed();
|
||||
let mut targets = BTreeMap::new();
|
||||
let mut expressions = Vec::new();
|
||||
for (n, r) in &ready {
|
||||
ensure!(
|
||||
r.metadata.region_id == RegionId::new(id.table_id(), *n)
|
||||
&& r.inputs.iter().map(|f| f.file_id).eq(ids.iter().copied()),
|
||||
Invalid {
|
||||
reason: "conflicting reservation"
|
||||
}
|
||||
);
|
||||
let expr =
|
||||
crate::region::parse_partition_expr(r.metadata.partition_expr.as_deref())?
|
||||
.ok_or_else(|| {
|
||||
Invalid {
|
||||
reason: "missing partition expression",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
expressions.push(expr);
|
||||
targets.insert(
|
||||
r.metadata.region_id,
|
||||
MultiRegionTarget {
|
||||
metadata: Arc::new(r.metadata.clone()),
|
||||
options: r.options.clone(),
|
||||
inputs: r.inputs.iter().map(|f| (f.file_id(), f.clone())).collect(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut columns = std::collections::HashSet::new();
|
||||
for expression in &expressions {
|
||||
expression.collect_column_names(&mut columns);
|
||||
}
|
||||
ensure!(
|
||||
columns.len() == 1,
|
||||
Invalid {
|
||||
reason: "expected one partition tag"
|
||||
}
|
||||
);
|
||||
let rule = MultiDimPartitionRule::try_new(
|
||||
columns.into_iter().collect(),
|
||||
(0..region_count(id)).collect(),
|
||||
expressions,
|
||||
true,
|
||||
)
|
||||
.context(crate::error::RouteMultiRegionSnafu)?;
|
||||
let plan = MultiRegionCompactionPlan {
|
||||
partition_rule: Arc::new(rule),
|
||||
sources: inputs.clone(),
|
||||
targets,
|
||||
memory_limit: std::env::var("TESTBED_SHARED_COMPACTION_MEMORY_MIB")
|
||||
.unwrap_or_else(|_| "8192".into())
|
||||
.parse::<usize>()
|
||||
.map_err(|_| {
|
||||
Invalid {
|
||||
reason: "invalid shared memory MiB",
|
||||
}
|
||||
.build()
|
||||
})?
|
||||
.checked_mul(1 << 20)
|
||||
.ok_or_else(|| {
|
||||
Invalid {
|
||||
reason: "shared memory MiB overflow",
|
||||
}
|
||||
.build()
|
||||
})?,
|
||||
max_active_workers: 2,
|
||||
spill_limit: 0,
|
||||
max_output_file_size: 256 << 20,
|
||||
window_seconds: DAY,
|
||||
};
|
||||
let context = MultiRegionCompactionContext {
|
||||
access_layer: ctx.access_layer.clone(),
|
||||
cache: ctx.cache_manager.clone(),
|
||||
config: ctx.engine_config.clone(),
|
||||
protection: Arc::new(Guard {
|
||||
store: store.clone(),
|
||||
root: root.clone(),
|
||||
}),
|
||||
cancellation: cancel.clone(),
|
||||
spill_directory: Default::default(),
|
||||
};
|
||||
common_telemetry::info!(
|
||||
"table merge start table={} round={} batch={} memory_limit_bytes={} table_batch_limit={}",
|
||||
id.table_id(),
|
||||
round,
|
||||
index,
|
||||
plan.memory_limit,
|
||||
batch_limit()
|
||||
);
|
||||
let execution_start = Instant::now();
|
||||
let output = compact_regions(plan, context).await?;
|
||||
let execution = execution_start.elapsed();
|
||||
ensure!(
|
||||
output.stats.source_files == *WIDTH as u64
|
||||
&& output.stats.source_rows == output.stats.output_rows,
|
||||
Invalid {
|
||||
reason: "table scan accounting mismatch"
|
||||
}
|
||||
);
|
||||
common_telemetry::info!(
|
||||
"testbed shared compaction table={} round={} batch={} region_ready_wait_ms={} execution_ms={} stats={:?}",
|
||||
id.table_id(),
|
||||
round,
|
||||
index,
|
||||
ready_wait.as_millis(),
|
||||
execution.as_millis(),
|
||||
output.stats
|
||||
);
|
||||
create(store, &result_key, &output.files).await?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Persist the completion marker after the manifest edit, before the worker
|
||||
/// makes the new L1s selectable. This also leaves the old-layout replay intact.
|
||||
pub(crate) async fn record_publication(ctx: &CompactionContext, inputs: &[FileMeta]) -> Result<()> {
|
||||
let root = prefix(ctx.region_id, cursor(ctx.region_id));
|
||||
let store = ctx.access_layer.object_store();
|
||||
let ids: Vec<FileId> = read(store, &format!("{root}/sources"))
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
Invalid {
|
||||
reason: "missing shared publication roster",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let input_ids = inputs.iter().map(|f| &f.file_id).collect();
|
||||
let (index, _) = batch_window::batch_for_unit(&ids, *WIDTH, &input_ids).ok_or_else(|| {
|
||||
Invalid {
|
||||
reason: "missing shared publication batch",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let batch = batch_root(&root, ids.len(), index);
|
||||
create(
|
||||
store,
|
||||
&format!("{batch}/applied-{}", ctx.region_id.region_number()),
|
||||
&true,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod readiness_tests {
|
||||
use super::*;
|
||||
use crate::compaction::test_util::{new_file_handle, primary_key_metadata_for_test};
|
||||
use crate::sst::file_purger::NoopFilePurger;
|
||||
use crate::sst::version::SstVersion;
|
||||
|
||||
#[test]
|
||||
fn only_a_full_registered_shared_batch_needs_a_retry() {
|
||||
let mut ssts = SstVersion::new(primary_key_metadata_for_test());
|
||||
assert!(!has_pending_shared_batch(&ssts));
|
||||
let mut files = Vec::new();
|
||||
for _ in 0..*WIDTH {
|
||||
let mut file = new_file_handle(FileId::random(), 0, 100, 0)
|
||||
.meta_ref()
|
||||
.clone();
|
||||
file.region_id = RegionId::new(42, 0);
|
||||
file.partition_expr = None;
|
||||
file.sequence = std::num::NonZeroU64::new(1);
|
||||
files.push(file);
|
||||
}
|
||||
let last = files.pop().unwrap();
|
||||
ssts.add_files(Arc::new(NoopFilePurger), files.into_iter());
|
||||
assert!(!has_pending_shared_batch(&ssts));
|
||||
let mut l1 = last.clone();
|
||||
l1.file_id = FileId::random();
|
||||
l1.level = 1;
|
||||
let mut unregistered = last.clone();
|
||||
unregistered.file_id = FileId::random();
|
||||
unregistered.sequence = None;
|
||||
ssts.add_files(Arc::new(NoopFilePurger), [l1, unregistered].into_iter());
|
||||
assert!(!has_pending_shared_batch(&ssts));
|
||||
ssts.add_files(Arc::new(NoopFilePurger), [last].into_iter());
|
||||
assert!(has_pending_shared_batch(&ssts));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! One immutable source roster per round. Position determines the batch on every DN.
|
||||
use std::collections::HashSet;
|
||||
use std::hash::Hash;
|
||||
|
||||
pub(super) fn new_roster<T>(
|
||||
ordered: impl Iterator<Item = T>,
|
||||
width: usize,
|
||||
slots: usize,
|
||||
) -> Vec<T> {
|
||||
let mut files: Vec<_> = ordered.take(width.saturating_mul(slots)).collect();
|
||||
files.truncate(files.len() / width * width);
|
||||
files
|
||||
}
|
||||
|
||||
pub(super) fn valid_roster<T: Eq + Hash>(files: &[T], width: usize) -> bool {
|
||||
!files.is_empty()
|
||||
&& files.len().is_multiple_of(width)
|
||||
&& files.iter().collect::<HashSet<_>>().len() == files.len()
|
||||
}
|
||||
|
||||
pub(super) fn batch_for_unit<'a, T: Eq + Hash>(
|
||||
roster: &'a [T],
|
||||
width: usize,
|
||||
reserved: &HashSet<&T>,
|
||||
) -> Option<(usize, &'a [T])> {
|
||||
if reserved.len() != width || !valid_roster(roster, width) {
|
||||
return None;
|
||||
}
|
||||
roster
|
||||
.chunks_exact(width)
|
||||
.enumerate()
|
||||
.find(|(_, batch)| batch.iter().all(|id| reserved.contains(id)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn disjoint_groups_and_retry_keep_identical_ownership() {
|
||||
for slots in [1, 8, 16, 24, 48] {
|
||||
let roster = new_roster(0..2053, 32, slots);
|
||||
let mut completed = HashSet::new();
|
||||
for (index, ids) in roster.chunks_exact(32).enumerate().rev() {
|
||||
let unit = ids.iter().rev().collect();
|
||||
assert_eq!(batch_for_unit(&roster, 32, &unit), Some((index, ids)));
|
||||
assert!(ids.iter().all(|id| completed.insert(*id)));
|
||||
assert_eq!(batch_for_unit(&roster, 32, &unit), Some((index, ids)));
|
||||
}
|
||||
assert_eq!(completed.len(), slots * 32);
|
||||
let next = new_roster((0..2053).filter(|id| !completed.contains(id)), 32, slots);
|
||||
assert!(next.iter().all(|id| !completed.contains(id)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reject_partial_mixed_and_duplicate_reservations() {
|
||||
let roster = new_roster(0..9, 4, 16);
|
||||
assert_eq!(roster, (0..8).collect::<Vec<_>>());
|
||||
assert!(new_roster(0..3, 4, 16).is_empty());
|
||||
for invalid in [&roster[1..5], &roster[..3]] {
|
||||
assert!(batch_for_unit(&roster, 4, &invalid.iter().collect()).is_none());
|
||||
}
|
||||
let duplicate = [0, 1, 2, 3, 3, 5, 6, 7];
|
||||
assert!(batch_for_unit(&duplicate, 4, &roster[..4].iter().collect()).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! Experimental concurrency knobs; unset values retain automatic parallelism 1.
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::LazyLock;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
fn configured(name: &str, fallback: usize) -> usize {
|
||||
match std::env::var(name) {
|
||||
Ok(value) => value
|
||||
.parse::<NonZeroUsize>()
|
||||
.expect("compaction parallelism must be positive")
|
||||
.get(),
|
||||
Err(_) => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
static AUTOMATIC: LazyLock<usize> =
|
||||
LazyLock::new(|| configured("TESTBED_AUTO_COMPACTION_PARALLELISM", 1));
|
||||
static SHARED: LazyLock<usize> =
|
||||
LazyLock::new(|| configured("TESTBED_SHARED_SCAN_PARALLELISM", *AUTOMATIC));
|
||||
|
||||
pub(crate) fn automatic_parallelism() -> usize {
|
||||
*AUTOMATIC
|
||||
}
|
||||
|
||||
pub(crate) fn merge_parallelism(region: RegionId, shared: bool, ordinary: usize) -> usize {
|
||||
select(region.region_number(), shared, ordinary, *SHARED)
|
||||
}
|
||||
|
||||
fn select(_number: u32, shared: bool, ordinary: usize, scanner: usize) -> usize {
|
||||
// Every participant holds an execution slot from ready to publication.
|
||||
// Followers must admit the same number of batches as the scanning Region.
|
||||
if shared { scanner } else { ordinary }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn all_shared_participants_get_scanner_parallelism() {
|
||||
for number in 0..12 {
|
||||
assert_eq!(16, select(number, true, 8, 16));
|
||||
assert_eq!(24, select(number, true, 8, 24));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_l1_keeps_its_own_limit_on_every_region() {
|
||||
for number in 0..12 {
|
||||
assert_eq!(8, select(number, false, 8, 16));
|
||||
assert_eq!(8, select(number, false, 8, 24));
|
||||
assert_eq!(4, select(number, false, 4, 32));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_keep_previous_execution_width() {
|
||||
for shared in [false, true] {
|
||||
for number in 0..12 {
|
||||
assert_eq!(1, select(number, shared, 1, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! Lossless multi-region SST compaction using a captured table partition rule.
|
||||
//!
|
||||
//! The caller selects and pins the inputs (for example, from LEVEL_SHARED), and
|
||||
//! supplies their effective metadata in every target. This primitive deliberately
|
||||
//! does not select files, change persisted levels, publish manifests, or fold row
|
||||
//! versions. Output protection and eventual publication belong to its caller.
|
||||
|
||||
mod source;
|
||||
mod spill;
|
||||
mod streaming;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod worker;
|
||||
mod writer;
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
|
||||
use common_base::cancellation::{CancellableFuture, CancellationHandle};
|
||||
use partition::PartitionRuleRef;
|
||||
use snafu::{OptionExt, ensure};
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::access_layer::AccessLayerRef;
|
||||
use crate::cache::CacheManagerRef;
|
||||
use crate::config::MitoConfig;
|
||||
use crate::error::{InvalidMultiRegionCompactionSnafu, Result};
|
||||
use crate::region::options::RegionOptions;
|
||||
use crate::sst::file::{FileMeta, RegionFileId};
|
||||
use crate::sst::parquet::SstInfo;
|
||||
use crate::sst::parquet::writer::SstWriteGuard;
|
||||
|
||||
/// A target partition and the source versions currently visible in its sequence domain.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MultiRegionTarget {
|
||||
pub metadata: RegionMetadataRef,
|
||||
pub options: RegionOptions,
|
||||
/// All selected sources, with the sequence metadata used by this target's reader.
|
||||
pub inputs: HashMap<RegionFileId, FileMeta>,
|
||||
}
|
||||
|
||||
/// Immutable inputs, routing snapshot and execution limits for one compaction.
|
||||
pub struct MultiRegionCompactionPlan {
|
||||
/// Captured table routing rule; the executor never fetches mutable routing metadata.
|
||||
pub partition_rule: PartitionRuleRef,
|
||||
/// Unique sources in stable tie-breaking order. The caller retains their GC protection.
|
||||
pub sources: Vec<FileMeta>,
|
||||
/// Metadata and routing must belong to the same physical-table snapshot.
|
||||
pub targets: BTreeMap<RegionId, MultiRegionTarget>,
|
||||
/// Shared byte budget for queued/cached runs and working batches, not a process RSS cap.
|
||||
/// Reader page decoding and SST/index writer memory also depend on the supplied MitoConfig.
|
||||
pub memory_limit: usize,
|
||||
/// One or two simultaneous run operations or SST writers. The upper bound limits
|
||||
/// uncharged working batches; idle region workers hold no slot.
|
||||
pub max_active_workers: usize,
|
||||
pub spill_limit: u64,
|
||||
pub max_output_file_size: usize,
|
||||
pub window_seconds: i64,
|
||||
}
|
||||
|
||||
/// Shared storage services and attempt-owned output/spill resources.
|
||||
pub struct MultiRegionCompactionContext {
|
||||
pub access_layer: AccessLayerRef,
|
||||
pub cache: CacheManagerRef,
|
||||
pub config: Arc<MitoConfig>,
|
||||
pub spill_directory: PathBuf,
|
||||
pub protection: Arc<dyn SstWriteGuard>,
|
||||
pub cancellation: Arc<CancellationHandle>,
|
||||
}
|
||||
|
||||
/// Source I/O and lossless output accounting, excluding footer and query reads.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct MultiRegionCompactionStats {
|
||||
pub source_files: u64,
|
||||
pub source_rows: u64,
|
||||
/// Row-group page bytes fetched from object storage, excluding footer traffic and retries.
|
||||
pub source_store_page_bytes: u64,
|
||||
pub output_rows: u64,
|
||||
pub output_bytes: u64,
|
||||
pub spilled_bytes: u64,
|
||||
/// Peak bytes reserved by queued and cached Arrow batches, including batch metadata.
|
||||
pub peak_buffered_bytes: u64,
|
||||
/// Critical-path wall time for reading, merging and routing, including scheduling.
|
||||
pub merge_route_us: u64,
|
||||
/// Producer blocked by a full destination writer channel.
|
||||
pub write_wait_us: u64,
|
||||
/// Time from closing writer channels until all final writes finish.
|
||||
pub write_drain_us: u64,
|
||||
}
|
||||
|
||||
/// Complete per-target outputs, including explicit empty partitions.
|
||||
pub struct MultiRegionCompactionOutput {
|
||||
pub files: BTreeMap<RegionId, Vec<FileMeta>>,
|
||||
/// Complete footer/index statistics for target hook delivery; not fabricated from FileMeta.
|
||||
pub sst_infos: BTreeMap<RegionId, Vec<SstInfo>>,
|
||||
pub stats: MultiRegionCompactionStats,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SourceCounters {
|
||||
files: AtomicU64,
|
||||
rows: AtomicU64,
|
||||
store_page_bytes: AtomicU64,
|
||||
}
|
||||
|
||||
/// Computes a complete result or an error. Any already-written outputs remain
|
||||
/// owned by the attempt's durable protection; this function never purges sources.
|
||||
pub async fn compact_regions(
|
||||
plan: MultiRegionCompactionPlan,
|
||||
context: MultiRegionCompactionContext,
|
||||
) -> Result<MultiRegionCompactionOutput> {
|
||||
let metadata = validate_plan(&plan)?;
|
||||
if context.cancellation.is_cancelled() {
|
||||
return crate::error::CompactionCancelledSnafu.fail();
|
||||
}
|
||||
let cancellation = context.cancellation.clone();
|
||||
let execution = async move {
|
||||
let counters = Arc::new(SourceCounters::default());
|
||||
let source =
|
||||
source::SharedSource::build(&plan, &context, metadata, counters.clone()).await?;
|
||||
if plan.spill_limit == 0 {
|
||||
streaming::execute(plan, context, source, counters).await
|
||||
} else {
|
||||
worker::execute(plan, context, source, counters).await
|
||||
}
|
||||
};
|
||||
CancellableFuture::new(execution, cancellation)
|
||||
.await
|
||||
.map_err(|_| crate::error::CompactionCancelledSnafu.build())?
|
||||
}
|
||||
|
||||
fn validate_plan(plan: &MultiRegionCompactionPlan) -> Result<RegionMetadataRef> {
|
||||
ensure!(
|
||||
!plan.sources.is_empty()
|
||||
&& plan.memory_limit >= 1024 * 1024
|
||||
&& plan.max_active_workers > 0
|
||||
&& plan.max_active_workers <= 2
|
||||
&& plan.max_output_file_size > 0
|
||||
&& plan.window_seconds > 0,
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Invalid sources or execution budgets"
|
||||
}
|
||||
);
|
||||
let first = plan
|
||||
.targets
|
||||
.values()
|
||||
.next()
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "No routing targets",
|
||||
})?;
|
||||
let mut sources = HashSet::new();
|
||||
for file in &plan.sources {
|
||||
ensure!(
|
||||
file.region_id.table_id() == first.metadata.region_id.table_id()
|
||||
&& sources.insert(file.file_id()),
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Expected unique source files from one physical table"
|
||||
}
|
||||
);
|
||||
}
|
||||
for (id, target) in &plan.targets {
|
||||
ensure!(
|
||||
*id == target.metadata.region_id
|
||||
&& id.table_id() == first.metadata.region_id.table_id()
|
||||
&& target.metadata.column_metadatas == first.metadata.column_metadatas
|
||||
&& target.metadata.primary_key == first.metadata.primary_key
|
||||
&& target.metadata.primary_key_encoding == first.metadata.primary_key_encoding,
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Target schemas are not a consistent physical-table snapshot"
|
||||
}
|
||||
);
|
||||
ensure!(
|
||||
target.inputs.len() == sources.len()
|
||||
&& target
|
||||
.inputs
|
||||
.iter()
|
||||
.all(|(key, file)| *key == file.file_id() && sources.contains(key)),
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Every target must describe the effective metadata of every selected source"
|
||||
}
|
||||
);
|
||||
}
|
||||
Ok(first.metadata.clone())
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY;
|
||||
use common_time::{Timestamp, timestamp::TimeUnit};
|
||||
use datatypes::arrow::array::{Array, UInt64Array};
|
||||
use datatypes::arrow::compute::take_record_batch;
|
||||
use datatypes::arrow::datatypes::SchemaRef;
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use parquet::file::metadata::PageIndexPolicy;
|
||||
use partition::PartitionRuleRef;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::codec::PrimaryKeyEncoding;
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::access_layer::AccessLayerRef;
|
||||
use crate::cache::CacheStrategy;
|
||||
use crate::compaction::json2::collect_json2_rewrite_plans_from_parquet;
|
||||
use crate::compaction::multi_region::{
|
||||
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, SourceCounters,
|
||||
};
|
||||
use crate::error::{
|
||||
ComputeArrowSnafu, InvalidMultiRegionCompactionSnafu, MultiRegionCompactionResourceSnafu,
|
||||
NewRecordBatchSnafu, Result,
|
||||
};
|
||||
use crate::read::compat::FlatCompatBatch;
|
||||
use crate::read::flat_projection::FlatProjectionMapper;
|
||||
use crate::read::read_columns::ReadColumns;
|
||||
use crate::read::timestamp_array_to_i64_slice;
|
||||
use crate::sst::file::{FileHandle, FileMeta};
|
||||
use crate::sst::file_purger::NoopFilePurger;
|
||||
use crate::sst::parquet::flat_format::{sequence_column_index, time_index_column_index};
|
||||
use crate::sst::parquet::format::need_override_sequence;
|
||||
use crate::sst::parquet::reader::{MetadataCacheMetrics, ParquetReader, ReaderMetrics};
|
||||
use crate::sst::parquet::{Json2RewriteTargets, Json2TargetLayout};
|
||||
|
||||
struct SourceBatch {
|
||||
batch: RecordBatch,
|
||||
source: FileMeta,
|
||||
legacy_override: bool,
|
||||
}
|
||||
|
||||
/// Retains only the input batch and row destinations, never future output arrays.
|
||||
/// Row indices break destination ties so each fragment preserves source order.
|
||||
struct RoutedBatch {
|
||||
input: SourceBatch,
|
||||
rows: Vec<(RegionId, i64, usize)>,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
impl RoutedBatch {
|
||||
/// Materializes one fragment on the blocking pool, only when dispatch pulls it.
|
||||
fn next_fragment(&mut self, router: &SharedSource) -> Result<Option<SourceEvent>> {
|
||||
router.check_cancelled()?;
|
||||
let Some(&(region_id, window, _)) = self.rows.get(self.offset) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let remaining = &self.rows[self.offset..];
|
||||
let len = remaining
|
||||
.partition_point(|(id, time_window, _)| (*id, *time_window) == (region_id, window));
|
||||
let indices =
|
||||
UInt64Array::from_iter_values(remaining[..len].iter().map(|(_, _, row)| *row as u64));
|
||||
let batch = router.target_batch(&self.input, region_id, &indices)?;
|
||||
self.offset += len;
|
||||
Ok(Some(SourceEvent::Batch {
|
||||
region_id,
|
||||
window,
|
||||
batch,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// Source boundaries are ordered after all routed fragments of that source.
|
||||
pub(crate) enum SourceEvent {
|
||||
Batch {
|
||||
region_id: RegionId,
|
||||
window: i64,
|
||||
batch: RecordBatch,
|
||||
},
|
||||
SourceEnd,
|
||||
}
|
||||
|
||||
pub(crate) struct SharedSource {
|
||||
layer: AccessLayerRef,
|
||||
cache: CacheStrategy,
|
||||
sources: Vec<FileMeta>,
|
||||
targets: BTreeMap<RegionId, MultiRegionTarget>,
|
||||
metadata: RegionMetadataRef,
|
||||
mapper: FlatProjectionMapper,
|
||||
json2_targets: Json2RewriteTargets,
|
||||
schema: SchemaRef,
|
||||
partition_rule: PartitionRuleRef,
|
||||
window_seconds: i64,
|
||||
batch_memory_limit: usize,
|
||||
cancellation: Arc<common_base::cancellation::CancellationHandle>,
|
||||
counters: Arc<SourceCounters>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for SharedSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("SharedTableSource")
|
||||
.field("source_files", &self.sources.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl SharedSource {
|
||||
pub(crate) async fn build(
|
||||
plan: &MultiRegionCompactionPlan,
|
||||
context: &MultiRegionCompactionContext,
|
||||
metadata: RegionMetadataRef,
|
||||
counters: Arc<SourceCounters>,
|
||||
) -> Result<Arc<Self>> {
|
||||
let mut common = (*metadata).clone();
|
||||
common.set_partition_expr(None);
|
||||
let metadata = Arc::new(common);
|
||||
let cache = CacheStrategy::Compaction(context.cache.clone());
|
||||
let mut footers = Vec::with_capacity(plan.sources.len());
|
||||
for file in &plan.sources {
|
||||
if context.cancellation.is_cancelled() {
|
||||
return crate::error::CompactionCancelledSnafu.fail();
|
||||
}
|
||||
let handle = FileHandle::new(file.clone(), Arc::new(NoopFilePurger));
|
||||
let path = handle.file_path(
|
||||
context.access_layer.table_dir(),
|
||||
context.access_layer.path_type(),
|
||||
);
|
||||
let (sst, _) = context
|
||||
.access_layer
|
||||
.read_sst(handle)
|
||||
.cache(cache.clone())
|
||||
.read_parquet_metadata(
|
||||
&path,
|
||||
file.file_size,
|
||||
&mut MetadataCacheMetrics::default(),
|
||||
PageIndexPolicy::Skip,
|
||||
)
|
||||
.await?;
|
||||
footers.push(sst.parquet_metadata());
|
||||
}
|
||||
let layouts = collect_json2_rewrite_plans_from_parquet(&metadata, &footers)?;
|
||||
let mut json2 = BTreeMap::new();
|
||||
for (name, layout) in layouts {
|
||||
let column =
|
||||
metadata
|
||||
.column_by_name(&name)
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "JSON2 layout names an unknown column",
|
||||
})?;
|
||||
let extension_metadata = column
|
||||
.column_schema
|
||||
.metadata()
|
||||
.get(EXTENSION_TYPE_METADATA_KEY)
|
||||
.cloned()
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "JSON2 extension metadata missing",
|
||||
})?;
|
||||
json2.insert(
|
||||
column.column_id,
|
||||
Json2TargetLayout {
|
||||
extension_metadata,
|
||||
target_layout: layout.target_layout,
|
||||
},
|
||||
);
|
||||
}
|
||||
let json2_targets = Arc::new(json2);
|
||||
// Sparse SSTs retain every tag in __primary_key. Materialize only the
|
||||
// routing tags; expanding all physical-table tags makes merge/take
|
||||
// proportional to schema width, then the writer discards them again.
|
||||
let projection: Vec<_> = metadata
|
||||
.column_metadatas
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, column)| {
|
||||
metadata.primary_key_encoding != PrimaryKeyEncoding::Sparse
|
||||
|| column.semantic_type != api::v1::SemanticType::Tag
|
||||
|| plan
|
||||
.partition_rule
|
||||
.partition_columns()
|
||||
.contains(&column.column_schema.name)
|
||||
})
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
let read_columns = ReadColumns::new(
|
||||
projection
|
||||
.iter()
|
||||
.map(|index| metadata.column_metadatas[*index].column_id),
|
||||
);
|
||||
let mapper = FlatProjectionMapper::new_with_json2_rewrite_targets(
|
||||
&metadata,
|
||||
projection,
|
||||
read_columns,
|
||||
&json2_targets,
|
||||
)?;
|
||||
let schema = mapper.input_arrow_schema(false);
|
||||
Ok(Arc::new(Self {
|
||||
layer: context.access_layer.clone(),
|
||||
cache,
|
||||
sources: plan.sources.clone(),
|
||||
targets: plan.targets.clone(),
|
||||
metadata,
|
||||
mapper,
|
||||
json2_targets,
|
||||
schema,
|
||||
partition_rule: plan.partition_rule.clone(),
|
||||
window_seconds: plan.window_seconds,
|
||||
batch_memory_limit: plan.memory_limit / 8,
|
||||
cancellation: context.cancellation.clone(),
|
||||
counters,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn schema(&self) -> SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
|
||||
fn raw_batches(
|
||||
self: Arc<Self>,
|
||||
file: FileMeta,
|
||||
) -> futures::stream::BoxStream<'static, Result<SourceBatch>> {
|
||||
Box::pin(async_stream::try_stream! {
|
||||
self.check_cancelled()?;
|
||||
// Preserve physical source sequences. Target-domain overrides are applied only after routing.
|
||||
let mut raw_meta = file.clone(); raw_meta.sequence = None; raw_meta.preserve_row_sequence = true;
|
||||
let handle = FileHandle::new(raw_meta, Arc::new(NoopFilePurger));
|
||||
let builder = self.layer.read_sst(handle).cache(self.cache.clone()).batch_size(1024)
|
||||
.projection(Some(self.mapper.read_columns().clone()))
|
||||
.expected_metadata(Some(self.metadata.clone())).json2_rewrite_targets(self.json2_targets.clone())
|
||||
.compaction(false).page_index_policy(PageIndexPolicy::Skip);
|
||||
let Some((context, selection)) = builder.build_reader_input(&mut ReaderMetrics::default()).await? else {
|
||||
self.counters.files.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
};
|
||||
let compat = FlatCompatBatch::try_new(&self.mapper, context.read_format(), false)?;
|
||||
let mut reader = ParquetReader::new(Arc::new(context), selection).await?;
|
||||
let expected_rows = u64::try_from(reader.parquet_metadata().file_metadata().num_rows())
|
||||
.map_err(|_| InvalidMultiRegionCompactionSnafu { reason: "Negative source footer row count" }.build())?;
|
||||
let mut read_rows = 0_u64;
|
||||
let legacy_override = need_override_sequence(&reader.parquet_metadata());
|
||||
while let Some(batch) = reader.next_record_batch().await? {
|
||||
self.check_cancelled()?;
|
||||
let batch = if let Some(compat) = &compat { compat.compat(batch)? } else { batch };
|
||||
if batch.get_array_memory_size() > self.batch_memory_limit {
|
||||
Err(MultiRegionCompactionResourceSnafu { reason: "Decoded source batch exceeds the shared reader budget" }.build())?;
|
||||
}
|
||||
self.counters.rows.fetch_add(batch.num_rows() as u64, Ordering::Relaxed);
|
||||
read_rows += batch.num_rows() as u64;
|
||||
yield SourceBatch { batch, source: file.clone(), legacy_override };
|
||||
}
|
||||
if read_rows != expected_rows {
|
||||
Err(InvalidMultiRegionCompactionSnafu { reason: "Shared source scan did not cover its complete footer row count" }.build())?;
|
||||
}
|
||||
let page_bytes = reader.fetched_store_page_bytes()?;
|
||||
self.counters.store_page_bytes.fetch_add(page_bytes, Ordering::Relaxed);
|
||||
self.counters.files.fetch_add(1, Ordering::Relaxed);
|
||||
})
|
||||
}
|
||||
pub(crate) fn batches(
|
||||
self: Arc<Self>,
|
||||
) -> futures::stream::BoxStream<'static, Result<SourceEvent>> {
|
||||
Box::pin(async_stream::try_stream! {
|
||||
for file in &self.sources {
|
||||
let mut input = self.clone().raw_batches(file.clone());
|
||||
while let Some(batch) = futures::TryStreamExt::try_next(&mut input).await? {
|
||||
let router=self.clone();
|
||||
let mut routed=common_runtime::spawn_blocking_compact(move || router.route(batch)).await.context(crate::error::JoinSnafu)??;
|
||||
loop {
|
||||
let router = self.clone();
|
||||
let (event, remaining) = common_runtime::spawn_blocking_compact(move || {
|
||||
let event = routed.next_fragment(&router)?;
|
||||
Ok::<_, crate::error::Error>((event, routed))
|
||||
}).await.context(crate::error::JoinSnafu)??;
|
||||
routed = remaining;
|
||||
let Some(event) = event else { break; };
|
||||
// Dispatch reserves/spills and sends this fragment before
|
||||
// polling again. No work slot is held across the yield.
|
||||
yield event;
|
||||
}
|
||||
}
|
||||
yield SourceEvent::SourceEnd;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A sorted source with target-domain sequences applied before the shared merge.
|
||||
/// This mode only accepts key-based partitioning: equal PKs in one source have
|
||||
/// the same target and substitution therefore preserves source ordering.
|
||||
pub(crate) fn ordered_input(
|
||||
self: Arc<Self>,
|
||||
file: FileMeta,
|
||||
) -> crate::read::BoxedRecordBatchStream {
|
||||
Box::pin(async_stream::try_stream! {
|
||||
let mut raw=self.clone().raw_batches(file);
|
||||
while let Some(input)=futures::TryStreamExt::try_next(&mut raw).await? {
|
||||
let idx=sequence_column_index(input.batch.num_columns());
|
||||
let sequences=input.batch.column(idx).as_any().downcast_ref::<UInt64Array>().context(InvalidMultiRegionCompactionSnafu{reason:"Expected non-null UInt64 sequence column"})?;
|
||||
let mut replacements=Vec::with_capacity(input.batch.num_rows());
|
||||
for (row,owner) in self.row_owners(&input.batch)?.into_iter().enumerate() {
|
||||
let f=&self.targets[&owner].inputs[&input.source.file_id()];
|
||||
let value=if owner!=f.region_id || (!f.preserve_row_sequence && input.legacy_override) { f.sequence } else { None };
|
||||
replacements.push(value.map_or_else(||sequences.value(row),|v|v.get()));
|
||||
}
|
||||
let mut cols=input.batch.columns().to_vec();
|
||||
cols[idx]=Arc::new(UInt64Array::from(replacements));
|
||||
yield RecordBatch::try_new(self.schema.clone(),cols).context(NewRecordBatchSnafu)?;
|
||||
}
|
||||
})
|
||||
}
|
||||
fn route(&self, input: SourceBatch) -> Result<RoutedBatch> {
|
||||
self.check_cancelled()?;
|
||||
let owners = self.row_owners(&input.batch)?;
|
||||
let windows = self.time_windows(&input.batch)?;
|
||||
let mut rows: Vec<_> = owners
|
||||
.into_iter()
|
||||
.zip(windows)
|
||||
.enumerate()
|
||||
.map(|(row, (region_id, window))| (region_id, window, row))
|
||||
.collect();
|
||||
rows.sort_unstable();
|
||||
Ok(RoutedBatch {
|
||||
input,
|
||||
rows,
|
||||
offset: 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn target_batch(
|
||||
&self,
|
||||
source: &SourceBatch,
|
||||
region_id: RegionId,
|
||||
indices: &UInt64Array,
|
||||
) -> Result<RecordBatch> {
|
||||
let target = self
|
||||
.targets
|
||||
.get(®ion_id)
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Routed fragment names an unknown region",
|
||||
})?;
|
||||
let input = target.inputs.get(&source.source.file_id()).context(
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Target has no effective metadata for the selected source",
|
||||
},
|
||||
)?;
|
||||
let filtered = take_record_batch(&source.batch, indices).context(ComputeArrowSnafu)?;
|
||||
let override_sequence = if input.region_id != region_id
|
||||
|| (!input.preserve_row_sequence && source.legacy_override)
|
||||
{
|
||||
input.sequence
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut columns = filtered.columns().to_vec();
|
||||
if let Some(sequence) = override_sequence {
|
||||
columns[sequence_column_index(filtered.num_columns())] =
|
||||
Arc::new(UInt64Array::from_value(sequence.get(), filtered.num_rows()));
|
||||
}
|
||||
RecordBatch::try_new(self.schema.clone(), columns).context(NewRecordBatchSnafu)
|
||||
}
|
||||
|
||||
pub(super) fn time_windows(&self, filtered: &RecordBatch) -> Result<Vec<i64>> {
|
||||
let time_index = filtered.column(time_index_column_index(filtered.num_columns()));
|
||||
ensure!(
|
||||
time_index.null_count() == 0,
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Null timestamp in shared source"
|
||||
}
|
||||
);
|
||||
let unit = self
|
||||
.metadata
|
||||
.time_index_column()
|
||||
.column_schema
|
||||
.data_type
|
||||
.as_timestamp()
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Time index is not a timestamp",
|
||||
})?
|
||||
.unit();
|
||||
timestamp_array_to_i64_slice(time_index)
|
||||
.iter()
|
||||
.map(|value| {
|
||||
Timestamp::new(*value, unit)
|
||||
.convert_to(TimeUnit::Second)
|
||||
.map(|value| value.value().div_euclid(self.window_seconds))
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Timestamp window overflow",
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
}
|
||||
|
||||
pub(super) fn row_owners(&self, batch: &RecordBatch) -> Result<Vec<RegionId>> {
|
||||
let rows = batch.num_rows();
|
||||
let masks = self
|
||||
.partition_rule
|
||||
.split_record_batch(batch)
|
||||
.context(crate::error::RouteMultiRegionSnafu)?;
|
||||
let mut owners = vec![None; rows];
|
||||
for (number, mask) in masks {
|
||||
ensure!(
|
||||
mask.array().len() == rows,
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Partition rule returned a mask with the wrong row count"
|
||||
}
|
||||
);
|
||||
let id = RegionId::new(self.metadata.region_id.table_id(), number);
|
||||
for (row, selected) in mask.array().iter().enumerate() {
|
||||
if selected == Some(true) {
|
||||
ensure!(
|
||||
owners[row].replace(id).is_none(),
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Source row matches multiple target partitions"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.resolve_unassigned(batch, &mut owners)?;
|
||||
owners
|
||||
.into_iter()
|
||||
.map(|owner| {
|
||||
owner.filter(|id| self.targets.contains_key(id)).context(
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Partition rule selected a region outside the captured targets",
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resolve_unassigned(
|
||||
&self,
|
||||
batch: &RecordBatch,
|
||||
owners: &mut [Option<RegionId>],
|
||||
) -> Result<()> {
|
||||
if owners.iter().all(Option::is_some) {
|
||||
return Ok(());
|
||||
}
|
||||
// Nullable vector predicates can leave unknown masks. Resolve only those
|
||||
// rows through the same rule's scalar API, including its default region.
|
||||
let columns = self
|
||||
.partition_rule
|
||||
.partition_columns()
|
||||
.iter()
|
||||
.map(|name| {
|
||||
let array =
|
||||
batch
|
||||
.column_by_name(name)
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Partition column missing from the source batch",
|
||||
})?;
|
||||
datatypes::vectors::Helper::try_into_vector(array.clone())
|
||||
.context(crate::error::ConvertVectorSnafu)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
for (row, owner) in owners
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.filter(|(_, owner)| owner.is_none())
|
||||
{
|
||||
let values = columns
|
||||
.iter()
|
||||
.map(|column| column.get(row))
|
||||
.collect::<Vec<_>>();
|
||||
let number = self
|
||||
.partition_rule
|
||||
.find_region(&values)
|
||||
.context(crate::error::RouteMultiRegionSnafu)?;
|
||||
*owner = Some(RegionId::new(self.metadata.region_id.table_id(), number));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_cancelled(&self) -> Result<()> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
return crate::error::CompactionCancelledSnafu.fail();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! Attempt-local ordered runs. All encoding, iteration and file I/O methods are
|
||||
//! synchronous and must be called on the blocking compaction pool. Drop only
|
||||
//! schedules cleanup, so cancelling an async owner never performs file I/O inline.
|
||||
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Cursor, Read, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use common_base::cancellation::CancellationHandle;
|
||||
use common_telemetry::warn;
|
||||
use datatypes::arrow::array::ArrayData;
|
||||
use datatypes::arrow::ipc::reader::StreamReader;
|
||||
use datatypes::arrow::ipc::writer::StreamWriter;
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::compaction::multi_region::{MultiRegionCompactionContext, MultiRegionCompactionPlan};
|
||||
use crate::error::{
|
||||
ComputeArrowSnafu, MultiRegionCompactionResourceSnafu, MultiRegionCompactionSpillSnafu, Result,
|
||||
};
|
||||
use crate::memtable::BoxedRecordBatchIterator;
|
||||
|
||||
pub(crate) struct RunStore {
|
||||
memory: Arc<Budget>,
|
||||
metadata: Arc<Budget>,
|
||||
disk: Arc<Budget>,
|
||||
directory: Arc<SpillDirectory>,
|
||||
cancellation: Arc<CancellationHandle>,
|
||||
stop: CancellationToken,
|
||||
batch_limit: usize,
|
||||
}
|
||||
|
||||
impl RunStore {
|
||||
pub(crate) async fn new(
|
||||
plan: &MultiRegionCompactionPlan,
|
||||
context: &MultiRegionCompactionContext,
|
||||
stop: CancellationToken,
|
||||
) -> Result<Arc<Self>> {
|
||||
let path = context
|
||||
.spill_directory
|
||||
.join(uuid::Uuid::new_v4().to_string());
|
||||
// Install the guard before awaiting creation: cancellation must not leak a directory.
|
||||
let directory = Arc::new(SpillDirectory(path));
|
||||
let creating = directory.clone();
|
||||
common_runtime::spawn_blocking_compact(move || {
|
||||
std::fs::create_dir_all(&creating.0).context(MultiRegionCompactionSpillSnafu)
|
||||
})
|
||||
.await
|
||||
.context(crate::error::JoinSnafu)??;
|
||||
Ok(Arc::new(Self {
|
||||
memory: Budget::new(
|
||||
(plan.memory_limit / 2) as u64,
|
||||
"Routed batch cache exhausted",
|
||||
),
|
||||
metadata: Budget::new(
|
||||
(plan.memory_limit / 8) as u64,
|
||||
"Too many regions or time windows",
|
||||
),
|
||||
disk: Budget::new(
|
||||
plan.spill_limit,
|
||||
"Multi-region temporary disk quota exhausted",
|
||||
),
|
||||
directory,
|
||||
cancellation: context.cancellation.clone(),
|
||||
stop,
|
||||
batch_limit: plan.memory_limit / 8,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_metadata(&self, bytes: usize) -> Result<Reservation> {
|
||||
self.metadata
|
||||
.reserve(bytes as u64)
|
||||
.context(MultiRegionCompactionResourceSnafu {
|
||||
reason: self.metadata.reason,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn check_cancelled(&self) -> Result<()> {
|
||||
ensure!(
|
||||
!self.stop.is_cancelled() && !self.cancellation.is_cancelled(),
|
||||
crate::error::CompactionCancelledSnafu
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn spilled_bytes(&self) -> u64 {
|
||||
self.disk.total.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(crate) fn peak_buffered_bytes(&self) -> u64 {
|
||||
self.memory.peak.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
struct Budget {
|
||||
limit: u64,
|
||||
used: AtomicU64,
|
||||
peak: AtomicU64,
|
||||
total: AtomicU64,
|
||||
reason: &'static str,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
fn new(limit: u64, reason: &'static str) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
limit,
|
||||
used: AtomicU64::new(0),
|
||||
peak: AtomicU64::new(0),
|
||||
total: AtomicU64::new(0),
|
||||
reason,
|
||||
})
|
||||
}
|
||||
|
||||
fn reserve(self: &Arc<Self>, bytes: u64) -> Option<Reservation> {
|
||||
let previous = self
|
||||
.used
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |used| {
|
||||
used.checked_add(bytes).filter(|next| *next <= self.limit)
|
||||
})
|
||||
.ok()?;
|
||||
self.peak.fetch_max(previous + bytes, Ordering::Relaxed);
|
||||
self.total.fetch_add(bytes, Ordering::Relaxed);
|
||||
Some(Reservation {
|
||||
budget: self.clone(),
|
||||
bytes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Reservation {
|
||||
budget: Arc<Budget>,
|
||||
bytes: u64,
|
||||
}
|
||||
|
||||
impl Reservation {
|
||||
fn grow(&mut self, bytes: u64) -> Result<()> {
|
||||
let mut extra = self
|
||||
.budget
|
||||
.reserve(bytes)
|
||||
.context(MultiRegionCompactionResourceSnafu {
|
||||
reason: self.budget.reason,
|
||||
})?;
|
||||
self.bytes += extra.bytes;
|
||||
extra.bytes = 0;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Reservation {
|
||||
fn drop(&mut self) {
|
||||
self.budget.used.fetch_sub(self.bytes, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
struct SpillDirectory(PathBuf);
|
||||
|
||||
impl Drop for SpillDirectory {
|
||||
fn drop(&mut self) {
|
||||
let path = self.0.clone();
|
||||
common_runtime::spawn_blocking_compact(move || {
|
||||
if let Err(error) = std::fs::remove_dir_all(&path)
|
||||
&& error.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
warn!(error; "Failed to remove multi-region spill directory: {}", path.display());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct BufferedBatch {
|
||||
batch: RecordBatch,
|
||||
_reservation: Reservation,
|
||||
}
|
||||
|
||||
/// A single sorted stream, not an arbitrary concatenation of different sources.
|
||||
pub(crate) enum Run {
|
||||
Memory(VecDeque<BufferedBatch>),
|
||||
Disk(DiskRun),
|
||||
}
|
||||
|
||||
impl Default for Run {
|
||||
fn default() -> Self {
|
||||
Self::Memory(VecDeque::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl Run {
|
||||
pub(crate) fn from_batch(batch: RecordBatch, store: &RunStore) -> Result<Self> {
|
||||
let mut run = Self::default();
|
||||
run.push(batch, store)?;
|
||||
Ok(run)
|
||||
}
|
||||
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
matches!(self, Self::Memory(batches) if batches.is_empty())
|
||||
}
|
||||
|
||||
pub(crate) fn push(&mut self, batch: RecordBatch, store: &RunStore) -> Result<()> {
|
||||
store.check_cancelled()?;
|
||||
if batch.num_rows() == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let bytes = batch_memory_size(&batch);
|
||||
ensure!(
|
||||
bytes <= store.batch_limit,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: format!(
|
||||
"Run batch of {} rows uses {bytes} bytes, exceeding working-batch budget {}",
|
||||
batch.num_rows(),
|
||||
store.batch_limit
|
||||
),
|
||||
}
|
||||
);
|
||||
if let Self::Memory(batches) = self {
|
||||
// Account for both Arrow storage and per-batch queue/lease metadata.
|
||||
if let Some(reservation) = store.memory.reserve((bytes + 128) as u64) {
|
||||
batches.push_back(BufferedBatch {
|
||||
batch,
|
||||
_reservation: reservation,
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
let mut disk = DiskRun::new(store);
|
||||
while let Some(buffered) = batches.pop_front() {
|
||||
disk.append(&buffered.batch, store)?;
|
||||
}
|
||||
*self = Self::Disk(disk);
|
||||
}
|
||||
if let Self::Disk(disk) = self {
|
||||
disk.append(&batch, store)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Appends fragments from the same source, in source order.
|
||||
pub(crate) fn append(&mut self, other: Self, store: &RunStore) -> Result<()> {
|
||||
if self.is_empty() {
|
||||
*self = other;
|
||||
return Ok(());
|
||||
}
|
||||
for batch in other.into_iter()? {
|
||||
self.push(batch?, store)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn into_iter(self) -> Result<BoxedRecordBatchIterator> {
|
||||
match self {
|
||||
Self::Memory(batches) => Ok(Box::new(
|
||||
batches.into_iter().map(|buffered| Ok(buffered.batch)),
|
||||
)),
|
||||
Self::Disk(run) => {
|
||||
let file = File::open(&run.path).context(MultiRegionCompactionSpillSnafu)?;
|
||||
let remaining = run.reservation.as_ref().map_or(0, |lease| lease.bytes);
|
||||
Ok(Box::new(DiskIterator {
|
||||
file: Some(file),
|
||||
run,
|
||||
remaining,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// IPC readers can share one allocation across several column buffers. Arrow's
|
||||
/// per-array estimate charges that entire allocation for every slice, rejecting
|
||||
/// valid batches after spilling. Deduplicate allocations within this batch, but
|
||||
/// retain Arrow's metadata cost and conservatively charge shared batches separately.
|
||||
fn batch_memory_size(batch: &RecordBatch) -> usize {
|
||||
let mut seen = HashSet::new();
|
||||
let duplicated: usize = batch
|
||||
.columns()
|
||||
.iter()
|
||||
.map(|array| duplicated_buffer_bytes(&array.to_data(), &mut seen))
|
||||
.sum();
|
||||
batch.get_array_memory_size() - duplicated
|
||||
}
|
||||
|
||||
fn duplicated_buffer_bytes(data: &ArrayData, seen: &mut HashSet<NonNull<u8>>) -> usize {
|
||||
let duplicated: usize = data
|
||||
.buffers()
|
||||
.iter()
|
||||
.chain(data.nulls().map(|nulls| nulls.buffer()))
|
||||
.filter(|buffer| !seen.insert(buffer.data_ptr()))
|
||||
.map(|buffer| buffer.capacity())
|
||||
.sum();
|
||||
duplicated
|
||||
+ data
|
||||
.child_data()
|
||||
.iter()
|
||||
.map(|child| duplicated_buffer_bytes(child, seen))
|
||||
.sum::<usize>()
|
||||
}
|
||||
|
||||
pub(crate) struct DiskRun {
|
||||
path: PathBuf,
|
||||
reservation: Option<Reservation>,
|
||||
max_frame_size: usize,
|
||||
directory: Arc<SpillDirectory>,
|
||||
}
|
||||
|
||||
impl DiskRun {
|
||||
fn new(store: &RunStore) -> Self {
|
||||
Self {
|
||||
path: store.directory.0.join(uuid::Uuid::new_v4().to_string()),
|
||||
reservation: Some(Reservation {
|
||||
budget: store.disk.clone(),
|
||||
bytes: 0,
|
||||
}),
|
||||
max_frame_size: store.batch_limit * 2,
|
||||
directory: store.directory.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames standalone Arrow IPC streams so appending doesn't retain one open
|
||||
/// descriptor or one batch-offset entry for every source/window combination.
|
||||
fn append(&mut self, batch: &RecordBatch, store: &RunStore) -> Result<()> {
|
||||
store.check_cancelled()?;
|
||||
let mut bytes = Vec::new();
|
||||
{
|
||||
let mut writer = StreamWriter::try_new(&mut bytes, batch.schema().as_ref())
|
||||
.context(ComputeArrowSnafu)?;
|
||||
writer.write(batch).context(ComputeArrowSnafu)?;
|
||||
writer.finish().context(ComputeArrowSnafu)?;
|
||||
}
|
||||
ensure!(
|
||||
bytes.len() <= store.batch_limit * 2,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: "Encoded run batch exceeds the compaction working-batch budget",
|
||||
}
|
||||
);
|
||||
self.reservation
|
||||
.as_mut()
|
||||
.context(MultiRegionCompactionResourceSnafu {
|
||||
reason: "Cannot append to a released spill run",
|
||||
})?
|
||||
.grow(bytes.len() as u64 + 8)?;
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&self.path)
|
||||
.context(MultiRegionCompactionSpillSnafu)?;
|
||||
file.write_all(&(bytes.len() as u64).to_le_bytes())
|
||||
.context(MultiRegionCompactionSpillSnafu)?;
|
||||
file.write_all(&bytes)
|
||||
.context(MultiRegionCompactionSpillSnafu)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove(&mut self) -> Result<()> {
|
||||
std::fs::remove_file(&self.path).context(MultiRegionCompactionSpillSnafu)?;
|
||||
self.reservation.take();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DiskRun {
|
||||
fn drop(&mut self) {
|
||||
let Some(reservation) = self.reservation.take() else {
|
||||
return;
|
||||
};
|
||||
let path = self.path.clone();
|
||||
let directory = self.directory.clone();
|
||||
// Keep disk quota and the directory alive until deletion has completed.
|
||||
common_runtime::spawn_blocking_compact(move || {
|
||||
if let Err(error) = std::fs::remove_file(&path)
|
||||
&& error.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
warn!(error; "Failed to remove multi-region spill run: {}", path.display());
|
||||
}
|
||||
drop(reservation);
|
||||
drop(directory);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct DiskIterator {
|
||||
file: Option<File>,
|
||||
run: DiskRun,
|
||||
remaining: u64,
|
||||
}
|
||||
|
||||
impl DiskIterator {
|
||||
fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
|
||||
if self.remaining == 0 {
|
||||
// Close before unlinking, including on Windows.
|
||||
if self.file.take().is_some() {
|
||||
self.run.remove()?;
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
let file = self
|
||||
.file
|
||||
.as_mut()
|
||||
.context(MultiRegionCompactionResourceSnafu {
|
||||
reason: "Spill run closed before EOF",
|
||||
})?;
|
||||
let mut length = [0; 8];
|
||||
file.read_exact(&mut length)
|
||||
.context(MultiRegionCompactionSpillSnafu)?;
|
||||
let length = u64::from_le_bytes(length);
|
||||
ensure!(
|
||||
self.remaining >= 8
|
||||
&& length <= self.remaining - 8
|
||||
&& length <= self.run.max_frame_size as u64,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: "Invalid spill frame length",
|
||||
}
|
||||
);
|
||||
let length = usize::try_from(length).map_err(|_| {
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: "Spill frame length overflow",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let mut bytes = vec![0; length];
|
||||
file.read_exact(&mut bytes)
|
||||
.context(MultiRegionCompactionSpillSnafu)?;
|
||||
self.remaining -= length as u64 + 8;
|
||||
let mut reader =
|
||||
StreamReader::try_new(Cursor::new(bytes), None).context(ComputeArrowSnafu)?;
|
||||
let batch = reader
|
||||
.next()
|
||||
.transpose()
|
||||
.context(ComputeArrowSnafu)?
|
||||
.context(MultiRegionCompactionResourceSnafu {
|
||||
reason: "Empty spill frame",
|
||||
})?;
|
||||
Ok(Some(batch))
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for DiskIterator {
|
||||
type Item = Result<RecordBatch>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.next_batch().transpose()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! Experimental key-partitioned streaming merge. Each input has one forward-only
|
||||
//! reader. Each nonempty destination has one bounded channel to its final SST writer.
|
||||
use super::{
|
||||
MultiRegionCompactionContext, MultiRegionCompactionOutput, MultiRegionCompactionPlan,
|
||||
MultiRegionCompactionStats, SourceCounters, source::SharedSource, writer,
|
||||
};
|
||||
use crate::error::{self, InvalidMultiRegionCompactionSnafu as Invalid, Result};
|
||||
use crate::read::{FlatSource, flat_merge::FlatMergeReader};
|
||||
use datatypes::arrow::array::UInt64Array;
|
||||
use datatypes::arrow::compute::take_record_batch;
|
||||
use snafu::{ResultExt, ensure};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, atomic::Ordering};
|
||||
use store_api::storage::RegionId;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
mod writer_block;
|
||||
use writer_block::{Packet, Sink};
|
||||
|
||||
pub(super) async fn execute(
|
||||
plan: MultiRegionCompactionPlan,
|
||||
context: MultiRegionCompactionContext,
|
||||
source: Arc<SharedSource>,
|
||||
counters: Arc<SourceCounters>,
|
||||
) -> Result<MultiRegionCompactionOutput> {
|
||||
let metadata = &plan.targets.first_key_value().unwrap().1.metadata;
|
||||
ensure!(
|
||||
plan.partition_rule
|
||||
.partition_columns()
|
||||
.iter()
|
||||
.all(|name| metadata
|
||||
.column_by_name(name)
|
||||
.is_some_and(|col| col.semantic_type == api::v1::SemanticType::Tag)),
|
||||
Invalid {
|
||||
reason: "Streaming compaction requires key-based partitioning"
|
||||
}
|
||||
);
|
||||
let target_rows = std::env::var("TESTBED_SHARED_WRITER_BLOCK_ROWS")
|
||||
.map_or(Ok(1usize), |s| s.parse())
|
||||
.map_err(|_| {
|
||||
Invalid {
|
||||
reason: "invalid writer block row target",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let limit = plan.targets.len() * 2;
|
||||
let batch_limit = plan.memory_limit / (plan.sources.len() + limit * 3 + 2);
|
||||
let mut output = MultiRegionCompactionOutput {
|
||||
files: plan.targets.keys().map(|id| (*id, vec![])).collect(),
|
||||
sst_infos: plan.targets.keys().map(|id| (*id, vec![])).collect(),
|
||||
stats: MultiRegionCompactionStats::default(),
|
||||
};
|
||||
let start = std::time::Instant::now();
|
||||
let mut writer_wait = std::time::Duration::ZERO;
|
||||
let mut merge = FlatMergeReader::new_stable(
|
||||
source.schema(),
|
||||
plan.sources
|
||||
.iter()
|
||||
.map(|f| source.clone().ordered_input(f.clone()))
|
||||
.collect(),
|
||||
1024,
|
||||
)
|
||||
.await?;
|
||||
let plan = Arc::new(plan);
|
||||
let context = Arc::new(context);
|
||||
let mut sinks = BTreeMap::new();
|
||||
let mut workers = JoinSet::new();
|
||||
while let Some(batch) = merge.next_batch().await? {
|
||||
if context.cancellation.is_cancelled() {
|
||||
return error::CompactionCancelledSnafu.fail();
|
||||
}
|
||||
ensure!(
|
||||
batch.get_array_memory_size() <= batch_limit,
|
||||
Invalid {
|
||||
reason: "Streaming merge batch exceeds resident slot budget"
|
||||
}
|
||||
);
|
||||
let mut groups: BTreeMap<(RegionId, i64), Vec<u64>> = BTreeMap::new();
|
||||
for (row, key) in source
|
||||
.row_owners(&batch)?
|
||||
.into_iter()
|
||||
.zip(source.time_windows(&batch)?)
|
||||
.enumerate()
|
||||
{
|
||||
groups.entry(key).or_default().push(row as u64);
|
||||
}
|
||||
for (key, rows) in groups {
|
||||
if !sinks.contains_key(&key) {
|
||||
ensure!(
|
||||
sinks.len() < limit,
|
||||
Invalid {
|
||||
reason: "Too many active region/window streams"
|
||||
}
|
||||
);
|
||||
let (tx, mut rx) = mpsc::channel::<Packet>(1);
|
||||
let schema = source.schema();
|
||||
let plan = plan.clone();
|
||||
let context = context.clone();
|
||||
workers.spawn(async move {
|
||||
let batches=async_stream::try_stream! { while let Some(packet)=rx.recv().await { for batch in packet { yield batch; } } };
|
||||
let source=FlatSource::new_stream(schema,Box::pin(batches));
|
||||
let (files,infos)=writer::write_target_group(&plan.targets[&key.0],source,&plan,&context).await?;
|
||||
Ok::<_,error::Error>((key.0,files,infos))
|
||||
});
|
||||
sinks.insert(key, Sink::new(tx, target_rows, batch_limit));
|
||||
}
|
||||
let fragment = take_record_batch(&batch, &UInt64Array::from(rows))
|
||||
.context(error::ComputeArrowSnafu)?;
|
||||
if !sinks
|
||||
.get_mut(&key)
|
||||
.unwrap()
|
||||
.push(fragment, &mut writer_wait)
|
||||
.await
|
||||
{
|
||||
if let Some(done) = workers.join_next().await {
|
||||
done.context(error::JoinSnafu)??;
|
||||
}
|
||||
return Invalid {
|
||||
reason: "Output writer stopped before end of input",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
}
|
||||
}
|
||||
for sink in sinks.values_mut() {
|
||||
if !sink.flush(&mut writer_wait).await {
|
||||
if let Some(done) = workers.join_next().await {
|
||||
done.context(error::JoinSnafu)??;
|
||||
}
|
||||
return Invalid {
|
||||
reason: "Output writer stopped before end of input",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
}
|
||||
let drain = std::time::Instant::now();
|
||||
drop(sinks);
|
||||
while let Some(done) = workers.join_next().await {
|
||||
let (id, files, infos) = done.context(error::JoinSnafu)??;
|
||||
output.stats.output_rows += files.iter().map(|f| f.num_rows).sum::<u64>();
|
||||
output.stats.output_bytes += files
|
||||
.iter()
|
||||
.map(|f| f.file_size + f.index_file_size)
|
||||
.sum::<u64>();
|
||||
output.files.get_mut(&id).unwrap().extend(files);
|
||||
output.sst_infos.get_mut(&id).unwrap().extend(infos);
|
||||
}
|
||||
let writer_drain = drain.elapsed();
|
||||
output.stats.write_wait_us = writer_wait.as_micros() as u64;
|
||||
output.stats.write_drain_us = writer_drain.as_micros() as u64;
|
||||
output.stats.merge_route_us = (start.elapsed() - writer_drain - writer_wait).as_micros() as u64;
|
||||
output.stats.source_files = counters.files.load(Ordering::Relaxed);
|
||||
output.stats.source_rows = counters.rows.load(Ordering::Relaxed);
|
||||
output.stats.source_store_page_bytes = counters.store_page_bytes.load(Ordering::Relaxed);
|
||||
ensure!(
|
||||
output.stats.source_rows == output.stats.output_rows
|
||||
&& output.stats.source_files == plan.sources.len() as u64,
|
||||
Invalid {
|
||||
reason: "Streaming compaction did not account for all input"
|
||||
}
|
||||
);
|
||||
Ok(output)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! Bounded writer messages. Individual Arrow batches retain their dictionaries and order.
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use smallvec::SmallVec;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
pub(super) type Packet = SmallVec<[RecordBatch; 1]>;
|
||||
|
||||
pub(super) struct Sink {
|
||||
sender: mpsc::Sender<Packet>,
|
||||
pending: Packet,
|
||||
bytes: usize,
|
||||
rows: usize,
|
||||
target_rows: usize,
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl Sink {
|
||||
pub(super) fn new(sender: mpsc::Sender<Packet>, target_rows: usize, slot_bytes: usize) -> Self {
|
||||
Self {
|
||||
sender,
|
||||
pending: Packet::new(),
|
||||
bytes: 0,
|
||||
rows: 0,
|
||||
target_rows,
|
||||
max_bytes: slot_bytes.min(4 << 20),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(&mut self, packet: Packet, wait: &mut Duration) -> bool {
|
||||
match self.sender.try_send(packet) {
|
||||
Ok(()) => true,
|
||||
Err(mpsc::error::TrySendError::Full(packet)) => {
|
||||
let start = Instant::now();
|
||||
let sent = self.sender.send(packet).await.is_ok();
|
||||
*wait += start.elapsed();
|
||||
sent
|
||||
}
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn flush(&mut self, wait: &mut Duration) -> bool {
|
||||
if self.pending.is_empty() {
|
||||
return true;
|
||||
}
|
||||
self.rows = 0;
|
||||
self.bytes = 0;
|
||||
let packet = std::mem::take(&mut self.pending);
|
||||
self.send(packet, wait).await
|
||||
}
|
||||
|
||||
pub(super) async fn push(&mut self, fragment: RecordBatch, wait: &mut Duration) -> bool {
|
||||
if self.target_rows <= 1 {
|
||||
return self.send(smallvec::smallvec![fragment], wait).await;
|
||||
}
|
||||
let bytes = fragment.get_array_memory_size();
|
||||
if bytes > self.max_bytes.saturating_sub(self.bytes) && !self.flush(wait).await {
|
||||
return false;
|
||||
}
|
||||
self.bytes += bytes;
|
||||
self.rows += fragment.num_rows();
|
||||
self.pending.push(fragment);
|
||||
if self.rows >= self.target_rows || self.bytes >= self.max_bytes || self.pending.len() == 16
|
||||
{
|
||||
return self.flush(wait).await;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use datatypes::arrow::array::{ArrayRef, UInt64Array};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn fragment(value: u64) -> RecordBatch {
|
||||
RecordBatch::try_from_iter([("n", Arc::new(UInt64Array::from(vec![value])) as ArrayRef)])
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retains_order_and_delivers_last_partial_packet() {
|
||||
let (tx, mut rx) = mpsc::channel(3);
|
||||
let mut sink = Sink::new(tx, 3, 65536);
|
||||
let mut wait = Duration::ZERO;
|
||||
for i in 0..7 {
|
||||
assert!(sink.push(fragment(i), &mut wait).await);
|
||||
}
|
||||
assert!(sink.flush(&mut wait).await);
|
||||
drop(sink);
|
||||
let mut values = vec![];
|
||||
let mut sizes = vec![];
|
||||
while let Some(packet) = rx.recv().await {
|
||||
sizes.push(packet.len());
|
||||
for f in packet {
|
||||
values.push(
|
||||
f.column(0)
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.unwrap()
|
||||
.value(0),
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(sizes, [3, 3, 1]);
|
||||
assert_eq!(values, (0..7).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn caps_bytes_and_reports_closed_writer_on_tail() {
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let bytes = fragment(0).get_array_memory_size();
|
||||
let mut sink = Sink::new(tx, 8192, bytes + 1);
|
||||
let mut wait = Duration::ZERO;
|
||||
assert!(sink.push(fragment(1), &mut wait).await);
|
||||
assert!(sink.push(fragment(2), &mut wait).await);
|
||||
assert_eq!(rx.recv().await.unwrap().len(), 1);
|
||||
drop(rx);
|
||||
assert!(!sink.flush(&mut wait).await);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,384 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! Workers only merge sealed source runs. A work-slot holder never waits for
|
||||
//! another source head or channel message: cache pressure spills or fails instead
|
||||
//! of waiting for a consumer. This keeps capacity-one channels live even with a
|
||||
//! single work slot. Binary carries merge contiguous source intervals so equal
|
||||
//! row keys retain the plan's source order across every merge pass.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use datatypes::arrow::datatypes::SchemaRef;
|
||||
use futures::stream::FuturesUnordered;
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::storage::RegionId;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
use crate::compaction::multi_region::source::{SharedSource, SourceEvent};
|
||||
use crate::compaction::multi_region::spill::{Reservation, Run, RunStore};
|
||||
use crate::compaction::multi_region::{
|
||||
MultiRegionCompactionContext, MultiRegionCompactionOutput, MultiRegionCompactionPlan,
|
||||
MultiRegionCompactionStats, SourceCounters, writer,
|
||||
};
|
||||
use crate::error::{InvalidMultiRegionCompactionSnafu, Result};
|
||||
use crate::read::FlatSource;
|
||||
use crate::read::flat_merge::FlatMergeIterator;
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::sst::parquet::SstInfo;
|
||||
|
||||
/// A closed channel is an error, not a substitute for either explicit boundary.
|
||||
enum Message {
|
||||
Batch { window: i64, run: Run },
|
||||
SourceEnd,
|
||||
Finish,
|
||||
}
|
||||
|
||||
struct RegionOutput {
|
||||
region_id: RegionId,
|
||||
files: Vec<FileMeta>,
|
||||
infos: Vec<SstInfo>,
|
||||
}
|
||||
|
||||
pub(crate) async fn execute(
|
||||
plan: MultiRegionCompactionPlan,
|
||||
context: MultiRegionCompactionContext,
|
||||
source: Arc<SharedSource>,
|
||||
counters: Arc<SourceCounters>,
|
||||
) -> Result<MultiRegionCompactionOutput> {
|
||||
let stop = CancellationToken::new();
|
||||
let _cancel_on_drop = stop.clone().drop_guard();
|
||||
let store = RunStore::new(&plan, &context, stop).await?;
|
||||
let slots = Arc::new(Semaphore::new(plan.max_active_workers));
|
||||
let plan = Arc::new(plan);
|
||||
let context = Arc::new(context);
|
||||
let resources = Arc::new(WorkerResources {
|
||||
plan: plan.clone(),
|
||||
context,
|
||||
slots: slots.clone(),
|
||||
});
|
||||
let mut senders = BTreeMap::new();
|
||||
let mut workers = FuturesUnordered::new();
|
||||
for ®ion_id in plan.targets.keys() {
|
||||
let (sender, receiver) = mpsc::channel(1);
|
||||
let state = RegionWorker {
|
||||
windows: BTreeMap::new(),
|
||||
completed_sources: 0,
|
||||
schema: source.schema(),
|
||||
// Includes the task and the channel's block-based allocation.
|
||||
_reservation: store.reserve_metadata(8 * 1024)?,
|
||||
store: store.clone(),
|
||||
};
|
||||
senders.insert(region_id, sender);
|
||||
workers.push(AbortOnDropHandle::new(common_runtime::spawn_compact(
|
||||
run_worker(region_id, state, receiver, resources.clone()),
|
||||
)));
|
||||
}
|
||||
let scan = dispatch(source, senders, store.clone(), slots);
|
||||
tokio::pin!(scan);
|
||||
let mut scan_finished = false;
|
||||
let mut output = MultiRegionCompactionOutput {
|
||||
files: BTreeMap::new(),
|
||||
sst_infos: BTreeMap::new(),
|
||||
stats: MultiRegionCompactionStats::default(),
|
||||
};
|
||||
while !scan_finished || !workers.is_empty() {
|
||||
tokio::select! {
|
||||
biased;
|
||||
Some(result) = workers.next(), if !workers.is_empty() => {
|
||||
let result = result.context(crate::error::JoinSnafu)??;
|
||||
output.stats.output_rows += result.files.iter().map(|file| file.num_rows).sum::<u64>();
|
||||
output.stats.output_bytes += result.files.iter().map(|file| file.file_size + file.index_file_size).sum::<u64>();
|
||||
output.files.insert(result.region_id, result.files);
|
||||
output.sst_infos.insert(result.region_id, result.infos);
|
||||
}
|
||||
result = &mut scan, if !scan_finished => {
|
||||
result?;
|
||||
scan_finished = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
output.stats.source_files = counters.files.load(Ordering::Relaxed);
|
||||
output.stats.source_rows = counters.rows.load(Ordering::Relaxed);
|
||||
output.stats.source_store_page_bytes = counters.store_page_bytes.load(Ordering::Relaxed);
|
||||
output.stats.spilled_bytes = store.spilled_bytes();
|
||||
output.stats.peak_buffered_bytes = store.peak_buffered_bytes();
|
||||
ensure!(
|
||||
output.stats.source_files == plan.sources.len() as u64
|
||||
&& output.stats.output_rows == output.stats.source_rows,
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Multi-region compaction did not account for every source row"
|
||||
}
|
||||
);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
async fn dispatch(
|
||||
source: Arc<SharedSource>,
|
||||
senders: BTreeMap<RegionId, mpsc::Sender<Message>>,
|
||||
store: Arc<RunStore>,
|
||||
slots: Arc<Semaphore>,
|
||||
) -> Result<()> {
|
||||
let mut batches = source.batches();
|
||||
while let Some(event) = batches.try_next().await? {
|
||||
store.check_cancelled()?;
|
||||
match event {
|
||||
SourceEvent::Batch {
|
||||
region_id,
|
||||
window,
|
||||
batch,
|
||||
} => {
|
||||
let buffer_store = store.clone();
|
||||
let run =
|
||||
blocking(slots.clone(), move || Run::from_batch(batch, &buffer_store)).await?;
|
||||
let sender =
|
||||
senders
|
||||
.get(®ion_id)
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Routed fragment names an unknown region",
|
||||
})?;
|
||||
send(sender, Message::Batch { window, run }).await;
|
||||
}
|
||||
SourceEvent::SourceEnd => {
|
||||
for sender in senders.values() {
|
||||
send(sender, Message::SourceEnd).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for sender in senders.values() {
|
||||
send(sender, Message::Finish).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send(sender: &mpsc::Sender<Message>, message: Message) {
|
||||
if sender.send(message).await.is_err() {
|
||||
// The supervisor polls every worker concurrently with dispatch. Let it
|
||||
// report the worker's original error/panic, not a racing channel error.
|
||||
futures::future::pending::<()>().await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn acquire_slot(slots: &Arc<Semaphore>) -> Result<OwnedSemaphorePermit> {
|
||||
slots.clone().acquire_owned().await.map_err(|_| {
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Compaction work semaphore closed",
|
||||
}
|
||||
.build()
|
||||
})
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(
|
||||
slots: Arc<Semaphore>,
|
||||
operation: impl FnOnce() -> Result<T> + Send + 'static,
|
||||
) -> Result<T> {
|
||||
let permit = acquire_slot(&slots).await?;
|
||||
common_runtime::spawn_blocking_compact(move || {
|
||||
let _permit = permit;
|
||||
operation()
|
||||
})
|
||||
.await
|
||||
.context(crate::error::JoinSnafu)?
|
||||
}
|
||||
|
||||
struct RegionWorker {
|
||||
windows: BTreeMap<i64, WindowRuns>,
|
||||
completed_sources: usize,
|
||||
schema: SchemaRef,
|
||||
_reservation: Reservation,
|
||||
store: Arc<RunStore>,
|
||||
}
|
||||
|
||||
impl RegionWorker {
|
||||
fn accept(&mut self, message: Message) -> Result<()> {
|
||||
self.store.check_cancelled()?;
|
||||
match message {
|
||||
Message::Batch { window, run } => {
|
||||
let window = match self.windows.entry(window) {
|
||||
std::collections::btree_map::Entry::Vacant(entry) => {
|
||||
entry.insert(WindowRuns::new(&self.store)?)
|
||||
}
|
||||
std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
|
||||
};
|
||||
window.current.append(run, &self.store)?;
|
||||
}
|
||||
Message::SourceEnd => {
|
||||
for window in self.windows.values_mut() {
|
||||
window.seal(&self.schema, &self.store)?;
|
||||
}
|
||||
self.completed_sources += 1;
|
||||
}
|
||||
Message::Finish => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct WindowRuns {
|
||||
current: Run,
|
||||
/// Occupied higher levels precede lower levels in the source order.
|
||||
levels: Vec<Option<Run>>,
|
||||
_reservation: Reservation,
|
||||
}
|
||||
|
||||
impl WindowRuns {
|
||||
fn new(store: &RunStore) -> Result<Self> {
|
||||
// Includes all binary merge levels, not just the current run.
|
||||
let bytes = std::mem::size_of::<Self>()
|
||||
+ 128
|
||||
+ usize::BITS as usize * std::mem::size_of::<Option<Run>>();
|
||||
Ok(Self {
|
||||
current: Run::default(),
|
||||
levels: Vec::new(),
|
||||
_reservation: store.reserve_metadata(bytes)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn seal(&mut self, schema: &SchemaRef, store: &RunStore) -> Result<()> {
|
||||
let mut run = std::mem::take(&mut self.current);
|
||||
if run.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for level in &mut self.levels {
|
||||
let Some(previous) = level.take() else {
|
||||
*level = Some(run);
|
||||
return Ok(());
|
||||
};
|
||||
run = merge(previous, run, schema, store)?;
|
||||
}
|
||||
self.levels.push(Some(run));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(self, schema: &SchemaRef, store: &RunStore) -> Result<Run> {
|
||||
ensure!(
|
||||
self.current.is_empty(),
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Cannot merge an unfinished source",
|
||||
}
|
||||
);
|
||||
let mut result = None;
|
||||
for run in self.levels.into_iter().rev().flatten() {
|
||||
result = Some(match result {
|
||||
None => run,
|
||||
Some(previous) => merge(previous, run, schema, store)?,
|
||||
});
|
||||
}
|
||||
result.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Empty output window",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn merge(left: Run, right: Run, schema: &SchemaRef, store: &RunStore) -> Result<Run> {
|
||||
store.check_cancelled()?;
|
||||
let iterator = FlatMergeIterator::new_stable(
|
||||
schema.clone(),
|
||||
vec![left.into_iter()?, right.into_iter()?],
|
||||
1024,
|
||||
)?;
|
||||
let mut output = Run::default();
|
||||
for batch in iterator {
|
||||
output.push(batch?, store)?;
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
struct WorkerResources {
|
||||
plan: Arc<MultiRegionCompactionPlan>,
|
||||
context: Arc<MultiRegionCompactionContext>,
|
||||
slots: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
async fn run_worker(
|
||||
region_id: RegionId,
|
||||
mut state: RegionWorker,
|
||||
mut receiver: mpsc::Receiver<Message>,
|
||||
resources: Arc<WorkerResources>,
|
||||
) -> Result<RegionOutput> {
|
||||
let WorkerResources {
|
||||
plan,
|
||||
context,
|
||||
slots,
|
||||
} = resources.as_ref();
|
||||
loop {
|
||||
let message = receiver
|
||||
.recv()
|
||||
.await
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Source channel closed without Finish",
|
||||
})?;
|
||||
if matches!(message, Message::Finish) {
|
||||
break;
|
||||
}
|
||||
state = blocking(slots.clone(), move || {
|
||||
state.accept(message)?;
|
||||
Ok(state)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
ensure!(
|
||||
state.completed_sources == plan.sources.len(),
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Region worker did not receive every source boundary",
|
||||
}
|
||||
);
|
||||
let target = plan
|
||||
.targets
|
||||
.get(®ion_id)
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Missing worker target",
|
||||
})?;
|
||||
let mut output = RegionOutput {
|
||||
region_id,
|
||||
files: Vec::new(),
|
||||
infos: Vec::new(),
|
||||
};
|
||||
while let Some((_, window)) = state.windows.pop_first() {
|
||||
let schema = state.schema.clone();
|
||||
let store = state.store.clone();
|
||||
let run = blocking(slots.clone(), move || window.finish(&schema, &store)).await?;
|
||||
// Writers share work slots with merges. No holder ever waits for a
|
||||
// channel or a not-yet-sealed source, even when there is only one slot.
|
||||
let permit = acquire_slot(slots).await?;
|
||||
let (mut iterator, permit) = common_runtime::spawn_blocking_compact(move || {
|
||||
Ok::<_, crate::error::Error>((run.into_iter()?, permit))
|
||||
})
|
||||
.await
|
||||
.context(crate::error::JoinSnafu)??;
|
||||
let store = state.store.clone();
|
||||
let stream = async_stream::try_stream! {
|
||||
loop {
|
||||
let checking = store.clone();
|
||||
let (next, returned) = common_runtime::spawn_blocking_compact(move || {
|
||||
checking.check_cancelled()?;
|
||||
let next = iterator.next().transpose()?;
|
||||
Ok::<_, crate::error::Error>((next, iterator))
|
||||
}).await.context(crate::error::JoinSnafu)??;
|
||||
iterator = returned;
|
||||
let Some(batch) = next else { break; };
|
||||
yield batch;
|
||||
}
|
||||
};
|
||||
let source = FlatSource::new_stream(state.schema.clone(), Box::pin(stream));
|
||||
let (files, infos) = writer::write_target_group(target, source, plan, context).await?;
|
||||
drop(permit);
|
||||
output.files.extend(files);
|
||||
output.infos.extend(infos);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use snafu::{ResultExt, ensure};
|
||||
use store_api::codec::PrimaryKeyEncoding;
|
||||
|
||||
use crate::access_layer::{Metrics, OperationType, SstWriteRequest, WriteType};
|
||||
use crate::compaction::multi_region::{
|
||||
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget,
|
||||
};
|
||||
use crate::error::{ComputeArrowSnafu, Result};
|
||||
use crate::read::FlatSource;
|
||||
use crate::sst::FormatType;
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::sst::parquet::metadata::extract_primary_key_range;
|
||||
use crate::sst::parquet::parallel_writer::EncodeRuntime;
|
||||
use crate::sst::parquet::{SstInfo, WriteOptions};
|
||||
|
||||
pub(crate) async fn write_target_group(
|
||||
target: &MultiRegionTarget,
|
||||
source: FlatSource,
|
||||
plan: &MultiRegionCompactionPlan,
|
||||
context: &MultiRegionCompactionContext,
|
||||
) -> Result<(Vec<FileMeta>, Vec<SstInfo>)> {
|
||||
if context.cancellation.is_cancelled() {
|
||||
return crate::error::CompactionCancelledSnafu.fail();
|
||||
}
|
||||
let minimum_chunk = context
|
||||
.access_layer
|
||||
.object_store()
|
||||
.info()
|
||||
.capability()
|
||||
.write_multi_min_size
|
||||
.unwrap_or(0);
|
||||
let write_buffer = if plan.spill_limit == 0 {
|
||||
(plan.memory_limit / (8 * plan.targets.len())).min(16 << 20)
|
||||
} else {
|
||||
plan.memory_limit / 8
|
||||
};
|
||||
ensure!(
|
||||
minimum_chunk <= write_buffer,
|
||||
crate::error::MultiRegionCompactionResourceSnafu {
|
||||
reason: "Storage multipart minimum exceeds the table writer budget",
|
||||
}
|
||||
);
|
||||
let source = output_projection(target, source, context.cancellation.clone())?;
|
||||
let trusted = target.options.preserve_row_sequence
|
||||
&& target.inputs.values().all(|file| {
|
||||
if file.region_id == target.metadata.region_id {
|
||||
file.preserve_row_sequence
|
||||
} else {
|
||||
file.sequence.is_some()
|
||||
}
|
||||
});
|
||||
let request = SstWriteRequest {
|
||||
op_type: OperationType::Compact,
|
||||
metadata: target.metadata.clone(),
|
||||
source,
|
||||
cache_manager: context.cache.clone(),
|
||||
max_sequence: None,
|
||||
sst_write_format: target.options.sst_format.unwrap_or(
|
||||
if context.config.default_flat_format {
|
||||
FormatType::Flat
|
||||
} else {
|
||||
FormatType::PrimaryKey
|
||||
},
|
||||
),
|
||||
preserve_row_sequence: trusted,
|
||||
index_options: target.options.index_options.clone(),
|
||||
index_config: context.config.index.clone(),
|
||||
inverted_index_config: context.config.inverted_index.clone(),
|
||||
fulltext_index_config: context.config.fulltext_index.clone(),
|
||||
bloom_filter_index_config: context.config.bloom_filter_index.clone(),
|
||||
};
|
||||
let options = WriteOptions {
|
||||
write_buffer_size: ReadableSize(write_buffer as u64),
|
||||
max_file_size: Some(plan.max_output_file_size),
|
||||
row_group_size: target.options.row_group_size(),
|
||||
float_field_encoding: target.options.float_field_encoding,
|
||||
// Work slots bound active writers; extra encoding tasks are not budgeted.
|
||||
encode_parallelism: 1,
|
||||
encode_runtime: EncodeRuntime::Compact,
|
||||
};
|
||||
let mut metrics = Metrics::new(WriteType::Compaction);
|
||||
let infos = context
|
||||
.access_layer
|
||||
.write_sst_with_guard(request, &options, &mut metrics, context.protection.clone())
|
||||
.await?;
|
||||
metrics.observe();
|
||||
let sequence = target
|
||||
.inputs
|
||||
.values()
|
||||
.map(|file| file.sequence)
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.and_then(|values| values.into_iter().max());
|
||||
let partition_expr =
|
||||
crate::region::parse_partition_expr(target.metadata.partition_expr.as_deref())?;
|
||||
let files = infos
|
||||
.iter()
|
||||
.map(|info| {
|
||||
let range = info
|
||||
.file_metadata
|
||||
.as_ref()
|
||||
.and_then(|footer| extract_primary_key_range(footer, &target.metadata));
|
||||
FileMeta {
|
||||
region_id: target.metadata.region_id,
|
||||
file_id: info.file_id,
|
||||
time_range: info.time_range,
|
||||
level: 1,
|
||||
file_size: info.file_size,
|
||||
max_row_group_uncompressed_size: info.max_row_group_uncompressed_size,
|
||||
available_indexes: info.index_metadata.build_available_indexes(),
|
||||
indexes: info.index_metadata.build_indexes(),
|
||||
index_file_size: info.index_metadata.file_size,
|
||||
index_version: 0,
|
||||
num_rows: info.num_rows as u64,
|
||||
num_row_groups: info.num_row_groups,
|
||||
sequence,
|
||||
partition_expr: partition_expr.clone(),
|
||||
num_series: info.num_series,
|
||||
primary_key_min: range.as_ref().map(|(min, _)| min.clone()),
|
||||
primary_key_max: range.map(|(_, max)| max),
|
||||
preserve_row_sequence: trusted,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Ok((files, infos.into_iter().collect()))
|
||||
}
|
||||
|
||||
fn output_projection(
|
||||
target: &MultiRegionTarget,
|
||||
mut source: FlatSource,
|
||||
cancellation: Arc<common_base::cancellation::CancellationHandle>,
|
||||
) -> Result<FlatSource> {
|
||||
let projection: Vec<_> = source
|
||||
.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, field)| {
|
||||
target.metadata.primary_key_encoding != PrimaryKeyEncoding::Sparse
|
||||
|| !target.metadata.primary_key.iter().any(|id| {
|
||||
target
|
||||
.metadata
|
||||
.column_by_id(*id)
|
||||
.is_some_and(|column| column.column_schema.name == *field.name())
|
||||
})
|
||||
})
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
let schema = Arc::new(
|
||||
source
|
||||
.schema()
|
||||
.project(&projection)
|
||||
.context(ComputeArrowSnafu)?,
|
||||
);
|
||||
let stream = async_stream::try_stream! {
|
||||
while let Some(batch) = source.next_batch().await? {
|
||||
if cancellation.is_cancelled() { Err(crate::error::CompactionCancelledSnafu.build())?; }
|
||||
yield batch.project(&projection).context(ComputeArrowSnafu)?;
|
||||
}
|
||||
};
|
||||
Ok(FlatSource::new_stream(schema, Box::pin(stream)))
|
||||
}
|
||||
@@ -12,6 +12,8 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
mod hybrid;
|
||||
mod local;
|
||||
mod planning;
|
||||
mod state;
|
||||
@@ -35,6 +37,7 @@ use tokio::sync::mpsc::Sender;
|
||||
use crate::access_layer::AccessLayerRef;
|
||||
use crate::cache::CacheManagerRef;
|
||||
use crate::compaction::memory_manager::CompactionMemoryManager;
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
use crate::compaction::task::MAX_PARALLEL_COMPACTION;
|
||||
use crate::config::MitoConfig;
|
||||
use crate::error::{
|
||||
@@ -100,6 +103,12 @@ pub(crate) struct CompactionScheduler {
|
||||
/// Scheduler-wide generation counter for compaction plans and executions.
|
||||
/// It outlives region statuses so close/reopen cannot reuse an old identity.
|
||||
next_plan_id: u64,
|
||||
#[cfg(feature = "enterprise")]
|
||||
shared: Option<Box<CompactionScheduler>>,
|
||||
#[cfg(feature = "enterprise")]
|
||||
shared_lane: bool,
|
||||
#[cfg(feature = "enterprise")]
|
||||
ddl_blocked: std::collections::HashSet<RegionId>,
|
||||
}
|
||||
|
||||
/// Describes the immediate action produced by a compaction terminal transition.
|
||||
@@ -172,6 +181,12 @@ impl CompactionScheduler {
|
||||
listener,
|
||||
plugins,
|
||||
next_plan_id: 0,
|
||||
#[cfg(feature = "enterprise")]
|
||||
shared: None,
|
||||
#[cfg(feature = "enterprise")]
|
||||
shared_lane: false,
|
||||
#[cfg(feature = "enterprise")]
|
||||
ddl_blocked: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,6 +197,11 @@ impl CompactionScheduler {
|
||||
access_layer: &AccessLayerRef,
|
||||
) {
|
||||
let region_id = version_control.region_id();
|
||||
#[cfg(feature = "enterprise")]
|
||||
if !self.shared_lane && crate::compaction::compactor::experiment::enabled(region_id) {
|
||||
self.shared_scheduler()
|
||||
.register_region(version_control, access_layer);
|
||||
}
|
||||
if let Some(status) = self.region_status.get_mut(®ion_id) {
|
||||
if Arc::ptr_eq(&status.version_control, version_control) {
|
||||
return;
|
||||
@@ -224,7 +244,21 @@ impl CompactionScheduler {
|
||||
manifest_ctx: &ManifestContextRef,
|
||||
schema_metadata_manager: SchemaMetadataManagerRef,
|
||||
) -> Result<bool> {
|
||||
self.schedule_compaction(
|
||||
#[cfg(feature = "enterprise")]
|
||||
let shared_started = if !self.shared_lane
|
||||
&& crate::compaction::compactor::experiment::enabled(version_control.region_id())
|
||||
{
|
||||
self.shared_scheduler().schedule_automatic_compaction(
|
||||
compact_options.clone(),
|
||||
version_control,
|
||||
access_layer,
|
||||
manifest_ctx,
|
||||
schema_metadata_manager.clone(),
|
||||
)?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let started = self.schedule_compaction(
|
||||
CompactionTrigger::Automatic,
|
||||
compact_options,
|
||||
version_control,
|
||||
@@ -232,9 +266,26 @@ impl CompactionScheduler {
|
||||
OptionOutputTx::none(),
|
||||
manifest_ctx,
|
||||
schema_metadata_manager,
|
||||
1, // Default for automatic compaction
|
||||
{
|
||||
#[cfg(feature = "enterprise")]
|
||||
{
|
||||
crate::compaction::compactor::experiment::automatic_parallelism()
|
||||
}
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
{
|
||||
1
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
)?;
|
||||
#[cfg(feature = "enterprise")]
|
||||
{
|
||||
return Ok(started || shared_started);
|
||||
}
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
{
|
||||
Ok(started)
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepts a manual compaction request for a region.
|
||||
@@ -266,6 +317,21 @@ impl CompactionScheduler {
|
||||
max_parallelism: usize,
|
||||
time_range: Option<TimestampRange>,
|
||||
) -> Result<bool> {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if !self.shared_lane
|
||||
&& crate::compaction::compactor::experiment::enabled(version_control.region_id())
|
||||
{
|
||||
return self.shared_scheduler().schedule_manual_compaction(
|
||||
compact_options,
|
||||
version_control,
|
||||
access_layer,
|
||||
waiter,
|
||||
manifest_ctx,
|
||||
schema_metadata_manager,
|
||||
max_parallelism,
|
||||
time_range,
|
||||
);
|
||||
}
|
||||
self.schedule_compaction(
|
||||
CompactionTrigger::Manual,
|
||||
compact_options,
|
||||
@@ -299,6 +365,38 @@ impl CompactionScheduler {
|
||||
manifest_ctx: &ManifestContextRef,
|
||||
schema_metadata_manager: SchemaMetadataManagerRef,
|
||||
) -> CompactionTransition {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if hybrid::is_shared_plan(finished.plan_id) && !self.shared_lane {
|
||||
let region_id = finished.region_id;
|
||||
let retry = matches!(
|
||||
&finished.result,
|
||||
planning::CompactionPlanningResult::RetryShared
|
||||
);
|
||||
let Some(shared) = self.shared.as_mut() else {
|
||||
return CompactionTransition::NoAction;
|
||||
};
|
||||
let transition = shared
|
||||
.handle_compaction_pick_finished_inner(
|
||||
finished,
|
||||
manifest_ctx,
|
||||
schema_metadata_manager.clone(),
|
||||
)
|
||||
.await;
|
||||
if retry
|
||||
&& !self
|
||||
.region_status
|
||||
.get(®ion_id)
|
||||
.is_some_and(|s| s.has_ddl())
|
||||
{
|
||||
return transition;
|
||||
}
|
||||
return self.after_shared_event(
|
||||
region_id,
|
||||
manifest_ctx,
|
||||
schema_metadata_manager,
|
||||
transition,
|
||||
);
|
||||
}
|
||||
self.handle_compaction_pick_finished_inner(finished, manifest_ctx, schema_metadata_manager)
|
||||
.await
|
||||
}
|
||||
@@ -422,6 +520,10 @@ impl CompactionScheduler {
|
||||
///
|
||||
/// The owning worker must invoke this after truncate completes.
|
||||
pub(crate) fn on_region_truncated(&mut self, region_id: RegionId) {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if let Some(shared) = &mut self.shared {
|
||||
shared.on_region_truncated(region_id);
|
||||
}
|
||||
self.fail_compaction(
|
||||
region_id,
|
||||
Arc::new(RegionTruncatedSnafu { region_id }.build()),
|
||||
@@ -453,7 +555,23 @@ impl CompactionScheduler {
|
||||
let Some(status) = self.region_status.get_mut(®ion_id) else {
|
||||
return Err((sender, request));
|
||||
};
|
||||
if !status.is_compacting() {
|
||||
#[cfg(feature = "enterprise")]
|
||||
let shared_running = self.shared.as_mut().is_some_and(|shared| {
|
||||
let running = shared
|
||||
.region_status
|
||||
.get(®ion_id)
|
||||
.is_some_and(CompactionStatus::is_compacting);
|
||||
if running || status.is_compacting() {
|
||||
shared.ddl_blocked.insert(region_id);
|
||||
if let Some(s) = shared.region_status.get_mut(®ion_id) {
|
||||
s.request_cancel();
|
||||
}
|
||||
}
|
||||
running
|
||||
});
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
let shared_running = false;
|
||||
if !status.is_compacting() && !shared_running {
|
||||
return Err((sender, request));
|
||||
}
|
||||
status.request_cancel();
|
||||
@@ -509,6 +627,11 @@ impl CompactionScheduler {
|
||||
return Ok(false);
|
||||
}
|
||||
let region_id = version_control.region_id();
|
||||
#[cfg(feature = "enterprise")]
|
||||
if self.ddl_blocked.contains(®ion_id) {
|
||||
waiter.send(CompactionCancelledSnafu.fail());
|
||||
return Ok(false);
|
||||
}
|
||||
let status = self.region_status.entry(region_id).or_insert_with(|| {
|
||||
CompactionStatus::new(region_id, version_control.clone(), access_layer.clone())
|
||||
});
|
||||
@@ -686,6 +809,10 @@ impl CompactionScheduler {
|
||||
if self.disable_compaction {
|
||||
return false;
|
||||
}
|
||||
#[cfg(feature = "enterprise")]
|
||||
if self.ddl_blocked.contains(®ion_id) {
|
||||
return false;
|
||||
}
|
||||
let Some(status) = self.region_status.get_mut(®ion_id) else {
|
||||
return false;
|
||||
};
|
||||
@@ -697,7 +824,16 @@ impl CompactionScheduler {
|
||||
manifest_ctx,
|
||||
self.listener.clone(),
|
||||
schema_metadata_manager,
|
||||
MAX_PARALLEL_COMPACTION,
|
||||
{
|
||||
#[cfg(feature = "enterprise")]
|
||||
{
|
||||
crate::compaction::compactor::experiment::automatic_parallelism()
|
||||
}
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
{
|
||||
MAX_PARALLEL_COMPACTION
|
||||
}
|
||||
},
|
||||
);
|
||||
// Bump the counter through a disjoint field borrow so the `status`
|
||||
// borrow stays alive; nothing could have removed the status since it
|
||||
@@ -763,6 +899,13 @@ impl CompactionScheduler {
|
||||
|
||||
/// Unregisters a closed or dropped region and fails its queued requests.
|
||||
fn remove_region(&mut self, region_id: RegionId, err: Arc<Error>) {
|
||||
#[cfg(feature = "enterprise")]
|
||||
{
|
||||
self.ddl_blocked.remove(®ion_id);
|
||||
if let Some(shared) = &mut self.shared {
|
||||
shared.remove_region(region_id, err.clone());
|
||||
}
|
||||
}
|
||||
if let Some(mut status) = self.region_status.remove(®ion_id) {
|
||||
status.on_failure(err);
|
||||
}
|
||||
@@ -773,6 +916,10 @@ impl CompactionScheduler {
|
||||
if let Some(status) = self.region_status.get_mut(®ion_id) {
|
||||
status.on_failure(err);
|
||||
}
|
||||
#[cfg(feature = "enterprise")]
|
||||
if let Some(shared) = &mut self.shared {
|
||||
shared.ddl_blocked.remove(®ion_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the cycle to idle and records any DDL handoff in the same resident entry.
|
||||
@@ -795,6 +942,17 @@ impl CompactionScheduler {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
#[cfg(feature = "enterprise")]
|
||||
if self.shared_running(region_id) {
|
||||
// This lane has terminated; the other lane will hand off the DDL.
|
||||
if let Some(status) = self.region_status.get_mut(®ion_id) {
|
||||
for waiter in status.take_waiters() {
|
||||
waiter.send(CompactionCancelledSnafu.fail());
|
||||
}
|
||||
status.become_idle();
|
||||
}
|
||||
return Some(Vec::new());
|
||||
}
|
||||
Some(self.finish_compaction_on_cancel(region_id))
|
||||
}
|
||||
|
||||
@@ -877,6 +1035,10 @@ impl CompactionScheduler {
|
||||
&& ddl.complete(generation, request_index)
|
||||
{
|
||||
status.executing_ddl = None;
|
||||
#[cfg(feature = "enterprise")]
|
||||
if let Some(shared) = &mut self.shared {
|
||||
shared.ddl_blocked.remove(®ion_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! Independent shared-L0 scheduling, reusing the ordinary scheduler and file leases.
|
||||
use super::*;
|
||||
|
||||
// Plans and units share the existing monotonic counter. Separate ID ranges let
|
||||
// existing worker notifications reach the right scheduler without wire changes.
|
||||
const SHARED_PLAN: u64 = 1 << 63;
|
||||
|
||||
pub(super) fn is_shared_plan(id: u64) -> bool {
|
||||
id & SHARED_PLAN != 0
|
||||
}
|
||||
|
||||
impl CompactionScheduler {
|
||||
pub(super) fn shared_scheduler(&mut self) -> &mut Self {
|
||||
if self.shared.is_none() {
|
||||
let mut child = Self::new(
|
||||
self.scheduler.clone(),
|
||||
self.request_sender.clone(),
|
||||
self.cache_manager.clone(),
|
||||
self.engine_config.clone(),
|
||||
self.listener.clone(),
|
||||
self.plugins.clone(),
|
||||
self.memory_manager.clone(),
|
||||
self.memory_policy,
|
||||
);
|
||||
child.shared_lane = true;
|
||||
child.next_plan_id = SHARED_PLAN;
|
||||
child.disable_compaction = self.disable_compaction;
|
||||
self.shared = Some(Box::new(child));
|
||||
}
|
||||
self.shared.as_mut().unwrap()
|
||||
}
|
||||
|
||||
pub(super) fn shared_running(&self, region_id: RegionId) -> bool {
|
||||
self.shared
|
||||
.as_ref()
|
||||
.and_then(|s| s.region_status.get(®ion_id))
|
||||
.is_some_and(CompactionStatus::is_compacting)
|
||||
}
|
||||
|
||||
/// A shared publication wakes L1 selection immediately, even while other
|
||||
/// shared units remain active. A remote L1 execution coalesces this wakeup.
|
||||
pub(super) fn after_shared_event(
|
||||
&mut self,
|
||||
region_id: RegionId,
|
||||
manifest: &ManifestContextRef,
|
||||
schemas: SchemaMetadataManagerRef,
|
||||
transition: CompactionTransition,
|
||||
) -> CompactionTransition {
|
||||
let Some(status) = self.region_status.get(®ion_id) else {
|
||||
return transition;
|
||||
};
|
||||
if status.has_ddl() {
|
||||
if !status.is_compacting() && !self.shared_running(region_id) {
|
||||
return CompactionTransition::from_pending_ddls(
|
||||
self.take_ready_ddls(region_id).unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
return transition;
|
||||
}
|
||||
let version = status.version_control.clone();
|
||||
let access = status.access_layer.clone();
|
||||
if let Err(err) = self.schedule_compaction(
|
||||
CompactionTrigger::Automatic,
|
||||
compact_request::Options::Regular(Default::default()),
|
||||
&version,
|
||||
&access,
|
||||
OptionOutputTx::none(),
|
||||
manifest,
|
||||
schemas,
|
||||
crate::compaction::compactor::experiment::automatic_parallelism(),
|
||||
None,
|
||||
) {
|
||||
warn!(err; "Failed to schedule L1 after shared publication for region {}", region_id);
|
||||
}
|
||||
transition
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::compaction::scheduler::planning::CompactionPlanningResult;
|
||||
use crate::test_util::version_util::VersionControlBuilder;
|
||||
use crate::test_util::{mock_schema_metadata_manager, scheduler_util::SchedulerEnv};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_planning_finishes_while_remote_l1_stays_active() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let mut scheduler = env.mock_compaction_scheduler(tx);
|
||||
let version = Arc::new(VersionControlBuilder::new().build());
|
||||
let id = version.region_id();
|
||||
scheduler.register_region(&version, &env.access_layer);
|
||||
scheduler
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_remote_task();
|
||||
let remote = CompactionExecution::for_test(0);
|
||||
let shared = scheduler.shared_scheduler();
|
||||
shared.register_region(&version, &env.access_layer);
|
||||
shared
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_picking(SHARED_PLAN);
|
||||
assert!(scheduler.shared_running(id));
|
||||
assert!(scheduler.is_current_execution(id, &remote));
|
||||
let manifest = env
|
||||
.mock_manifest_context(version.current().version.metadata.clone())
|
||||
.await;
|
||||
let (schemas, _) = mock_schema_metadata_manager();
|
||||
scheduler
|
||||
.handle_compaction_pick_finished(
|
||||
CompactionPickFinished {
|
||||
region_id: id,
|
||||
plan_id: SHARED_PLAN,
|
||||
result: CompactionPlanningResult::NoPlan,
|
||||
},
|
||||
&manifest,
|
||||
schemas,
|
||||
)
|
||||
.await;
|
||||
assert!(!scheduler.shared_running(id));
|
||||
assert!(
|
||||
scheduler.is_current_execution(id, &remote),
|
||||
"shared completion must not clear L1"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_completion_does_not_end_shared_work_and_close_clears_both() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let mut scheduler = env.mock_compaction_scheduler(tx);
|
||||
let version = Arc::new(VersionControlBuilder::new().build());
|
||||
let id = version.region_id();
|
||||
scheduler.register_region(&version, &env.access_layer);
|
||||
scheduler
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_remote_task();
|
||||
let shared = scheduler.shared_scheduler();
|
||||
shared.register_region(&version, &env.access_layer);
|
||||
shared
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_picking(SHARED_PLAN);
|
||||
let manifest = env
|
||||
.mock_manifest_context(version.current().version.metadata.clone())
|
||||
.await;
|
||||
let (schemas, _) = mock_schema_metadata_manager();
|
||||
let remote = CompactionExecution::for_test(0);
|
||||
scheduler
|
||||
.on_execution_finished(id, &remote, &manifest, schemas, false)
|
||||
.await;
|
||||
assert!(scheduler.shared_running(id));
|
||||
assert!(!scheduler.is_current_execution(id, &remote));
|
||||
scheduler.on_region_closed(id);
|
||||
assert!(!scheduler.region_status.contains_key(&id));
|
||||
assert!(
|
||||
!scheduler
|
||||
.shared
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.region_status
|
||||
.contains_key(&id)
|
||||
);
|
||||
assert!(!scheduler.can_apply_unit(id, SHARED_PLAN));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ddl_waits_for_both_lanes_without_blocking_their_terminal_callbacks() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let mut scheduler = env.mock_compaction_scheduler(tx);
|
||||
let version = Arc::new(VersionControlBuilder::new().build());
|
||||
let id = version.region_id();
|
||||
scheduler.register_region(&version, &env.access_layer);
|
||||
scheduler
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_remote_task();
|
||||
let shared = scheduler.shared_scheduler();
|
||||
shared.register_region(&version, &env.access_layer);
|
||||
shared
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_picking(SHARED_PLAN);
|
||||
let (reply, _response) = oneshot::channel();
|
||||
assert!(
|
||||
scheduler
|
||||
.try_cancel_and_add_ddl(id, reply.into(), (), |_| {
|
||||
DdlRequest::Truncate(store_api::region_request::RegionTruncateRequest::All)
|
||||
})
|
||||
.is_ok()
|
||||
);
|
||||
let manifest = env
|
||||
.mock_manifest_context(version.current().version.metadata.clone())
|
||||
.await;
|
||||
let (schemas, _) = mock_schema_metadata_manager();
|
||||
let first = scheduler
|
||||
.on_execution_finished(
|
||||
id,
|
||||
&CompactionExecution::for_test(0),
|
||||
&manifest,
|
||||
schemas.clone(),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
first.is_empty(),
|
||||
"DDL must not execute while shared planning still owns inputs"
|
||||
);
|
||||
let last = scheduler
|
||||
.handle_compaction_pick_finished(
|
||||
CompactionPickFinished {
|
||||
region_id: id,
|
||||
plan_id: SHARED_PLAN,
|
||||
result: CompactionPlanningResult::NoPlan,
|
||||
},
|
||||
&manifest,
|
||||
schemas,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(last.len(), 1);
|
||||
assert!(scheduler.shared.as_ref().unwrap().ddl_blocked.contains(&id));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod readiness_tests {
|
||||
use super::*;
|
||||
use crate::compaction::scheduler::planning::CompactionPlanningResult;
|
||||
use crate::test_util::version_util::VersionControlBuilder;
|
||||
use crate::test_util::{mock_schema_metadata_manager, scheduler_util::SchedulerEnv};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
#[tokio::test]
|
||||
async fn retry_reselects_without_a_write_and_keeps_remote_l1_active() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let mut scheduler = env.mock_compaction_scheduler(tx);
|
||||
let version = Arc::new(VersionControlBuilder::new().build());
|
||||
let id = version.region_id();
|
||||
scheduler.register_region(&version, &env.access_layer);
|
||||
scheduler
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_remote_task();
|
||||
let shared = scheduler.shared_scheduler();
|
||||
shared.register_region(&version, &env.access_layer);
|
||||
shared
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_picking(SHARED_PLAN);
|
||||
shared.next_plan_id = SHARED_PLAN + 1;
|
||||
let manifest = env
|
||||
.mock_manifest_context(version.current().version.metadata.clone())
|
||||
.await;
|
||||
let (schemas, _) = mock_schema_metadata_manager();
|
||||
let transition = scheduler
|
||||
.handle_compaction_pick_finished(
|
||||
CompactionPickFinished {
|
||||
region_id: id,
|
||||
plan_id: SHARED_PLAN,
|
||||
result: CompactionPlanningResult::RetryShared,
|
||||
},
|
||||
&manifest,
|
||||
schemas,
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(
|
||||
transition,
|
||||
CompactionTransition::AutomaticFollowupScheduled
|
||||
));
|
||||
assert!(scheduler.shared.as_ref().unwrap().region_status[&id].is_picking(SHARED_PLAN + 1));
|
||||
assert!(scheduler.is_current_execution(id, &CompactionExecution::for_test(0)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retry_releases_ddl_instead_of_restarting_canceled_selection() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let mut scheduler = env.mock_compaction_scheduler(tx);
|
||||
let version = Arc::new(VersionControlBuilder::new().build());
|
||||
let id = version.region_id();
|
||||
scheduler.register_region(&version, &env.access_layer);
|
||||
let shared = scheduler.shared_scheduler();
|
||||
shared.register_region(&version, &env.access_layer);
|
||||
shared
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_picking(SHARED_PLAN);
|
||||
let (reply, _response) = oneshot::channel();
|
||||
assert!(
|
||||
scheduler
|
||||
.try_cancel_and_add_ddl(id, reply.into(), (), |_| {
|
||||
DdlRequest::Truncate(store_api::region_request::RegionTruncateRequest::All)
|
||||
})
|
||||
.is_ok()
|
||||
);
|
||||
let manifest = env
|
||||
.mock_manifest_context(version.current().version.metadata.clone())
|
||||
.await;
|
||||
let (schemas, _) = mock_schema_metadata_manager();
|
||||
let transition = scheduler
|
||||
.handle_compaction_pick_finished(
|
||||
CompactionPickFinished {
|
||||
region_id: id,
|
||||
plan_id: SHARED_PLAN,
|
||||
result: CompactionPlanningResult::RetryShared,
|
||||
},
|
||||
&manifest,
|
||||
schemas,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(transition.len(), 1);
|
||||
assert!(!scheduler.shared_running(id));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_retry_cannot_restart_a_closed_and_reopened_region() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let mut scheduler = env.mock_compaction_scheduler(tx);
|
||||
let version = Arc::new(VersionControlBuilder::new().build());
|
||||
let id = version.region_id();
|
||||
scheduler.register_region(&version, &env.access_layer);
|
||||
let shared = scheduler.shared_scheduler();
|
||||
shared.register_region(&version, &env.access_layer);
|
||||
shared
|
||||
.region_status
|
||||
.get_mut(&id)
|
||||
.unwrap()
|
||||
.start_picking(SHARED_PLAN);
|
||||
scheduler.on_region_closed(id);
|
||||
scheduler.register_region(&version, &env.access_layer);
|
||||
scheduler
|
||||
.shared_scheduler()
|
||||
.register_region(&version, &env.access_layer);
|
||||
let manifest = env
|
||||
.mock_manifest_context(version.current().version.metadata.clone())
|
||||
.await;
|
||||
let (schemas, _) = mock_schema_metadata_manager();
|
||||
let transition = scheduler
|
||||
.handle_compaction_pick_finished(
|
||||
CompactionPickFinished {
|
||||
region_id: id,
|
||||
plan_id: SHARED_PLAN,
|
||||
result: CompactionPlanningResult::RetryShared,
|
||||
},
|
||||
&manifest,
|
||||
schemas,
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(transition, CompactionTransition::NoAction));
|
||||
assert!(!scheduler.shared_running(id));
|
||||
assert!(!scheduler.region_status[&id].is_compacting());
|
||||
}
|
||||
}
|
||||
@@ -211,6 +211,13 @@ impl CompactionScheduler {
|
||||
|
||||
/// Accepts an edit from any current unit that has started committing and is not finished.
|
||||
pub(crate) fn can_apply_unit(&self, region_id: RegionId, id: u64) -> bool {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if super::hybrid::is_shared_plan(id) && !self.shared_lane {
|
||||
return self
|
||||
.shared
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.can_apply_unit(region_id, id));
|
||||
}
|
||||
self.region_status.get(®ion_id).is_some_and(|status| {
|
||||
matches!(&status.active.phase, CompactionPhase::Units(local)
|
||||
if local.can_apply(id))
|
||||
@@ -224,6 +231,13 @@ impl CompactionScheduler {
|
||||
id: u64,
|
||||
result: std::result::Result<bool, Arc<Error>>,
|
||||
) {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if super::hybrid::is_shared_plan(id) && !self.shared_lane {
|
||||
if let Some(s) = &mut self.shared {
|
||||
s.on_unit_finished(region_id, id, result);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(local) = self.local_units_mut(region_id) {
|
||||
local.finish(id, result);
|
||||
}
|
||||
@@ -236,6 +250,27 @@ impl CompactionScheduler {
|
||||
id: u64,
|
||||
manifest: &ManifestContextRef,
|
||||
schemas: SchemaMetadataManagerRef,
|
||||
) -> CompactionTransition {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if super::hybrid::is_shared_plan(id) && !self.shared_lane {
|
||||
let Some(shared) = self.shared.as_mut() else {
|
||||
return CompactionTransition::NoAction;
|
||||
};
|
||||
let transition = shared
|
||||
.on_unit_released_inner(region_id, id, manifest, schemas.clone())
|
||||
.await;
|
||||
return self.after_shared_event(region_id, manifest, schemas, transition);
|
||||
}
|
||||
self.on_unit_released_inner(region_id, id, manifest, schemas)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn on_unit_released_inner(
|
||||
&mut self,
|
||||
region_id: RegionId,
|
||||
id: u64,
|
||||
manifest: &ManifestContextRef,
|
||||
schemas: SchemaMetadataManagerRef,
|
||||
) -> CompactionTransition {
|
||||
let Some(local) = self.local_units_mut(region_id) else {
|
||||
return CompactionTransition::NoAction;
|
||||
|
||||
@@ -79,6 +79,9 @@ impl CompactionRequest {
|
||||
pub(crate) enum CompactionPlanningResult {
|
||||
Prepared(PreparedCompaction),
|
||||
NoPlan,
|
||||
/// A shared roster/readiness miss while a full batch remains registered.
|
||||
#[cfg(feature = "enterprise")]
|
||||
RetryShared,
|
||||
Error(Arc<Error>),
|
||||
}
|
||||
|
||||
@@ -90,6 +93,8 @@ impl fmt::Debug for CompactionPlanningResult {
|
||||
.field(&prepared.compaction_region.region_id)
|
||||
.finish(),
|
||||
Self::NoPlan => f.write_str("NoPlan"),
|
||||
#[cfg(feature = "enterprise")]
|
||||
Self::RetryShared => f.write_str("RetryShared"),
|
||||
Self::Error(err) => f.debug_tuple("Error").field(err).finish(),
|
||||
}
|
||||
}
|
||||
@@ -131,6 +136,8 @@ impl CompactionScheduler {
|
||||
max_background_compactions,
|
||||
time_range,
|
||||
trigger,
|
||||
#[cfg(feature = "enterprise")]
|
||||
super::hybrid::is_shared_plan(plan_id),
|
||||
);
|
||||
Self::notify_planning_result(region_id, plan_id, request_sender, planning).await;
|
||||
});
|
||||
@@ -185,6 +192,7 @@ impl CompactionScheduler {
|
||||
max_background_compactions: usize,
|
||||
time_range: Option<TimestampRange>,
|
||||
trigger: CompactionTrigger,
|
||||
#[cfg(feature = "enterprise")] shared_lane: bool,
|
||||
) -> CompactionPlanningResult {
|
||||
let region_id = request.region_id();
|
||||
let (dynamic_compaction_opts, ttl) = find_dynamic_options(
|
||||
@@ -253,12 +261,46 @@ impl CompactionScheduler {
|
||||
let _pick_timer = COMPACTION_STAGE_ELAPSED
|
||||
.with_label_values(&["pick"])
|
||||
.start_timer();
|
||||
let picker_output = match picker.pick(&compaction_region).await {
|
||||
#[cfg(feature = "enterprise")]
|
||||
let picked = if crate::compaction::compactor::experiment::enabled(region_id) {
|
||||
if shared_lane {
|
||||
crate::compaction::compactor::experiment::pick(&compaction_region).await
|
||||
} else {
|
||||
let mut local_only = compaction_region.clone();
|
||||
local_only.current_version.ssts =
|
||||
Arc::new(local_only.current_version.ssts.without_shared_l0());
|
||||
picker.pick(&local_only).await
|
||||
}
|
||||
} else {
|
||||
picker.pick(&compaction_region).await
|
||||
};
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
let picked = picker.pick(&compaction_region).await;
|
||||
let picker_output = match picked {
|
||||
Ok(output) => output,
|
||||
Err(err) => return CompactionPlanningResult::Error(Arc::new(err)),
|
||||
};
|
||||
|
||||
let Some(picker_output) = picker_output else {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if shared_lane
|
||||
&& crate::compaction::compactor::experiment::has_pending_shared_batch(
|
||||
&compaction_region.current_version.ssts,
|
||||
)
|
||||
{
|
||||
// Remain in Picking, so writes coalesce and close/DDL retain the
|
||||
// existing generation/cancellation handling. No compaction slot
|
||||
// or SST snapshot is held during the delay.
|
||||
drop(compaction_region);
|
||||
drop(current_version);
|
||||
drop(_pick_timer);
|
||||
common_telemetry::debug!(
|
||||
"hybrid_shared_ready_retry region={} delay_ms=500",
|
||||
region_id
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
return CompactionPlanningResult::RetryShared;
|
||||
}
|
||||
return CompactionPlanningResult::NoPlan;
|
||||
};
|
||||
|
||||
@@ -302,6 +344,19 @@ impl CompactionScheduler {
|
||||
}
|
||||
|
||||
match finished.result {
|
||||
#[cfg(feature = "enterprise")]
|
||||
CompactionPlanningResult::RetryShared => {
|
||||
if let Some(status) = self.region_status.get_mut(®ion_id) {
|
||||
status.mark_automatic_trigger();
|
||||
}
|
||||
self.finish_compaction_planning(
|
||||
region_id,
|
||||
None,
|
||||
manifest_ctx,
|
||||
schema_metadata_manager,
|
||||
)
|
||||
.await
|
||||
}
|
||||
CompactionPlanningResult::Prepared(mut prepared) => {
|
||||
let current = status.version_control.current().version;
|
||||
let Some(picker_output) =
|
||||
@@ -444,11 +499,38 @@ impl CompactionScheduler {
|
||||
ttl,
|
||||
} = prepared;
|
||||
let region_id = compaction_region.region_id;
|
||||
let dynamic_compaction_opts = &compaction_region.region_options.compaction;
|
||||
|
||||
// If specified to run compaction remotely, we schedule the compaction job remotely.
|
||||
// It will fall back to local compaction if there is no remote job scheduler.
|
||||
let waiters = if dynamic_compaction_opts.remote_compaction() {
|
||||
#[cfg(feature = "enterprise")]
|
||||
let shared_local = crate::compaction::compactor::experiment::enabled(region_id)
|
||||
&& crate::compaction::compactor::experiment::shared_inputs(
|
||||
picker_output
|
||||
.outputs
|
||||
.iter()
|
||||
.flat_map(|o| o.inputs.iter().map(|f| f.meta_ref())),
|
||||
);
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
let shared_local = false;
|
||||
#[cfg(feature = "enterprise")]
|
||||
let compaction_region = {
|
||||
let mut region = compaction_region;
|
||||
region.max_parallelism = crate::compaction::compactor::experiment::merge_parallelism(
|
||||
region_id,
|
||||
shared_local,
|
||||
region.max_parallelism,
|
||||
);
|
||||
common_telemetry::info!(
|
||||
"hybrid_parallelism region={} shared={} max_parallelism={} outputs={}",
|
||||
region_id,
|
||||
shared_local,
|
||||
region.max_parallelism,
|
||||
picker_output.outputs.len()
|
||||
);
|
||||
region
|
||||
};
|
||||
let dynamic_compaction_opts = &compaction_region.region_options.compaction;
|
||||
let waiters = if dynamic_compaction_opts.remote_compaction() && !shared_local {
|
||||
if let Some(remote_job_scheduler) = &self.plugins.get::<RemoteJobSchedulerRef>() {
|
||||
let execution = CompactionExecution::new(plan_id, files.clone());
|
||||
let remote_compaction_job = CompactionJob {
|
||||
|
||||
@@ -135,7 +135,7 @@ pub struct TwcsPicker {
|
||||
}
|
||||
|
||||
impl TwcsPicker {
|
||||
/// Picks at most one compaction input per window and schedules them across
|
||||
/// Picks disjoint active L1 groups, retaining one closed-window pick, across
|
||||
/// windows by [`PickClass`], newer windows first within a class.
|
||||
async fn build_output(
|
||||
&self,
|
||||
@@ -186,7 +186,7 @@ impl TwcsPicker {
|
||||
let time_windows = time_windows.clone();
|
||||
let primary_key_mapper = primary_key_mapper.clone();
|
||||
handles.push(common_runtime::spawn_blocking_compact(move || {
|
||||
let pick = time_windows.get(&window).and_then(|files| {
|
||||
let pick = time_windows.get(&window).map_or_else(Vec::new, |files| {
|
||||
picker.pick_window(
|
||||
region_id,
|
||||
files,
|
||||
@@ -194,6 +194,7 @@ impl TwcsPicker {
|
||||
time_window_size,
|
||||
region_sequence,
|
||||
&primary_key_mapper,
|
||||
max_outputs,
|
||||
)
|
||||
});
|
||||
(window, pick)
|
||||
@@ -202,7 +203,7 @@ impl TwcsPicker {
|
||||
}
|
||||
for result in futures::future::join_all(handles).await {
|
||||
let (window, pick) = result.context(JoinSnafu)?;
|
||||
picks.extend(pick.map(|pick| (window, pick)));
|
||||
picks.extend(pick.into_iter().map(|pick| (window, pick)));
|
||||
}
|
||||
// Windows are visited newest first, so older windows cannot displace
|
||||
// a full set of picks of the first class.
|
||||
@@ -256,7 +257,7 @@ impl TwcsPicker {
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Picks the compaction inputs of one window, or `None` if it needs none.
|
||||
/// Picks inputs of one window; closed-window overlap rules stay unchanged.
|
||||
fn pick_window(
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
@@ -265,7 +266,8 @@ impl TwcsPicker {
|
||||
time_window_size: Option<i64>,
|
||||
region_sequence: u64,
|
||||
mapper: &PrimaryKeyRangeMapper,
|
||||
) -> Option<WindowPick> {
|
||||
max_outputs: usize,
|
||||
) -> Vec<WindowPick> {
|
||||
let mut files: Vec<_> = window.files().cloned().collect();
|
||||
let quiet = is_quiet_window(&files, region_sequence);
|
||||
|
||||
@@ -290,11 +292,11 @@ impl TwcsPicker {
|
||||
let (l0_files, l1_files): (Vec<_>, Vec<_>) =
|
||||
files.into_iter().partition(|file| file.level() == 0);
|
||||
if !self.all_windows_inactive && active_window == Some(window.time_window) {
|
||||
self.pick_active_window(l0_files, l1_files, mapper)
|
||||
self.pick_active_window(l0_files, l1_files, mapper, max_outputs)
|
||||
} else if window.files.len() < self.inactive_window_trigger_file_num
|
||||
&& l1_files.len() < self.inactive_window_l1_merge_trigger
|
||||
{
|
||||
None
|
||||
Vec::new()
|
||||
} else {
|
||||
let settling = !self.all_windows_inactive
|
||||
&& is_settling_window(window.time_window, active_window, time_window_size);
|
||||
@@ -316,6 +318,8 @@ impl TwcsPicker {
|
||||
found_runs: pick.units,
|
||||
})
|
||||
})
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,7 +338,8 @@ impl TwcsPicker {
|
||||
l0_files: Vec<FileHandle>,
|
||||
l1_files: Vec<FileHandle>,
|
||||
mapper: &PrimaryKeyRangeMapper,
|
||||
) -> Option<WindowPick> {
|
||||
max_outputs: usize,
|
||||
) -> Vec<WindowPick> {
|
||||
if l0_files.len() >= self.trigger_file_num {
|
||||
let (inputs, found_runs) = pick_candidate_files(
|
||||
l0_files,
|
||||
@@ -343,24 +348,34 @@ impl TwcsPicker {
|
||||
mapper,
|
||||
);
|
||||
if !inputs.is_empty() {
|
||||
return Some(WindowPick {
|
||||
return vec![WindowPick {
|
||||
class: PickClass::L0Merge,
|
||||
branch: "active:pick_count_first",
|
||||
inputs,
|
||||
found_runs,
|
||||
});
|
||||
}];
|
||||
}
|
||||
}
|
||||
if l1_files.len() < self.active_window_l1_merge_trigger {
|
||||
return None;
|
||||
return Vec::new();
|
||||
}
|
||||
let pick = units::pick_active_l1(&l1_files, mapper, self.pick_limits())?;
|
||||
Some(WindowPick {
|
||||
class: PickClass::FileReduction,
|
||||
branch: "active:pick_l1_file_reduction",
|
||||
inputs: pick.inputs,
|
||||
found_runs: pick.units,
|
||||
})
|
||||
// LastNonNull requires its existing overlap closure. LastRow groups
|
||||
// may share key ranges but never input files; full-window tombstone
|
||||
// checks below retain markers needed by sibling groups.
|
||||
let limit = if self.merge_mode == MergeMode::LastRow {
|
||||
max_outputs
|
||||
} else {
|
||||
1
|
||||
};
|
||||
units::pick_active_l1_many(&l1_files, mapper, self.pick_limits(), limit)
|
||||
.into_iter()
|
||||
.map(|pick| WindowPick {
|
||||
class: PickClass::FileReduction,
|
||||
branch: "active:pick_l1_file_reduction",
|
||||
inputs: pick.inputs,
|
||||
found_runs: pick.units,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An inactive window should converge at a bounded rewrite cost:
|
||||
@@ -3379,6 +3394,87 @@ mod tests {
|
||||
assert!(output.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_active_l1_many_same_window_preserves_deletes() {
|
||||
let files = (0..128)
|
||||
.map(|idx| {
|
||||
new_file_handle_with_size_and_sequence(FileId::random(), 0, 999, 1, idx + 1, 100)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let windows = assign_to_windows(files.iter(), 1);
|
||||
let active = windows.keys().next().copied();
|
||||
let picker = TwcsPicker {
|
||||
trigger_file_num: 16,
|
||||
active_window_l1_merge_trigger: 8,
|
||||
inactive_window_trigger_file_num: 2,
|
||||
inactive_window_l1_merge_trigger: 8,
|
||||
time_window_seconds: Some(1),
|
||||
max_output_file_size: None,
|
||||
append_mode: false,
|
||||
merge_mode: MergeMode::LastRow,
|
||||
max_background_tasks: Some(8),
|
||||
time_range: None,
|
||||
all_windows_inactive: false,
|
||||
};
|
||||
let outputs = picker
|
||||
.build_output_with_time_range(RegionId::from_u64(1), windows, active, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(8, outputs.len());
|
||||
let mut seen = HashSet::new();
|
||||
for output in outputs {
|
||||
assert_eq!(16, output.inputs.len());
|
||||
// Sibling groups still contain old versions and deletion markers.
|
||||
assert!(!output.filter_deleted);
|
||||
for file in output.inputs {
|
||||
assert!(seen.insert(file.file_id()));
|
||||
}
|
||||
}
|
||||
assert_eq!(128, seen.len());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_active_l1_many_keeps_l0_priority_and_last_non_null() {
|
||||
let l1 = (0..128)
|
||||
.map(|idx| {
|
||||
new_file_handle_with_size_and_sequence(FileId::random(), 0, 999, 1, idx + 1, 100)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut picker = TwcsPicker {
|
||||
trigger_file_num: 2,
|
||||
active_window_l1_merge_trigger: 8,
|
||||
inactive_window_trigger_file_num: 2,
|
||||
inactive_window_l1_merge_trigger: 8,
|
||||
time_window_seconds: Some(1),
|
||||
max_output_file_size: None,
|
||||
append_mode: false,
|
||||
merge_mode: MergeMode::LastRow,
|
||||
max_background_tasks: Some(8),
|
||||
time_range: None,
|
||||
all_windows_inactive: false,
|
||||
};
|
||||
let mut mixed = l1.clone();
|
||||
mixed.extend((0..2).map(|_| {
|
||||
new_file_handle_with_size_and_sequence(FileId::random(), 0, 999, 0, 1000, 100)
|
||||
}));
|
||||
let windows = assign_to_windows(mixed.iter(), 1);
|
||||
let active = windows.keys().next().copied();
|
||||
let output = picker
|
||||
.build_output_with_time_range(RegionId::from_u64(1), windows, active, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(1, output.len());
|
||||
assert!(output[0].inputs.iter().all(|f| f.level() == 0));
|
||||
picker.merge_mode = MergeMode::LastNonNull;
|
||||
let windows = assign_to_windows(l1.iter(), 1);
|
||||
let active = windows.keys().next().copied();
|
||||
let output = picker
|
||||
.build_output_with_time_range(RegionId::from_u64(1), windows, active, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(1, output.len());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_active_window_l1_safety_trigger_is_independent_of_l0_trigger() {
|
||||
let files = (0..8)
|
||||
|
||||
@@ -175,6 +175,79 @@ fn pick_active_l1_with_budget(
|
||||
pick_reducing_interval(&mut units, l1_files, options)
|
||||
}
|
||||
|
||||
/// Picks disjoint input groups in one search for an active L1 window.
|
||||
/// The original reduction and rewrite-cost rules apply to every group. Output
|
||||
/// overlap is allowed for LastRow; tombstone filtering still uses the full
|
||||
/// original window in TwcsPicker, including the other selected groups.
|
||||
pub(crate) fn pick_active_l1_many(
|
||||
files: &[FileHandle],
|
||||
mapper: &PrimaryKeyRangeMapper,
|
||||
options: PickLimits,
|
||||
max_picks: usize,
|
||||
) -> Vec<UnitPick> {
|
||||
if max_picks == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
if max_picks == 1 {
|
||||
return pick_active_l1(files, mapper, options).into_iter().collect();
|
||||
}
|
||||
let extents = extents_of(files, mapper);
|
||||
let index = ExtentIndex::new(&extents);
|
||||
let mut units = conflict_units(files, &extents, &index, CONFLICT_GRAPH_BUDGET)
|
||||
.unwrap_or_else(|| single_file_units(files, &extents));
|
||||
split_oversized_units(&mut units, files, &extents, options.max_input_files);
|
||||
let picks = pick_reducing_intervals(&mut units, files, options, max_picks);
|
||||
if !picks.is_empty() || units.len() == files.len() {
|
||||
return picks;
|
||||
}
|
||||
// Retain the original fallback when a large peer prevents an entire unit
|
||||
// from satisfying the reduction cost, but smaller files can be merged.
|
||||
split_oversized_units(&mut units, files, &extents, 1);
|
||||
pick_reducing_intervals(&mut units, files, options, max_picks)
|
||||
}
|
||||
|
||||
fn pick_reducing_intervals(
|
||||
units: &mut [Unit],
|
||||
files: &[FileHandle],
|
||||
options: PickLimits,
|
||||
max_picks: usize,
|
||||
) -> Vec<UnitPick> {
|
||||
sort_units(units);
|
||||
let mut candidates = Vec::new();
|
||||
for_each_interval(units, &[], options.max_input_files, |range, stats| {
|
||||
let reduction = stats
|
||||
.num_files
|
||||
.saturating_sub(options.predicted_outputs(stats));
|
||||
if stats.num_files >= 2
|
||||
&& reduction > 0
|
||||
&& options.within_reduction_cost(stats.size, reduction)
|
||||
&& stats.largest_file_size <= stats.size - stats.largest_file_size
|
||||
{
|
||||
candidates.push((Reverse(reduction), stats.size, range));
|
||||
}
|
||||
});
|
||||
// Stable ordering preserves the original best pick when scores tie.
|
||||
candidates.sort_by_key(|(reduction, size, _)| (*reduction, *size));
|
||||
let mut selected = vec![false; units.len()];
|
||||
let mut picks = Vec::new();
|
||||
for (_, _, range) in candidates {
|
||||
if selected[range.clone()].iter().any(|used| *used) {
|
||||
continue;
|
||||
}
|
||||
selected[range.clone()].fill(true);
|
||||
picks.push(UnitPick {
|
||||
inputs: collect_inputs(&units[range], files),
|
||||
reduces_files: true,
|
||||
units: units.len(),
|
||||
dense_fallback: false,
|
||||
});
|
||||
if picks.len() == max_picks {
|
||||
break;
|
||||
}
|
||||
}
|
||||
picks
|
||||
}
|
||||
|
||||
/// Picks the interval of `units` that removes the most files within the
|
||||
/// rewrite budget, then rewrites the fewest bytes.
|
||||
fn pick_reducing_interval(
|
||||
@@ -1185,6 +1258,112 @@ mod tests {
|
||||
|
||||
const MAX_OUTPUT: u64 = 16;
|
||||
|
||||
fn uniform_l1_files(count: usize) -> Vec<FileHandle> {
|
||||
(0..count).map(|_| file(0, 100, b"a", b"z", 2)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_active_l1_many_owns_each_file_once() {
|
||||
let files = uniform_l1_files(128);
|
||||
let mapper = primary_key_mapper_for_test();
|
||||
let picks = pick_active_l1_many(&files, &mapper, limits(512), 8);
|
||||
assert_eq!(8, picks.len());
|
||||
let mut seen = HashSet::new();
|
||||
for pick in picks {
|
||||
assert_eq!(16, pick.inputs.len());
|
||||
assert!(pick.reduces_files);
|
||||
for file in pick.inputs {
|
||||
assert!(
|
||||
seen.insert(file.file_id().file_id()),
|
||||
"same input in two groups"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(ids(&files), seen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_active_l1_many_matches_original_first_pick_and_limit() {
|
||||
let files = uniform_l1_files(128);
|
||||
let mapper = primary_key_mapper_for_test();
|
||||
let first = pick_active_l1(&files, &mapper, limits(512)).unwrap();
|
||||
for count in [1, 2, 4, 8] {
|
||||
let picks = pick_active_l1_many(&files, &mapper, limits(512), count);
|
||||
assert_eq!(count, picks.len());
|
||||
assert_eq!(ids(&first.inputs), ids(&picks[0].inputs));
|
||||
}
|
||||
assert!(pick_active_l1_many(&files, &mapper, limits(512), 0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_active_l1_many_keeps_unmergeable_tail_and_large_peer() {
|
||||
let mapper = primary_key_mapper_for_test();
|
||||
let files = uniform_l1_files(33);
|
||||
let picks = pick_active_l1_many(&files, &mapper, limits(512), 8);
|
||||
assert_eq!(2, picks.len());
|
||||
assert_eq!(32, picks.iter().map(|p| p.inputs.len()).sum::<usize>());
|
||||
let mut files = vec![file(0, 1000, b"a", b"z", 1 << 20)];
|
||||
files.extend(uniform_l1_files(32));
|
||||
let picks = pick_active_l1_many(&files, &mapper, limits(512), 8);
|
||||
assert_eq!(2, picks.len());
|
||||
assert!(
|
||||
picks
|
||||
.iter()
|
||||
.flat_map(|p| &p.inputs)
|
||||
.all(|f| f.file_id() != files[0].file_id())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_active_l1_many_rejects_nonreducing_files() {
|
||||
let mapper = primary_key_mapper_for_test();
|
||||
let files = (0..32)
|
||||
.map(|_| file(0, 100, b"a", b"z", 1024))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(pick_active_l1_many(&files, &mapper, limits(512), 8).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_active_l1_many_random_windows_reduce_file_count() {
|
||||
let mapper = primary_key_mapper_for_test();
|
||||
let mut rng = Rng(731);
|
||||
let mut total_groups = 0;
|
||||
for _ in 0..100 {
|
||||
let mut files = oversized_window(&mut rng);
|
||||
loop {
|
||||
let handles = files.iter().map(|f| f.handle.clone()).collect::<Vec<_>>();
|
||||
let picks = pick_active_l1_many(&handles, &mapper, limits(MAX_OUTPUT), 8);
|
||||
if picks.is_empty() {
|
||||
break;
|
||||
}
|
||||
assert!(picks.len() <= 8);
|
||||
let old_count = files.len();
|
||||
let mut selected = HashSet::new();
|
||||
let mut outputs = Vec::new();
|
||||
for pick in picks {
|
||||
assert!((2..=16).contains(&pick.inputs.len()));
|
||||
let input_ids = ids(&pick.inputs);
|
||||
for id in &input_ids {
|
||||
assert!(selected.insert(*id));
|
||||
}
|
||||
let inputs = files
|
||||
.iter()
|
||||
.filter(|f| input_ids.contains(&f.handle.file_id().file_id()))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let group_outputs = merge(&inputs, &mut rng);
|
||||
assert!(group_outputs.len() < inputs.len());
|
||||
outputs.extend(group_outputs);
|
||||
total_groups += 1;
|
||||
}
|
||||
files.retain(|f| !selected.contains(&f.handle.file_id().file_id()));
|
||||
files.extend(outputs);
|
||||
assert!(files.len() < old_count);
|
||||
}
|
||||
}
|
||||
assert!(total_groups > 0);
|
||||
}
|
||||
|
||||
fn file(start: i64, end: i64, min: &[u8], max: &[u8], size: u64) -> FileHandle {
|
||||
new_file_handle_with_size_sequence_and_primary_key_range(
|
||||
FileId::random(),
|
||||
|
||||
@@ -44,6 +44,39 @@ use crate::worker::WorkerId;
|
||||
#[snafu(visibility(pub))]
|
||||
#[stack_trace_debug]
|
||||
pub enum Error {
|
||||
#[cfg(feature = "enterprise")]
|
||||
#[snafu(display("Failed to route multi-region compaction input"))]
|
||||
RouteMultiRegion {
|
||||
#[snafu(source)]
|
||||
source: PartitionError,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
#[cfg(feature = "enterprise")]
|
||||
#[snafu(display("Invalid multi-region compaction: {reason}"))]
|
||||
InvalidMultiRegionCompaction {
|
||||
reason: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
#[snafu(display("Multi-region compaction resource limit: {reason}"))]
|
||||
MultiRegionCompactionResource {
|
||||
reason: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
#[snafu(display("Multi-region compaction temporary run I/O failed"))]
|
||||
MultiRegionCompactionSpill {
|
||||
#[snafu(source)]
|
||||
error: std::io::Error,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Unexpected data type"))]
|
||||
DataTypeMismatch {
|
||||
source: datatypes::error::Error,
|
||||
@@ -1503,6 +1536,14 @@ impl ErrorExt for Error {
|
||||
use Error::*;
|
||||
|
||||
match self {
|
||||
#[cfg(feature = "enterprise")]
|
||||
RouteMultiRegion { source, .. } => source.status_code(),
|
||||
#[cfg(feature = "enterprise")]
|
||||
InvalidMultiRegionCompaction { .. } => StatusCode::InvalidArguments,
|
||||
#[cfg(feature = "enterprise")]
|
||||
MultiRegionCompactionResource { .. } => StatusCode::RuntimeResourcesExhausted,
|
||||
#[cfg(feature = "enterprise")]
|
||||
MultiRegionCompactionSpill { .. } => StatusCode::Internal,
|
||||
DataTypeMismatch { source, .. } => source.status_code(),
|
||||
OpenDal { .. } | ManifestDeltaNotFound { .. } | ReadParquet { .. } => {
|
||||
StatusCode::StorageUnavailable
|
||||
|
||||
@@ -425,6 +425,13 @@ impl LocalGcWorker {
|
||||
region: Option<MitoRegionRef>,
|
||||
tmp_ref_files: &HashSet<FileRef>,
|
||||
) -> Result<RegionGcOutcome> {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if crate::compaction::compactor::experiment::enabled(region_id) {
|
||||
return Ok(RegionGcOutcome {
|
||||
removed_files: vec![],
|
||||
extension_cleanup_failed: false,
|
||||
});
|
||||
}
|
||||
let mode = if self.full_file_listing {
|
||||
"full_listing"
|
||||
} else {
|
||||
|
||||
@@ -47,6 +47,19 @@ use crate::sst::parquet::flat_format::{
|
||||
};
|
||||
use crate::sst::parquet::format::{FIXED_POS_COLUMN_NUM, PrimaryKeyArray};
|
||||
|
||||
macro_rules! pipeline_time {
|
||||
($name:expr, $future:expr) => {{
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
{
|
||||
crate::sst::index::pipeline_profile::measure($name, $future).await
|
||||
}
|
||||
#[cfg(not(all(test, target_os = "linux")))]
|
||||
{
|
||||
$future.await
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// Checks whether interleaving the selected rows from byte columns would overflow
|
||||
/// i32 offsets. Similar to arrow-rs `interleave_bytes()`, accumulates offsets and
|
||||
/// returns an error if the capacity exceeds `i32::MAX`.
|
||||
@@ -361,6 +374,8 @@ impl BatchBuilder {
|
||||
///
|
||||
/// Returns `None` if no pending rows
|
||||
pub fn build_record_batch(&mut self) -> Result<Option<RecordBatch>> {
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
let _timing = crate::sst::index::pipeline_profile::SyncScope::new("merge_materialize");
|
||||
if self.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -796,6 +811,26 @@ impl FlatMergeIterator {
|
||||
schema: SchemaRef,
|
||||
iters: Vec<BoxedRecordBatchIterator>,
|
||||
batch_size: usize,
|
||||
) -> Result<Self> {
|
||||
Self::build(schema, iters, batch_size, |_| 0)
|
||||
}
|
||||
|
||||
/// Breaks equal row keys by input order, preserving source order across batches.
|
||||
/// Callers performing multiple merge passes must supply contiguous source intervals.
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub(crate) fn new_stable(
|
||||
schema: SchemaRef,
|
||||
iters: Vec<BoxedRecordBatchIterator>,
|
||||
batch_size: usize,
|
||||
) -> Result<Self> {
|
||||
Self::build(schema, iters, batch_size, |index| index)
|
||||
}
|
||||
|
||||
fn build(
|
||||
schema: SchemaRef,
|
||||
iters: Vec<BoxedRecordBatchIterator>,
|
||||
batch_size: usize,
|
||||
source_rank: fn(usize) -> usize,
|
||||
) -> Result<Self> {
|
||||
let mut in_progress = BatchBuilder::new(schema, iters.len(), batch_size);
|
||||
let mut nodes = Vec::with_capacity(iters.len());
|
||||
@@ -803,6 +838,7 @@ impl FlatMergeIterator {
|
||||
for (node_index, iter) in iters.into_iter().enumerate() {
|
||||
let mut node = IterNode {
|
||||
node_index,
|
||||
stable_rank: source_rank(node_index),
|
||||
iter,
|
||||
cursor: None,
|
||||
};
|
||||
@@ -943,6 +979,25 @@ impl FlatMergeReader {
|
||||
iters: Vec<BoxedRecordBatchStream>,
|
||||
batch_size: usize,
|
||||
metrics_reporter: Option<Arc<dyn MergeMetricsReport>>,
|
||||
) -> Result<Self> {
|
||||
Self::with_source_rank(schema, iters, batch_size, metrics_reporter, |_| 0).await
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub(crate) async fn new_stable(
|
||||
schema: SchemaRef,
|
||||
iters: Vec<BoxedRecordBatchStream>,
|
||||
batch_size: usize,
|
||||
) -> Result<Self> {
|
||||
Self::with_source_rank(schema, iters, batch_size, None, |n| n).await
|
||||
}
|
||||
|
||||
async fn with_source_rank(
|
||||
schema: SchemaRef,
|
||||
iters: Vec<BoxedRecordBatchStream>,
|
||||
batch_size: usize,
|
||||
metrics_reporter: Option<Arc<dyn MergeMetricsReport>>,
|
||||
rank: fn(usize) -> usize,
|
||||
) -> Result<Self> {
|
||||
let start = Instant::now();
|
||||
let metrics = MergeMetrics::default();
|
||||
@@ -952,6 +1007,7 @@ impl FlatMergeReader {
|
||||
for (node_index, iter) in iters.into_iter().enumerate() {
|
||||
let mut node = StreamNode {
|
||||
node_index,
|
||||
stable_rank: rank(node_index),
|
||||
iter,
|
||||
cursor: None,
|
||||
};
|
||||
@@ -1010,7 +1066,7 @@ impl FlatMergeReader {
|
||||
/// Converts the reader into a stream.
|
||||
pub fn into_stream(mut self) -> impl Stream<Item = Result<RecordBatch>> {
|
||||
try_stream! {
|
||||
while let Some(batch) = self.next_batch().await? {
|
||||
while let Some(batch) = pipeline_time!("merge_kernel", self.next_batch())? {
|
||||
yield batch;
|
||||
}
|
||||
}
|
||||
@@ -1105,6 +1161,8 @@ impl Drop for FlatMergeReader {
|
||||
struct GenericNode<T> {
|
||||
/// Index of the node.
|
||||
node_index: usize,
|
||||
/// Optional source-order tie breaker; zero retains the original comparison.
|
||||
stable_rank: usize,
|
||||
/// Iterator of this `Node`.
|
||||
iter: T,
|
||||
/// Current batch to be read. The node should ensure the batch is not empty (The
|
||||
@@ -1140,7 +1198,7 @@ impl<T> NodeCmp for GenericNode<T> {
|
||||
|
||||
impl<T> PartialEq for GenericNode<T> {
|
||||
fn eq(&self, other: &GenericNode<T>) -> bool {
|
||||
self.cursor == other.cursor
|
||||
self.cursor == other.cursor && self.stable_rank == other.stable_rank
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1156,7 +1214,10 @@ impl<T> Ord for GenericNode<T> {
|
||||
fn cmp(&self, other: &GenericNode<T>) -> Ordering {
|
||||
// The std binary heap is a max heap, but we want the nodes are ordered in
|
||||
// ascend order, so we compare the nodes in reverse order.
|
||||
other.cursor.cmp(&self.cursor)
|
||||
other
|
||||
.cursor
|
||||
.cmp(&self.cursor)
|
||||
.then_with(|| other.stable_rank.cmp(&self.stable_rank))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1236,7 +1297,7 @@ impl GenericNode<BoxedRecordBatchStream> {
|
||||
|
||||
/// Fetches a non-empty batch from the iter.
|
||||
async fn advance_inner_iter(&mut self) -> Result<Option<RecordBatch>> {
|
||||
while let Some(batch) = self.iter.try_next().await? {
|
||||
while let Some(batch) = pipeline_time!("merge_input_next", self.iter.try_next())? {
|
||||
if batch.num_rows() > 0 {
|
||||
return Ok(Some(batch));
|
||||
}
|
||||
|
||||
@@ -35,6 +35,19 @@ use crate::read::flat_projection::FlatProjectionMapper;
|
||||
use crate::read::scan_util::PartitionMetrics;
|
||||
use crate::read::series_scan::SeriesBatch;
|
||||
|
||||
macro_rules! pipeline_time {
|
||||
($name:expr, $future:expr) => {{
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
{
|
||||
crate::sst::index::pipeline_profile::measure($name, $future).await
|
||||
}
|
||||
#[cfg(not(all(test, target_os = "linux")))]
|
||||
{
|
||||
$future.await
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// All kinds of [`Batch`]es to produce in scanner.
|
||||
pub enum ScanBatch {
|
||||
Series(SeriesBatch),
|
||||
@@ -140,11 +153,12 @@ pub(crate) fn spawn_compact_stream(
|
||||
semaphore: Option<Arc<Semaphore>>,
|
||||
) -> BoxedRecordBatchStream {
|
||||
let (sender, mut receiver) = mpsc::channel(capacity);
|
||||
let read_source = semaphore.is_some();
|
||||
let task = common_runtime::spawn_compact(async move {
|
||||
loop {
|
||||
// Releases the permit before sending, so a full channel never holds it.
|
||||
let permit = match &semaphore {
|
||||
Some(semaphore) => match semaphore.acquire().await {
|
||||
Some(semaphore) => match pipeline_time!("read_slot_wait", semaphore.acquire()) {
|
||||
Ok(permit) => Some(permit),
|
||||
Err(e) => {
|
||||
let reason = format!("Failed to acquire a stream permit: {e}");
|
||||
@@ -154,14 +168,31 @@ pub(crate) fn spawn_compact_stream(
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let next = stream.next().await;
|
||||
let next = pipeline_time!(
|
||||
if read_source {
|
||||
"read_produce"
|
||||
} else {
|
||||
"merge_produce"
|
||||
},
|
||||
stream.next()
|
||||
);
|
||||
drop(permit);
|
||||
let Some(result) = next else {
|
||||
break;
|
||||
};
|
||||
// Stops after forwarding the first error or once the consumer is gone.
|
||||
let failed = result.is_err();
|
||||
if sender.send(result).await.is_err() || failed {
|
||||
if pipeline_time!(
|
||||
if read_source {
|
||||
"read_send_wait"
|
||||
} else {
|
||||
"merge_send_wait"
|
||||
},
|
||||
sender.send(result)
|
||||
)
|
||||
.is_err()
|
||||
|| failed
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -170,7 +201,9 @@ pub(crate) fn spawn_compact_stream(
|
||||
let abort = AbortOnDrop(task.abort_handle());
|
||||
Box::pin(try_stream! {
|
||||
let _abort = abort;
|
||||
while let Some(batch) = receiver.recv().await {
|
||||
while let Some(batch) = pipeline_time!(
|
||||
if read_source { "merge_receive_input" } else { "writer_receive_merged" },
|
||||
receiver.recv()) {
|
||||
yield batch?;
|
||||
}
|
||||
task.await.context(JoinSnafu)?;
|
||||
|
||||
@@ -163,6 +163,10 @@ impl LocalFilePurger {
|
||||
|
||||
/// Deletes the file(and it's index, if any) from cache and storage.
|
||||
fn delete_file(&self, file_meta: FileMeta) {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if crate::compaction::compactor::experiment::enabled(file_meta.region_id) {
|
||||
return;
|
||||
}
|
||||
let sst_layer = self.sst_layer.clone();
|
||||
let cache_manager = self.cache_manager.clone();
|
||||
if let Err(e) = self.scheduler.schedule(Box::pin(async move {
|
||||
|
||||
@@ -12,6 +12,22 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
pub(crate) mod flat_profile;
|
||||
|
||||
macro_rules! profile_flat {
|
||||
($name:expr, $future:expr) => {{
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
{
|
||||
crate::sst::index::flat_profile::measure($name, $future).await
|
||||
}
|
||||
#[cfg(not(all(test, target_os = "linux")))]
|
||||
{
|
||||
$future.await
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
pub(crate) mod bloom_filter;
|
||||
mod column;
|
||||
#[cfg(test)]
|
||||
@@ -341,8 +357,11 @@ impl Indexer {
|
||||
|
||||
/// Updates the index with the given flat format RecordBatch.
|
||||
pub async fn update_flat(&mut self, batch: &RecordBatch) {
|
||||
self.do_update_flat(batch).await;
|
||||
profile_flat!("update_flat", self.do_update_flat(batch));
|
||||
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
flat_profile::sync("flush_mem_metrics", || self.flush_mem_metrics());
|
||||
#[cfg(not(all(test, target_os = "linux")))]
|
||||
self.flush_mem_metrics();
|
||||
}
|
||||
|
||||
@@ -3071,3 +3090,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
pub(crate) mod pipeline_profile;
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
//! Linux test-only timing. No changes to production index policy or scheduling.
|
||||
//! CPU is measured around each poll, so migration between polls is safe.
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::{Future, poll_fn};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
static ENABLED: AtomicBool = AtomicBool::new(false);
|
||||
static DATA: Mutex<BTreeMap<&'static str, Stage>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
#[derive(Default, Serialize)]
|
||||
struct Stage {
|
||||
calls: u64,
|
||||
polls: u64,
|
||||
pending_polls: u64,
|
||||
elapsed_ns: u64,
|
||||
poll_wall_ns: u64,
|
||||
thread_cpu_ns: u64,
|
||||
}
|
||||
|
||||
fn cpu_ns() -> u64 {
|
||||
let mut t = libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: 0,
|
||||
};
|
||||
// SAFETY: valid writable timespec; this clock measures only the polling thread.
|
||||
assert_eq!(
|
||||
unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut t) },
|
||||
0
|
||||
);
|
||||
t.tv_sec as u64 * 1_000_000_000 + t.tv_nsec as u64
|
||||
}
|
||||
|
||||
pub(crate) fn start() {
|
||||
DATA.lock().unwrap().clear();
|
||||
ENABLED.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn finish() -> serde_json::Value {
|
||||
ENABLED.store(false, Ordering::Relaxed);
|
||||
serde_json::to_value(&*DATA.lock().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn record(name: &'static str, value: Stage) {
|
||||
let mut data = DATA.lock().unwrap();
|
||||
let s = data.entry(name).or_default();
|
||||
s.calls += 1;
|
||||
s.polls += value.polls;
|
||||
s.pending_polls += value.pending_polls;
|
||||
s.elapsed_ns += value.elapsed_ns;
|
||||
s.poll_wall_ns += value.poll_wall_ns;
|
||||
s.thread_cpu_ns += value.thread_cpu_ns;
|
||||
}
|
||||
|
||||
pub(crate) async fn measure<F: Future>(name: &'static str, future: F) -> F::Output {
|
||||
if !ENABLED.load(Ordering::Relaxed) {
|
||||
return future.await;
|
||||
}
|
||||
let mut future = std::pin::pin!(future);
|
||||
let start = Instant::now();
|
||||
let mut s = Stage::default();
|
||||
let result = poll_fn(|cx| {
|
||||
let wall = Instant::now();
|
||||
let cpu = cpu_ns();
|
||||
let result = future.as_mut().poll(cx);
|
||||
s.thread_cpu_ns += cpu_ns() - cpu;
|
||||
s.poll_wall_ns += wall.elapsed().as_nanos() as u64;
|
||||
s.polls += 1;
|
||||
s.pending_polls += u64::from(result.is_pending());
|
||||
result
|
||||
})
|
||||
.await;
|
||||
s.elapsed_ns = start.elapsed().as_nanos() as u64;
|
||||
record(name, s);
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn sync<T>(name: &'static str, f: impl FnOnce() -> T) -> T {
|
||||
if !ENABLED.load(Ordering::Relaxed) {
|
||||
return f();
|
||||
}
|
||||
let start = Instant::now();
|
||||
let cpu = cpu_ns();
|
||||
let result = f();
|
||||
let cpu = cpu_ns() - cpu;
|
||||
let elapsed = start.elapsed().as_nanos() as u64;
|
||||
record(
|
||||
name,
|
||||
Stage {
|
||||
polls: 1,
|
||||
elapsed_ns: elapsed,
|
||||
poll_wall_ns: elapsed,
|
||||
thread_cpu_ns: cpu,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_time_is_not_thread_cpu() {
|
||||
start();
|
||||
measure(
|
||||
"sleep",
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)),
|
||||
)
|
||||
.await;
|
||||
let result = finish();
|
||||
let s = &result["sleep"];
|
||||
assert!(s["pending_polls"].as_u64().unwrap() > 0);
|
||||
assert!(s["elapsed_ns"].as_u64().unwrap() > s["poll_wall_ns"].as_u64().unwrap());
|
||||
}
|
||||
@@ -154,7 +154,7 @@ impl Indexer {
|
||||
return true;
|
||||
};
|
||||
|
||||
let Err(err) = creator.update_flat(batch).await else {
|
||||
let Err(err) = profile_flat!("inverted", creator.update_flat(batch)) else {
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -179,7 +179,7 @@ impl Indexer {
|
||||
return true;
|
||||
};
|
||||
|
||||
let Err(err) = creator.update_flat(batch).await else {
|
||||
let Err(err) = profile_flat!("fulltext", creator.update_flat(batch)) else {
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -204,7 +204,7 @@ impl Indexer {
|
||||
return true;
|
||||
};
|
||||
|
||||
let Err(err) = creator.update_flat(batch).await else {
|
||||
let Err(err) = profile_flat!("bloom", creator.update_flat(batch)) else {
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
@@ -239,9 +239,7 @@ impl InvertedIndexer {
|
||||
.index_creator
|
||||
.push_with_name_n(target_key, value, count)
|
||||
{
|
||||
self.index_creator
|
||||
.spill()
|
||||
.await
|
||||
profile_flat!("inverted_spill", self.index_creator.spill())
|
||||
.context(PushIndexValueSnafu)?;
|
||||
}
|
||||
}
|
||||
@@ -263,9 +261,7 @@ impl InvertedIndexer {
|
||||
.index_creator
|
||||
.push_with_name_n(target_key, value, count)
|
||||
{
|
||||
self.index_creator
|
||||
.spill()
|
||||
.await
|
||||
profile_flat!("inverted_spill", self.index_creator.spill())
|
||||
.context(PushIndexValueSnafu)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed 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.
|
||||
|
||||
//! Linux test-only pipeline timers. Parent/child and parallel durations overlap.
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::{Future, poll_fn};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
static ENABLED: AtomicBool = AtomicBool::new(false);
|
||||
static DATA: Mutex<BTreeMap<&'static str, Stage>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
#[derive(Default, Serialize)]
|
||||
struct Stage {
|
||||
calls: u64,
|
||||
polls: u64,
|
||||
pending_polls: u64,
|
||||
elapsed_ns: u64,
|
||||
poll_wall_ns: u64,
|
||||
thread_cpu_ns: u64,
|
||||
max_elapsed_ns: u64,
|
||||
active: u64,
|
||||
peak_active: u64,
|
||||
}
|
||||
|
||||
fn cpu_ns() -> u64 {
|
||||
let mut t = libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: 0,
|
||||
};
|
||||
// SAFETY: valid writable timespec, sampled on the current polling thread.
|
||||
assert_eq!(
|
||||
unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut t) },
|
||||
0
|
||||
);
|
||||
t.tv_sec as u64 * 1_000_000_000 + t.tv_nsec as u64
|
||||
}
|
||||
|
||||
pub(crate) fn start(enabled: bool) {
|
||||
DATA.lock().unwrap().clear();
|
||||
ENABLED.store(enabled, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn finish() -> serde_json::Value {
|
||||
ENABLED.store(false, Ordering::Relaxed);
|
||||
serde_json::to_value(&*DATA.lock().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn enter(name: &'static str) {
|
||||
let mut data = DATA.lock().unwrap();
|
||||
let s = data.entry(name).or_default();
|
||||
s.active += 1;
|
||||
s.peak_active = s.peak_active.max(s.active);
|
||||
}
|
||||
|
||||
fn record(name: &'static str, v: Stage, leave: bool) {
|
||||
let mut data = DATA.lock().unwrap();
|
||||
let s = data.entry(name).or_default();
|
||||
s.calls += 1;
|
||||
s.polls += v.polls;
|
||||
s.pending_polls += v.pending_polls;
|
||||
s.elapsed_ns += v.elapsed_ns;
|
||||
s.poll_wall_ns += v.poll_wall_ns;
|
||||
s.thread_cpu_ns += v.thread_cpu_ns;
|
||||
s.max_elapsed_ns = s.max_elapsed_ns.max(v.elapsed_ns);
|
||||
if leave {
|
||||
s.active -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn measure<F: Future>(name: &'static str, future: F) -> F::Output {
|
||||
if !ENABLED.load(Ordering::Relaxed) {
|
||||
return future.await;
|
||||
}
|
||||
let mut future = std::pin::pin!(future);
|
||||
enter(name);
|
||||
let start = Instant::now();
|
||||
let mut v = Stage::default();
|
||||
let result = poll_fn(|cx| {
|
||||
let wall = Instant::now();
|
||||
let cpu = cpu_ns();
|
||||
let result = future.as_mut().poll(cx);
|
||||
v.thread_cpu_ns += cpu_ns() - cpu;
|
||||
v.poll_wall_ns += wall.elapsed().as_nanos() as u64;
|
||||
v.polls += 1;
|
||||
v.pending_polls += u64::from(result.is_pending());
|
||||
result
|
||||
})
|
||||
.await;
|
||||
v.elapsed_ns = start.elapsed().as_nanos() as u64;
|
||||
record(name, v, true);
|
||||
result
|
||||
}
|
||||
|
||||
/// Only use within synchronous code; never retain across `.await` or migrate threads.
|
||||
pub(crate) struct SyncScope(Option<(&'static str, Instant, u64)>);
|
||||
|
||||
impl SyncScope {
|
||||
pub(crate) fn new(name: &'static str) -> Self {
|
||||
if ENABLED.load(Ordering::Relaxed) {
|
||||
enter(name);
|
||||
Self(Some((name, Instant::now(), cpu_ns())))
|
||||
} else {
|
||||
Self(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SyncScope {
|
||||
fn drop(&mut self) {
|
||||
if let Some((name, wall, cpu)) = self.0 {
|
||||
let cpu = cpu_ns() - cpu;
|
||||
let elapsed = wall.elapsed().as_nanos() as u64;
|
||||
record(
|
||||
name,
|
||||
Stage {
|
||||
polls: 1,
|
||||
elapsed_ns: elapsed,
|
||||
poll_wall_ns: elapsed,
|
||||
thread_cpu_ns: cpu,
|
||||
..Default::default()
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn queue_wait(name: &'static str, duration: Duration) {
|
||||
if ENABLED.load(Ordering::Relaxed) {
|
||||
record(
|
||||
name,
|
||||
Stage {
|
||||
elapsed_ns: duration.as_nanos() as u64,
|
||||
..Default::default()
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn field_stage(field: usize) -> &'static str {
|
||||
match field {
|
||||
0 => "encode_field_0",
|
||||
1 => "encode_field_1",
|
||||
2 => "encode_field_2",
|
||||
3 => "encode_field_3",
|
||||
4 => "encode_field_4",
|
||||
_ => "encode_field_other",
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn distinguishes_pending_from_cpu() {
|
||||
start(true);
|
||||
measure("test_wait", tokio::time::sleep(Duration::from_millis(20))).await;
|
||||
{
|
||||
let _scope = SyncScope::new("test_sync");
|
||||
std::hint::black_box(42);
|
||||
}
|
||||
let v = finish();
|
||||
assert!(v["test_wait"]["pending_polls"].as_u64().unwrap() > 0);
|
||||
assert!(
|
||||
v["test_wait"]["elapsed_ns"].as_u64().unwrap()
|
||||
> v["test_wait"]["poll_wall_ns"].as_u64().unwrap()
|
||||
);
|
||||
assert_eq!(v["test_sync"]["calls"], 1);
|
||||
assert_eq!(v["test_sync"]["active"], 0);
|
||||
}
|
||||
@@ -32,6 +32,19 @@ use parquet::file::metadata::ParquetMetaData;
|
||||
use parquet::file::properties::WriterProperties;
|
||||
use parquet::file::writer::SerializedFileWriter;
|
||||
|
||||
macro_rules! pipeline_time {
|
||||
($name:expr, $future:expr) => {{
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
{
|
||||
crate::sst::index::pipeline_profile::measure($name, $future).await
|
||||
}
|
||||
#[cfg(not(all(test, target_os = "linux")))]
|
||||
{
|
||||
$future.await
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// Runtime whose blocking pool encodes the columns of a writer.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum EncodeRuntime {
|
||||
@@ -209,8 +222,19 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
|
||||
.map(|fields| {
|
||||
let batches = batches.clone();
|
||||
let schema = self.arrow_schema.clone();
|
||||
self.runtime
|
||||
.spawn(move || encode_fields(&schema, &batches, fields))
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
let submitted = Instant::now();
|
||||
self.runtime.spawn(move || {
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
crate::sst::index::pipeline_profile::queue_wait(
|
||||
"encode_queue_wait",
|
||||
submitted.elapsed(),
|
||||
);
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
let _timing =
|
||||
crate::sst::index::pipeline_profile::SyncScope::new("encode_task");
|
||||
encode_fields(&schema, &batches, fields)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(())
|
||||
@@ -224,8 +248,7 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
|
||||
let mut chunks = Vec::with_capacity(self.leaf_fields.len());
|
||||
let mut tasks = mem::take(&mut self.encoding).into_iter();
|
||||
while let Some(task) = tasks.next() {
|
||||
let encoded = task
|
||||
.await
|
||||
let encoded = pipeline_time!("encode_join_wait", task)
|
||||
.map_err(|e| ParquetError::External(Box::new(e)))
|
||||
.and_then(|encoded| encoded);
|
||||
let (task_chunks, costs) = match encoded {
|
||||
@@ -240,12 +263,17 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
|
||||
self.field_costs[field] = cost;
|
||||
}
|
||||
}
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
let assembly_timing =
|
||||
crate::sst::index::pipeline_profile::SyncScope::new("encode_assemble");
|
||||
chunks.sort_unstable_by_key(|(leaf, _)| *leaf);
|
||||
let mut row_group = self.file_writer.next_row_group()?;
|
||||
for (_, chunk) in chunks {
|
||||
chunk.append_to_row_group(&mut row_group)?;
|
||||
}
|
||||
row_group.close()?;
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
drop(assembly_timing);
|
||||
self.write_buffered_bytes().await
|
||||
}
|
||||
|
||||
@@ -255,7 +283,10 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
|
||||
if bytes.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.async_writer.write(Bytes::from(bytes)).await
|
||||
pipeline_time!(
|
||||
"sst_output_write",
|
||||
self.async_writer.write(Bytes::from(bytes))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,6 +341,10 @@ fn encode_fields(
|
||||
let mut chunks = Vec::new();
|
||||
let mut costs = Vec::with_capacity(fields.len());
|
||||
for (field, mut writers) in fields {
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
let _timing = crate::sst::index::pipeline_profile::SyncScope::new(
|
||||
crate::sst::index::pipeline_profile::field_stage(field),
|
||||
);
|
||||
let start = Instant::now();
|
||||
for batch in batches {
|
||||
let leaves = compute_leaves(schema.field(field), batch.column(field))?;
|
||||
|
||||
@@ -2453,6 +2453,20 @@ impl ParquetReader {
|
||||
pub fn parquet_metadata(&self) -> Arc<ParquetMetaData> {
|
||||
self.context.reader_builder().parquet_meta.clone()
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub(crate) fn fetched_store_page_bytes(&self) -> Result<u64> {
|
||||
self.fetch_metrics
|
||||
.data
|
||||
.lock()
|
||||
.map(|m| m.page_size_to_fetch_store)
|
||||
.map_err(|_| {
|
||||
crate::error::UnexpectedSnafu {
|
||||
reason: "Source fetch metrics lock poisoned",
|
||||
}
|
||||
.build()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Reader to read a row group of a parquet file in flat format, returning RecordBatch.
|
||||
|
||||
@@ -214,6 +214,13 @@ pub struct ParquetWriter<'a, F: WriterFactory, I: IndexerBuilder, P: FilePathPro
|
||||
file_cleaner: Option<TempFileCleaner>,
|
||||
/// Write metrics
|
||||
metrics: &'a mut Metrics,
|
||||
write_guard: Option<Arc<dyn SstWriteGuard>>,
|
||||
}
|
||||
|
||||
/// Registers durable ownership before either an SST or its index is published to storage.
|
||||
#[async_trait::async_trait]
|
||||
pub trait SstWriteGuard: Send + Sync {
|
||||
async fn before_create(&self, file_id: RegionFileId) -> Result<()>;
|
||||
}
|
||||
|
||||
pub trait WriterFactory {
|
||||
@@ -227,6 +234,7 @@ pub trait WriterFactory {
|
||||
|
||||
pub struct ObjectStoreWriterFactory {
|
||||
object_store: ObjectStore,
|
||||
concurrency: usize,
|
||||
}
|
||||
|
||||
impl WriterFactory for ObjectStoreWriterFactory {
|
||||
@@ -236,7 +244,7 @@ impl WriterFactory for ObjectStoreWriterFactory {
|
||||
self.object_store
|
||||
.writer_with(file_path)
|
||||
.chunk(write_buffer_size)
|
||||
.concurrent(DEFAULT_WRITE_CONCURRENCY)
|
||||
.concurrent(self.concurrency)
|
||||
.await
|
||||
.map(|v| v.into_futures_async_write().compat_write())
|
||||
.context(OpenDalSnafu)
|
||||
@@ -248,6 +256,11 @@ where
|
||||
P: FilePathProvider,
|
||||
I: IndexerBuilder,
|
||||
{
|
||||
pub(crate) fn with_write_concurrency(mut self, concurrency: usize) -> Self {
|
||||
self.writer_factory.concurrency = concurrency;
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn new_with_object_store(
|
||||
object_store: ObjectStore,
|
||||
metadata: RegionMetadataRef,
|
||||
@@ -257,7 +270,10 @@ where
|
||||
metrics: &'a mut Metrics,
|
||||
) -> ParquetWriter<'a, ObjectStoreWriterFactory, I, P> {
|
||||
ParquetWriter::new(
|
||||
ObjectStoreWriterFactory { object_store },
|
||||
ObjectStoreWriterFactory {
|
||||
object_store,
|
||||
concurrency: DEFAULT_WRITE_CONCURRENCY,
|
||||
},
|
||||
metadata,
|
||||
index_config,
|
||||
indexer_builder,
|
||||
@@ -289,9 +305,6 @@ where
|
||||
metrics: &'a mut Metrics,
|
||||
) -> ParquetWriter<'a, F, I, P> {
|
||||
let init_file = FileId::random();
|
||||
let indexer = indexer_builder
|
||||
.build(RegionFileId::new(metadata.region_id, init_file), 0, None)
|
||||
.await;
|
||||
|
||||
ParquetWriter {
|
||||
path_provider,
|
||||
@@ -301,13 +314,20 @@ where
|
||||
metadata,
|
||||
index_config,
|
||||
indexer_builder,
|
||||
current_indexer: Some(indexer),
|
||||
// Build lazily with the actual row-group size, after the write guard.
|
||||
current_indexer: None,
|
||||
bytes_written: Arc::new(AtomicUsize::new(0)),
|
||||
file_cleaner: None,
|
||||
metrics,
|
||||
write_guard: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_write_guard(mut self, guard: Option<Arc<dyn SstWriteGuard>>) -> Self {
|
||||
self.write_guard = guard;
|
||||
self
|
||||
}
|
||||
|
||||
/// Finishes current SST file and index file.
|
||||
async fn finish_current_file(
|
||||
&mut self,
|
||||
@@ -601,6 +621,14 @@ where
|
||||
self.metadata.region_id,
|
||||
self.current_file,
|
||||
));
|
||||
if let Some(guard) = &self.write_guard {
|
||||
guard
|
||||
.before_create(RegionFileId::new(
|
||||
self.metadata.region_id,
|
||||
self.current_file,
|
||||
))
|
||||
.await?;
|
||||
}
|
||||
let writer = SizeAwareWriter::new(
|
||||
self.writer_factory
|
||||
.create(&sst_file_path, opts.write_buffer_size.as_bytes() as usize)
|
||||
|
||||
@@ -59,6 +59,17 @@ impl SstVersion {
|
||||
self.levels.as_ref()
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub(crate) fn without_shared_l0(&self) -> Self {
|
||||
let mut filtered = self.clone();
|
||||
for level in Arc::make_mut(&mut filtered.levels) {
|
||||
level
|
||||
.files
|
||||
.retain(|_, f| !crate::compaction::compactor::experiment::is_shared(f.meta_ref()));
|
||||
}
|
||||
filtered
|
||||
}
|
||||
|
||||
/// Returns the current handle matching the selected file's identity in its immutable level.
|
||||
pub(crate) fn file_for_compaction(&self, selected: &FileHandle) -> Option<&FileHandle> {
|
||||
let current = self
|
||||
|
||||
@@ -686,6 +686,10 @@ async fn edit_region(
|
||||
&& preload_sst_cache
|
||||
{
|
||||
for file_meta in &edit.files_to_add {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if crate::compaction::compactor::experiment::enabled(region_id) {
|
||||
continue;
|
||||
}
|
||||
let write_cache = write_cache.clone();
|
||||
let layer = region.access_layer.clone();
|
||||
let listener = listener.clone();
|
||||
|
||||
Reference in New Issue
Block a user