kosiew commented on code in PR #26875:
URL: https://github.com/apache/datafusion/pull/26875#discussion_r4740809694


##########
datafusion/physical-plan/src/distribution_requirements.rs:
##########
@@ -366,6 +366,9 @@ fn compatible_co_partitioning_layout(
 
     match (first_partitioning, other_partitioning) {
         (Partitioning::Hash(_, _), Partitioning::Hash(_, _)) => true,
+        (Partitioning::Grouped(left), Partitioning::Grouped(right)) => {

Review Comment:
   Please test partitioned joins over genuinely bucketed FileScanConfig inputs 
through stock distribution enforcement. Assert correct results against an 
UnknownPartitioning baseline, no exchange for matching layouts, and shuffling 
for reordered groups and mixed Grouped/native Hash inputs. Set 
target_partitions above the group count.



##########
datafusion/physical-optimizer/src/ensure_requirements/enforce_distribution.rs:
##########
@@ -1932,7 +1937,12 @@ pub fn ensure_distribution_with_stats(
                     }
                 }
                 Distribution::UnspecifiedDistribution => {
-                    if policy.add_roundrobin {
+                    if policy.add_roundrobin

Review Comment:
   Could we document this policy tradeoff? Preserving grouping through 
operators such as FilterExec enables downstream join reuse, but also forgoes 
optional round-robin parallelism when no downstream join exists.



##########
datafusion/physical-expr/src/partitioning.rs:
##########
@@ -3293,3 +3426,52 @@ mod partition_count_proto_tests {
         assert_eq!(decoded_range.split_points(), split_points);
     }
 }
+
+#[cfg(all(test, feature = "proto"))]
+mod grouped_tests {
+    use super::*;
+    use crate::expressions::Column;
+    use crate::proto_test_util::{StubDecoder, StubEncoder};
+    use arrow::datatypes::{DataType, Field, Schema};
+    use datafusion_physical_expr_common::physical_expr::{
+        proto_decode::PhysicalExprDecodeCtx, 
proto_encode::PhysicalExprEncodeCtx,
+    };
+
+    #[test]
+    fn grouped_wire_identity_is_not_just_partition_count() -> Result<()> {
+        let keys: Vec<Arc<dyn PhysicalExpr>> = vec![Arc::new(Column::new("a", 
0))];
+        let grouped = GroupedPartitioning::try_new(
+            keys,
+            "test:integer-modulo:4".into(),
+            vec![vec![0], vec![2]],
+        )?;
+        let encoder = StubEncoder::ok();
+        let encoded = Partitioning::Grouped(grouped.clone())
+            .try_to_proto(&PhysicalExprEncodeCtx::new(&encoder))?;
+        let schema = Schema::new(vec![Field::new("a", DataType::Int32, 
false)]);
+        let decoder = StubDecoder::ok();
+        let decoded = Partitioning::try_from_proto(
+            &encoded,
+            &PhysicalExprDecodeCtx::new(&schema, &decoder),
+        )?
+        .unwrap();
+        let Partitioning::Grouped(decoded) = decoded else {
+            panic!("lost source grouping on the wire")
+        };
+        assert!(decoded.compatible_layout(&grouped));
+        assert_eq!(decoded.keys().len(), grouped.keys().len());

Review Comment:
   The stub codecs discard key identity. Could we add a Grouped fixture with 
two distinct keys to 
`new_file_scan_config_serde_roundtrips_all_partitioning_variants` and verify 
full grouping equality, including key identity and order?



##########
datafusion/physical-expr/src/partitioning.rs:
##########
@@ -135,13 +137,102 @@ impl Display for Partitioning {
                 write!(f, "Hash([{phy_exprs_str}], {size})")
             }
             Partitioning::Range(range) => write!(f, "{range}"),
+            Partitioning::Grouped(grouped) => write!(
+                f,
+                "Grouped({}, {:?}, {})",
+                grouped.scheme(),
+                grouped.group_ids(),
+                grouped.partition_count()
+            ),
             Partitioning::UnknownPartitioning(size) => {
                 write!(f, "UnknownPartitioning({size})")
             }
         }
     }
 }
 
+/// Source-defined grouping that keeps equal keys in the same output partition.
+///
+/// Equal schemes must identify the same key-to-group function and label 
encoding.
+/// Group IDs are unique and follow output partition order. Empty groups can
+/// retain their positions to align inputs.
+#[derive(Debug, Clone)]
+pub struct GroupedPartitioning {
+    keys: Vec<Arc<dyn PhysicalExpr>>,
+    layout: Arc<GroupLayout>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+struct GroupLayout {
+    scheme: String,
+    group_ids: Vec<Vec<u8>>,
+}
+
+impl GroupedPartitioning {
+    /// Declare a grouping with nonempty keys, scheme, and unique group IDs.
+    pub fn try_new(
+        keys: Vec<Arc<dyn PhysicalExpr>>,
+        scheme: String,
+        group_ids: Vec<Vec<u8>>,
+    ) -> Result<Self> {
+        if keys.is_empty() || scheme.is_empty() || group_ids.is_empty() {
+            return datafusion_common::plan_err!(
+                "Grouped partitioning requires keys, a semantic scheme, and 
groups"
+            );
+        }
+        let unique: std::collections::HashSet<_> = group_ids.iter().collect();
+        if unique.len() != group_ids.len() {
+            return datafusion_common::plan_err!("Grouped partition IDs must be 
unique");
+        }
+        Ok(Self {
+            keys,
+            layout: Arc::new(GroupLayout { scheme, group_ids }),
+        })
+    }
+
+    /// Expressions that define the grouping keys.
+    pub fn keys(&self) -> &[Arc<dyn PhysicalExpr>] {
+        &self.keys
+    }
+
+    /// Canonical identifier for the key-to-group function.
+    pub fn scheme(&self) -> &str {
+        &self.layout.scheme
+    }
+
+    /// Canonical group labels, in execution-partition order.
+    pub fn group_ids(&self) -> &[Vec<u8>] {
+        &self.layout.group_ids
+    }
+
+    /// Number of output partitions.
+    pub fn partition_count(&self) -> usize {
+        self.layout.group_ids.len()
+    }
+
+    /// Compare schemes and ordered group IDs. Callers check key expressions 
separately.
+    pub fn compatible_layout(&self, other: &Self) -> bool {
+        self.layout == other.layout
+    }
+
+    /// Remap key expressions without changing their arity or group layout.
+    pub fn with_keys(&self, keys: Vec<Arc<dyn PhysicalExpr>>) -> Result<Self> {

Review Comment:
   Please document that each replacement expression must preserve the original 
key value at its corresponding position. Arity alone cannot prevent reordering 
keys and invalidating an order-sensitive grouping scheme.



##########
datafusion/physical-expr/src/partitioning.rs:
##########
@@ -118,6 +118,8 @@ pub enum Partitioning {
     Hash(Vec<Arc<dyn PhysicalExpr>>, usize),
     /// Partition rows by source-declared ranges
     Range(RangePartitioning),
+    /// Source-defined key groups.
+    Grouped(GroupedPartitioning),

Review Comment:
   Please document the variant's contract: provider-defined equal-key 
colocation, distinct from native Hash, not an executable repartitioning target, 
and conservatively treated as UnknownPartitioning with the same count when 
unsupported.



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to