leaves12138 commented on code in PR #307: URL: https://github.com/apache/paimon-rust/pull/307#discussion_r3556692462
########## crates/paimon/src/table/partition_stat.rs: ########## @@ -0,0 +1,174 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Per-partition statistics computed by scanning the latest snapshot's manifest entries. +//! +//! Mirrors what Java Paimon exposes via the `$partitions` system table for runtime introspection. + +use std::collections::HashMap; + +use crate::io::FileIO; +use crate::spec::{ + avro::from_avro_bytes_fast, BinaryRow, CoreOptions, FileKind, ManifestEntry, ManifestFileMeta, + PartitionComputer, Snapshot, +}; +use crate::table::SnapshotManager; +use crate::table::Table; + +const MANIFEST_DIR: &str = "manifest"; + +/// Per-partition aggregated statistics. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PartitionStat { + /// Partition key/value mapping (e.g. `{"dt": "2024-01-01", "hr": "10"}`). + pub partition: HashMap<String, String>, + /// Net record count (added rows minus deleted rows) across all live data files. + pub record_count: i64, + /// Net data file count (additions minus deletions). + pub file_count: u64, + /// Net total bytes for live data files. + pub total_size_bytes: u64, +} + +#[derive(Default)] +struct Accum { + record_count: i64, + file_count: i64, + total_size_bytes: i64, +} + +impl Table { + /// Compute per-partition statistics from the latest snapshot. + /// + /// **Warning:** This method reads all manifest lists and entries from the latest snapshot. + /// For tables with a large number of manifests, this operation can be expensive. + /// + /// Returns an empty Vec when the table has no snapshots yet. + pub async fn partition_stats(&self) -> crate::Result<Vec<PartitionStat>> { + let sm = SnapshotManager::new(self.file_io().clone(), self.location().to_string()); + let snapshot = match sm.get_latest_snapshot().await? { + Some(s) => s, + None => return Ok(Vec::new()), + }; + + let entries = read_all_manifest_entries(self.file_io(), self.location(), &snapshot).await?; + + let schema = self.schema(); + let core = CoreOptions::new(schema.options()); + let computer = PartitionComputer::new( + schema.partition_keys(), + schema.fields(), + core.partition_default_name(), + core.legacy_partition_name(), + )?; + + aggregate_partition_stats(&entries, &computer) + } + + /// List all partition values present in the latest snapshot. + /// + /// **Warning:** This method computes partition statistics which reads all manifest lists + /// and entries. For large tables, this operation can be expensive. + /// + /// Returns an empty Vec when the table has no snapshots yet. + pub async fn list_partitions(&self) -> crate::Result<Vec<HashMap<String, String>>> { + Ok(self + .partition_stats() + .await? + .into_iter() + .map(|s| s.partition) + .collect()) + } +} + +async fn read_manifest_list( + file_io: &FileIO, + table_path: &str, + list_name: &str, +) -> crate::Result<Vec<ManifestFileMeta>> { + if list_name.is_empty() { + return Ok(Vec::new()); + } + let path = format!( + "{}/{}/{}", + table_path.trim_end_matches('/'), + MANIFEST_DIR, + list_name + ); + let input = file_io.new_input(&path)?; + let bytes = input.read().await?; + from_avro_bytes_fast::<ManifestFileMeta>(&bytes) +} + +async fn read_all_manifest_entries( + file_io: &FileIO, + table_path: &str, + snapshot: &Snapshot, +) -> crate::Result<Vec<ManifestEntry>> { + let mut metas = read_manifest_list(file_io, table_path, snapshot.base_manifest_list()).await?; + metas.extend(read_manifest_list(file_io, table_path, snapshot.delta_manifest_list()).await?); + + let manifest_dir = format!("{}/{}", table_path.trim_end_matches('/'), MANIFEST_DIR); + let mut all_entries = Vec::new(); + for meta in metas { + let path = format!("{}/{}", manifest_dir, meta.file_name()); + let input = file_io.new_input(&path)?; + let bytes = input.read().await?; + let entries = from_avro_bytes_fast::<ManifestEntry>(&bytes)?; + all_entries.extend(entries); + } + Ok(all_entries) +} + +fn aggregate_partition_stats( + entries: &[ManifestEntry], + computer: &PartitionComputer, +) -> crate::Result<Vec<PartitionStat>> { + let mut grouped: HashMap<Vec<u8>, Accum> = HashMap::new(); Review Comment: This still groups raw manifest entries without calling `merge_active_entries`, and it still uses `HashMap`. The new overwrite test only exercises a simple ADD/DELETE pair where signed sums happen to work; duplicate ADD entries present across base/delta manifests remain double-counted, and return order remains randomized between processes. Please reuse the live-entry semantics from `list_partitions_from_file_system` (`merge_active_entries` followed by `BTreeMap` aggregation) and add a duplicate-entry regression. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
