|
| 1 | +use std::fs::DirEntry; |
| 2 | +use std::path::PathBuf; |
| 3 | + |
| 4 | +use polars_core::prelude::*; |
| 5 | +use polars_core::utils::{accumulate_dataframes_vertical_unchecked, split_df}; |
| 6 | +use polars_core::POOL; |
| 7 | +use rayon::prelude::*; |
| 8 | + |
| 9 | +use crate::executors::sinks::sort::ooc::read_df; |
| 10 | +use crate::executors::sinks::sort::sink::sort_accumulated; |
| 11 | +use crate::operators::{DataChunk, PExecutionContext, Source, SourceResult}; |
| 12 | + |
| 13 | +pub struct SortSource { |
| 14 | + files: std::vec::IntoIter<(u32, PathBuf)>, |
| 15 | + n_threads: usize, |
| 16 | + sort_idx: usize, |
| 17 | + reverse: bool, |
| 18 | + chunk_offset: IdxSize, |
| 19 | + slice: Option<(i64, usize)>, |
| 20 | + finished: bool, |
| 21 | + |
| 22 | + // The sorted partitions |
| 23 | + // are used check if a directory is already completely sorted |
| 24 | + // if the lower boundary of a partition is equal to the upper |
| 25 | + // boundary, the whole dictionary is already sorted |
| 26 | + // this dictionary may also be very large as in the extreme case |
| 27 | + // we sort a column with a constant value, then the binary search |
| 28 | + // ensures that all files will be written to a single folder |
| 29 | + // in that case we just read the files |
| 30 | + partitions: Series, |
| 31 | + sorted_directory_in_process: Option<std::vec::IntoIter<DirEntry>>, |
| 32 | +} |
| 33 | + |
| 34 | +impl SortSource { |
| 35 | + pub(super) fn new( |
| 36 | + mut files: Vec<(u32, PathBuf)>, |
| 37 | + sort_idx: usize, |
| 38 | + reverse: bool, |
| 39 | + slice: Option<(i64, usize)>, |
| 40 | + partitions: Series, |
| 41 | + ) -> Self { |
| 42 | + files.sort_unstable_by_key(|entry| entry.0); |
| 43 | + |
| 44 | + let n_threads = POOL.current_num_threads(); |
| 45 | + let files = files.into_iter(); |
| 46 | + |
| 47 | + Self { |
| 48 | + files, |
| 49 | + n_threads, |
| 50 | + sort_idx, |
| 51 | + reverse, |
| 52 | + chunk_offset: 0, |
| 53 | + slice, |
| 54 | + finished: false, |
| 55 | + partitions, |
| 56 | + sorted_directory_in_process: None, |
| 57 | + } |
| 58 | + } |
| 59 | + fn finish_batch(&mut self, dfs: Vec<DataFrame>) -> Vec<DataChunk> { |
| 60 | + // TODO: make utility functions to save these allocations |
| 61 | + let chunk_offset = self.chunk_offset; |
| 62 | + self.chunk_offset += dfs.len() as IdxSize; |
| 63 | + dfs.into_iter() |
| 64 | + .enumerate() |
| 65 | + .map(|(i, df)| DataChunk { |
| 66 | + chunk_index: chunk_offset + i as IdxSize, |
| 67 | + data: df, |
| 68 | + }) |
| 69 | + .collect() |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +impl Source for SortSource { |
| 74 | + fn get_batches(&mut self, _context: &PExecutionContext) -> PolarsResult<SourceResult> { |
| 75 | + // early return |
| 76 | + if self.finished { |
| 77 | + return Ok(SourceResult::Finished); |
| 78 | + } |
| 79 | + |
| 80 | + // this branch processes the directories containing a single sort key |
| 81 | + // e.g. the lower_bound == upper_bound |
| 82 | + if let Some(files) = &mut self.sorted_directory_in_process { |
| 83 | + let read = files |
| 84 | + .take(self.n_threads) |
| 85 | + .map(|entry| read_df(&entry)) |
| 86 | + .collect::<PolarsResult<Vec<DataFrame>>>()?; |
| 87 | + let mut df = match (read.len(), &mut self.slice) { |
| 88 | + (0, _) => { |
| 89 | + // depleted directory, continue with normal sorting |
| 90 | + self.sorted_directory_in_process = None; |
| 91 | + return self.get_batches(_context); |
| 92 | + } |
| 93 | + // there is not slice and we got exactly enough files |
| 94 | + // so we return, happy path |
| 95 | + (n, None) if n == self.n_threads => { |
| 96 | + return Ok(SourceResult::GotMoreData(self.finish_batch(read))) |
| 97 | + } |
| 98 | + // there is a slice, so we concat and apply the slice |
| 99 | + // and then later split over the number of threads |
| 100 | + (_, Some((offset, len))) => { |
| 101 | + let df = accumulate_dataframes_vertical_unchecked(read); |
| 102 | + let df_len = df.height(); |
| 103 | + |
| 104 | + // whole batch can be skipped |
| 105 | + let out = if *offset as usize >= df_len { |
| 106 | + *offset -= df_len as i64; |
| 107 | + return self.get_batches(_context); |
| 108 | + } else { |
| 109 | + let out = df.slice(*offset, *len); |
| 110 | + *len = len.saturating_sub(df_len); |
| 111 | + *offset = 0; |
| 112 | + out |
| 113 | + }; |
| 114 | + if *len == 0 { |
| 115 | + self.finished = true; |
| 116 | + } |
| 117 | + out |
| 118 | + } |
| 119 | + // The number of files read are lower than the number of |
| 120 | + // batches we have to return, so we first accumulate |
| 121 | + // and then split over the number of threads |
| 122 | + (_, None) => accumulate_dataframes_vertical_unchecked(read), |
| 123 | + }; |
| 124 | + let batch = split_df(&mut df, self.n_threads)?; |
| 125 | + return Ok(SourceResult::GotMoreData(self.finish_batch(batch))); |
| 126 | + } |
| 127 | + |
| 128 | + match self.files.next() { |
| 129 | + None => Ok(SourceResult::Finished), |
| 130 | + Some((partition, path)) => { |
| 131 | + let files = std::fs::read_dir(path)?.collect::<std::io::Result<Vec<_>>>()?; |
| 132 | + |
| 133 | + // both lower and upper can fail. |
| 134 | + // lower can fail because the search_sorted can add the sort idx at the end of the array, which is i == len |
| 135 | + if let (Ok(lower), Ok(upper)) = ( |
| 136 | + self.partitions.get(partition as usize), |
| 137 | + self.partitions.get(partition as usize + 1), |
| 138 | + ) { |
| 139 | + if lower == upper && !files.is_empty() { |
| 140 | + let files = files.into_iter(); |
| 141 | + self.sorted_directory_in_process = Some(files); |
| 142 | + return self.get_batches(_context); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + // read the files in a single partition in parallel |
| 147 | + let dfs = POOL.install(|| { |
| 148 | + files |
| 149 | + .par_iter() |
| 150 | + .map(read_df) |
| 151 | + .collect::<PolarsResult<Vec<DataFrame>>>() |
| 152 | + })?; |
| 153 | + let df = accumulate_dataframes_vertical_unchecked(dfs); |
| 154 | + // sort a single partition |
| 155 | + let current_slice = self.slice; |
| 156 | + let mut df = match &mut self.slice { |
| 157 | + None => sort_accumulated(df, self.sort_idx, self.reverse, None), |
| 158 | + Some((offset, len)) => { |
| 159 | + let df_len = df.height(); |
| 160 | + assert!(*offset >= 0); |
| 161 | + let out = if *offset as usize >= df_len { |
| 162 | + *offset -= df_len as i64; |
| 163 | + Ok(df.slice(0, 0)) |
| 164 | + } else { |
| 165 | + let out = |
| 166 | + sort_accumulated(df, self.sort_idx, self.reverse, current_slice); |
| 167 | + *len = len.saturating_sub(df_len); |
| 168 | + *offset = 0; |
| 169 | + out |
| 170 | + }; |
| 171 | + if *len == 0 { |
| 172 | + self.finished = true; |
| 173 | + } |
| 174 | + out |
| 175 | + } |
| 176 | + }?; |
| 177 | + |
| 178 | + // convert to chunks |
| 179 | + let dfs = split_df(&mut df, self.n_threads)?; |
| 180 | + Ok(SourceResult::GotMoreData(self.finish_batch(dfs))) |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + fn fmt(&self) -> &str { |
| 186 | + "sort_source" |
| 187 | + } |
| 188 | +} |
0 commit comments