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


##########
datafusion/sqllogictest/test_files/cte.slt:
##########
@@ -1994,3 +1994,71 @@ SET datafusion.execution.target_partitions = 4;
 
 statement ok
 RESET datafusion.execution.parquet.pushdown_filters;
+
+# Shared Utf8View buffers in a recursive CollectLeft join must not exhaust the 
pool.

Review Comment:
   Could we document why these fixture values matter? The eight-row chains 
determine recursion depth, keys longer than 12 bytes require out-of-line 
Utf8View storage, and the batch size produces multiple batches sharing buffers.



##########
datafusion/physical-plan/src/recursive_query.rs:
##########
@@ -565,4 +582,112 @@ mod tests {
         assert!(exec.recursive_term().schema().field(0).is_nullable());
         Ok(())
     }
+
+    /// Returns the output row count and peak reservation of a recursive query
+    /// with `batches` as the static term and `recursive_term` over `t`.
+    async fn run_recursive_query(
+        schema: &SchemaRef,
+        batches: Vec<RecordBatch>,
+        recursive_term: impl FnOnce(Arc<dyn ExecutionPlan>) -> Result<Arc<dyn 
ExecutionPlan>>,
+    ) -> Result<(usize, usize)> {
+        let static_term =
+            TestMemoryExec::try_new_exec(&[batches], Arc::clone(schema), 
None)?;
+        let work_table = Arc::new(WorkTableExec::new(
+            "t".to_string(),
+            Arc::clone(schema),
+            None,
+        )?);
+        let exec = Arc::new(RecursiveQueryExec::try_new(
+            "t".to_string(),
+            Arc::clone(schema),
+            static_term,
+            recursive_term(work_table)?,
+            false,
+        )?);
+        let pool = 
Arc::new(PeakRecordingPool::new(Arc::new(GreedyMemoryPool::new(
+            usize::MAX / 2,
+        ))));
+        let runtime = RuntimeEnvBuilder::new()
+            .with_memory_pool(Arc::clone(&pool) as Arc<dyn MemoryPool>)
+            .build_arc()?;
+        let context = Arc::new(TaskContext::default().with_runtime(runtime));
+        let rows = collect(exec, context)
+            .await?
+            .iter()
+            .map(|b| b.num_rows())
+            .sum();
+        assert_eq!(pool.reserved(), 0);
+        Ok((rows, pool.peak_reserved()))
+    }
+
+    #[tokio::test]
+    async fn recursive_query_reserves_shared_buffers_once_per_iteration() -> 
Result<()> {
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("s", DataType::Utf8View, true),
+            Field::new("n", DataType::Int64, false),
+        ]));
+        let strings: StringViewArray = (0..256)
+            .map(|i| Some(format!("{i:05} {}", "a long string ".repeat(16))))
+            .collect();
+        let string_data: usize =
+            strings.data_buffers().iter().map(|b| b.capacity()).sum();
+        let strings: ArrayRef = Arc::new(strings);
+        let n: ArrayRef = Arc::new(Int64Array::from(vec![0; 256]));
+        // 16 batches that share the same string buffers
+        let batches: Vec<RecordBatch> = (0..16)
+            .map(|i| {
+                let columns = vec![strings.slice(i * 16, 16), n.slice(i * 16, 
16)];
+                RecordBatch::try_new(Arc::clone(&schema), columns).unwrap()
+            })
+            .collect();
+        let sum_of_batches: usize =
+            batches.iter().map(|b| b.get_array_memory_size()).sum();
+
+        // SELECT s, n + 1 FROM t WHERE n < 1: one more iteration over the 
same strings
+        let (rows, peak) = run_recursive_query(&schema, batches, |work_table| {
+            let n = col("n", &schema)?;
+            let filter = FilterExec::try_new(
+                binary(Arc::clone(&n), Operator::Lt, lit(1i64), &schema)?,
+                work_table,
+            )?
+            .with_batch_size(16)?;
+            let next_n = binary(n, Operator::Plus, lit(1i64), &schema)?;
+            let projection = ProjectionExec::try_new(
+                vec![
+                    (col("s", &schema)?, "s".to_string()),
+                    (next_n, "n".to_string()),
+                ],
+                Arc::new(filter),
+            )?;
+            Ok(Arc::new(projection))
+        })
+        .await?;
+
+        assert_eq!(rows, 512);
+        // the work table and the next iteration each hold the strings
+        assert!(peak >= 2 * string_data, "{peak} < 2 * {string_data}");
+        assert!(peak < sum_of_batches, "{peak} >= {sum_of_batches}");
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn recursive_query_reserves_array_objects() -> Result<()> {
+        // a NullArray has no buffers, only the array object
+        let schema = Arc::new(Schema::new(vec![Field::new("n", DataType::Null, 
true)]));
+        let batches: Vec<RecordBatch> = (0..16)
+            .map(|_| {
+                let column: ArrayRef = Arc::new(NullArray::new(1));
+                RecordBatch::try_new(Arc::clone(&schema), 
vec![column]).unwrap()
+            })
+            .collect();
+
+        let (rows, peak) = run_recursive_query(&schema, batches, |work_table| {
+            Ok(Arc::new(FilterExec::try_new(lit(false), work_table)?))
+        })
+        .await?;
+
+        assert_eq!(rows, 16);
+        assert!(peak > 0);

Review Comment:
   Could we use `assert_eq!(peak, 16 * std::mem::size_of::<NullArray>())`? This 
verifies exact accounting for the 16 distinct array objects rather than merely 
checking for a nonzero reservation.



##########
datafusion/sqllogictest/test_files/cte.slt:
##########
@@ -1994,3 +1994,71 @@ SET datafusion.execution.target_partitions = 4;
 
 statement ok
 RESET datafusion.execution.parquet.pushdown_filters;
+
+# Shared Utf8View buffers in a recursive CollectLeft join must not exhaust the 
pool.
+statement ok
+SET datafusion.execution.target_partitions = 2;
+
+statement ok
+SET datafusion.optimizer.hash_join_single_partition_threshold = 1000000000;
+
+statement ok
+SET datafusion.optimizer.hash_join_single_partition_threshold_rows = 
1000000000;
+
+statement ok
+COPY (
+  SELECT 'trace-' || lpad(CAST(value / 8 AS VARCHAR), 10, '0') AS trace_id,
+         'span-' || lpad(CAST(value AS VARCHAR), 12, '0') AS span_id,
+         CASE WHEN value % 8 = 0 THEN NULL
+              ELSE 'span-' || lpad(CAST(value - 1 AS VARCHAR), 12, '0') END AS 
parent_span_id
+  FROM generate_series(0, 79999)
+) TO 'test_files/scratch/cte/recursive_shared_buffers.parquet' STORED AS 
PARQUET;
+
+statement ok
+CREATE EXTERNAL TABLE recursive_spans STORED AS PARQUET
+LOCATION 'test_files/scratch/cte/recursive_shared_buffers.parquet';
+
+statement ok
+SET datafusion.execution.batch_size = 1024;
+
+statement ok
+SET datafusion.runtime.memory_limit = '50M';
+
+query II
+WITH RECURSIVE tree AS (
+    SELECT trace_id, span_id, 0 AS depth FROM recursive_spans WHERE 
parent_span_id IS NULL
+    UNION ALL
+    SELECT c.trace_id, c.span_id, p.depth + 1
+    FROM recursive_spans c JOIN tree p ON c.trace_id = p.trace_id AND 
c.parent_span_id = p.span_id
+)
+SELECT depth, count(*) FROM tree GROUP BY depth ORDER BY depth;
+----
+0 10000
+1 10000
+2 10000
+3 10000
+4 10000
+5 10000
+6 10000
+7 10000
+
+statement ok
+RESET datafusion.runtime.memory_limit;
+
+statement ok
+RESET datafusion.catalog.create_default_catalog_and_schema;

Review Comment:
   Please remove this RESET. The fixture never sets this option, and resetting 
it could overwrite a harness-supplied setting.



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