1#[cfg(test)]
16mod tests;
17
18use datafusion::arrow::buffer::ScalarBuffer;
19use datafusion_common::DataFusionError;
20use datatypes::error::InvalidSeriesSnafu;
21use datatypes::series::histogram::HistogramView;
22use datatypes::series::raw::{RawSeriesChunk, RawTimestamps};
23use datatypes::series::samples::{SampleRef, Samples, SeriesFields, SeriesSchema};
24
25pub(crate) fn merge_raw_identity_charging(
32 schema: &SeriesSchema,
33 chunks: &[RawSeriesChunk],
34 reserve: &mut dyn FnMut(usize) -> std::result::Result<(), DataFusionError>,
35 shrink: &mut dyn FnMut(usize),
36) -> std::result::Result<RawSeriesChunk, DataFusionError> {
37 let invalid = |reason: &str| {
38 DataFusionError::External(Box::new(
39 InvalidSeriesSnafu {
40 reason: reason.to_string(),
41 }
42 .build(),
43 ))
44 };
45 let Some(first) = chunks.first() else {
46 return Err(invalid("cannot merge an empty raw identity"));
47 };
48 if schema.eval_grid.is_some() {
49 return Err(invalid("raw series schema cannot have an evaluation grid"));
50 }
51 let key = first.primary_key.clone();
52 let labels = first
53 .metric
54 .as_ref()
55 .ok_or_else(|| invalid("raw identity chunk has no explicit labels"))?
56 .clone();
57 for chunk in chunks {
58 if chunk.primary_key != key {
59 return Err(invalid("raw identity chunks have different primary keys"));
60 }
61 if chunk.metric.as_ref() != Some(&labels) {
62 return Err(invalid(
63 "raw identity chunks have different or missing labels",
64 ));
65 }
66 if chunk.fields.len() != schema.fields.len()
67 || chunk
68 .fields
69 .iter()
70 .any(|field| field.len() != chunk.time.len())
71 {
72 return Err(invalid("raw identity chunk shape does not match schema"));
73 }
74 }
75
76 let mut row_count = 0usize;
77 for chunk in chunks.iter() {
78 row_count = row_count.saturating_add(chunk.time.len());
79 }
80 let chunks_are_ordered_and_disjoint = chunks.windows(2).all(|pair| {
81 pair[0]
82 .time
83 .as_buffer()
84 .last()
85 .zip(pair[1].time.as_buffer().first())
86 .is_some_and(|(last, first)| last < first)
87 });
88 let mut transient_workspace_bytes = 0usize;
89 let mut output_fields = Vec::with_capacity(schema.fields.len());
90 let times = if chunks_are_ordered_and_disjoint {
91 reserve(row_count.saturating_mul(std::mem::size_of::<i64>()))?;
92 let mut times = Vec::with_capacity(row_count);
93 for chunk in chunks {
94 times.extend_from_slice(chunk.time.as_buffer());
95 }
96 for field_index in 0..schema.fields.len() {
97 let mut parts = Vec::with_capacity(chunks.len());
98 for chunk in chunks {
99 let source = chunk
100 .fields
101 .get(field_index)
102 .ok_or_else(|| invalid("field index out of bounds"))?;
103 reserve(std::mem::size_of::<Samples>())?;
104 parts.push(
105 source
106 .slice(0, chunk.time.len())
107 .map_err(|error| DataFusionError::External(Box::new(error)))?,
108 );
109 }
110 output_fields.push(
111 Samples::try_from_chunks(parts)
112 .map_err(|error| DataFusionError::External(Box::new(error)))?,
113 );
114 }
115 times
116 } else {
117 transient_workspace_bytes = row_count
118 .saturating_mul(std::mem::size_of::<(i64, usize, usize)>())
119 .saturating_mul(2);
120 reserve(row_count.saturating_mul(std::mem::size_of::<(i64, usize, usize)>()))?;
121 let mut rows = Vec::with_capacity(row_count);
122 for (chunk_index, chunk) in chunks.iter().enumerate() {
123 for row_index in 0..chunk.time.len() {
124 rows.push((chunk.time.as_buffer()[row_index], chunk_index, row_index));
125 }
126 }
127 rows.sort_unstable();
128
129 reserve(
130 rows.len()
131 .saturating_mul(std::mem::size_of::<(i64, usize, usize)>()),
132 )?;
133 let mut selected = Vec::with_capacity(rows.len());
134 let mut index = 0;
135 while index < rows.len() {
136 let mut end = index + 1;
137 while end < rows.len() && rows[end].0 == rows[index].0 {
138 end += 1;
139 }
140 for duplicate in &rows[index + 1..end] {
141 for field_index in 0..schema.fields.len() {
142 if !samples_equal(
143 chunks[rows[index].1]
144 .fields
145 .get(field_index)
146 .ok_or_else(|| invalid("field index out of bounds"))?
147 .sample(rows[index].2),
148 chunks[duplicate.1]
149 .fields
150 .get(field_index)
151 .ok_or_else(|| invalid("field index out of bounds"))?
152 .sample(duplicate.2),
153 ) {
154 return Err(invalid("duplicate raw timestamp has conflicting samples"));
155 }
156 }
157 }
158 selected.push(rows[index]);
159 index = end;
160 }
161
162 reserve(selected.len().saturating_mul(std::mem::size_of::<i64>()))?;
163 let mut times = Vec::with_capacity(selected.len());
164 for row in &selected {
165 times.push(row.0);
166 }
167 for field_index in 0..schema.fields.len() {
168 let mut parts = Vec::new();
169 let mut start = 0;
170 while start < selected.len() {
171 let (chunk_index, row_index) = (selected[start].1, selected[start].2);
172 let mut end = start + 1;
173 while end < selected.len()
174 && selected[end].1 == chunk_index
175 && selected[end].2 == selected[end - 1].2 + 1
176 {
177 end += 1;
178 }
179 let source = chunks[chunk_index]
180 .fields
181 .get(field_index)
182 .ok_or_else(|| invalid("field index out of bounds"))?;
183 reserve(std::mem::size_of::<Samples>())?;
184 parts.push(
185 source
186 .slice(row_index, end - start)
187 .map_err(|error| DataFusionError::External(Box::new(error)))?,
188 );
189 start = end;
190 }
191 output_fields.push(
192 Samples::try_from_chunks(parts)
193 .map_err(|error| DataFusionError::External(Box::new(error)))?,
194 );
195 }
196 times
197 };
198 let result = RawSeriesChunk::try_new(
199 schema,
200 key,
201 Some(labels),
202 RawTimestamps::try_new(ScalarBuffer::from(times))
203 .map_err(|error| DataFusionError::External(Box::new(error)))?,
204 SeriesFields::try_from_vec(output_fields)
205 .map_err(|error| DataFusionError::External(Box::new(error)))?,
206 true,
207 )
208 .map_err(|error| DataFusionError::External(Box::new(error)))?;
209 shrink(transient_workspace_bytes);
211 Ok(result)
212}
213
214fn samples_equal(left: SampleRef<'_>, right: SampleRef<'_>) -> bool {
215 match (left, right) {
216 (SampleRef::Missing, SampleRef::Missing) => true,
217 (SampleRef::Float(a), SampleRef::Float(b)) => a.to_bits() == b.to_bits(),
218 (SampleRef::Histogram(a), SampleRef::Histogram(b)) => histograms_equal(a, b),
219 _ => false,
220 }
221}
222
223fn histograms_equal(a: HistogramView<'_>, b: HistogramView<'_>) -> bool {
224 a.schema == b.schema
225 && a.zero_threshold.to_bits() == b.zero_threshold.to_bits()
226 && a.sum.to_bits() == b.sum.to_bits()
227 && a.count.to_bits() == b.count.to_bits()
228 && a.zero_count.to_bits() == b.zero_count.to_bits()
229 && a.reset_hint == b.reset_hint
230 && a.start_timestamp == b.start_timestamp
231 && float_slices_equal(a.custom_values, b.custom_values)
232 && a.positive.span_offsets == b.positive.span_offsets
233 && a.positive.span_lengths == b.positive.span_lengths
234 && float_slices_equal(a.positive.buckets, b.positive.buckets)
235 && a.negative.span_offsets == b.negative.span_offsets
236 && a.negative.span_lengths == b.negative.span_lengths
237 && float_slices_equal(a.negative.buckets, b.negative.buckets)
238}
239
240fn float_slices_equal(a: &[f64], b: &[f64]) -> bool {
241 a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.to_bits() == b.to_bits())
242}