1use std::sync::Arc;
55
56use datatypes::arrow::array::{
57 Array, ArrayRef, AsArray, Float64Array, Int32Array, Int64Array, ListArray, StructArray,
58 TimestampMillisecondArray,
59};
60use datatypes::arrow::buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer};
61use datatypes::arrow::datatypes::{
62 DataType, Fields, Float64Type, Int32Type, Int64Type, TimeUnit, TimestampMillisecondType,
63};
64
65use crate::error::Result;
66use crate::series_index::samples::codec::{self, Cursor, put_varint};
67use crate::series_index::samples::metadata::CHUNK_LIMIT;
68use crate::series_index::samples::{MAX_ROWS, invalid, require};
69
70pub(super) const ENCODING: u16 = 8;
72const VALUE_BOUND: usize = 11;
75const ROW_FRAMING_BOUND: usize = 1;
77const CHILD_FRAMING_BOUND: usize = 64;
80const HEADER_BOUND: usize = 16;
83const DECODED_VALUE_BYTES: usize = 48;
86
87pub(super) fn encode(array: &StructArray) -> Result<Vec<u8>> {
90 let layout = layout(array.fields())?;
91 let rows = array.len();
92 let mut body = Vec::new();
93 let mut list_values = 0usize;
94 for (child, column) in layout.iter().zip(array.columns()) {
95 match child {
96 Child::Scalar(scalar) => {
97 let values = Values::new(*scalar, column.as_ref())?;
98 put_nullable(
99 &mut body,
100 &(0..rows).map(|i| values.get(i)).collect::<Vec<_>>(),
101 );
102 }
103 Child::List(scalar) => {
104 let list = column
105 .as_list_opt::<i32>()
106 .ok_or_else(|| invalid("invalid native histogram list child"))?;
107 let offsets = list.value_offsets();
108 let lengths = (0..rows)
109 .map(|i| {
110 list.is_valid(i)
111 .then(|| (offsets[i + 1] - offsets[i]) as u64)
112 })
113 .collect::<Vec<_>>();
114 put_nullable(&mut body, &lengths);
115 let values = Values::new(*scalar, list.values().as_ref())?;
116 let items = (0..rows)
119 .filter(|&i| list.is_valid(i))
120 .flat_map(|i| offsets[i] as usize..offsets[i + 1] as usize)
121 .map(|j| values.get(j))
122 .collect::<Vec<_>>();
123 if !items.is_empty() {
124 put_nullable(&mut body, &items);
125 }
126 list_values += items.len();
127 }
128 }
129 }
130 let mut out = vec![
131 u8::try_from(layout.len()).map_err(|_| invalid("too many native histogram children"))?,
132 ];
133 out.extend(layout.iter().map(|child| child.code()));
134 put_varint(&mut out, list_values as u64);
135 if array.null_count() > 0 {
136 let start = out.len();
137 out.resize(start + rows.div_ceil(8), 0);
138 for i in (0..rows).filter(|&i| array.is_valid(i)) {
139 out[start + i / 8] |= 1 << (i % 8);
140 }
141 }
142 out.extend(body);
143 Ok(out)
144}
145
146pub(super) fn decoded_bytes(bytes: &[u8], rows: usize) -> Result<usize> {
148 let mut c = Cursor::new(bytes);
149 let children = c.u8()? as usize;
150 c.take(children)?;
151 let list_values = list_value_count(&mut c)?;
152 Ok((rows * children + list_values) * DECODED_VALUE_BYTES)
153}
154
155pub(super) fn decode(
158 bytes: &[u8],
159 data_type: &DataType,
160 rows: usize,
161 nulls: u32,
162) -> Result<StructArray> {
163 let DataType::Struct(fields) = data_type else {
164 return Err(invalid("native histogram chunk requires a struct type"));
165 };
166 let layout = layout(fields)?;
167 let nulls = nulls as usize;
168 require(
169 (1..=MAX_ROWS).contains(&rows) && nulls <= rows,
170 "invalid native histogram row count",
171 )?;
172 let mut c = Cursor::new(bytes);
173 require(
174 c.u8()? as usize == layout.len(),
175 "native histogram child count mismatch",
176 )?;
177 for child in &layout {
178 require(
179 c.u8()? == child.code(),
180 "native histogram child kind mismatch",
181 )?;
182 }
183 let mut remaining = list_value_count(&mut c)?;
184 let validity = if nulls == 0 {
185 None
186 } else {
187 let bitmap = c.take(rows.div_ceil(8))?;
188 if !rows.is_multiple_of(8) {
189 require(
190 bitmap[bitmap.len() - 1] >> (rows % 8) == 0,
191 "nonzero native histogram validity padding",
192 )?;
193 }
194 let validity = BooleanBuffer::new(Buffer::from(bitmap.to_vec()), 0, rows);
195 require(
196 validity.count_set_bits() + nulls == rows,
197 "native histogram validity count mismatch",
198 )?;
199 Some(NullBuffer::new(validity))
200 };
201 let mut children = Vec::with_capacity(layout.len());
202 for (child, field) in layout.iter().zip(fields.iter()) {
203 let array = match child {
204 Child::Scalar(scalar) => scalar.build(take_nullable(&mut c, rows)?)?,
205 Child::List(scalar) => {
206 let DataType::List(item) = field.data_type() else {
207 return Err(invalid("native histogram list child requires a list type"));
208 };
209 let lengths = take_nullable(&mut c, rows)?;
210 let mut offsets = Vec::with_capacity(rows + 1);
211 offsets.push(0i32);
212 let mut total = 0usize;
213 for length in &lengths {
214 total = total
215 .checked_add(length.unwrap_or(0) as usize)
216 .filter(|total| *total <= remaining)
217 .ok_or_else(|| invalid("native histogram list value count mismatch"))?;
218 offsets.push(total as i32);
220 }
221 remaining -= total;
222 let items = if total == 0 {
223 Vec::new()
224 } else {
225 take_nullable(&mut c, total)?
226 };
227 let list_nulls = lengths
228 .iter()
229 .any(Option::is_none)
230 .then(|| NullBuffer::from_iter(lengths.iter().map(Option::is_some)));
231 Arc::new(
232 ListArray::try_new(
233 item.clone(),
234 OffsetBuffer::new(offsets.into()),
235 scalar.build(items)?,
236 list_nulls,
237 )
238 .map_err(|e| invalid(format!("invalid native histogram list: {e}")))?,
239 )
240 }
241 };
242 children.push(array);
243 }
244 require(remaining == 0, "native histogram list value count mismatch")?;
245 c.end()?;
246 StructArray::try_new(fields.clone(), children, validity)
247 .map_err(|e| invalid(format!("invalid native histogram struct: {e}")))
248}
249
250pub(crate) fn check_sample_size(children: usize, list_items: usize) -> Result<()> {
253 require(
254 ChunkBound::default()
255 .with_bytes(children, row_bytes(children, list_items))
256 .is_some(),
257 "native histogram sample exceeds the Narthex samples chunk limit",
258 )
259}
260
261pub(crate) fn check_array_sample_sizes(array: &StructArray) -> Result<()> {
263 (0..array.len())
264 .try_for_each(|row| check_sample_size(array.num_columns(), list_items(array, row)))
265}
266
267#[derive(Debug, Clone, Copy, Default)]
270pub(super) struct ChunkBound {
271 rows: usize,
272 bytes: usize,
273}
274
275impl ChunkBound {
276 pub(super) fn with_row(&self, array: &StructArray, row: usize) -> Option<Self> {
278 self.with_bytes(
279 array.num_columns(),
280 row_bytes(array.num_columns(), list_items(array, row)),
281 )
282 }
283
284 fn with_bytes(&self, children: usize, row_bytes: usize) -> Option<Self> {
285 let bytes = self.bytes + row_bytes;
286 let rows = self.rows + 1;
287 let chunk = HEADER_BOUND + children * CHILD_FRAMING_BOUND + rows.div_ceil(8) + bytes;
288 (chunk <= CHUNK_LIMIT).then_some(Self { rows, bytes })
289 }
290}
291
292fn row_bytes(children: usize, list_items: usize) -> usize {
295 ROW_FRAMING_BOUND + VALUE_BOUND * (children + list_items)
296}
297
298fn list_items(array: &StructArray, row: usize) -> usize {
300 array
301 .columns()
302 .iter()
303 .filter_map(|column| column.as_list_opt::<i32>())
304 .filter(|list| list.is_valid(row))
305 .map(|list| list.value_length(row) as usize)
306 .sum()
307}
308
309fn list_value_count(c: &mut Cursor<'_>) -> Result<usize> {
312 let count = c.varint()?;
313 require(
314 count <= CHUNK_LIMIT as u64,
315 "native histogram list value count exceeds limit",
316 )?;
317 Ok(count as usize)
318}
319
320fn put_nullable(out: &mut Vec<u8>, values: &[Option<u64>]) {
323 let nulls = values.iter().filter(|v| v.is_none()).count();
324 put_varint(out, nulls as u64);
325 if nulls < values.len() {
326 let bytes = codec::encode_float(values);
327 put_varint(out, bytes.len() as u64);
328 out.extend(bytes);
329 }
330}
331
332fn take_nullable(c: &mut Cursor<'_>, count: usize) -> Result<Vec<Option<u64>>> {
334 let nulls = c.varint()?;
335 require(
336 nulls <= count as u64,
337 "native histogram null count exceeds values",
338 )?;
339 let nulls = nulls as usize;
340 if nulls == count {
341 return Ok(vec![None; count]);
342 }
343 let length = usize::try_from(c.varint()?)
344 .map_err(|_| invalid("native histogram section length overflow"))?;
345 codec::decode_xor(c.take(length)?, count, nulls)
346}
347
348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
350enum Scalar {
351 Float64,
352 Int32,
353 Int64,
354 TimestampMillisecond,
355}
356
357impl Scalar {
358 fn from_arrow(data_type: &DataType) -> Result<Self> {
359 match data_type {
360 DataType::Float64 => Ok(Self::Float64),
361 DataType::Int32 => Ok(Self::Int32),
362 DataType::Int64 => Ok(Self::Int64),
363 DataType::Timestamp(TimeUnit::Millisecond, None) => Ok(Self::TimestampMillisecond),
364 other => Err(invalid(format!(
365 "unsupported native histogram child type {other}"
366 ))),
367 }
368 }
369
370 fn code(self) -> u8 {
371 match self {
372 Self::Float64 => 1,
373 Self::Int32 => 2,
374 Self::Int64 => 3,
375 Self::TimestampMillisecond => 4,
376 }
377 }
378
379 fn build(self, values: Vec<Option<u64>>) -> Result<ArrayRef> {
380 let signed = |bits: u64| codec::unzig(bits) as i64;
381 Ok(match self {
382 Self::Float64 => Arc::new(Float64Array::from_iter(
383 values.into_iter().map(|v| v.map(f64::from_bits)),
384 )),
385 Self::Int32 => Arc::new(Int32Array::from(
386 values
387 .into_iter()
388 .map(|v| {
389 v.map(|bits| {
390 i32::try_from(signed(bits))
391 .map_err(|_| invalid("native histogram Int32 value overflow"))
392 })
393 .transpose()
394 })
395 .collect::<Result<Vec<_>>>()?,
396 )),
397 Self::Int64 => Arc::new(Int64Array::from_iter(
398 values.into_iter().map(|v| v.map(signed)),
399 )),
400 Self::TimestampMillisecond => Arc::new(TimestampMillisecondArray::from_iter(
401 values.into_iter().map(|v| v.map(signed)),
402 )),
403 })
404 }
405}
406
407enum Values<'a> {
409 Float64(&'a Float64Array),
410 Int32(&'a Int32Array),
411 Int64(&'a Int64Array),
412 TimestampMillisecond(&'a TimestampMillisecondArray),
413}
414
415impl<'a> Values<'a> {
416 fn new(scalar: Scalar, array: &'a dyn Array) -> Result<Self> {
417 let values = match scalar {
418 Scalar::Float64 => array.as_primitive_opt::<Float64Type>().map(Self::Float64),
419 Scalar::Int32 => array.as_primitive_opt::<Int32Type>().map(Self::Int32),
420 Scalar::Int64 => array.as_primitive_opt::<Int64Type>().map(Self::Int64),
421 Scalar::TimestampMillisecond => array
422 .as_primitive_opt::<TimestampMillisecondType>()
423 .map(Self::TimestampMillisecond),
424 };
425 values.ok_or_else(|| invalid("native histogram child does not match its type"))
426 }
427
428 fn get(&self, index: usize) -> Option<u64> {
429 match self {
430 Self::Float64(a) => a.is_valid(index).then(|| a.value(index).to_bits()),
431 Self::Int32(a) => a
432 .is_valid(index)
433 .then(|| codec::zig(i64::from(a.value(index)))),
434 Self::Int64(a) => a.is_valid(index).then(|| codec::zig(a.value(index))),
435 Self::TimestampMillisecond(a) => a.is_valid(index).then(|| codec::zig(a.value(index))),
436 }
437 }
438}
439
440#[derive(Debug, Clone, Copy, PartialEq, Eq)]
441enum Child {
442 Scalar(Scalar),
443 List(Scalar),
444}
445
446impl Child {
447 fn code(self) -> u8 {
448 match self {
449 Self::Scalar(scalar) => scalar.code(),
450 Self::List(scalar) => 0x10 | scalar.code(),
451 }
452 }
453}
454
455fn layout(fields: &Fields) -> Result<Vec<Child>> {
456 fields
457 .iter()
458 .map(|field| match field.data_type() {
459 DataType::List(item) => Scalar::from_arrow(item.data_type()).map(Child::List),
460 other => Scalar::from_arrow(other).map(Child::Scalar),
461 })
462 .collect()
463}
464
465#[cfg(test)]
466pub(crate) mod tests {
467 use common_query::native_histogram::{
468 COUNT_F64_FIELD, COUNT_I64_FIELD, COUNTER_RESET_HINT, CUSTOM_BUCKETS_SCHEMA,
469 CUSTOM_VALUES_FIELD, GAUGE_RESET_HINT, NEGATIVE_BUCKETS_F64_FIELD,
470 NEGATIVE_BUCKETS_I64_FIELD, NEGATIVE_SPAN_LENGTHS_FIELD, NEGATIVE_SPAN_OFFSETS_FIELD,
471 NOT_COUNTER_RESET_HINT, POSITIVE_BUCKETS_F64_FIELD, POSITIVE_BUCKETS_I64_FIELD,
472 POSITIVE_SPAN_LENGTHS_FIELD, POSITIVE_SPAN_OFFSETS_FIELD, RESET_HINT_FIELD, SCHEMA_FIELD,
473 START_TIMESTAMP_FIELD, SUM_FIELD, ZERO_COUNT_F64_FIELD, ZERO_COUNT_I64_FIELD,
474 ZERO_THRESHOLD_FIELD, native_histogram_value_type,
475 };
476 use datatypes::arrow::array::new_empty_array;
477 use datatypes::arrow::compute::concat;
478 use datatypes::arrow::datatypes::Field;
479 use datatypes::data_type::DataType as _;
480
481 use super::*;
482
483 #[derive(Debug, Clone, Default)]
485 pub(crate) struct TestHistogram {
486 pub(crate) schema: i32,
487 pub(crate) zero_threshold: f64,
488 pub(crate) sum: f64,
489 pub(crate) reset_hint: i32,
490 pub(crate) start: Option<i64>,
491 pub(crate) custom_values: Option<Vec<f64>>,
492 pub(crate) positive_spans: Vec<(i32, i32)>,
493 pub(crate) negative_spans: Vec<(i32, i32)>,
494 pub(crate) ints: Option<(i64, i64, Vec<i64>, Vec<i64>)>,
496 pub(crate) floats: Option<(f64, f64, Vec<f64>, Vec<f64>)>,
498 }
499
500 pub(crate) fn histogram_array(rows: &[Option<TestHistogram>]) -> StructArray {
503 let DataType::Struct(fields) = native_histogram_value_type().as_arrow_type() else {
504 unreachable!("the native histogram type is a struct")
505 };
506 let floats = |f: &dyn Fn(&TestHistogram) -> Option<f64>| -> ArrayRef {
507 Arc::new(Float64Array::from_iter(
508 rows.iter().map(|row| row.as_ref().and_then(f)),
509 ))
510 };
511 let ints = |f: &dyn Fn(&TestHistogram) -> Option<i64>| -> ArrayRef {
512 Arc::new(Int64Array::from_iter(
513 rows.iter().map(|row| row.as_ref().and_then(f)),
514 ))
515 };
516 let int32s = |f: &dyn Fn(&TestHistogram) -> i32| -> ArrayRef {
517 Arc::new(Int32Array::from_iter(
518 rows.iter().map(|row| row.as_ref().map(f)),
519 ))
520 };
521 let children = fields
522 .iter()
523 .map(|field| -> ArrayRef {
524 let list = |f: &dyn Fn(&TestHistogram) -> Option<ArrayRef>| {
525 list_array(
526 field,
527 &rows
528 .iter()
529 .map(|row| row.as_ref().and_then(f))
530 .collect::<Vec<_>>(),
531 )
532 };
533 let spans = |spans: &[(i32, i32)], offsets: bool| -> ArrayRef {
534 Arc::new(Int32Array::from_iter_values(
535 spans
536 .iter()
537 .map(|(offset, length)| if offsets { *offset } else { *length }),
538 ))
539 };
540 match field.name().as_str() {
541 SCHEMA_FIELD => int32s(&|h| h.schema),
542 RESET_HINT_FIELD => int32s(&|h| h.reset_hint),
543 ZERO_THRESHOLD_FIELD => floats(&|h| Some(h.zero_threshold)),
544 SUM_FIELD => floats(&|h| Some(h.sum)),
545 START_TIMESTAMP_FIELD => Arc::new(TimestampMillisecondArray::from_iter(
546 rows.iter().map(|row| row.as_ref().and_then(|h| h.start)),
547 )),
548 CUSTOM_VALUES_FIELD => list(&|h| {
549 h.custom_values
550 .clone()
551 .map(|v| Arc::new(Float64Array::from(v)) as ArrayRef)
552 }),
553 POSITIVE_SPAN_OFFSETS_FIELD => list(&|h| Some(spans(&h.positive_spans, true))),
554 POSITIVE_SPAN_LENGTHS_FIELD => list(&|h| Some(spans(&h.positive_spans, false))),
555 NEGATIVE_SPAN_OFFSETS_FIELD => list(&|h| Some(spans(&h.negative_spans, true))),
556 NEGATIVE_SPAN_LENGTHS_FIELD => list(&|h| Some(spans(&h.negative_spans, false))),
557 COUNT_I64_FIELD => ints(&|h| h.ints.as_ref().map(|i| i.0)),
558 ZERO_COUNT_I64_FIELD => ints(&|h| h.ints.as_ref().map(|i| i.1)),
559 POSITIVE_BUCKETS_I64_FIELD => list(&|h| {
560 h.ints
561 .as_ref()
562 .map(|i| Arc::new(Int64Array::from(i.2.clone())) as ArrayRef)
563 }),
564 NEGATIVE_BUCKETS_I64_FIELD => list(&|h| {
565 h.ints
566 .as_ref()
567 .map(|i| Arc::new(Int64Array::from(i.3.clone())) as ArrayRef)
568 }),
569 COUNT_F64_FIELD => floats(&|h| h.floats.as_ref().map(|f| f.0)),
570 ZERO_COUNT_F64_FIELD => floats(&|h| h.floats.as_ref().map(|f| f.1)),
571 POSITIVE_BUCKETS_F64_FIELD => list(&|h| {
572 h.floats
573 .as_ref()
574 .map(|f| Arc::new(Float64Array::from(f.2.clone())) as ArrayRef)
575 }),
576 NEGATIVE_BUCKETS_F64_FIELD => list(&|h| {
577 h.floats
578 .as_ref()
579 .map(|f| Arc::new(Float64Array::from(f.3.clone())) as ArrayRef)
580 }),
581 other => unreachable!("unknown native histogram field {other}"),
582 }
583 })
584 .collect();
585 let validity = NullBuffer::from_iter(rows.iter().map(Option::is_some));
586 StructArray::new(
587 fields,
588 children,
589 (validity.null_count() > 0).then_some(validity),
590 )
591 }
592
593 fn list_array(field: &Field, rows: &[Option<ArrayRef>]) -> ArrayRef {
594 let DataType::List(item) = field.data_type() else {
595 unreachable!("{} is a list", field.name())
596 };
597 let mut offsets = vec![0i32];
598 for row in rows {
599 offsets.push(offsets.last().unwrap() + row.as_ref().map_or(0, |a| a.len() as i32));
600 }
601 let parts = rows
602 .iter()
603 .flatten()
604 .map(|a| a.as_ref())
605 .collect::<Vec<_>>();
606 let values = if parts.is_empty() {
607 new_empty_array(item.data_type())
608 } else {
609 concat(&parts).unwrap()
610 };
611 let validity = NullBuffer::from_iter(rows.iter().map(Option::is_some));
612 Arc::new(ListArray::new(
613 item.clone(),
614 OffsetBuffer::new(offsets.into()),
615 values,
616 (validity.null_count() > 0).then_some(validity),
617 ))
618 }
619
620 pub(crate) fn fixture() -> Vec<Option<TestHistogram>> {
621 vec![
622 Some(TestHistogram {
624 schema: 3,
625 zero_threshold: 0.001,
626 sum: 12.5,
627 reset_hint: COUNTER_RESET_HINT.into(),
628 start: Some(-1_000),
629 positive_spans: vec![(-2, 2), (3, 1)],
630 negative_spans: vec![(0, 1)],
631 ints: Some((7, 1, vec![2, -1, 1], vec![-3])),
632 ..Default::default()
633 }),
634 None,
635 Some(TestHistogram {
637 sum: -0.0,
638 reset_hint: GAUGE_RESET_HINT.into(),
639 floats: Some((0.0, 0.0, vec![], vec![])),
640 ..Default::default()
641 }),
642 Some(TestHistogram {
644 schema: CUSTOM_BUCKETS_SCHEMA,
645 sum: 4.25,
646 reset_hint: NOT_COUNTER_RESET_HINT.into(),
647 custom_values: Some(vec![0.1, 0.5, f64::INFINITY]),
648 positive_spans: vec![(0, 3)],
649 floats: Some((6.0, 0.0, vec![1.0, 2.5, 2.5], vec![])),
650 ..Default::default()
651 }),
652 ]
653 }
654
655 #[test]
656 fn histogram_chunk_round_trips_and_names_its_type() {
657 let array = histogram_array(&fixture());
658 let bytes = encode(&array).unwrap();
659 let decoded = decode(
660 &bytes,
661 array.data_type(),
662 array.len(),
663 array.null_count() as u32,
664 )
665 .unwrap();
666 assert_eq!(array, decoded);
667 for row in [3, 1] {
670 let slice = array.slice(row, 1);
671 let decoded = decode(
672 &encode(&slice).unwrap(),
673 slice.data_type(),
674 1,
675 slice.null_count() as u32,
676 )
677 .unwrap();
678 assert_eq!(slice, decoded);
679 }
680
681 let DataType::Struct(fields) = array.data_type() else {
683 unreachable!()
684 };
685 let mut changed = fields
686 .iter()
687 .map(|f| f.as_ref().clone())
688 .collect::<Vec<_>>();
689 changed[0] = Field::new(changed[0].name(), DataType::Int64, true);
690 let error = decode(
691 &bytes,
692 &DataType::Struct(changed.into()),
693 array.len(),
694 array.null_count() as u32,
695 )
696 .unwrap_err();
697 assert!(error.to_string().contains("child kind mismatch"), "{error}");
698 let fewer = fields.iter().skip(1).cloned().collect::<Fields>();
699 let error = decode(&bytes, &DataType::Struct(fewer), array.len(), 1).unwrap_err();
700 assert!(
701 error.to_string().contains("child count mismatch"),
702 "{error}"
703 );
704 assert!(decode(&bytes, array.data_type(), array.len(), 0).is_err());
706 }
707}