1use std::fmt::Display;
5use std::fmt::Formatter;
6use std::hash::Hash;
7
8use itertools::Itertools;
9use vortex_array::dtype::DType;
10use vortex_array::dtype::FieldName;
11use vortex_array::dtype::FieldNames;
12use vortex_array::dtype::Nullability;
13use vortex_array::dtype::StructFields;
14use vortex_array::expr::BoundExpression;
15use vortex_array::expr::ExactBoundExpr;
16use vortex_array::expr::bound::get_item;
17use vortex_array::expr::bound::pack;
18use vortex_array::expr::traversal::NodeExt;
19use vortex_array::expr::traversal::NodeRewriter;
20use vortex_array::expr::traversal::Transformed;
21use vortex_array::expr::traversal::TraversalOrder;
22use vortex_array::scalar_fn::fns::get_item::GetItem;
23use vortex_array::scalar_fn::fns::pack::Pack;
24use vortex_error::VortexExpect;
25use vortex_error::VortexResult;
26use vortex_error::vortex_ensure_eq;
27use vortex_utils::aliases::hash_map::HashMap;
28
29use crate::analysis::Annotation;
30use crate::analysis::AnnotationFn;
31use crate::analysis::BoundAnnotations;
32use crate::analysis::descendent_bound_annotations;
33
34pub fn partition_bound<A: AnnotationFn<BoundExpression>>(
38 expr: BoundExpression,
39 annotate_fn: A,
40) -> VortexResult<BoundPartitionedExpr<A::Annotation>>
41where
42 A::Annotation: Display,
43 FieldName: From<A::Annotation>,
44{
45 let annotations = descendent_bound_annotations(&expr, annotate_fn);
47 partition_bound_annotations(expr, annotations)
48}
49
50pub fn partition_bound_annotations<A>(
54 expr: BoundExpression,
55 annotations: BoundAnnotations<A>,
56) -> VortexResult<BoundPartitionedExpr<A>>
57where
58 A: Display + Clone + Eq + Hash,
59 FieldName: From<A>,
60{
61 let mut collector = PartitionCollector::<A>::new(&annotations);
62 expr.clone().rewrite(&mut collector)?;
63
64 let mut partitions = Vec::with_capacity(collector.sub_expressions.len());
65 let mut partition_annotations = Vec::with_capacity(collector.sub_expressions.len());
66
67 for (annotation, exprs) in collector.sub_expressions {
68 let names: FieldNames = exprs
70 .iter()
71 .enumerate()
72 .map(|(idx, _)| PartitionCollector::field_name(&annotation, idx))
73 .collect();
74 let expr = pack(names.into_iter().zip(exprs), Nullability::NonNullable);
75
76 partitions.push(expr);
77 partition_annotations.push(annotation);
78 }
79
80 let partition_names = partition_annotations
81 .iter()
82 .map(|id| FieldName::from(id.clone()))
83 .collect::<FieldNames>();
84 let root_scope = partition_root_dtype(&partition_names, &partitions);
85 let mut rewriter = PartitionRootRewriter::new(&annotations, root_scope);
86 let root = expr.rewrite(&mut rewriter)?.value;
87
88 Ok(BoundPartitionedExpr {
89 root,
90 partitions: partitions.into_boxed_slice(),
91 partition_names,
92 partition_annotations: partition_annotations.into_boxed_slice(),
93 })
94}
95
96#[derive(Debug)]
101pub struct BoundPartitionedExpr<A> {
102 pub root: BoundExpression,
104 pub partitions: Box<[BoundExpression]>,
106 pub partition_names: FieldNames,
108 pub partition_annotations: Box<[A]>,
110}
111
112impl<A: Display> Display for BoundPartitionedExpr<A> {
113 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
114 write!(
115 f,
116 "root: {} {{{}}}",
117 self.root,
118 self.partition_names
119 .iter()
120 .zip(self.partitions.iter())
121 .map(|(name, partition)| format!("{name}: {partition}"))
122 .join(", ")
123 )
124 }
125}
126
127impl<A: Annotation> BoundPartitionedExpr<A>
128where
129 FieldName: From<A>,
130{
131 pub fn find_partition(&self, id: &A) -> Option<&BoundExpression> {
134 let id = FieldName::from(id.clone());
135 self.partition_names
136 .iter()
137 .position(|field| field == id)
138 .map(|idx| &self.partitions[idx])
139 }
140
141 pub fn replace_partitions(&mut self, partitions: Box<[BoundExpression]>) -> VortexResult<()> {
143 vortex_ensure_eq!(partitions.len(), self.partition_names.len());
144
145 let root_dtype = partition_root_dtype(&self.partition_names, &partitions);
146 let root = replace_root_dtype(self.root.clone(), root_dtype)?;
147 self.partitions = partitions;
148 self.root = root;
149 Ok(())
150 }
151
152 pub fn collapse_single_partitions(&mut self) -> VortexResult<()> {
162 let mut collapsed = HashMap::new();
163 let partitions = self
164 .partitions
165 .iter()
166 .zip_eq(self.partition_names.iter())
167 .map(|(partition, partition_name)| {
168 if let Some(pack) = partition.as_opt::<Pack>()
169 && let [value] = partition.children()
170 {
171 let value_name = pack.names.get(0).vortex_expect("pack has one field");
172 collapsed.insert(partition_name.clone(), value_name.clone());
173 value.clone()
174 } else {
175 partition.clone()
176 }
177 })
178 .collect::<Box<[_]>>();
179 if collapsed.is_empty() {
180 return Ok(());
181 }
182
183 let root_dtype = partition_root_dtype(&self.partition_names, &partitions);
184 let root = self
185 .root
186 .clone()
187 .transform_down(|node| {
188 if let Some(value_name) = node.as_opt::<GetItem>()
189 && let partition_access = &node.children()[0]
190 && let Some(partition_name) = partition_access.as_opt::<GetItem>()
191 && partition_access.children()[0].is_root()
192 && collapsed.get(partition_name) == Some(value_name)
193 {
194 return Ok(Transformed {
195 value: get_item(
196 partition_name.clone(),
197 BoundExpression::new_root(root_dtype.clone()),
198 ),
199 changed: true,
200 order: TraversalOrder::Skip,
201 });
202 }
203 if node.is_root() {
204 return Ok(Transformed {
205 value: BoundExpression::new_root(root_dtype.clone()),
206 changed: true,
207 order: TraversalOrder::Skip,
208 });
209 }
210 Ok(Transformed::no(node))
211 })?
212 .into_inner();
213
214 self.partitions = partitions;
215 self.root = root;
216 Ok(())
217 }
218}
219
220#[derive(Debug)]
221struct PartitionCollector<'a, A: Annotation> {
222 annotations: &'a BoundAnnotations<A>,
223 sub_expressions: Vec<(A, Vec<BoundExpression>)>,
226 positions: HashMap<A, usize>,
228}
229
230impl<'a, A: Annotation + Display> PartitionCollector<'a, A> {
231 fn new(annotations: &'a BoundAnnotations<A>) -> Self {
232 Self {
233 sub_expressions: Vec::new(),
234 positions: HashMap::new(),
235 annotations,
236 }
237 }
238
239 fn field_name(annotation: &A, idx: usize) -> FieldName {
242 format!("{annotation}_{idx}").into()
243 }
244}
245
246impl<A: Annotation + Display> NodeRewriter for PartitionCollector<'_, A>
247where
248 FieldName: From<A>,
249{
250 type NodeTy = BoundExpression;
251
252 fn visit_down(&mut self, node: Self::NodeTy) -> VortexResult<Transformed<Self::NodeTy>> {
253 match self.annotations.get(&ExactBoundExpr(node.clone())) {
254 Some(annotations) if annotations.len() == 1 => {
256 let annotation = annotations
257 .iter()
258 .next()
259 .vortex_expect("expected one field");
260 let position = *self.positions.entry(annotation.clone()).or_insert_with(|| {
261 self.sub_expressions.push((annotation.clone(), Vec::new()));
262 self.sub_expressions.len() - 1
263 });
264 self.sub_expressions[position].1.push(node.clone());
265 Ok(Transformed {
266 value: node,
267 changed: false,
268 order: TraversalOrder::Skip,
269 })
270 }
271
272 _ => Ok(Transformed::no(node)),
274 }
275 }
276
277 fn visit_up(&mut self, node: Self::NodeTy) -> VortexResult<Transformed<Self::NodeTy>> {
278 Ok(Transformed::no(node))
279 }
280}
281
282struct PartitionRootRewriter<'a, A: Annotation> {
283 annotations: &'a BoundAnnotations<A>,
284 partition_offsets: HashMap<A, usize>,
285 root_dtype: DType,
286}
287
288impl<'a, A: Annotation> PartitionRootRewriter<'a, A> {
289 fn new(annotations: &'a BoundAnnotations<A>, root_dtype: DType) -> Self {
290 Self {
291 annotations,
292 partition_offsets: HashMap::new(),
293 root_dtype,
294 }
295 }
296}
297
298impl<A: Annotation + Display> NodeRewriter for PartitionRootRewriter<'_, A>
299where
300 FieldName: From<A>,
301{
302 type NodeTy = BoundExpression;
303
304 fn visit_down(&mut self, node: Self::NodeTy) -> VortexResult<Transformed<Self::NodeTy>> {
305 let Some(annotations) = self.annotations.get(&ExactBoundExpr(node.clone())) else {
306 return Ok(Transformed::no(node));
307 };
308 if annotations.len() != 1 {
309 return Ok(Transformed::no(node));
310 }
311
312 let annotation = annotations
313 .iter()
314 .next()
315 .vortex_expect("expected one annotation");
316 let offset = self
317 .partition_offsets
318 .entry(annotation.clone())
319 .or_default();
320 let field_name = PartitionCollector::field_name(annotation, *offset);
321 *offset += 1;
322
323 let partition = get_item(
324 FieldName::from(annotation.clone()),
325 BoundExpression::new_root(self.root_dtype.clone()),
326 );
327 let value = get_item(field_name, partition);
328
329 Ok(Transformed {
330 value,
331 changed: true,
332 order: TraversalOrder::Skip,
333 })
334 }
335}
336
337fn partition_root_dtype(names: &FieldNames, partitions: &[BoundExpression]) -> DType {
338 DType::Struct(
339 StructFields::new(
340 names.clone(),
341 partitions
342 .iter()
343 .map(|partition| partition.dtype().clone())
344 .collect(),
345 ),
346 Nullability::NonNullable,
347 )
348}
349
350fn replace_root_dtype(expr: BoundExpression, root_dtype: DType) -> VortexResult<BoundExpression> {
351 Ok(expr
352 .transform_down(|node| {
353 if node.is_root() {
354 Ok(Transformed {
355 value: BoundExpression::new_root(root_dtype.clone()),
356 changed: true,
357 order: TraversalOrder::Skip,
358 })
359 } else {
360 Ok(Transformed::no(node))
361 }
362 })?
363 .into_inner())
364}
365
366#[cfg(test)]
367mod tests {
368 use rstest::fixture;
369 use rstest::rstest;
370 use vortex_array::dtype::DType;
371 use vortex_array::dtype::Nullability::NonNullable;
372 use vortex_array::dtype::Nullability::Nullable;
373 use vortex_array::dtype::PType::I32;
374 use vortex_array::dtype::StructFields;
375 use vortex_array::expr::checked_add;
376 use vortex_array::expr::col;
377 use vortex_array::expr::get_item;
378 use vortex_array::expr::lit;
379 use vortex_array::expr::merge;
380 use vortex_array::expr::pack;
381 use vortex_array::expr::root;
382
383 use super::*;
384 use crate::analysis::make_bound_free_field_annotator;
385
386 #[fixture]
387 fn dtype() -> DType {
388 DType::Struct(
389 StructFields::from_iter([
390 (
391 "a",
392 DType::Struct(
393 StructFields::from_iter([("x", I32.into()), ("y", DType::from(I32))]),
394 NonNullable,
395 ),
396 ),
397 ("b", I32.into()),
398 ("c", I32.into()),
399 ]),
400 NonNullable,
401 )
402 }
403
404 fn partition_by_field(
405 expr: BoundExpression,
406 dtype: &DType,
407 ) -> VortexResult<BoundPartitionedExpr<FieldName>> {
408 let fields = dtype.as_struct_fields_opt().unwrap();
409 partition_bound(expr, make_bound_free_field_annotator(fields))
410 }
411
412 #[rstest]
413 fn test_expr_top_level_ref(dtype: DType) {
414 let fields = dtype.as_struct_fields_opt().unwrap();
415
416 let expr = root();
417 let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
418
419 assert_eq!(partitioned.partitions.len(), 0);
421 assert_eq!(partitioned.root, root().bind(&dtype).unwrap());
422
423 let expr = pack(
425 fields
426 .names()
427 .iter()
428 .map(|name| (name.clone(), col(name.clone()))),
429 NonNullable,
430 );
431 let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
432
433 assert_eq!(partitioned.partitions.len(), fields.names().len());
434 for name in fields.names().iter() {
435 let expected = pack([(format!("{name}_0"), col(name.clone()))], NonNullable)
436 .bind(&dtype)
437 .unwrap();
438 assert_eq!(partitioned.find_partition(name), Some(&expected));
439 }
440 }
441
442 #[rstest]
443 fn test_collapse_single_partitions(dtype: DType) -> VortexResult<()> {
444 let expr = pack(
445 [
446 ("x", get_item("c", root())),
447 ("y", get_item("x", get_item("a", root()))),
448 ("z", get_item("y", get_item("a", root()))),
449 ],
450 NonNullable,
451 );
452 let mut partitioned = partition_by_field(expr.bind(&dtype)?, &dtype)?;
453 assert_eq!(
455 partitioned.partition_names,
456 FieldNames::from_iter(["c", "a"].map(FieldName::from))
457 );
458
459 partitioned.collapse_single_partitions()?;
460
461 assert_eq!(
462 partitioned.partitions[0],
463 get_item("c", root()).bind(&dtype)?
464 );
465 assert_eq!(
466 partitioned.partitions[1],
467 pack(
468 [
469 ("a_0", get_item("x", get_item("a", root()))),
470 ("a_1", get_item("y", get_item("a", root()))),
471 ],
472 NonNullable
473 )
474 .bind(&dtype)?
475 );
476 let root_dtype =
477 partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
478 assert_eq!(
479 partitioned.root,
480 pack(
481 [
482 ("x", get_item("c", root())),
483 ("y", get_item("a_0", get_item("a", root()))),
484 ("z", get_item("a_1", get_item("a", root()))),
485 ],
486 NonNullable
487 )
488 .bind(&root_dtype)?
489 );
490 Ok(())
491 }
492
493 #[rstest]
494 fn test_expr_top_level_ref_get_item_and_split(dtype: DType) {
495 let expr = get_item("y", get_item("a", root()));
496
497 let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
498 let root_dtype =
499 partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
500 assert_eq!(
501 partitioned.root,
502 get_item("a_0", get_item("a", root()))
503 .bind(&root_dtype)
504 .unwrap()
505 );
506 }
507
508 #[rstest]
509 fn test_expr_top_level_ref_get_item_and_split_pack(dtype: DType) {
510 let expr = pack(
511 [
512 ("x", get_item("x", get_item("a", root()))),
513 ("y", get_item("y", get_item("a", root()))),
514 ("c", get_item("c", root())),
515 ],
516 NonNullable,
517 );
518 let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
519
520 let split_a = partitioned.find_partition(&"a".into()).unwrap();
521 assert_eq!(
522 split_a,
523 &pack(
524 [
525 ("a_0", get_item("x", get_item("a", root()))),
526 ("a_1", get_item("y", get_item("a", root())))
527 ],
528 NonNullable
529 )
530 .bind(&dtype)
531 .unwrap()
532 );
533 }
534
535 #[rstest]
536 fn test_expr_top_level_ref_get_item_add(dtype: DType) {
537 let expr = checked_add(get_item("y", get_item("a", root())), lit(1));
538 let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
539
540 assert_eq!(partitioned.partitions.len(), 1);
542 let expected = pack([("a_0", expr)], NonNullable).bind(&dtype).unwrap();
543 assert_eq!(partitioned.find_partition(&"a".into()), Some(&expected));
544 let root_dtype =
545 partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
546 assert_eq!(
547 partitioned.root,
548 get_item("a_0", col("a")).bind(&root_dtype).unwrap()
549 );
550 }
551
552 #[rstest]
553 fn test_expr_top_level_ref_get_item_add_cannot_split(dtype: DType) {
554 let expr = checked_add(get_item("y", get_item("a", root())), get_item("b", root()));
555 let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
556
557 assert_eq!(partitioned.partitions.len(), 2);
559 let expected_a = pack([("a_0", get_item("y", col("a")))], NonNullable)
560 .bind(&dtype)
561 .unwrap();
562 let expected_b = pack([("b_0", col("b"))], NonNullable).bind(&dtype).unwrap();
563 assert_eq!(partitioned.find_partition(&"a".into()), Some(&expected_a));
564 assert_eq!(partitioned.find_partition(&"b".into()), Some(&expected_b));
565 let root_dtype =
566 partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
567 let expected_root = checked_add(get_item("a_0", col("a")), get_item("b_0", col("b")))
568 .bind(&root_dtype)
569 .unwrap();
570 assert_eq!(partitioned.root, expected_root);
571 }
572
573 #[rstest]
574 fn test_expr_merge(dtype: DType) {
575 let expr = merge([col("a"), pack([("b", col("b"))], NonNullable)]);
576
577 let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
578 let expected = merge([get_item("a_0", col("a")), get_item("b_0", col("b"))]);
579 let root_dtype =
580 partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
581 assert_eq!(
582 partitioned.root,
583 expected.bind(&root_dtype).unwrap(),
584 "{} {}",
585 partitioned.root,
586 expected
587 );
588
589 assert_eq!(partitioned.partitions.len(), 2);
590
591 let part_a = partitioned.find_partition(&"a".into()).unwrap();
592 let expected_a = pack([("a_0", col("a"))], NonNullable);
593 assert_eq!(
594 part_a,
595 &expected_a.bind(&dtype).unwrap(),
596 "{part_a} {expected_a}"
597 );
598
599 let part_b = partitioned.find_partition(&"b".into()).unwrap();
600 let expected_b = pack([("b_0", pack([("b", col("b"))], NonNullable))], NonNullable);
601 assert_eq!(
602 part_b,
603 &expected_b.bind(&dtype).unwrap(),
604 "{part_b} {expected_b}"
605 );
606 }
607
608 #[rstest]
609 fn replacing_partitions_refreshes_root_dtype(dtype: DType) -> VortexResult<()> {
610 let mut partitioned = partition_by_field(col("b").bind(&dtype)?, &dtype)?;
611 let field_dtype = DType::Primitive(I32, Nullable);
612 let replacement = pack([("b_0", root())], NonNullable).bind(&field_dtype)?;
613
614 partitioned.replace_partitions(vec![replacement].into_boxed_slice())?;
615
616 assert_eq!(partitioned.root.dtype(), &field_dtype);
617 Ok(())
618 }
619}