jayzhan211 commented on code in PR #27129:
URL: https://github.com/apache/datafusion/pull/27129#discussion_r4655964064


##########
datafusion/physical-plan/src/aggregates/clustered_final_stream.rs:
##########
@@ -768,4 +789,149 @@ mod tests {
         let limit = held_memory(&plan).await?;
         assert_resources_exhausted_under_limit(&plan, limit).await
     }
+
+    /// The table stays small: only the incoming batch can exceed the limit.
+    #[tokio::test]
+    async fn clustered_final_refuses_large_state_batch() -> Result<()> {
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("k", DataType::Utf8, false),
+            Field::new("v", DataType::Int64, false),
+        ]));
+        let group_by =
+            PhysicalGroupBy::new_single(vec![(col("k", &schema)?, 
"k".into())]);
+        let aggregate = Arc::new(
+            AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema)?])
+                .schema(Arc::clone(&schema))
+                .alias("sum")
+                .build()?,
+        );
+        let empty = TestMemoryExec::try_new_exec(&[vec![]], 
Arc::clone(&schema), None)?;
+        let state = AggregateExec::try_new(
+            AggregateMode::Partial,
+            group_by.clone(),
+            vec![Arc::clone(&aggregate)],
+            vec![None],
+            empty,
+            Arc::clone(&schema),
+        )?
+        .schema();
+        // 64 rows of 16 KB string keys (1 MB), like the few rows of a 
`median` state.
+        let key_str = "a".repeat(16 * 1024);
+        let keys: ArrayRef = Arc::new(StringArray::from_iter_values(
+            (0..64).map(|_| key_str.as_str()),
+        ));
+        let values: ArrayRef = Arc::new(Int64Array::from(vec![1_i64; 64]));
+        let batch = RecordBatch::try_new(Arc::clone(&state), vec![keys, 
values])?;
+        let ordering =
+            LexOrdering::new([PhysicalSortExpr::new_default(col("k", 
&state)?)]).unwrap();
+        let input = TestMemoryExec::try_new(&[vec![batch]], 
Arc::clone(&state), None)?
+            .try_with_sort_information(vec![ordering])?;
+        let plan = AggregateExec::try_new(
+            AggregateMode::Final,
+            group_by.as_final(),
+            vec![aggregate],
+            vec![None],
+            Arc::new(TestMemoryExec::update_cache(&Arc::new(input))),
+            state,
+        )?;
+        assert_eq!(plan.group_clustering_mode(), &GroupClusteringMode::Full);
+        assert_resources_exhausted_under_limit(&plan, 512 * 1024).await?;
+        assert_output_unchanged_under_limit(&plan, 4 * 1024 * 1024).await
+    }
+
+    /// Spilling the table makes room for a state batch that did not fit next 
to it.
+    #[tokio::test]
+    async fn clustered_final_spills_to_admit_large_state_batch() -> Result<()> 
{
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("k1", DataType::Int64, false),
+            Field::new("k2", DataType::Utf8, false),
+            Field::new("v", DataType::Int64, false),
+        ]));
+        let group_by = PhysicalGroupBy::new_single(vec![
+            (col("k1", &schema)?, "k1".into()),
+            (col("k2", &schema)?, "k2".into()),
+        ]);
+        let aggregate = Arc::new(
+            AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema)?])
+                .schema(Arc::clone(&schema))
+                .alias("sum")
+                .build()?,
+        );
+        let empty = TestMemoryExec::try_new_exec(&[vec![]], 
Arc::clone(&schema), None)?;
+        let state = AggregateExec::try_new(
+            AggregateMode::Partial,
+            group_by.clone(),
+            vec![Arc::clone(&aggregate)],
+            vec![None],
+            empty,
+            Arc::clone(&schema),
+        )?
+        .schema();
+        let regular_batch = {
+            let k1: ArrayRef = Arc::new(Int64Array::from(vec![0_i64; 4000]));
+            let k2: ArrayRef = Arc::new(StringArray::from_iter_values(
+                (0..4000).map(|i| format!("k_{i:04}")),
+            ));
+            let v: ArrayRef = Arc::new(Int64Array::from(vec![1_i64; 4000]));
+            RecordBatch::try_new(Arc::clone(&state), vec![k1, k2, v])?
+        };
+        // 64 rows of 32 KB string keys (2 MB), like the few rows of a 
`median` state.
+        let large_batch = {
+            let large_str = "x".repeat(32 * 1024);
+            let k1: ArrayRef = Arc::new(Int64Array::from(vec![0_i64; 64]));
+            let k2: ArrayRef = Arc::new(StringArray::from_iter_values(
+                (0..64).map(|i| format!("large_{i:02}_{large_str}")),
+            ));
+            let v: ArrayRef = Arc::new(Int64Array::from(vec![1_i64; 64]));
+            RecordBatch::try_new(Arc::clone(&state), vec![k1, k2, v])?
+        };
+        let ordering =
+            LexOrdering::new([PhysicalSortExpr::new_default(col("k1", 
&state)?)])
+                .unwrap();
+        let input = TestMemoryExec::try_new(
+            &[vec![regular_batch, large_batch]],
+            Arc::clone(&state),
+            None,
+        )?
+        .try_with_sort_information(vec![ordering])?;
+        let plan = Arc::new(AggregateExec::try_new(
+            AggregateMode::Final,
+            group_by.as_final(),
+            vec![aggregate],
+            vec![None],
+            Arc::new(TestMemoryExec::update_cache(&Arc::new(input))),
+            state,
+        )?);
+        assert_eq!(
+            plan.group_clustering_mode(),
+            &GroupClusteringMode::Partial(vec![0])
+        );
+
+        // Fits the large batch, but not next to the table of 4000 groups.
+        let runtime = RuntimeEnvBuilder::new()
+            .with_memory_pool(Arc::new(GreedyMemoryPool::new(2600 * 1024)))

Review Comment:
   Same as in `hash_stream.rs`: the table (310 KB) and the batch charge (2.05 
MB) both fit in 2600 KB, so the retry never runs and removing it passes every 
test. 2300 KB makes this test reach the retry and fail without it:
   
   ```suggestion
               .with_memory_pool(Arc::new(GreedyMemoryPool::new(2300 * 1024)))
   ```



##########
datafusion/physical-plan/src/aggregates/hash_stream.rs:
##########
@@ -1843,4 +1866,232 @@ mod tests {
         );
         Ok(())
     }
+
+    #[tokio::test]
+    async fn final_hash_reserves_incoming_state_batch() -> Result<()> {
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("k", DataType::Utf8, false),
+            Field::new("v", DataType::Int64, false),
+        ]));
+        let group_by =
+            PhysicalGroupBy::new_single(vec![(col("k", &schema)?, 
"k".into())]);
+        let aggregate = Arc::new(
+            AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema)?])
+                .schema(Arc::clone(&schema))
+                .alias("sum")
+                .build()?,
+        );
+        let empty = TestMemoryExec::try_new_exec(&[vec![]], 
Arc::clone(&schema), None)?;
+        let partial = AggregateExec::try_new(
+            AggregateMode::Partial,
+            group_by.clone(),
+            vec![Arc::clone(&aggregate)],
+            vec![None],
+            empty,
+            Arc::clone(&schema),
+        )?;
+        let state_schema = partial.schema();
+        // 64 rows that reference 1 MB of string keys, like the few rows of a 
`median` state.
+        let key_str = "a".repeat(16 * 1024);
+        let keys: ArrayRef = Arc::new(StringArray::from_iter_values(
+            (0..64).map(|_| key_str.as_str()),
+        ));
+        let values: ArrayRef = Arc::new(Int64Array::from(vec![1_i64; 64]));
+        let batch = RecordBatch::try_new(Arc::clone(&state_schema), vec![keys, 
values])?;
+        let input = TestMemoryExec::try_new_exec(
+            &[vec![batch]],
+            Arc::clone(&state_schema),
+            None,
+        )?;
+        let final_aggregate = Arc::new(AggregateExec::try_new(
+            AggregateMode::Final,
+            group_by.as_final(),
+            vec![aggregate],
+            vec![None],
+            input,
+            state_schema,
+        )?);
+        assert_eq!(
+            final_aggregate.group_clustering_mode(),
+            &GroupClusteringMode::None
+        );
+
+        let config = SessionConfig::new()
+            .set_bool("datafusion.execution.enable_migration_aggregate", true);
+        let runtime = RuntimeEnvBuilder::new()
+            .with_memory_pool(Arc::new(GreedyMemoryPool::new(64 * 1024)))
+            .build_arc()?;
+        let context = Arc::new(
+            TaskContext::default()
+                .with_session_config(config.clone())
+                .with_runtime(runtime),
+        );
+        let err = collect(final_aggregate.execute(0, context)?)
+            .await
+            .unwrap_err();
+        assert!(matches!(
+            err.find_root(),
+            DataFusionError::ResourcesExhausted(_)
+        ));
+
+        let runtime = RuntimeEnvBuilder::new()
+            .with_memory_pool(Arc::new(GreedyMemoryPool::new(3 * 1024 * 1024)))
+            .build_arc()?;
+        let context = Arc::new(
+            TaskContext::default()
+                .with_session_config(config)
+                .with_runtime(runtime),
+        );
+        let output = collect(final_aggregate.execute(0, context)?).await?;
+        let result = output[0]
+            .column(1)
+            .as_any()
+            .downcast_ref::<Int64Array>()
+            .unwrap();
+        assert_eq!(result.value(0), 64);
+        Ok(())
+    }
+
+    /// Spilling the table makes room for a state batch that did not fit next 
to it.
+    #[tokio::test]
+    async fn final_hash_spills_to_admit_large_state_batch() -> Result<()> {
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("k", DataType::Utf8, false),
+            Field::new("v", DataType::Int64, false),
+        ]));
+        let group_by =
+            PhysicalGroupBy::new_single(vec![(col("k", &schema)?, 
"k".into())]);
+        let aggregate = Arc::new(
+            AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema)?])
+                .schema(Arc::clone(&schema))
+                .alias("sum")
+                .build()?,
+        );
+        let empty = TestMemoryExec::try_new_exec(&[vec![]], 
Arc::clone(&schema), None)?;
+        let state = AggregateExec::try_new(
+            AggregateMode::Partial,
+            group_by.clone(),
+            vec![Arc::clone(&aggregate)],
+            vec![None],
+            empty,
+            Arc::clone(&schema),
+        )?
+        .schema();
+        let regular_batch = {
+            let keys: ArrayRef = Arc::new(StringArray::from_iter_values(
+                (0..4000).map(|i| format!("k_{i:04}")),
+            ));
+            let values: ArrayRef = Arc::new(Int64Array::from(vec![1_i64; 
4000]));
+            RecordBatch::try_new(Arc::clone(&state), vec![keys, values])?
+        };
+        // 64 rows of 32 KB string keys (2 MB), like the few rows of a 
`median` state.
+        let large_batch = {
+            let large_str = "x".repeat(32 * 1024);
+            let keys: ArrayRef = Arc::new(StringArray::from_iter_values(
+                (0..64).map(|i| format!("large_{i:02}_{large_str}")),
+            ));
+            let values: ArrayRef = Arc::new(Int64Array::from(vec![1_i64; 64]));
+            RecordBatch::try_new(Arc::clone(&state), vec![keys, values])?
+        };
+        let input = TestMemoryExec::try_new_exec(
+            &[vec![regular_batch, large_batch]],
+            Arc::clone(&state),
+            None,
+        )?;
+        let plan = Arc::new(AggregateExec::try_new(
+            AggregateMode::Final,
+            group_by.as_final(),
+            vec![aggregate],
+            vec![None],
+            input,
+            Arc::clone(&state),
+        )?);
+        // Fits the large batch, but not next to the table of 4000 groups.
+        let runtime = RuntimeEnvBuilder::new()
+            .with_memory_pool(Arc::new(GreedyMemoryPool::new(2600 * 1024)))

Review Comment:
   @yashdotrv thanks for the update; the slice fix and the new tests look good. 
With the new row sizing, this test no longer reaches the spill-and-retry path: 
the table holds 432 KB and the batch charge is 2.05 MB, so both fit in 2600 KB, 
and removing the retry passes every test. At 2400 KB the batch no longer fits 
beside the table, so the retry runs, and the test fails without it:
   
   ```suggestion
               .with_memory_pool(Arc::new(GreedyMemoryPool::new(2400 * 1024)))
   ```



##########
datafusion/physical-plan/src/aggregates/aggregate_stream.rs:
##########
@@ -1029,4 +1053,148 @@ mod tests {
 
         Ok(())
     }
+
+    #[tokio::test]
+    async fn final_aggregate_reserves_incoming_state_batch() -> Result<()> {

Review Comment:
   This test still passes if the up-front charge is removed, because 
`array_agg` keeps the batch and is charged after merging anyway. Could you add 
a test with `max`, which keeps only one value of the batch? Then only the new 
charge can refuse the batch: the test below passes now and fails with the 
charge removed.
   
   <details>
   <summary>Test for the ungrouped path (uses imports already in the 
module)</summary>
   
   ```rs
   /// `max` keeps one value of the batch, so only the up-front reservation
   /// can refuse a state batch that holds 1 MB.
   #[tokio::test]
   async fn final_aggregate_reserves_state_batch_it_does_not_retain() -> 
Result<()> {
       let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Utf8, 
false)]));
       let aggregate = Arc::new(
           AggregateExprBuilder::new(max_udaf(), vec![col("v", &schema)?])
               .schema(Arc::clone(&schema))
               .alias("max")
               .build()?,
       );
       let empty = TestMemoryExec::try_new_exec(&[vec![]], Arc::clone(&schema), 
None)?;
       let state = AggregateExec::try_new(
           AggregateMode::Partial,
           PhysicalGroupBy::default(),
           vec![Arc::clone(&aggregate)],
           vec![None],
           empty,
           Arc::clone(&schema),
       )?
       .schema();
       // 64 rows of 16 KB string states (1 MB).
       let value = "a".repeat(16 * 1024);
       let values: ArrayRef = Arc::new(StringArray::from_iter_values(
           (0..64).map(|_| value.as_str()),
       ));
       let batch = RecordBatch::try_new(Arc::clone(&state), vec![values])?;
       let input =
           TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&state), 
None)?;
       let plan: Arc<dyn ExecutionPlan> = Arc::new(AggregateExec::try_new(
           AggregateMode::Final,
           PhysicalGroupBy::default(),
           vec![aggregate],
           vec![None],
           input,
           state,
       )?);
       let runtime = RuntimeEnvBuilder::new()
           .with_memory_pool(Arc::new(GreedyMemoryPool::new(512 * 1024)))
           .build_arc()?;
       let context = Arc::new(TaskContext::default().with_runtime(runtime));
       let err = collect(plan, context).await.unwrap_err();
       assert!(matches!(
           err.find_root(),
           DataFusionError::ResourcesExhausted(_)
       ));
       Ok(())
   }
   ```
   </details>



##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -218,6 +218,34 @@ mod skip_partial;
 mod spill;
 mod topk;
 
+/// Batches passing between operators are bounded by `batch_size` rows and are
+/// not charged to the memory pool. A partial-state batch is charged only when
+/// its rows carry more than this many bytes on average, which means a row 
holds
+/// many input values (`median`, `array_agg`), so its size follows the input.
+const MAX_IN_FLIGHT_STATE_BYTES_PER_ROW: usize = 1024;
+
+/// Below this size a batch is never charged, whatever its row count.
+const MIN_CHARGED_STATE_BATCH_BYTES: usize = 64 * 1024;
+
+fn incoming_state_batch_reservation_bytes(batch: &RecordBatch) -> usize {
+    let in_flight_bytes = batch
+        .num_rows()
+        .saturating_mul(MAX_IN_FLIGHT_STATE_BYTES_PER_ROW)
+        .max(MIN_CHARGED_STATE_BATCH_BYTES);
+    let buffer_bytes =
+        datafusion_common::utils::memory::get_record_batch_memory_size(batch);
+    if buffer_bytes <= in_flight_bytes {

Review Comment:
   Optional: this early return also decides the outcome for shared `Utf8View` 
values, not only the cost. 8192 views of one 2 KB value hold 130 KB, but their 
rows count 16 MB, so removing it makes such a batch fail in a 4 MB pool. No 
test covers that today; the one below passes now and fails without the early 
return.
   
   <details>
   <summary>Test for `aggregate_stream.rs`</summary>
   
   ```rs
   /// Views of one shared value count it once per row, so only the buffers
   /// the batch holds decide whether it is charged.
   #[tokio::test]
   async fn final_aggregate_does_not_charge_shared_view_bytes() -> Result<()> {
       let schema = Arc::new(Schema::new(vec![Field::new(
           "v",
           DataType::Utf8View,
           false,
       )]));
       let aggregate = Arc::new(
           AggregateExprBuilder::new(max_udaf(), vec![col("v", &schema)?])
               .schema(Arc::clone(&schema))
               .alias("max")
               .build()?,
       );
       let empty = TestMemoryExec::try_new_exec(&[vec![]], Arc::clone(&schema), 
None)?;
       let state = AggregateExec::try_new(
           AggregateMode::Partial,
           PhysicalGroupBy::default(),
           vec![Arc::clone(&aggregate)],
           vec![None],
           empty,
           Arc::clone(&schema),
       )?
       .schema();
       // 8192 views of one 2 KB value: 130 KB of buffers, 16 MB counted per 
row.
       let value = "a".repeat(2 * 1024);
       let mut builder =
           arrow::array::StringViewBuilder::new().with_deduplicate_strings();
       for _ in 0..8192 {
           builder.append_value(&value);
       }
       let values: ArrayRef = Arc::new(builder.finish());
       let batch = RecordBatch::try_new(Arc::clone(&state), vec![values])?;
       let input =
           TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&state), 
None)?;
       let plan: Arc<dyn ExecutionPlan> = Arc::new(AggregateExec::try_new(
           AggregateMode::Final,
           PhysicalGroupBy::default(),
           vec![aggregate],
           vec![None],
           input,
           state,
       )?);
       let runtime = RuntimeEnvBuilder::new()
           .with_memory_pool(Arc::new(GreedyMemoryPool::new(4 * 1024 * 1024)))
           .build_arc()?;
       let context = Arc::new(TaskContext::default().with_runtime(runtime));
       collect(plan, context).await?;
       Ok(())
   }
   ```
   </details>



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