1use std::mem::size_of;
16use std::sync::Arc;
17
18use arrow::array::{Array, BooleanArray, Float64Array, ListArray, StructArray};
19use arrow::datatypes::DataType;
20
21use crate::error::{InvalidSeriesSnafu, Result};
22use crate::series::SeriesLabels;
23use crate::series::histogram::{
24 BucketSideView, HistogramBatch, HistogramView, fields as histogram_fields,
25};
26use crate::series::time::TimeAxis;
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
35pub enum AggregateStateKind {
36 Sum,
37 Count,
38 Avg,
39 Min,
40 Max,
41 Group,
42 Stddev,
43 Stdvar,
44 HistogramSum,
46 HistogramAvg,
48}
49
50impl AggregateStateKind {
51 pub const fn as_str(self) -> &'static str {
53 match self {
54 Self::Sum => "sum",
55 Self::Count => "count",
56 Self::Avg => "avg",
57 Self::Min => "min",
58 Self::Max => "max",
59 Self::Group => "group",
60 Self::Stddev => "stddev",
61 Self::Stdvar => "stdvar",
62 Self::HistogramSum => "histogram_sum",
63 Self::HistogramAvg => "histogram_avg",
64 }
65 }
66 pub fn parse(text: &str) -> Result<Self> {
68 match text {
69 "sum" => Ok(Self::Sum),
70 "count" => Ok(Self::Count),
71 "avg" => Ok(Self::Avg),
72 "min" => Ok(Self::Min),
73 "max" => Ok(Self::Max),
74 "group" => Ok(Self::Group),
75 "stddev" => Ok(Self::Stddev),
76 "stdvar" => Ok(Self::Stdvar),
77 "histogram_sum" => Ok(Self::HistogramSum),
78 "histogram_avg" => Ok(Self::HistogramAvg),
79 _ => invalid("unknown aggregate state kind"),
80 }
81 }
82 pub const fn is_histogram(self) -> bool {
84 matches!(self, Self::HistogramSum | Self::HistogramAvg)
85 }
86 pub fn components(self) -> &'static [StateComponent] {
91 use StateComponent as C;
92 match self {
93 Self::Sum => &[C::Value, C::Compensation],
94 Self::Count => &[C::Count],
95 Self::Avg => &[
96 C::Value,
97 C::Mean,
98 C::Compensation,
99 C::Count,
100 C::IncrementalMean,
101 ],
102 Self::Min | Self::Max => &[C::Value],
103 Self::Group => &[],
104 Self::Stddev | Self::Stdvar => &[C::Value, C::Mean, C::Count],
105 Self::HistogramSum => &[
108 C::HistogramValue,
109 C::HistogramCompensation,
110 C::Poisoned,
111 C::IncompatibleLayout,
112 C::CustomBoundsReconciled,
113 C::CounterResetSeen,
114 C::NotCounterResetSeen,
115 ],
116 Self::HistogramAvg => &[
119 C::HistogramValue,
120 C::HistogramCompensation,
121 C::Count,
122 C::IncrementalMean,
123 C::Poisoned,
124 C::IncompatibleLayout,
125 C::CustomBoundsReconciled,
126 C::CounterResetSeen,
127 C::NotCounterResetSeen,
128 ],
129 }
130 }
131}
132
133#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
135pub enum StateComponent {
136 Value,
137 Mean,
138 Compensation,
139 Count,
140 IncrementalMean,
141 HistogramValue,
143 HistogramCompensation,
145 Poisoned,
147 IncompatibleLayout,
149 CustomBoundsReconciled,
151 CounterResetSeen,
153 NotCounterResetSeen,
155}
156
157impl StateComponent {
158 pub const fn as_str(self) -> &'static str {
160 match self {
161 Self::Value => "value",
162 Self::Mean => "mean",
163 Self::Compensation => "compensation",
164 Self::Count => "count",
165 Self::IncrementalMean => "incremental_mean",
166 Self::HistogramValue => "histogram_value",
167 Self::HistogramCompensation => "histogram_compensation",
168 Self::Poisoned => "poisoned",
169 Self::IncompatibleLayout => "incompatible_layout",
170 Self::CustomBoundsReconciled => "custom_bounds_reconciled",
171 Self::CounterResetSeen => "counter_reset_seen",
172 Self::NotCounterResetSeen => "not_counter_reset_seen",
173 }
174 }
175 pub fn parse(text: &str) -> Result<Self> {
177 match text {
178 "value" => Ok(Self::Value),
179 "mean" => Ok(Self::Mean),
180 "compensation" => Ok(Self::Compensation),
181 "count" => Ok(Self::Count),
182 "incremental_mean" => Ok(Self::IncrementalMean),
183 "histogram_value" => Ok(Self::HistogramValue),
184 "histogram_compensation" => Ok(Self::HistogramCompensation),
185 "poisoned" => Ok(Self::Poisoned),
186 "incompatible_layout" => Ok(Self::IncompatibleLayout),
187 "custom_bounds_reconciled" => Ok(Self::CustomBoundsReconciled),
188 "counter_reset_seen" => Ok(Self::CounterResetSeen),
189 "not_counter_reset_seen" => Ok(Self::NotCounterResetSeen),
190 _ => invalid("unknown aggregate state component"),
191 }
192 }
193 pub(crate) fn element_type(self) -> DataType {
199 match self {
200 Self::HistogramValue | Self::HistogramCompensation => {
201 DataType::Struct(histogram_fields())
202 }
203 Self::IncrementalMean
204 | Self::Poisoned
205 | Self::IncompatibleLayout
206 | Self::CustomBoundsReconciled
207 | Self::CounterResetSeen
208 | Self::NotCounterResetSeen => DataType::Boolean,
209 Self::Value | Self::Mean | Self::Compensation | Self::Count => DataType::Float64,
210 }
211 }
212}
213
214#[derive(Clone, Copy, Debug, Default, PartialEq)]
216pub struct AggregateStateValues {
217 pub value: f64,
219 pub mean: f64,
221 pub compensation: f64,
223 pub count: f64,
225 pub incremental_mean: bool,
227}
228
229#[derive(Clone, Debug)]
236pub struct HistogramState {
237 pub value: Arc<HistogramBatch>,
239 pub compensation: Arc<HistogramBatch>,
244 pub count: f64,
246 pub incremental_mean: bool,
248 pub poisoned: bool,
250 pub incompatible_layout: bool,
252 pub custom_bounds_reconciled: bool,
254 pub counter_reset_seen: bool,
256 pub not_counter_reset_seen: bool,
258}
259
260impl HistogramState {
261 pub fn validate_layout(&self) -> Result<()> {
266 let value = single_histogram(&self.value)?;
267 let compensation = single_histogram(&self.compensation)?;
268 if self.poisoned {
269 return Ok(());
270 }
271 check_layout(value, compensation)
272 }
273
274 pub fn bool_component(&self, component: StateComponent) -> Option<bool> {
276 match component {
277 StateComponent::IncrementalMean => Some(self.incremental_mean),
278 StateComponent::Poisoned => Some(self.poisoned),
279 StateComponent::IncompatibleLayout => Some(self.incompatible_layout),
280 StateComponent::CustomBoundsReconciled => Some(self.custom_bounds_reconciled),
281 StateComponent::CounterResetSeen => Some(self.counter_reset_seen),
282 StateComponent::NotCounterResetSeen => Some(self.not_counter_reset_seen),
283 _ => None,
284 }
285 }
286
287 pub fn heap_bytes(&self) -> usize {
290 self.value
291 .as_arrow()
292 .get_array_memory_size()
293 .saturating_add(self.compensation.as_arrow().get_array_memory_size())
294 }
295}
296
297#[derive(Clone, Debug)]
303pub enum StatePayload {
304 Float(AggregateStateValues),
306 Histogram(Box<HistogramState>),
308}
309
310impl StatePayload {
311 pub fn float(&self) -> Option<&AggregateStateValues> {
313 match self {
314 Self::Float(values) => Some(values),
315 Self::Histogram(_) => None,
316 }
317 }
318 pub fn histogram(&self) -> Option<&HistogramState> {
320 match self {
321 Self::Float(_) => None,
322 Self::Histogram(state) => Some(state),
323 }
324 }
325 pub fn float_component(&self, component: StateComponent) -> Option<f64> {
328 match self {
329 Self::Float(values) => match component {
330 StateComponent::Value => Some(values.value),
331 StateComponent::Mean => Some(values.mean),
332 StateComponent::Compensation => Some(values.compensation),
333 StateComponent::Count => Some(values.count),
334 _ => None,
335 },
336 Self::Histogram(state) => match component {
337 StateComponent::Count => Some(state.count),
338 _ => None,
339 },
340 }
341 }
342 pub fn bool_component(&self, component: StateComponent) -> Option<bool> {
344 match self {
345 Self::Float(values) => match component {
346 StateComponent::IncrementalMean => Some(values.incremental_mean),
347 _ => None,
348 },
349 Self::Histogram(state) => state.bool_component(component),
350 }
351 }
352 pub fn histogram_component(&self, component: StateComponent) -> Option<&Arc<HistogramBatch>> {
354 let Self::Histogram(state) = self else {
355 return None;
356 };
357 match component {
358 StateComponent::HistogramValue => Some(&state.value),
359 StateComponent::HistogramCompensation => Some(&state.compensation),
360 _ => None,
361 }
362 }
363 pub fn heap_bytes(&self) -> usize {
368 match self {
369 Self::Float(_) => 0,
370 Self::Histogram(state) => {
371 size_of::<HistogramState>().saturating_add(state.heap_bytes())
372 }
373 }
374 }
375}
376
377fn single_histogram(batch: &HistogramBatch) -> Result<HistogramView<'_>> {
379 if batch.len() != 1 {
380 return invalid("a histogram state component carries exactly one histogram");
381 }
382 batch
383 .view(0)
384 .ok_or_else(|| invalid_series("empty histogram state component"))
385}
386
387fn check_layout(value: HistogramView<'_>, compensation: HistogramView<'_>) -> Result<()> {
390 if value.schema != compensation.schema {
391 return invalid("histogram compensation schema does not match its value");
392 }
393 if value.zero_threshold.to_bits() != compensation.zero_threshold.to_bits() {
394 return invalid("histogram compensation zero threshold does not match its value");
395 }
396 if !same_bounds(value.custom_values, compensation.custom_values) {
397 return invalid("histogram compensation custom bounds do not match its value");
398 }
399 if bucket_indices(value.positive) != bucket_indices(compensation.positive)
400 || bucket_indices(value.negative) != bucket_indices(compensation.negative)
401 {
402 return invalid("histogram compensation bucket indices do not match its value");
403 }
404 Ok(())
405}
406
407fn same_bounds(lhs: &[f64], rhs: &[f64]) -> bool {
408 lhs.len() == rhs.len()
409 && lhs
410 .iter()
411 .zip(rhs)
412 .all(|(lhs, rhs)| lhs.to_bits() == rhs.to_bits())
413}
414
415fn bucket_indices(side: BucketSideView<'_>) -> Vec<i32> {
417 let mut indices = Vec::with_capacity(side.buckets.len());
418 let mut cursor = 0i32;
419 for (span, (&offset, &length)) in side.span_offsets.iter().zip(side.span_lengths).enumerate() {
420 cursor = if span == 0 {
421 offset
422 } else {
423 cursor.saturating_add(offset)
424 };
425 for index in cursor..cursor.saturating_add(length) {
426 indices.push(index);
427 }
428 cursor = cursor.saturating_add(length);
429 }
430 indices
431}
432
433#[derive(Clone, Debug, PartialEq, Eq)]
435pub struct AggregateStateSchema {
436 pub kind: AggregateStateKind,
437 pub components: Arc<[StateComponent]>,
438}
439
440impl AggregateStateSchema {
441 pub fn try_new(kind: AggregateStateKind, components: Vec<StateComponent>) -> Result<Self> {
447 if kind != AggregateStateKind::Group && components.is_empty() {
448 return invalid("aggregate state components must not be empty");
449 }
450 if components.as_slice() != kind.components() {
451 return invalid("aggregate state components do not match kind");
452 }
453 Ok(Self {
454 kind,
455 components: components.into(),
456 })
457 }
458 pub fn from_text(kind: &str, components: &str) -> Result<Self> {
460 let kind = AggregateStateKind::parse(kind)?;
461 let parsed = if components.is_empty() {
462 Vec::new()
463 } else {
464 components
465 .split(',')
466 .map(StateComponent::parse)
467 .collect::<Result<Vec<_>>>()?
468 };
469 Self::try_new(kind, parsed)
470 }
471 pub fn components_text(&self) -> String {
473 self.components
474 .iter()
475 .map(|component| component.as_str())
476 .collect::<Vec<_>>()
477 .join(",")
478 }
479}
480
481#[derive(Clone, Debug)]
483pub struct StateSeries {
484 pub metric: SeriesLabels,
486 pub time: TimeAxis,
488 pub states: Vec<Vec<Option<StatePayload>>>,
490}
491
492fn invalid<T>(reason: &str) -> Result<T> {
493 InvalidSeriesSnafu {
494 reason: reason.to_string(),
495 }
496 .fail()
497}
498
499#[derive(Clone, Debug)]
502pub struct StateFieldsBatch {
503 kind: AggregateStateKind,
504 components: Arc<[StateComponent]>,
505 fields: Vec<StructArray>,
506}
507
508impl StateFieldsBatch {
509 pub fn try_from_arrow(fields: StructArray, schema: &AggregateStateSchema) -> Result<Self> {
511 if fields.num_columns() == 0 {
512 return invalid("state fields array has no fields");
513 }
514 let mut items = Vec::with_capacity(fields.num_columns());
515 for (column, field) in fields.columns().iter().zip(fields.fields()) {
516 let DataType::List(item) = field.data_type() else {
517 return invalid("state field is not a list");
518 };
519 let DataType::Struct(members) = item.data_type() else {
520 return invalid("state list item is not a struct");
521 };
522 if members.len() != schema.components.len() {
523 return invalid("state component count mismatch");
524 }
525 for (member, expected) in members.iter().zip(schema.components.iter()) {
526 if member.name() != expected.as_str() {
527 return invalid("state component order mismatch");
528 }
529 if member.data_type() != &expected.element_type() {
530 return invalid("state component type mismatch");
531 }
532 }
533 let list = column
534 .as_any()
535 .downcast_ref::<ListArray>()
536 .ok_or_else(|| invalid_series("state field list type mismatch"))?;
537 if list.is_null(0) {
538 return invalid("null state field list");
539 }
540 let item_array = list.value(0);
541 let item_struct = item_array
542 .as_any()
543 .downcast_ref::<StructArray>()
544 .ok_or_else(|| invalid_series("state item struct type mismatch"))?;
545 items.push(item_struct.clone());
546 }
547 Ok(Self {
548 kind: schema.kind,
549 components: schema.components.clone(),
550 fields: items,
551 })
552 }
553 pub fn len(&self) -> usize {
555 self.fields.len()
556 }
557 pub fn is_empty(&self) -> bool {
559 self.fields.is_empty()
560 }
561 pub fn field(&self, index: usize) -> Option<&StructArray> {
563 self.fields.get(index)
564 }
565 pub fn kind(&self) -> AggregateStateKind {
567 self.kind
568 }
569 pub fn components(&self) -> &[StateComponent] {
571 &self.components
572 }
573 pub fn field_values(
575 &self,
576 field: usize,
577 component: StateComponent,
578 ) -> Result<Option<&Float64Array>> {
579 let Some(index) = self.components.iter().position(|value| *value == component) else {
580 return Ok(None);
581 };
582 self.fields
583 .get(field)
584 .ok_or_else(|| invalid_series("state field index out of range"))?
585 .column(index)
586 .as_any()
587 .downcast_ref::<Float64Array>()
588 .map(Some)
589 .ok_or_else(|| invalid_series("state float component type mismatch"))
590 }
591 pub fn field_bool_values(
593 &self,
594 field: usize,
595 component: StateComponent,
596 ) -> Result<Option<&BooleanArray>> {
597 let Some(index) = self.components.iter().position(|value| *value == component) else {
598 return Ok(None);
599 };
600 self.fields
601 .get(field)
602 .ok_or_else(|| invalid_series("state field index out of range"))?
603 .column(index)
604 .as_any()
605 .downcast_ref::<BooleanArray>()
606 .map(Some)
607 .ok_or_else(|| invalid_series("state boolean component type mismatch"))
608 }
609 pub fn field_histograms(
614 &self,
615 field: usize,
616 component: StateComponent,
617 ) -> Result<Option<&StructArray>> {
618 let Some(index) = self.components.iter().position(|value| *value == component) else {
619 return Ok(None);
620 };
621 self.fields
622 .get(field)
623 .ok_or_else(|| invalid_series("state field index out of range"))?
624 .column(index)
625 .as_any()
626 .downcast_ref::<StructArray>()
627 .map(Some)
628 .ok_or_else(|| invalid_series("state histogram component type mismatch"))
629 }
630 pub fn field_histogram(
632 &self,
633 field: usize,
634 component: StateComponent,
635 position: usize,
636 ) -> Result<Option<HistogramBatch>> {
637 let Some(column) = self.field_histograms(field, component)? else {
638 return Ok(None);
639 };
640 if position >= column.len() {
641 return invalid("state position out of range");
642 }
643 if column.is_null(position) {
644 return Ok(None);
645 }
646 HistogramBatch::try_from_arrow(column.slice(position, 1)).map(Some)
647 }
648 pub fn is_present(&self, field: usize, position: usize) -> Result<bool> {
650 let items = self
651 .fields
652 .get(field)
653 .ok_or_else(|| invalid_series("state field index out of range"))?;
654 if position >= items.len() {
655 return invalid("state position out of range");
656 }
657 Ok(!items.is_null(position))
658 }
659}
660
661fn invalid_series(reason: &str) -> crate::error::Error {
662 InvalidSeriesSnafu {
663 reason: reason.to_string(),
664 }
665 .build()
666}