feat(index): align MG capacity with KLL and add indexed Puffin blob lookups (#10711)

* feat(index): configure frequent items and index Puffin footer keys

Signed-off-by: WenyXu <wenymedia@gmail.com>

* test(puffin): use fixed-size chunks in the window read benchmark

Signed-off-by: WenyXu <wenymedia@gmail.com>

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
Weny Xu
2026-11-30 05:29:01 +00:00
committed by GitHub
parent 64b636e75c
commit 9b60ed4cc0
7 changed files with 170 additions and 42 deletions
+1 -4
View File
@@ -1510,10 +1510,7 @@ mod tests {
r#"{"precision":10}"#.to_string(),
),
("greptime:kll".to_string(), r#"{"capacity":64}"#.to_string()),
(
"greptime:mg".to_string(),
r#"{"max-counters":64}"#.to_string(),
),
("greptime:mg".to_string(), r#"{"capacity":64}"#.to_string()),
]);
let column = ColumnSchema::new("v", ConcreteDataType::int64_datatype(), true)
.with_metadata(metadata.clone());
+33 -35
View File
@@ -75,20 +75,22 @@ impl Default for KllOptions {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Visit, VisitMut)]
#[serde(default, rename_all = "kebab-case")]
pub struct MgOptions {
/// Maximum number of counters, greater than zero; defaults to 64.
#[serde(deserialize_with = "deserialize_mg_max_counters")]
pub max_counters: u32,
/// Sketch capacity, a power of two from 8 through 2^30.
/// The sketch retains at most `3 * capacity / 4` distinct items.
/// The default capacity of 64 allows up to 48 items.
#[serde(deserialize_with = "deserialize_mg_capacity")]
pub capacity: u32,
}
impl MgOptions {
/// Validates the supported algorithm parameter range.
pub fn validate(&self) -> Result<()> {
ensure!(
self.max_counters > 0,
self.capacity.is_power_of_two() && (8..=1 << 30).contains(&self.capacity),
InvalidSketchOptionSnafu {
msg: format!(
"MG max_counters must be positive, got {}",
self.max_counters
"MG capacity must be a power of two between 8 and 2^30, got {}",
self.capacity
)
}
);
@@ -98,7 +100,7 @@ impl MgOptions {
impl Default for MgOptions {
fn default() -> Self {
Self { max_counters: 64 }
Self { capacity: 64 }
}
}
@@ -122,14 +124,14 @@ fn deserialize_kll_capacity<'de, D: Deserializer<'de>>(
Ok(capacity)
}
fn deserialize_mg_max_counters<'de, D: Deserializer<'de>>(
fn deserialize_mg_capacity<'de, D: Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<u32, D::Error> {
let max_counters = u32::deserialize(deserializer)?;
MgOptions { max_counters }
let capacity = u32::deserialize(deserializer)?;
MgOptions { capacity }
.validate()
.map_err(serde::de::Error::custom)?;
Ok(max_counters)
Ok(capacity)
}
#[cfg(test)]
@@ -174,8 +176,12 @@ mod tests {
.is_err()
);
}
assert!(serde_json::from_str::<MgOptions>(r#"{"max-counters":0}"#).is_err());
assert!(serde_json::from_str::<MgOptions>(r#"{"max-counters":4294967296}"#).is_err());
for size in [0u32, 7, 9, 1 << 31] {
assert!(
serde_json::from_str::<MgOptions>(&format!(r#"{{"capacity":{size}}}"#)).is_err()
);
}
assert!(serde_json::from_str::<MgOptions>(r#"{"capacity":4294967296}"#).is_err());
for capacity in [8, u16::MAX] {
let options = KllOptions { capacity };
assert_eq!(
@@ -184,10 +190,8 @@ mod tests {
.unwrap()
);
}
for capacity in [1, u32::MAX] {
let options = MgOptions {
max_counters: capacity,
};
for capacity in [8, 1 << 30] {
let options = MgOptions { capacity };
assert_eq!(
options,
serde_json::from_str::<MgOptions>(&serde_json::to_string(&options).unwrap())
@@ -212,7 +216,7 @@ mod tests {
let field = Field::try_from(&column).unwrap();
assert_eq!(field.metadata()[HLL_KEY], r#"{"precision":10}"#);
assert_eq!(field.metadata()[KLL_KEY], r#"{"capacity":64}"#);
assert_eq!(field.metadata()[MG_KEY], r#"{"max-counters":64}"#);
assert_eq!(field.metadata()[MG_KEY], r#"{"capacity":64}"#);
assert_eq!(column, ColumnSchema::try_from(&field).unwrap());
assert_eq!(
column,
@@ -225,11 +229,7 @@ mod tests {
.is_err()
);
assert!(column.set_kll_options(&KllOptions { capacity: 7 }).is_err());
assert!(
column
.set_mg_options(&MgOptions { max_counters: 0 })
.is_err()
);
assert!(column.set_mg_options(&MgOptions { capacity: 0 }).is_err());
assert_eq!(before, column);
column
.set_hll_options(&HllOptions { precision: 12 })
@@ -237,9 +237,7 @@ mod tests {
column
.set_kll_options(&KllOptions { capacity: 128 })
.unwrap();
column
.set_mg_options(&MgOptions { max_counters: 256 })
.unwrap();
column.set_mg_options(&MgOptions { capacity: 256 }).unwrap();
assert_eq!(
Some(HllOptions { precision: 12 }),
column.hll_options().unwrap()
@@ -249,7 +247,7 @@ mod tests {
column.kll_options().unwrap()
);
assert_eq!(
Some(MgOptions { max_counters: 256 }),
Some(MgOptions { capacity: 256 }),
column.mg_options().unwrap()
);
column.unset_hll_options();
@@ -259,13 +257,13 @@ mod tests {
column.kll_options().unwrap()
);
assert_eq!(
Some(MgOptions { max_counters: 256 }),
Some(MgOptions { capacity: 256 }),
column.mg_options().unwrap()
);
column.unset_kll_options();
assert_eq!(None, column.kll_options().unwrap());
assert_eq!(
Some(MgOptions { max_counters: 256 }),
Some(MgOptions { capacity: 256 }),
column.mg_options().unwrap()
);
column.unset_mg_options();
@@ -290,17 +288,17 @@ mod tests {
}
#[test]
fn test_mg_max_counters_serialization() {
let expected = MgOptions { max_counters: 128 };
fn test_mg_capacity_serialization() {
let expected = MgOptions { capacity: 128 };
assert_eq!(
expected,
serde_json::from_str::<MgOptions>(r#"{"max-counters":128}"#).unwrap()
serde_json::from_str::<MgOptions>(r#"{"capacity":128}"#).unwrap()
);
assert_eq!(
r#"{"max-counters":128}"#,
r#"{"capacity":128}"#,
serde_json::to_string(&expected).unwrap()
);
assert!(serde_json::from_str::<MgOptions>(r#"{"max-counters":0}"#).is_err());
assert!(serde_json::from_str::<MgOptions>(r#"{"capacity":0}"#).is_err());
}
#[test]
@@ -308,7 +306,7 @@ mod tests {
for (error, value) in [
(HllOptions { precision: 19 }.validate().unwrap_err(), "19"),
(KllOptions { capacity: 7 }.validate().unwrap_err(), "7"),
(MgOptions { max_counters: 0 }.validate().unwrap_err(), "0"),
(MgOptions { capacity: 0 }.validate().unwrap_err(), "0"),
] {
assert!(error.to_string().contains(value), "{error}");
}
+1 -1
View File
@@ -175,7 +175,7 @@ async fn test_engine_create_rejects_missing_sketch_provider_before_manifest() {
for (key, value) in [
(datatypes::schema::HLL_KEY, r#"{"precision":10}"#),
(datatypes::schema::KLL_KEY, r#"{"capacity":64}"#),
(datatypes::schema::MG_KEY, r#"{"max-counters":64}"#),
(datatypes::schema::MG_KEY, r#"{"capacity":64}"#),
(datatypes::schema::HLL_KEY, "invalid"),
] {
let mut request = CreateRequestBuilder::new().build();
+1 -1
View File
@@ -936,7 +936,7 @@ mod tests {
let (key, value) = match kind {
IndexType::HllIndex => (datatypes::schema::HLL_KEY, r#"{"precision":10}"#),
IndexType::KllIndex => (datatypes::schema::KLL_KEY, r#"{"capacity":64}"#),
IndexType::MgIndex => (datatypes::schema::MG_KEY, r#"{"max-counters":64}"#),
IndexType::MgIndex => (datatypes::schema::MG_KEY, r#"{"capacity":64}"#),
_ => unreachable!(),
};
schema.mut_metadata().insert(key.into(), value.into());
+41
View File
@@ -34,6 +34,17 @@ pub struct FileMetadata {
}
impl FileMetadata {
/// Builds a reusable key lookup for callers reading many blobs from this footer.
/// The index stores one position per blob and borrows every key.
pub fn index_blob_keys(&self) -> BlobKeyIndex<'_> {
let mut positions: Vec<_> = (0..self.blobs.len()).collect();
positions.sort_unstable_by_key(|&index| self.blobs[index].blob_type.as_str());
BlobKeyIndex {
metadata: self,
positions,
}
}
/// Calculates the memory usage of the file metadata in bytes.
pub fn memory_usage(&self) -> usize {
self.blobs
@@ -49,6 +60,36 @@ impl FileMetadata {
}
}
/// Sorted footer positions for repeated unique-key lookups.
pub struct BlobKeyIndex<'a> {
metadata: &'a FileMetadata,
positions: Vec<usize>,
}
impl<'a> BlobKeyIndex<'a> {
/// Returns the matching metadata. Repeated keys are ambiguous.
pub fn get(&self, key: &str) -> crate::error::Result<Option<&'a BlobMetadata>> {
let blobs = &self.metadata.blobs;
let start = self
.positions
.partition_point(|&i| blobs[i].blob_type.as_str() < key);
let Some(&i) = self.positions.get(start) else {
return Ok(None);
};
if blobs[i].blob_type != key {
return Ok(None);
}
if self
.positions
.get(start + 1)
.is_some_and(|&next| blobs[next].blob_type == key)
{
return crate::error::AmbiguousBlobSnafu { blob: key }.fail();
}
Ok(Some(&blobs[i]))
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
@@ -209,7 +209,9 @@ where
Ok(cached.clone())
}
async fn puffin_reader(&self) -> Result<PuffinFileReader<F::Reader>> {
/// Opens this immutable file for multiple raw blob reads using its footer metadata.
/// The caller handles compression when reading raw blobs.
pub async fn puffin_reader(&self) -> Result<PuffinFileReader<F::Reader>> {
let mut reader = self.puffin_file_accessor.reader(&self.handle).await?;
if let Some(file_size_hint) = self.file_size_hint {
reader.with_file_size_hint(file_size_hint);
+90
View File
@@ -655,10 +655,12 @@ async fn check_reader_local_metadata_reuse_without_global_cache(blob_count: usiz
let cold_reads = reads.swap(0, Ordering::Relaxed);
assert!(cold_reads > 0);
let index = first.index_blob_keys();
// Metadata inspection and uncompressed lookup must reuse one footer.
for column in 0..blob_count {
let key = format!("column.{column}");
let metadata = reader.blob_metadata(&key).await.unwrap().unwrap();
assert_eq!(index.get(&key).unwrap().unwrap(), &metadata);
assert_eq!(7, metadata.length);
assert_eq!(None, metadata.compression_codec);
reader.blob(&key).await.unwrap();
@@ -746,5 +748,93 @@ async fn test_blob_metadata_rejects_duplicate_keys() {
let error = reader.blob_metadata("duplicate").await.unwrap_err();
assert!(matches!(error, crate::error::Error::AmbiguousBlob { .. }));
assert!(reader.blob_metadata("missing").await.unwrap().is_none());
let footer = reader.metadata().await.unwrap();
let keys = footer.index_blob_keys();
assert!(matches!(
keys.get("duplicate"),
Err(crate::error::Error::AmbiguousBlob { .. })
));
assert!(keys.get("missing").unwrap().is_none());
check_blob(&file, "duplicate", b"first", &stager, &reader, false).await;
}
/// Reads 1024 adjacent windows from one local Puffin file. Each variant reads the same
/// payloads in the same order. Rotate the order to distribute cache warm-up effects.
#[tokio::test]
#[ignore = "many-window Puffin lookup and range-read ablation"]
#[expect(clippy::print_stdout, reason = "Benchmark emits raw timings")]
async fn benchmark_many_window_blob_reads() {
use crate::file_format::reader::AsyncReader;
use crate::puffin_manager::file_accessor::PuffinFileAccessor;
use std::time::Instant;
const WINDOWS: usize = 1024;
const SIZE: usize = 256;
let (_dir, stager) = new_bounded_stager("window_reads", 1024 * 1024).await;
let accessor = Arc::new(MockFileAccessor::new("window_reads"));
let manager = FsPuffinManager::new(stager, accessor.clone());
let file = "windows".to_string();
let mut writer = manager.writer(&file).await.unwrap();
let keys: Vec<_> = (0..WINDOWS).map(|w| format!("sketch.hll.{w}")).collect();
for (i, key) in keys.iter().enumerate() {
put_blob(key, &[i as u8; SIZE], None, &mut writer).await;
}
writer.finish().await.unwrap();
for round in 0..5 {
for variant in 0..4 {
let mode = (round + variant) % 4;
let reader = manager.reader(&file).await.unwrap();
let footer = reader.metadata().await.unwrap();
let start = Instant::now();
let mut checksum = 0_u64;
let index = (mode > 0).then(|| footer.index_blob_keys());
let raw = accessor.reader(&file).await.unwrap();
let mut shared = reader.puffin_reader().await.unwrap();
let batch = if mode == 3 { 16 } else { 1 };
for chunk in keys.chunks(batch) {
if mode == 0 {
let meta = reader.blob_metadata(&chunk[0]).await.unwrap().unwrap();
let guard = reader.blob(&chunk[0]).await.unwrap();
let blob = guard.reader().await.unwrap();
checksum += u64::from(blob.read(0..meta.length as u64).await.unwrap()[0]);
} else {
let index = index.as_ref().unwrap();
let first = index.get(&chunk[0]).unwrap().unwrap();
if mode == 1 {
let mut single = reader.puffin_reader().await.unwrap();
let blob = single.blob_reader(first).unwrap();
checksum += u64::from(blob.read(0..SIZE as u64).await.unwrap()[0]);
} else if mode == 2 {
let blob = shared.blob_reader(first).unwrap();
checksum += u64::from(blob.read(0..SIZE as u64).await.unwrap()[0]);
} else {
for (i, key) in chunk.iter().enumerate() {
let meta = index.get(key).unwrap().unwrap();
assert_eq!(meta.offset, first.offset + (i * SIZE) as i64);
assert_eq!(meta.length, SIZE as i64);
}
let offset = first.offset as u64;
let bytes = raw
.read(offset..offset + (SIZE * chunk.len()) as u64)
.await
.unwrap();
checksum += bytes
.as_chunks::<SIZE>()
.0
.iter()
.map(|b| u64::from(b[0]))
.sum::<u64>();
}
}
}
assert_eq!(
checksum,
(0..WINDOWS).map(|i| u64::from(i as u8)).sum::<u64>()
);
println!(
"round={round} mode={mode} elapsed_us={}",
start.elapsed().as_micros()
);
}
}
}