|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use datafusion_execution::memory_pool::proxy::VecAllocExt; |
| 19 | + |
| 20 | +use crate::physical_expr::EmitTo; |
| 21 | + |
| 22 | +/// Tracks grouping state when the data is ordered entirely by its |
| 23 | +/// group keys |
| 24 | +/// |
| 25 | +/// When the group values are sorted, as soon as we see group `n+1` we |
| 26 | +/// know we will never see any rows for group `n again and thus they |
| 27 | +/// can be emitted. |
| 28 | +/// |
| 29 | +/// For example, given `SUM(amt) GROUP BY id` if the input is sorted |
| 30 | +/// by `id` as soon as a new `id` value is seen all previous values |
| 31 | +/// can be emitted. |
| 32 | +/// |
| 33 | +/// The state is tracked like this: |
| 34 | +/// |
| 35 | +/// ```text |
| 36 | +/// ┌─────┐ ┌──────────────────┐ |
| 37 | +/// │┌───┐│ │ ┌──────────────┐ │ ┏━━━━━━━━━━━━━━┓ |
| 38 | +/// ││ 0 ││ │ │ 123 │ │ ┌─────┃ 13 ┃ |
| 39 | +/// │└───┘│ │ └──────────────┘ │ │ ┗━━━━━━━━━━━━━━┛ |
| 40 | +/// │ ... │ │ ... │ │ |
| 41 | +/// │┌───┐│ │ ┌──────────────┐ │ │ current |
| 42 | +/// ││12 ││ │ │ 234 │ │ │ |
| 43 | +/// │├───┤│ │ ├──────────────┤ │ │ |
| 44 | +/// ││12 ││ │ │ 234 │ │ │ |
| 45 | +/// │├───┤│ │ ├──────────────┤ │ │ |
| 46 | +/// ││13 ││ │ │ 456 │◀┼───┘ |
| 47 | +/// │└───┘│ │ └──────────────┘ │ |
| 48 | +/// └─────┘ └──────────────────┘ |
| 49 | +/// |
| 50 | +/// group indices group_values current tracks the most |
| 51 | +/// (in group value recent group index |
| 52 | +/// order) |
| 53 | +/// ``` |
| 54 | +/// |
| 55 | +/// In this diagram, the current group is `13`, and thus groups |
| 56 | +/// `0..12` can be emitted. Note that `13` can not yet be emitted as |
| 57 | +/// there may be more values in the next batch with the same group_id. |
| 58 | +#[derive(Debug)] |
| 59 | +pub(crate) struct GroupOrderingFull { |
| 60 | + state: State, |
| 61 | + /// Hash values for groups in 0..current |
| 62 | + hashes: Vec<u64>, |
| 63 | +} |
| 64 | + |
| 65 | +#[derive(Debug)] |
| 66 | +enum State { |
| 67 | + /// Seen no input yet |
| 68 | + Start, |
| 69 | + |
| 70 | + /// Data is in progress. `current is the current group for which |
| 71 | + /// values are being generated. Can emit `current` - 1 |
| 72 | + InProgress { current: usize }, |
| 73 | + |
| 74 | + /// Seen end of input: all groups can be emitted |
| 75 | + Complete, |
| 76 | +} |
| 77 | + |
| 78 | +impl GroupOrderingFull { |
| 79 | + pub fn new() -> Self { |
| 80 | + Self { |
| 81 | + state: State::Start, |
| 82 | + hashes: vec![], |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + // How many groups be emitted, or None if no data can be emitted |
| 87 | + pub fn emit_to(&self) -> Option<EmitTo> { |
| 88 | + match &self.state { |
| 89 | + State::Start => None, |
| 90 | + State::InProgress { current, .. } => { |
| 91 | + if *current == 0 { |
| 92 | + // Can not emit if still on the first row |
| 93 | + None |
| 94 | + } else { |
| 95 | + // otherwise emit all rows prior to the current group |
| 96 | + Some(EmitTo::First(*current)) |
| 97 | + } |
| 98 | + } |
| 99 | + State::Complete { .. } => Some(EmitTo::All), |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + /// remove the first n groups from the internal state, shifting |
| 104 | + /// all existing indexes down by `n`. Returns stored hash values |
| 105 | + pub fn remove_groups(&mut self, n: usize) -> &[u64] { |
| 106 | + match &mut self.state { |
| 107 | + State::Start => panic!("invalid state: start"), |
| 108 | + State::InProgress { current } => { |
| 109 | + // shift down by n |
| 110 | + assert!(*current >= n); |
| 111 | + *current -= n; |
| 112 | + self.hashes.drain(0..n); |
| 113 | + } |
| 114 | + State::Complete { .. } => panic!("invalid state: complete"), |
| 115 | + }; |
| 116 | + &self.hashes |
| 117 | + } |
| 118 | + |
| 119 | + /// Note that the input is complete so any outstanding groups are done as well |
| 120 | + pub fn input_done(&mut self) { |
| 121 | + self.state = match self.state { |
| 122 | + State::Start => State::Complete, |
| 123 | + State::InProgress { .. } => State::Complete, |
| 124 | + State::Complete => State::Complete, |
| 125 | + }; |
| 126 | + } |
| 127 | + |
| 128 | + /// Called when new groups are added in a batch. See documentation |
| 129 | + /// on [`super::GroupOrdering::new_groups`] |
| 130 | + pub fn new_groups( |
| 131 | + &mut self, |
| 132 | + group_indices: &[usize], |
| 133 | + batch_hashes: &[u64], |
| 134 | + total_num_groups: usize, |
| 135 | + ) { |
| 136 | + assert!(total_num_groups > 0); |
| 137 | + assert_eq!(group_indices.len(), batch_hashes.len()); |
| 138 | + |
| 139 | + // copy any hash values |
| 140 | + self.hashes.resize(total_num_groups, 0); |
| 141 | + for (&group_index, &hash) in group_indices.iter().zip(batch_hashes.iter()) { |
| 142 | + self.hashes[group_index] = hash; |
| 143 | + } |
| 144 | + |
| 145 | + // Update state |
| 146 | + let max_group_index = total_num_groups - 1; |
| 147 | + self.state = match self.state { |
| 148 | + State::Start => State::InProgress { |
| 149 | + current: max_group_index, |
| 150 | + }, |
| 151 | + State::InProgress { current } => { |
| 152 | + // expect to see new group indexes when called again |
| 153 | + assert!(current <= max_group_index, "{current} <= {max_group_index}"); |
| 154 | + State::InProgress { |
| 155 | + current: max_group_index, |
| 156 | + } |
| 157 | + } |
| 158 | + State::Complete { .. } => { |
| 159 | + panic!("Saw new group after input was complete"); |
| 160 | + } |
| 161 | + }; |
| 162 | + } |
| 163 | + |
| 164 | + pub(crate) fn size(&self) -> usize { |
| 165 | + std::mem::size_of::<Self>() + self.hashes.allocated_size() |
| 166 | + } |
| 167 | +} |
0 commit comments