1use super::{InProgressArray, generic::GenericInProgressArray};
6use crate::dictionary::{KeyMapping, child_values_ptr_eq, merge_dictionary_values_with_masks};
7use crate::take::{TakeOptions, take};
8use ahash::RandomState;
9use arrow_array::cast::AsArray;
10use arrow_array::types::ArrowDictionaryKeyType;
11use arrow_array::{
12 Array, ArrayRef, DictionaryArray, PrimitiveArray, UInt32Array, downcast_integer,
13 new_empty_array,
14};
15use arrow_buffer::{
16 ArrowNativeType, BooleanBufferBuilder, NullBuffer, NullBufferBuilder, ScalarBuffer,
17};
18use arrow_schema::{ArrowError, DataType};
19use std::collections::HashMap;
20use std::mem::size_of;
21use std::sync::Arc;
22
23const INDEXED_COPY_MAX_SELECTIVITY_DENOMINATOR: usize = 16;
24
25struct KeyChunk<K: ArrowDictionaryKeyType> {
26 keys: ScalarBuffer<K::Native>,
28 nulls: Option<NullBuffer>,
30 source: usize,
32}
33
34pub(crate) fn create_in_progress_dictionary(
35 key_type: &DataType,
36 value_type: &DataType,
37) -> Box<dyn InProgressArray> {
38 macro_rules! create {
39 ($key:ty, $value_type:ident) => {
40 Box::new(InProgressDictionaryArray::<$key>::new($value_type))
41 };
42 }
43
44 match value_type {
45 DataType::Utf8 | DataType::LargeUtf8 | DataType::Binary | DataType::LargeBinary => {
46 downcast_integer! {
47 key_type => (create, value_type),
48 _ => unreachable!("illegal dictionary key type {key_type}"),
49 }
50 }
51 _ => Box::new(GenericInProgressArray::new()),
52 }
53}
54
55struct InProgressDictionaryArray<K: ArrowDictionaryKeyType> {
56 source: Option<ArrayRef>,
58 len: usize,
60 empty_values: ArrayRef,
62 sources: Vec<ArrayRef>,
64 source_ids: HashMap<usize, usize, RandomState>,
66 chunks: Vec<KeyChunk<K>>,
68}
69
70impl<K: ArrowDictionaryKeyType> std::fmt::Debug for InProgressDictionaryArray<K> {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 f.debug_struct("InProgressDictionaryArray").finish()
73 }
74}
75
76impl<K: ArrowDictionaryKeyType> InProgressDictionaryArray<K> {
77 fn new(value_type: &DataType) -> Self {
78 Self {
79 source: None,
80 len: 0,
81 empty_values: new_empty_array(value_type),
82 sources: Vec::new(),
83 source_ids: HashMap::with_hasher(RandomState::with_seeds(0, 0, 0, 0)),
84 chunks: Vec::new(),
85 }
86 }
87
88 fn source_id(&mut self, values: ArrayRef) -> usize {
91 if let Some(last) = self.chunks.last()
92 && child_values_ptr_eq(&self.sources[last.source], &values)
93 {
94 return last.source;
95 }
96 let values_id = Arc::as_ptr(&values).cast::<()>() as usize;
97 if let Some(&source) = self.source_ids.get(&values_id) {
98 return source;
99 }
100 if let Some(source) = self
101 .sources
102 .iter()
103 .position(|existing| child_values_ptr_eq(existing, &values))
104 {
105 return source;
106 }
107 let source = self.sources.len();
108 self.sources.push(values);
109 self.source_ids.insert(values_id, source);
110 source
111 }
112
113 fn merge_sources(
117 sources: &[ArrayRef],
118 chunks: &[KeyChunk<K>],
119 len: usize,
120 ) -> Result<(Vec<K::Native>, ArrayRef), ArrowError> {
121 let mut referenced = sources
122 .iter()
123 .map(|source| {
124 let mut mask = BooleanBufferBuilder::new(source.len());
125 mask.advance(source.len());
126 mask
127 })
128 .collect::<Vec<_>>();
129
130 for chunk in chunks {
131 let mask = &mut referenced[chunk.source];
132 match &chunk.nulls {
133 Some(nulls) => nulls
134 .inner()
135 .set_indices()
136 .for_each(|offset| mask.set_bit(chunk.keys[offset].as_usize(), true)),
137 None => chunk
138 .keys
139 .iter()
140 .for_each(|key| mask.set_bit(key.as_usize(), true)),
141 }
142 }
143
144 let referenced = referenced
145 .into_iter()
146 .map(BooleanBufferBuilder::build)
147 .collect::<Vec<_>>();
148 let source_refs = sources
149 .iter()
150 .map(|source| source.as_ref() as &dyn Array)
151 .collect::<Vec<_>>();
152 let merged = merge_dictionary_values_with_masks::<K>(&source_refs, &referenced)?;
153
154 let mut keys = Vec::with_capacity(len);
155 for chunk in chunks {
156 let KeyMapping::Dense(mapping) = &merged.key_mappings[chunk.source] else {
157 unreachable!("merge_dictionary_values_with_masks returns dense mappings");
158 };
159 match &chunk.nulls {
160 Some(nulls) => keys.extend(chunk.keys.iter().enumerate().map(|(offset, key)| {
161 if nulls.is_valid(offset) {
162 mapping[key.as_usize()]
163 } else {
164 K::Native::default()
165 }
166 })),
167 None => keys.extend(chunk.keys.iter().map(|key| mapping[key.as_usize()])),
168 }
169 }
170 Ok((keys, merged.values))
171 }
172
173 fn build_nulls(chunks: &[KeyChunk<K>], len: usize) -> Option<NullBuffer> {
175 let mut nulls = NullBufferBuilder::new(len);
176 for chunk in chunks {
177 match &chunk.nulls {
178 Some(chunk_nulls) => nulls.append_buffer(chunk_nulls),
179 None => nulls.append_n_non_nulls(chunk.keys.len()),
180 }
181 }
182 nulls.finish()
183 }
184}
185
186impl<K: ArrowDictionaryKeyType> InProgressArray for InProgressDictionaryArray<K> {
187 fn supports_dense_indexed_copy(&self) -> bool {
188 true
189 }
190
191 fn set_source(&mut self, source: Option<ArrayRef>) {
192 self.source = source;
193 }
194
195 fn copy_rows(&mut self, offset: usize, len: usize) -> Result<(), ArrowError> {
196 if len == 0 {
197 return Ok(());
198 }
199 let source = Arc::clone(self.source.as_ref().ok_or_else(|| {
200 ArrowError::InvalidArgumentError(
201 "Internal Error: InProgressDictionaryArray: source not set".to_string(),
202 )
203 })?);
204 let dictionary = source.as_dictionary::<K>();
205 let keys = dictionary.keys();
206 let source = self.source_id(Arc::clone(dictionary.values()));
207 self.chunks.push(KeyChunk {
208 keys: keys.values().slice(offset, len),
209 nulls: keys.nulls().map(|nulls| nulls.slice(offset, len)),
210 source,
211 });
212 self.len += len;
213 Ok(())
214 }
215
216 unsafe fn copy_rows_by_indices(
217 &mut self,
218 source: &ArrayRef,
219 indices: &UInt32Array,
220 ) -> Result<(), ArrowError> {
221 if indices.is_empty() {
222 return Ok(());
223 }
224 if indices.len() > source.len() / INDEXED_COPY_MAX_SELECTIVITY_DENOMINATOR {
225 let taken = take(
226 source.as_ref(),
227 indices,
228 Some(TakeOptions {
229 check_bounds: false,
230 }),
231 )?;
232 self.set_source(Some(taken));
233 let result = self.copy_rows(0, indices.len());
234 self.set_source(None);
235 return result;
236 }
237 let dictionary = source.as_dictionary::<K>();
238 let values = dictionary.values();
239 let keys = dictionary.keys();
240 let key_values = keys.values();
241 debug_assert!(
242 indices
243 .values()
244 .iter()
245 .all(|&idx| (idx as usize) < key_values.len()),
246 "copy_rows_by_indices requires caller-validated in-bounds indices",
247 );
248 let mut gathered = Vec::with_capacity(indices.len());
249 unsafe {
252 for &idx in indices.values() {
253 gathered.push(*key_values.get_unchecked(idx as usize));
254 }
255 }
256 let nulls = keys.nulls().and_then(|nulls| {
257 if nulls.null_count() == 0 {
258 return None;
259 }
260 let mut gathered = NullBufferBuilder::new(indices.len());
261 unsafe { super::append_gathered_nulls(&mut gathered, nulls, indices) };
264 gathered.finish()
265 });
266 let source = self.source_id(Arc::clone(values));
267 self.chunks.push(KeyChunk {
268 keys: ScalarBuffer::from(gathered),
269 nulls,
270 source,
271 });
272 self.len += indices.len();
273 Ok(())
274 }
275
276 fn finish(&mut self) -> Result<ArrayRef, ArrowError> {
277 let sources = std::mem::take(&mut self.sources);
278 let chunks = std::mem::take(&mut self.chunks);
279 let len = std::mem::take(&mut self.len);
280 self.source_ids.clear();
281
282 let (keys, values) = match sources.len() {
283 0 => (Vec::new(), Arc::clone(&self.empty_values)),
284 1 => (
285 chunks
286 .iter()
287 .flat_map(|chunk| chunk.keys.iter().copied())
288 .collect(),
289 Arc::clone(&sources[0]),
290 ),
291 _ => Self::merge_sources(&sources, &chunks, len)?,
292 };
293 let nulls = Self::build_nulls(&chunks, len);
294 let keys = PrimitiveArray::<K>::try_new(ScalarBuffer::from(keys), nulls)?;
295 Ok(Arc::new(DictionaryArray::try_new(keys, values)?))
296 }
297
298 fn size(&self) -> usize {
300 self.source
301 .as_ref()
302 .map_or(0, |source| source.get_array_memory_size())
303 + self
304 .sources
305 .iter()
306 .map(|source| source.get_array_memory_size())
307 .sum::<usize>()
308 + self.sources.capacity() * size_of::<ArrayRef>()
309 + self.source_ids.capacity() * size_of::<(usize, usize)>()
310 + self.chunks.capacity() * size_of::<KeyChunk<K>>()
311 + self
312 .chunks
313 .iter()
314 .map(|chunk| {
315 chunk.keys.inner().capacity()
316 + chunk
317 .nulls
318 .as_ref()
319 .map_or(0, |nulls| nulls.inner().inner().capacity())
320 })
321 .sum::<usize>()
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328 use crate::coalesce::BatchCoalescer;
329 use arrow_array::types::{Int8Type, Int32Type};
330 use arrow_array::{Int8Array, Int32Array, RecordBatch, StringArray};
331
332 fn batch(values: &ArrayRef, keys: Vec<Option<i32>>) -> RecordBatch {
333 let dictionary = Arc::new(DictionaryArray::<Int32Type>::new(
334 Int32Array::from(keys),
335 Arc::clone(values),
336 )) as ArrayRef;
337 RecordBatch::try_from_iter([("dict", dictionary)]).unwrap()
338 }
339
340 #[test]
341 fn coalesces_repeated_and_distinct_values() {
342 let first_values = Arc::new(StringArray::from(vec!["a", "b"])) as ArrayRef;
343 let second_values = Arc::new(StringArray::from(vec!["b", "c"])) as ArrayRef;
344 let batches = [
345 batch(&first_values, vec![Some(0), None]),
346 batch(&second_values, vec![Some(0), Some(1)]),
347 batch(&first_values, vec![Some(1), Some(0)]),
348 ];
349 let mut coalescer = BatchCoalescer::new(batches[0].schema(), 6);
350 for batch in batches {
351 coalescer.push_batch(batch).unwrap();
352 }
353
354 let output = coalescer.next_completed_batch().unwrap();
355 let output = output.column(0).as_dictionary::<Int32Type>();
356 let values = output.values().as_string::<i32>();
357 let decoded = output
358 .keys_iter()
359 .map(|key| key.map(|key| values.value(key)))
360 .collect::<Vec<_>>();
361 assert_eq!(
362 decoded,
363 vec![Some("a"), None, Some("b"), Some("c"), Some("b"), Some("a")]
364 );
365 assert_eq!(values.len(), 4);
366 }
367
368 #[test]
369 fn reuses_one_values_array() {
370 let values = Arc::new(StringArray::from(vec!["a", "b"])) as ArrayRef;
371 let mut coalescer = BatchCoalescer::new(batch(&values, vec![Some(0)]).schema(), 2);
372 coalescer.push_batch(batch(&values, vec![Some(0)])).unwrap();
373 coalescer.push_batch(batch(&values, vec![Some(1)])).unwrap();
374
375 let output = coalescer.next_completed_batch().unwrap();
376 let output = output.column(0).as_dictionary::<Int32Type>();
377 assert!(Arc::ptr_eq(output.values(), &values));
378 }
379
380 #[test]
381 fn indexed_copy_reuses_values_and_preserves_sliced_null_keys() {
382 let values = Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef;
383 let keys =
384 Int32Array::from_iter((0..66).map(|idx| (idx != 1).then_some(idx % 3))).slice(1, 64);
385 let source =
386 Arc::new(DictionaryArray::<Int32Type>::new(keys, Arc::clone(&values))) as ArrayRef;
387 let mut in_progress = InProgressDictionaryArray::<Int32Type>::new(&DataType::Utf8);
388 unsafe {
390 in_progress
391 .copy_rows_by_indices(&source, &UInt32Array::from(vec![9, 1, 0, 1]))
392 .unwrap()
393 };
394
395 let output = in_progress.finish().unwrap();
396 let output = output.as_dictionary::<Int32Type>();
397 assert!(Arc::ptr_eq(output.values(), &values));
398 assert_eq!(
399 output.keys(),
400 &Int32Array::from(vec![Some(1), Some(2), None, Some(2)])
401 );
402 }
403
404 #[test]
405 fn indexed_copy_remaps_sparse_values_across_sources() {
406 let first_values = Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef;
407 let second_values = Arc::new(StringArray::from(vec!["c", "a", "d"])) as ArrayRef;
408 let keys = (0..64)
409 .map(|idx| (idx != 3).then_some(idx % 3))
410 .collect::<Vec<_>>();
411 let first = batch(&first_values, keys.clone());
412 let second = batch(&second_values, keys);
413 let mut coalescer = BatchCoalescer::new(first.schema(), 8);
414
415 coalescer
417 .push_batch_with_indices(first, &UInt32Array::from(vec![3, 1, 0, 1]))
418 .unwrap();
419 coalescer
420 .push_batch_with_indices(second, &UInt32Array::from(vec![2, 0, 3, 0]))
421 .unwrap();
422
423 let output = coalescer.next_completed_batch().unwrap();
424 let output = output.column(0).as_dictionary::<Int32Type>();
425 let values = output.values().as_string::<i32>();
426 let decoded = output
427 .keys_iter()
428 .map(|key| key.map(|key| values.value(key)))
429 .collect::<Vec<_>>();
430 assert_eq!(
431 decoded,
432 vec![
433 None,
434 Some("b"),
435 Some("a"),
436 Some("b"),
437 Some("d"),
438 Some("c"),
439 None,
440 Some("c"),
441 ]
442 );
443 assert_eq!(values.len(), 4);
444 }
445
446 #[test]
447 fn indexed_copy_dense_fallback_preserves_null_keys() {
448 let values = Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef;
449 let source = Arc::new(DictionaryArray::<Int32Type>::new(
450 Int32Array::from(vec![Some(0), None, Some(2), Some(1)]),
451 Arc::clone(&values),
452 )) as ArrayRef;
453 let mut in_progress = InProgressDictionaryArray::<Int32Type>::new(&DataType::Utf8);
454 unsafe {
456 in_progress
457 .copy_rows_by_indices(&source, &UInt32Array::from(vec![3, 1, 0]))
458 .unwrap()
459 };
460
461 let output = in_progress.finish().unwrap();
462 let output = output.as_dictionary::<Int32Type>();
463 assert!(Arc::ptr_eq(output.values(), &values));
464 assert_eq!(
465 output.keys(),
466 &Int32Array::from(vec![Some(1), None, Some(0)])
467 );
468 }
469
470 #[test]
471 fn reuses_values_with_shared_buffers() {
472 let values = StringArray::from_iter_values((0..128).map(|i| format!("value-{i}")));
473 let first_values = Arc::new(values.clone()) as ArrayRef;
474 let second_values = Arc::new(values) as ArrayRef;
475 let make_batch = |values| {
476 let dictionary =
477 DictionaryArray::<Int8Type>::new(Int8Array::from_iter_values(0..=127), values);
478 RecordBatch::try_from_iter([("dict", Arc::new(dictionary) as ArrayRef)]).unwrap()
479 };
480
481 let first = make_batch(Arc::clone(&first_values));
482 let mut coalescer = BatchCoalescer::new(first.schema(), 256);
483 coalescer.push_batch(first).unwrap();
484 coalescer.push_batch(make_batch(second_values)).unwrap();
485
486 let output = coalescer.next_completed_batch().unwrap();
487 let output = output.column(0).as_dictionary::<Int8Type>();
488 assert!(Arc::ptr_eq(output.values(), &first_values));
489 assert_eq!(
490 output.keys().values(),
491 &(0..=127).chain(0..=127).collect::<Vec<_>>()
492 );
493 }
494
495 #[test]
496 fn remaps_sparse_values_across_sources() {
497 let first = Arc::new(DictionaryArray::<Int32Type>::new(
498 Int32Array::from_iter_values([1, 2, 0, 2, 1]),
499 Arc::new(StringArray::from(vec!["a", "unused-a", "b"])),
500 )) as ArrayRef;
501 let second = Arc::new(DictionaryArray::<Int32Type>::new(
502 Int32Array::from_iter_values([2, 1, 0, 1, 2]),
503 Arc::new(StringArray::from(vec!["b", "c", "unused-b"])),
504 )) as ArrayRef;
505
506 let mut in_progress = InProgressDictionaryArray::<Int32Type>::new(&DataType::Utf8);
507 in_progress.set_source(Some(first));
508 in_progress.copy_rows(1, 3).unwrap();
509 in_progress.set_source(Some(second));
510 in_progress.copy_rows(1, 3).unwrap();
511
512 let output = in_progress.finish().unwrap();
513 let output = output.as_dictionary::<Int32Type>();
514 assert_eq!(output.keys().values(), &[1, 0, 1, 3, 2, 3]);
515 assert_eq!(
516 output
517 .values()
518 .as_string::<i32>()
519 .iter()
520 .collect::<Vec<_>>(),
521 vec![Some("a"), Some("b"), Some("b"), Some("c")]
522 );
523 }
524
525 #[test]
526 fn remaps_keys_when_deduplication_is_required() {
527 let make_values = || {
528 Arc::new(StringArray::from_iter_values(
529 (0..70).map(|idx| format!("value-{idx}")),
530 )) as ArrayRef
531 };
532 let first_values = make_values();
533 let second_values = make_values();
534 let make_dictionary = |values| {
535 Arc::new(DictionaryArray::<Int8Type>::new(
536 Int8Array::from_iter_values(0..70),
537 values,
538 )) as ArrayRef
539 };
540
541 let mut in_progress = InProgressDictionaryArray::<Int8Type>::new(&DataType::Utf8);
542 in_progress.set_source(Some(make_dictionary(first_values)));
543 in_progress.copy_rows(0, 70).unwrap();
544 in_progress.set_source(Some(make_dictionary(second_values)));
545 in_progress.copy_rows(0, 70).unwrap();
546
547 let output = in_progress.finish().unwrap();
548 let output = output.as_dictionary::<Int8Type>();
549 let values = output.values().as_string::<i32>();
550 for (idx, key) in output.keys().values().iter().enumerate() {
551 assert_eq!(values.value(*key as usize), format!("value-{}", idx % 70));
552 }
553 assert!(values.len() <= i8::MAX as usize + 1);
554 }
555}