This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/hudi-rs.git


The following commit(s) were added to refs/heads/main by this push:
     new 6f4a8a49 perf(core): build record index entries in the parallel write 
path (#1094)
6f4a8a49 is described below

commit 6f4a8a492d3a8fa37a19424add46c654de309188
Author: Y Ethan Guo <[email protected]>
AuthorDate: Sat Dec 5 10:59:16 2026 -0800

    perf(core): build record index entries in the parallel write path (#1094)
    
    * perf(core): build record index entries in the parallel write path
    
    A bulk load with the record index built one RecordIndexEntry per row on
    the calling thread (three String clones each), routed every key to its
    shard serially, and then encoded the same Avro payload once per key.
    
    Append now hands the metadata writer the record keys of each base file
    as one group, moving them instead of cloning. update_record_index routes
    keys to shards on the blocking pool, a contiguous slice of groups per
    task, and encodes each location's payload once; a shard's HFile is
    written from its sorted keys and the shared payloads. Generic entries
    from the other writers are grouped into runs of consecutive keys at one
    location and take the same path.
    
    The record index HFile content is byte-identical to before, and the log
    block headers are the same: keys keep their input order within a shard,
    so the stable sort orders a key written to two files the same way. A new
    test holds every shard's log blocks, HFile bytes included and headers
    compared as a map, to the per-entry encoding for generic entries and for
    grouped inserts routed by one and by several tasks; another routes runs
    over several tasks directly, independent of the host's parallelism.
    
    * refactor(core): assert record index puts come through one carrier
---
 crates/core/src/hfile/writer.rs             |  19 +-
 crates/core/src/metadata/table/encode.rs    |  29 +-
 crates/core/src/write/append.rs             |  29 +-
 crates/core/src/write/metadata.rs           | 519 +++++++++++++++++++++++++---
 crates/core/src/write/mod.rs                |   8 +-
 crates/core/src/write/rewrite/compaction.rs |   1 +
 crates/core/src/write/rewrite/cow.rs        |   1 +
 crates/core/src/write/rewrite/mor.rs        |   2 +
 8 files changed, 542 insertions(+), 66 deletions(-)

diff --git a/crates/core/src/hfile/writer.rs b/crates/core/src/hfile/writer.rs
index 8a55aaca..fdf59232 100644
--- a/crates/core/src/hfile/writer.rs
+++ b/crates/core/src/hfile/writer.rs
@@ -54,9 +54,24 @@ impl HFileWriter {
     ) -> Result<Vec<u8>> {
         let mut entries: Vec<&(String, Vec<u8>)> = entries.iter().collect();
         entries.sort_by(|left, right| left.0.cmp(&right.0));
+        Self::write_sorted(
+            entries
+                .into_iter()
+                .map(|(key, value)| (key.as_bytes(), value.as_slice())),
+            file_info,
+            codec,
+        )
+    }
+
+    /// Write cells already in ascending key order into a single data block.
+    pub(crate) fn write_sorted<'a>(
+        cells: impl IntoIterator<Item = (&'a [u8], &'a [u8])>,
+        file_info: BTreeMap<String, Vec<u8>>,
+        codec: CompressionCodec,
+    ) -> Result<Vec<u8>> {
         let mut builder = 
HFileBuilder::new(usize::MAX).with_compression(codec)?;
-        for (key, value) in entries {
-            builder.append(key.as_bytes(), value)?;
+        for (key, value) in cells {
+            builder.append(key, value)?;
         }
         builder.finish(file_info)
     }
diff --git a/crates/core/src/metadata/table/encode.rs 
b/crates/core/src/metadata/table/encode.rs
index 5f1981dc..7ac0c856 100644
--- a/crates/core/src/metadata/table/encode.rs
+++ b/crates/core/src/metadata/table/encode.rs
@@ -319,19 +319,32 @@ pub struct RecordIndexEntry {
 /// `recordIndexMetadata` NPEs Java's RLI reader.
 ///
 /// Written straight into Avro binary rather than through a generic `Value`
-/// tree, since the record's shape is fixed and a write encodes one entry per
-/// row. The tests hold this encoding to the generic `Value` encoding.
+/// tree, since the record's shape is fixed. The tests hold this encoding to
+/// the generic `Value` encoding.
 pub fn encode_record_index_entry(entry: &RecordIndexEntry) -> Result<Vec<u8>> {
     if entry.is_deleted {
         return Err(CoreError::MetadataTable(
             "RLI deletes must be written as delete log blocks, not null 
payloads".to_string(),
         ));
     }
-    let (high, low, file_index, file_id_str, encoding) =
-        encode_file_id_for_record_index(&entry.file_id);
+    Ok(encode_record_index_location(
+        &entry.partition_path,
+        &entry.file_id,
+        entry.instant_time_millis,
+    ))
+}
+
+/// The record-index payload for a key at this location. The record key
+/// lives on the HFile key only, so every key at one location shares it.
+pub(crate) fn encode_record_index_location(
+    partition_path: &str,
+    file_id: &str,
+    instant_time_millis: i64,
+) -> Vec<u8> {
+    let (high, low, file_index, file_id_str, encoding) = 
encode_file_id_for_record_index(file_id);
     // Field order and union branches follow HoodieMetadata.avsc: a union is
     // its branch index then the value, `null` encodes as nothing.
-    let mut out = Vec::with_capacity(56 + entry.partition_path.len() + 
file_id_str.len());
+    let mut out = Vec::with_capacity(56 + partition_path.len() + 
file_id_str.len());
     for _ in MetaField::field_names() {
         put_int(&mut out, 0); // _hoodie_* meta fields: null
     }
@@ -342,7 +355,7 @@ pub fn encode_record_index_entry(entry: &RecordIndexEntry) 
-> Result<Vec<u8>> {
     put_int(&mut out, 0); // ColumnStatsMetadata: null
     put_int(&mut out, 1); // recordIndexMetadata: HoodieRecordIndexInfo
     put_int(&mut out, 1);
-    put_string(&mut out, &entry.partition_path);
+    put_string(&mut out, partition_path);
     put_int(&mut out, 1);
     put_long(&mut out, high);
     put_int(&mut out, 1);
@@ -352,11 +365,11 @@ pub fn encode_record_index_entry(entry: 
&RecordIndexEntry) -> Result<Vec<u8>> {
     put_int(&mut out, 1);
     put_string(&mut out, &file_id_str);
     put_int(&mut out, 1);
-    put_long(&mut out, entry.instant_time_millis);
+    put_long(&mut out, instant_time_millis);
     put_int(&mut out, encoding);
     put_int(&mut out, 0); // position: null
     put_int(&mut out, 0); // SecondaryIndexMetadata: null
-    Ok(out)
+    out
 }
 
 /// Avro zig-zag varint for a `long`.
diff --git a/crates/core/src/write/append.rs b/crates/core/src/write/append.rs
index 823a321b..c1324a47 100644
--- a/crates/core/src/write/append.rs
+++ b/crates/core/src/write/append.rs
@@ -42,14 +42,13 @@ use crate::merge::RecordMergeStrategyValue;
 use crate::metadata::HUDI_METADATA_DIR;
 use crate::metadata::commit::{HoodieCommitMetadata, HoodieWriteStat};
 use crate::metadata::meta_field::MetaField;
-use crate::metadata::table::encode::RecordIndexEntry;
 use crate::table::Table;
 use crate::timeline::instant::{Action, Instant};
 use crate::write::WriteResult;
 use crate::write::keygen::{
     hoodie_keys_for_batch, hoodie_keys_for_batch_with_offset, 
relative_data_path,
 };
-use crate::write::metadata::is_column_stats_enabled;
+use crate::write::metadata::{RecordIndexInserts, is_column_stats_enabled};
 
 static LAST_EPOCH_MILLIS: AtomicI64 = AtomicI64::new(0);
 
@@ -112,7 +111,7 @@ pub async fn append_batches(table: &mut Table, batches: 
&[RecordBatch]) -> Resul
 
     let mut write_stats: HashMap<String, Vec<HoodieWriteStat>> = 
HashMap::new();
     let mut files_mdt = Vec::new();
-    let mut rli_entries = Vec::new();
+    let mut rli_inserts = Vec::new();
     let rli_instant_millis = crate::index::is_record_index_enabled(table)
         .then(|| crate::write::metadata::instant_millis(&table.hudi_configs, 
&request_instant));
     let mut stats_updates = Vec::new();
@@ -256,7 +255,7 @@ pub async fn append_batches(table: &mut Table, batches: 
&[RecordBatch]) -> Resul
 
     // Phase 3 (sequential): assemble outputs in plan order; clean up on error.
     let mut first_error = None;
-    for (plan, result) in chunk_plans.iter().zip(results) {
+    for (plan, result) in chunk_plans.into_iter().zip(results) {
         match result {
             Ok(output) => {
                 written_paths.push(plan.base_file_path.clone());
@@ -289,15 +288,16 @@ pub async fn append_batches(table: &mut Table, batches: 
&[RecordBatch]) -> Resul
                     output.size,
                 ));
                 if let Some(instant_time_millis) = rli_instant_millis {
-                    for key in &plan.chunk_keys {
-                        rli_entries.push(RecordIndexEntry {
-                            record_key: key.record_key.clone(),
-                            partition_path: plan.partition_path.clone(),
-                            file_id: plan.file_id.clone(),
-                            instant_time_millis,
-                            is_deleted: false,
-                        });
-                    }
+                    rli_inserts.push(RecordIndexInserts {
+                        partition_path: plan.partition_path,
+                        file_id: plan.file_id,
+                        instant_time_millis,
+                        record_keys: plan
+                            .chunk_keys
+                            .into_iter()
+                            .map(|key| key.record_key)
+                            .collect(),
+                    });
                 }
             }
             Err(error) => {
@@ -328,7 +328,8 @@ pub async fn append_batches(table: &mut Table, batches: 
&[RecordBatch]) -> Resul
                 .into_iter()
                 .map(|(partition, file_name, size)| (partition, file_name, 
size, false))
                 .collect(),
-            record_index: rli_entries,
+            record_index: Vec::new(),
+            record_index_inserts: rli_inserts,
             column_stats: stats_updates,
             replaced_paths: Vec::new(),
         },
diff --git a/crates/core/src/write/metadata.rs 
b/crates/core/src/write/metadata.rs
index c4e96a67..a6da6c7b 100644
--- a/crates/core/src/write/metadata.rs
+++ b/crates/core/src/write/metadata.rs
@@ -35,7 +35,7 @@ use crate::metadata::table::column_stats::{
 use crate::metadata::table::encode::{
     ColumnStatValue, ColumnStatsMetadata, FilesMetadataEntry, 
RecordIndexEntry, StatsIndexVersion,
     decode_column_stats_entry, encode_all_partitions, encode_column_stats, 
encode_files_record,
-    encode_partition_stats, encode_record_index_entry, 
files_metadata_avro_schema_json,
+    encode_partition_stats, encode_record_index_location, 
files_metadata_avro_schema_json,
     hoodie_metadata_schema_json, record_index_metadata_avro_schema_json,
 };
 use crate::metadata::table::hash::{column_stats_index_key, 
partition_stats_index_key};
@@ -104,12 +104,22 @@ fn encode_metadata_hfile(
     schema_json: &str,
     codec: CompressionCodec,
 ) -> Result<Vec<u8>> {
-    HFileWriter::write_with_compression(
-        entries,
-        BTreeMap::from([("schema".to_string(), 
schema_json.as_bytes().to_vec())]),
-        codec,
-    )
-    .map_err(|error| crate::error::CoreError::HFile(error.to_string()))
+    HFileWriter::write_with_compression(entries, 
metadata_hfile_info(schema_json), codec)
+        .map_err(|error| crate::error::CoreError::HFile(error.to_string()))
+}
+
+/// [`encode_metadata_hfile`] for cells already in ascending key order.
+fn encode_sorted_metadata_hfile<'a>(
+    cells: impl IntoIterator<Item = (&'a [u8], &'a [u8])>,
+    schema_json: &str,
+    codec: CompressionCodec,
+) -> Result<Vec<u8>> {
+    HFileWriter::write_sorted(cells, metadata_hfile_info(schema_json), codec)
+        .map_err(|error| crate::error::CoreError::HFile(error.to_string()))
+}
+
+fn metadata_hfile_info(schema_json: &str) -> BTreeMap<String, Vec<u8>> {
+    BTreeMap::from([("schema".to_string(), schema_json.as_bytes().to_vec())])
 }
 
 async fn write_metadata_hfile(
@@ -436,86 +446,126 @@ pub async fn update_files_partition_entries(
     }])
 }
 
-/// Append record-index put/delete entries.
+/// Record keys one write placed in a single data file, so they share one
+/// record index location.
+pub(crate) struct RecordIndexInserts {
+    pub partition_path: String,
+    pub file_id: String,
+    /// Instant time as epoch millis (Hudi RLI wire format).
+    pub instant_time_millis: i64,
+    pub record_keys: Vec<String>,
+}
+
+/// Append record-index put/delete entries and per-file `inserts`.
 ///
 /// Puts are HFile data blocks. Deletes are v3 delete log blocks — never type-5
 /// records with null `recordIndexMetadata`, which NPEs Java's RLI reader.
 ///
 /// Returns the `record_index` partition write stats for the caller's single
 /// MDT deltacommit (see [`write_metadata_commit`]). At most `max_parallelism`
-/// shards are built at once.
+/// tasks route keys, and at most `max_parallelism` shards are built at once.
 pub async fn update_record_index(
     data_storage: &Storage,
     instant: &str,
     entries: Vec<RecordIndexEntry>,
+    inserts: Vec<RecordIndexInserts>,
     max_parallelism: usize,
     codec: CompressionCodec,
 ) -> Result<Vec<HoodieWriteStat>> {
-    if entries.is_empty() {
+    if entries.is_empty() && inserts.is_empty() {
         return Ok(Vec::new());
     }
+    // `inserts` are routed after the puts in `entries`, so a key in both would
+    // resolve to its `inserts` location; no caller sends puts through both.
+    debug_assert!(
+        inserts.is_empty() || entries.iter().all(|entry| entry.is_deleted),
+        "record index puts arrive through either `entries` or `inserts`, not 
both"
+    );
     let num_groups = detect_rli_num_file_groups(data_storage).await?;
     let schema_json = record_index_metadata_avro_schema_json()?.to_string();
-    // Only the routing happens here; each shard encodes its own entries on
-    // the blocking pool below.
-    let mut puts_by_shard: HashMap<usize, Vec<RecordIndexEntry>> = 
HashMap::new();
-    let mut deletes_by_shard: HashMap<usize, Vec<(String, String)>> = 
HashMap::new();
+    let mut deletes_by_shard: Vec<Vec<(String, String)>> = vec![Vec::new(); 
num_groups];
+    // Consecutive puts at one location form one run, so its payload is
+    // encoded once rather than per key.
+    let mut runs: Vec<RecordIndexInserts> = Vec::new();
     for entry in entries {
-        let shard = map_record_key_to_file_group_index(&entry.record_key, 
num_groups);
         if entry.is_deleted {
+            let shard = map_record_key_to_file_group_index(&entry.record_key, 
num_groups);
             // DeleteRecord.partitionPath is the MDT partition (Java HoodieKey 
for RLI deletes).
-            deletes_by_shard.entry(shard).or_default().push((
+            deletes_by_shard[shard].push((
                 entry.record_key,
                 MetadataPartitionType::RecordIndex
                     .partition_name()
                     .to_string(),
             ));
-        } else {
-            puts_by_shard.entry(shard).or_default().push(entry);
+            continue;
+        }
+        match runs.last_mut() {
+            Some(run)
+                if run.instant_time_millis == entry.instant_time_millis
+                    && run.file_id == entry.file_id
+                    && run.partition_path == entry.partition_path =>
+            {
+                run.record_keys.push(entry.record_key);
+            }
+            _ => runs.push(RecordIndexInserts {
+                partition_path: entry.partition_path,
+                file_id: entry.file_id,
+                instant_time_millis: entry.instant_time_millis,
+                record_keys: vec![entry.record_key],
+            }),
         }
     }
+    runs.extend(inserts);
 
-    let shards: std::collections::BTreeSet<usize> = puts_by_shard
-        .keys()
-        .chain(deletes_by_shard.keys())
-        .copied()
-        .collect();
-    // Building a shard's blocks (sorting its keys, encoding the HFile) is
-    // CPU-only, so up to one shard per core (and no more than 
`max_parallelism`)
-    // is built on the blocking pool while finished shards are written, in 
shard
-    // order, and released.
     use futures::StreamExt;
     let parallelism = std::thread::available_parallelism()
         .map_or(4, std::num::NonZeroUsize::get)
         .min(max_parallelism)
         .max(1);
+
+    let RoutedPuts {
+        payloads,
+        mut puts_by_shard,
+    } = route_record_index_puts(runs, num_groups, parallelism).await?;
+    let payloads = std::sync::Arc::new(payloads);
+
+    let shards: Vec<usize> = (0..num_groups)
+        .filter(|&shard| !puts_by_shard[shard].is_empty() || 
!deletes_by_shard[shard].is_empty())
+        .collect();
+    // Building a shard's blocks (sorting its keys, encoding the HFile) is
+    // CPU-only, so up to one shard per core (and no more than 
`max_parallelism`)
+    // is built on the blocking pool while finished shards are written, in 
shard
+    // order, and released.
     let mut builds = futures::stream::iter(shards)
         .map(|shard| {
-            let puts = puts_by_shard.remove(&shard).unwrap_or_default();
-            let deletes = deletes_by_shard.remove(&shard).unwrap_or_default();
+            let puts = std::mem::take(&mut puts_by_shard[shard]);
+            let deletes = std::mem::take(&mut deletes_by_shard[shard]);
+            let payloads = payloads.clone();
             let schema_json = schema_json.clone();
             let instant = instant.to_string();
             tokio::task::spawn_blocking(move || -> Result<(usize, Vec<u8>, 
i64)> {
-                let puts = puts
-                    .into_iter()
-                    .map(|entry| {
-                        let bytes = encode_record_index_entry(&entry)?;
-                        Ok((entry.record_key, bytes))
-                    })
-                    .collect::<Result<Vec<(String, Vec<u8>)>>>()?;
+                let mut cells: Vec<&(usize, String)> = 
puts.iter().flatten().collect();
+                // Stable: equal keys keep write order, and readers take the 
last.
+                cells.sort_by(|left, right| left.1.cmp(&right.1));
                 let mut log_bytes = Vec::new();
                 let mut num_writes = 0i64;
-                if !puts.is_empty() {
-                    num_writes += puts.len() as i64;
-                    let hfile = encode_metadata_hfile(&puts, &schema_json, 
codec)?;
-                    log_bytes.extend(LogFileWriter::write_log_block(
+                if !cells.is_empty() {
+                    num_writes += cells.len() as i64;
+                    let hfile = encode_sorted_metadata_hfile(
+                        cells
+                            .iter()
+                            .map(|(run, key)| (key.as_bytes(), 
payloads[*run].as_slice())),
+                        &schema_json,
+                        codec,
+                    )?;
+                    log_bytes = LogFileWriter::write_log_block(
                         BlockType::HfileData,
                         HashMap::from([
                             (BlockMetadataKey::InstantTime, instant.clone()),
                             (BlockMetadataKey::Schema, schema_json),
                         ]),
                         &hfile,
-                    ));
+                    );
                 }
                 if !deletes.is_empty() {
                     num_writes += deletes.len() as i64;
@@ -555,6 +605,93 @@ pub async fn update_record_index(
     Ok(stats)
 }
 
+/// Record keys routed to one record index shard, each tagged with the index
+/// of its run's payload.
+type ShardKeys = Vec<(usize, String)>;
+
+/// Record index puts routed to shards.
+struct RoutedPuts {
+    /// Each run's record index payload, by run index.
+    payloads: Vec<Vec<u8>>,
+    /// Per shard, its keys from each routing task in task order.
+    puts_by_shard: Vec<Vec<ShardKeys>>,
+}
+
+/// Route `runs` to shards on the blocking pool, a contiguous slice of runs
+/// per task and at most `tasks` tasks. Each shard sees its keys in input
+/// order, which keeps the order of equal keys (a key written to two files)
+/// through the stable sort of a shard's keys.
+async fn route_record_index_puts(
+    runs: Vec<RecordIndexInserts>,
+    num_groups: usize,
+    tasks: usize,
+) -> Result<RoutedPuts> {
+    let total_keys: usize = runs.iter().map(|run| run.record_keys.len()).sum();
+    let keys_per_task = total_keys.div_ceil(tasks.max(1)).max(1);
+    let mut routing = Vec::new();
+    let mut task_runs = Vec::new();
+    let mut task_keys = 0;
+    let mut first_run = 0;
+    for (index, run) in runs.into_iter().enumerate() {
+        task_keys += run.record_keys.len();
+        task_runs.push(run);
+        if task_keys >= keys_per_task {
+            let batch = std::mem::take(&mut task_runs);
+            routing.push(tokio::task::spawn_blocking(move || {
+                route_record_index_runs(first_run, batch, num_groups)
+            }));
+            first_run = index + 1;
+            task_keys = 0;
+        }
+    }
+    if !task_runs.is_empty() {
+        routing.push(tokio::task::spawn_blocking(move || {
+            route_record_index_runs(first_run, task_runs, num_groups)
+        }));
+    }
+    let mut payloads = Vec::new();
+    let mut puts_by_shard: Vec<Vec<ShardKeys>> = vec![Vec::new(); num_groups];
+    for task in routing {
+        let (task_payloads, buckets) = task.await.map_err(|e| {
+            crate::error::CoreError::Write(format!("record index routing 
failed: {e}"))
+        })?;
+        payloads.extend(task_payloads);
+        for (shard, bucket) in buckets.into_iter().enumerate() {
+            if !bucket.is_empty() {
+                puts_by_shard[shard].push(bucket);
+            }
+        }
+    }
+    Ok(RoutedPuts {
+        payloads,
+        puts_by_shard,
+    })
+}
+
+/// Encode each run's record index payload and move its keys into per-shard
+/// buckets, each key tagged with its run's index among all runs (`first_run`
+/// is the index of `runs[0]`).
+fn route_record_index_runs(
+    first_run: usize,
+    runs: Vec<RecordIndexInserts>,
+    num_groups: usize,
+) -> (Vec<Vec<u8>>, Vec<ShardKeys>) {
+    let mut payloads = Vec::with_capacity(runs.len());
+    let mut buckets: Vec<ShardKeys> = vec![Vec::new(); num_groups];
+    for (offset, run) in runs.into_iter().enumerate() {
+        payloads.push(encode_record_index_location(
+            &run.partition_path,
+            &run.file_id,
+            run.instant_time_millis,
+        ));
+        for record_key in run.record_keys {
+            let shard = map_record_key_to_file_group_index(&record_key, 
num_groups);
+            buckets[shard].push((first_run + offset, record_key));
+        }
+    }
+    (payloads, buckets)
+}
+
 async fn detect_rli_num_file_groups(storage: &Storage) -> Result<usize> {
     detect_num_file_groups(
         storage,
@@ -1775,6 +1912,7 @@ pub fn epoch_millis_to_instant_in(millis: i64, timezone: 
&str) -> String {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use crate::metadata::table::encode::encode_record_index_entry;
 
     #[test]
     fn test_metadata_hfile_codec_accepts_none_and_gz_only() {
@@ -2418,4 +2556,303 @@ mod tests {
         assert!(tagged[&key("a")].is_none(), "deleted key must stay deleted");
         assert!(tagged[&key("b")].is_some());
     }
+
+    /// A log block as (block type, header, content, footer).
+    type LogBlock = (u32, BTreeMap<u32, String>, Vec<u8>, Vec<u8>);
+
+    /// The blocks of a log file, so two files compare equal whatever order
+    /// their headers were written in.
+    fn parse_log_blocks(mut bytes: &[u8]) -> Vec<LogBlock> {
+        use crate::file_group::log_file::log_format::MAGIC;
+        fn take<'a>(bytes: &mut &'a [u8], n: usize) -> &'a [u8] {
+            let (head, rest) = bytes.split_at(n);
+            *bytes = rest;
+            head
+        }
+        let u32_at = |bytes: &mut &[u8]| u32::from_be_bytes(take(bytes, 
4).try_into().unwrap());
+        let u64_at = |bytes: &mut &[u8]| u64::from_be_bytes(take(bytes, 
8).try_into().unwrap());
+        let mut blocks = Vec::new();
+        while !bytes.is_empty() {
+            assert_eq!(take(&mut bytes, MAGIC.len()), MAGIC);
+            let block_length = u64_at(&mut bytes) as usize;
+            let mut block = take(&mut bytes, block_length - 8);
+            assert_eq!(u32_at(&mut block), 1, "log format version");
+            let block_type = u32_at(&mut block);
+            let mut header = BTreeMap::new();
+            for _ in 0..u32_at(&mut block) {
+                let key = u32_at(&mut block);
+                let len = u32_at(&mut block) as usize;
+                let value = String::from_utf8(take(&mut block, 
len).to_vec()).unwrap();
+                header.insert(key, value);
+            }
+            let content_len = u64_at(&mut block) as usize;
+            let content = take(&mut block, content_len).to_vec();
+            let footer = block.to_vec();
+            assert_eq!(u64_at(&mut bytes) as usize, block_length + 
MAGIC.len());
+            blocks.push((block_type, header, content, footer));
+        }
+        blocks
+    }
+
+    /// Bulk-load inserts and generic entries write the same record index log
+    /// blocks, HFile bytes included, as encoding every entry on its own and
+    /// sorting each shard's entries, whatever the routing parallelism.
+    #[tokio::test]
+    async fn test_update_record_index_matches_per_entry_encoding() {
+        use crate::config::table::TableTypeValue;
+
+        let dir = tempfile::tempdir().unwrap();
+        let table = Table::create(dir.path().to_str().unwrap())
+            .with_table_name("t")
+            .with_table_type(TableTypeValue::MergeOnRead)
+            .with_record_key_fields(["id"])
+            .create()
+            .await
+            .unwrap();
+        let storage = table.file_system_view.storage.clone();
+        let codec = metadata_hfile_codec_for(&table).unwrap();
+
+        // Locations: UUID file ids with and without a file index, a non-UUID
+        // file id, partitioned and not, two instants.
+        let locations = [
+            (
+                "",
+                "6a2f3c1e-8b4d-4f6a-9c2e-1d3b5a7f9e0c-0",
+                1_700_000_000_000i64,
+            ),
+            (
+                "city=sf",
+                "0b9e8d7c-6a5f-4e3d-8c2b-1a0f9e8d7c6b",
+                1_700_000_000_000,
+            ),
+            ("city=sf", "not-a-uuid-file-id", 1_700_000_000_000),
+            (
+                "",
+                "6a2f3c1e-8b4d-4f6a-9c2e-1d3b5a7f9e0c-0",
+                1_700_000_123_456,
+            ),
+        ];
+        let mut entries = Vec::new();
+        for i in 0..3000usize {
+            // Runs of varying length, then alternating locations.
+            let location = if i < 2000 { i / 450 % 4 } else { i % 4 };
+            let (partition_path, file_id, instant_time_millis) = 
locations[location];
+            entries.push(RecordIndexEntry {
+                record_key: format!("key-{:05}", (i * 7919) % 3000),
+                partition_path: partition_path.to_string(),
+                file_id: file_id.to_string(),
+                instant_time_millis,
+                is_deleted: false,
+            });
+        }
+        // Every 10th key written again to another file in the same commit, so
+        // each shard holds equal keys whose order only a stable sort keeps.
+        for i in (0..3000).step_by(10) {
+            entries.push(RecordIndexEntry {
+                record_key: format!("key-{i:05}"),
+                partition_path: "city=la".to_string(),
+                file_id: "c4d5e6f7-0a1b-4c2d-8e3f-9a0b1c2d3e4f-1".to_string(),
+                instant_time_millis: 1_700_000_999_999,
+                is_deleted: false,
+            });
+        }
+        // Non-ASCII keys, and a key written to two files in one commit (its
+        // first location is 3).
+        for (record_key, location) in [("ключ", 0), ("鍵", 1), ("🔑", 2), 
("key-00042", 0)] {
+            let (partition_path, file_id, instant_time_millis) = 
locations[location];
+            entries.push(RecordIndexEntry {
+                record_key: record_key.to_string(),
+                partition_path: partition_path.to_string(),
+                file_id: file_id.to_string(),
+                instant_time_millis,
+                is_deleted: false,
+            });
+        }
+        let deletes: Vec<RecordIndexEntry> = ["gone-1", "gone-2", "key-00007"]
+            .into_iter()
+            .map(|record_key| RecordIndexEntry {
+                record_key: record_key.to_string(),
+                partition_path: String::new(),
+                file_id: String::new(),
+                instant_time_millis: 0,
+                is_deleted: true,
+            })
+            .collect();
+
+        // Reference: every entry encoded on its own, each shard's puts sorted
+        // into one HFile, then its deletes.
+        let schema_json = record_index_metadata_avro_schema_json()
+            .unwrap()
+            .to_string();
+        let expected = |instant: &str| {
+            let mut by_shard: BTreeMap<usize, Vec<u8>> = BTreeMap::new();
+            for shard in 0..DEFAULT_RLI_NUM_FILE_GROUPS {
+                let puts: Vec<(String, Vec<u8>)> = entries
+                    .iter()
+                    .filter(|e| {
+                        map_record_key_to_file_group_index(
+                            &e.record_key,
+                            DEFAULT_RLI_NUM_FILE_GROUPS,
+                        ) == shard
+                    })
+                    .map(|e| (e.record_key.clone(), 
encode_record_index_entry(e).unwrap()))
+                    .collect();
+                let shard_deletes: Vec<(String, String)> = deletes
+                    .iter()
+                    .filter(|e| {
+                        map_record_key_to_file_group_index(
+                            &e.record_key,
+                            DEFAULT_RLI_NUM_FILE_GROUPS,
+                        ) == shard
+                    })
+                    .map(|e| (e.record_key.clone(), 
"record_index".to_string()))
+                    .collect();
+                let mut log_bytes = Vec::new();
+                if !puts.is_empty() {
+                    log_bytes.extend(LogFileWriter::write_log_block(
+                        BlockType::HfileData,
+                        HashMap::from([
+                            (BlockMetadataKey::InstantTime, 
instant.to_string()),
+                            (BlockMetadataKey::Schema, schema_json.clone()),
+                        ]),
+                        &encode_metadata_hfile(&puts, &schema_json, 
codec).unwrap(),
+                    ));
+                }
+                if !shard_deletes.is_empty() {
+                    log_bytes.extend(
+                        crate::write::build_delete_log_block(instant, 
&shard_deletes, 0).unwrap(),
+                    );
+                }
+                if !log_bytes.is_empty() {
+                    by_shard.insert(shard, log_bytes);
+                }
+            }
+            by_shard
+        };
+        let written = |instant: &str, stats: &[HoodieWriteStat]| {
+            let mut by_shard = BTreeMap::new();
+            for shard in 0..DEFAULT_RLI_NUM_FILE_GROUPS {
+                let path = dir.path().join(format!(
+                    "{METADATA_BASE}/record_index/.{}_{instant}.log.1_0-0-0",
+                    record_index_file_id(shard)
+                ));
+                if let Ok(bytes) = std::fs::read(path) {
+                    by_shard.insert(shard, bytes);
+                }
+            }
+            assert_eq!(stats.len(), by_shard.len());
+            by_shard
+        };
+        let assert_same = |instant: &str, stats: &[HoodieWriteStat]| {
+            let expected = expected(instant);
+            let written = written(instant, stats);
+            assert_eq!(
+                written.keys().collect::<Vec<_>>(),
+                expected.keys().collect::<Vec<_>>()
+            );
+            for (shard, bytes) in &written {
+                assert_eq!(bytes.len(), expected[shard].len(), "shard {shard} 
size");
+                assert_eq!(
+                    parse_log_blocks(bytes),
+                    parse_log_blocks(&expected[shard]),
+                    "shard {shard} blocks"
+                );
+            }
+            let num_writes: i64 = stats.iter().filter_map(|stat| 
stat.num_writes).sum();
+            assert_eq!(num_writes as usize, entries.len() + deletes.len());
+        };
+
+        // Generic entries, puts and deletes mixed.
+        let mut mixed = entries.clone();
+        mixed.extend(deletes.iter().cloned());
+        let instant = "20240101000000001";
+        let stats = update_record_index(storage.as_ref(), instant, mixed, 
Vec::new(), 4, codec)
+            .await
+            .unwrap();
+        assert_same(instant, &stats);
+
+        // The same puts as per-file inserts, routed by one task and by 
several.
+        let mut inserts: Vec<RecordIndexInserts> = Vec::new();
+        for entry in &entries {
+            match inserts.last_mut() {
+                Some(run)
+                    if run.file_id == entry.file_id
+                        && run.partition_path == entry.partition_path
+                        && run.instant_time_millis == 
entry.instant_time_millis =>
+                {
+                    run.record_keys.push(entry.record_key.clone());
+                }
+                _ => inserts.push(RecordIndexInserts {
+                    partition_path: entry.partition_path.clone(),
+                    file_id: entry.file_id.clone(),
+                    instant_time_millis: entry.instant_time_millis,
+                    record_keys: vec![entry.record_key.clone()],
+                }),
+            }
+        }
+        for (instant, parallelism) in [("20240101000000002", 1), 
("20240101000000003", 3)] {
+            let inserts = inserts
+                .iter()
+                .map(|run| RecordIndexInserts {
+                    partition_path: run.partition_path.clone(),
+                    file_id: run.file_id.clone(),
+                    instant_time_millis: run.instant_time_millis,
+                    record_keys: run.record_keys.clone(),
+                })
+                .collect();
+            let stats = update_record_index(
+                storage.as_ref(),
+                instant,
+                deletes.clone(),
+                inserts,
+                parallelism,
+                codec,
+            )
+            .await
+            .unwrap();
+            assert_same(instant, &stats);
+        }
+    }
+
+    /// Routing over several tasks tags each key with its own run's payload
+    /// and keeps each shard's keys in input order, whatever the host's
+    /// parallelism.
+    #[tokio::test]
+    async fn test_route_record_index_puts_across_tasks() {
+        let num_groups = 4;
+        let runs: Vec<RecordIndexInserts> = (0..7)
+            .map(|run| RecordIndexInserts {
+                partition_path: format!("p{run}"),
+                file_id: format!("file-{run}"),
+                instant_time_millis: 1_700_000_000_000 + run as i64,
+                record_keys: (0..(run + 1) * 5).map(|i| 
format!("k{run}-{i}")).collect(),
+            })
+            .collect();
+        let mut expected_payloads = Vec::new();
+        let mut expected: Vec<Vec<(usize, String)>> = vec![Vec::new(); 
num_groups];
+        for (index, run) in runs.iter().enumerate() {
+            expected_payloads.push(encode_record_index_location(
+                &run.partition_path,
+                &run.file_id,
+                run.instant_time_millis,
+            ));
+            for key in &run.record_keys {
+                expected[map_record_key_to_file_group_index(key, num_groups)]
+                    .push((index, key.clone()));
+            }
+        }
+
+        let routed = route_record_index_puts(runs, num_groups, 
3).await.unwrap();
+        assert_eq!(routed.payloads, expected_payloads);
+        assert!(
+            routed.puts_by_shard.iter().any(|tasks| tasks.len() > 1),
+            "keys must come from more than one routing task"
+        );
+        let by_shard: Vec<Vec<(usize, String)>> = routed
+            .puts_by_shard
+            .into_iter()
+            .map(|tasks| tasks.into_iter().flatten().collect())
+            .collect();
+        assert_eq!(by_shard, expected);
+    }
 }
diff --git a/crates/core/src/write/mod.rs b/crates/core/src/write/mod.rs
index 1c6eb871..78f4111d 100644
--- a/crates/core/src/write/mod.rs
+++ b/crates/core/src/write/mod.rs
@@ -533,6 +533,9 @@ pub(crate) struct MetadataTableUpdates {
     /// `files` partition entries as (partition path, file name, size, 
is_deleted).
     pub files: Vec<(String, String, i64, bool)>,
     pub record_index: Vec<crate::metadata::table::encode::RecordIndexEntry>,
+    /// Record index puts grouped by the file their keys were written to. A
+    /// write sends its puts through this or through `record_index`, not both.
+    pub record_index_inserts: Vec<metadata::RecordIndexInserts>,
     pub column_stats: Vec<metadata::StatsFileUpdate>,
     /// Base files this write replaced or rewrote. The column stats update
     /// leaves them out of its partition_stats scan; they stay listed in the
@@ -686,11 +689,14 @@ pub(crate) async fn complete_write(
                     .await?,
                 );
             }
-            if crate::index::is_record_index_enabled(table) && 
!updates.record_index.is_empty() {
+            if crate::index::is_record_index_enabled(table)
+                && (!updates.record_index.is_empty() || 
!updates.record_index_inserts.is_empty())
+            {
                 let stats = metadata::update_record_index(
                     storage.as_ref(),
                     instant,
                     std::mem::take(&mut updates.record_index),
+                    std::mem::take(&mut updates.record_index_inserts),
                     write_task_parallelism(table),
                     codec,
                 )
diff --git a/crates/core/src/write/rewrite/compaction.rs 
b/crates/core/src/write/rewrite/compaction.rs
index 9bf5cc4c..0f271e5a 100644
--- a/crates/core/src/write/rewrite/compaction.rs
+++ b/crates/core/src/write/rewrite/compaction.rs
@@ -546,6 +546,7 @@ async fn execute_compaction(
             // Compaction keeps every record in its file group, so the record
             // index has nothing to learn.
             record_index: Vec::new(),
+            record_index_inserts: Vec::new(),
             column_stats: stats_updates,
             replaced_paths,
         },
diff --git a/crates/core/src/write/rewrite/cow.rs 
b/crates/core/src/write/rewrite/cow.rs
index 6fbf1e22..087066bb 100644
--- a/crates/core/src/write/rewrite/cow.rs
+++ b/crates/core/src/write/rewrite/cow.rs
@@ -310,6 +310,7 @@ pub(super) async fn finalize_rewrite_commit(
         crate::write::MetadataTableUpdates {
             files: additions,
             record_index: rli_entries,
+            record_index_inserts: Vec::new(),
             column_stats: stats_updates,
             replaced_paths: old_paths.to_vec(),
         },
diff --git a/crates/core/src/write/rewrite/mor.rs 
b/crates/core/src/write/rewrite/mor.rs
index b8792e00..11eb6650 100644
--- a/crates/core/src/write/rewrite/mor.rs
+++ b/crates/core/src/write/rewrite/mor.rs
@@ -621,6 +621,7 @@ pub(super) async fn mor_upsert_batches(
         crate::write::MetadataTableUpdates {
             files: files_mdt,
             record_index: rli_entries,
+            record_index_inserts: Vec::new(),
             column_stats: stats_updates,
             replaced_paths: Vec::new(),
         },
@@ -821,6 +822,7 @@ async fn mor_delete_copies(
         crate::write::MetadataTableUpdates {
             files: files_mdt,
             record_index,
+            record_index_inserts: Vec::new(),
             column_stats: Vec::new(),
             replaced_paths: Vec::new(),
         },

Reply via email to