Skip to main content

mito2/series_index/
samples.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Narthex samples files. Wire contract: `docs/formats/mito-samples.md`.
16
17pub(crate) mod bulk;
18mod codec;
19mod histogram;
20mod key_pages;
21mod metadata;
22#[cfg(test)]
23pub(crate) use histogram::tests::{TestHistogram, histogram_array};
24pub(crate) use metadata::{Group, Page, PageReference};
25pub(crate) mod reader;
26#[cfg(test)]
27mod tests;
28pub(crate) mod writer;
29
30use bytes::Bytes;
31use std::collections::HashSet;
32use std::sync::Arc;
33
34use common_query::native_histogram::{is_native_histogram_value_type, native_histogram_value_type};
35use datatypes::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit};
36use datatypes::data_type::DataType as _;
37use serde::{Deserialize, Serialize};
38use store_api::storage::FileId;
39
40use crate::error::Result;
41use crate::series_index::artifact::ArtifactFormat;
42use crate::series_index::columnar::{invalid, require, unsupported};
43use crate::series_index::identity::IdentityEncoding;
44use crate::series_index::{MetricSeriesId, TABLE_ID_COLUMN, TSID_COLUMN};
45use crate::sst::location;
46
47/// Reject unsupported narthex schemas before accepting mutations that cannot flush.
48pub(crate) fn validate_narthex_metadata(
49    metadata: &store_api::metadata::RegionMetadata,
50) -> Result<()> {
51    crate::series_index::writer::validate_metadata(metadata)?;
52    require(
53        matches!(
54            metadata
55                .time_index_column()
56                .column_schema
57                .data_type
58                .as_arrow_type(),
59            DataType::Timestamp(_, None)
60        ),
61        "narthex samples require a timestamp time index",
62    )?;
63    for column in metadata.field_columns() {
64        require(
65            ValueColumn::new(column).is_ok() && column.column_schema.is_nullable(),
66            "Narthex samples require nullable Float64 or native histogram fields",
67        )?;
68    }
69    Ok(())
70}
71
72/// Rejects native histogram samples a Narthex region could not store, before the write is
73/// accepted: every sample must fit one samples chunk on its own.
74pub(crate) fn check_histogram_rows(
75    metadata: &store_api::metadata::RegionMetadata,
76    rows: &api::v1::Rows,
77) -> Result<()> {
78    use api::v1::value::ValueData;
79
80    for (index, column) in rows.schema.iter().enumerate() {
81        if !metadata
82            .column_by_name(&column.column_name)
83            .is_some_and(|c| is_native_histogram_value_type(&c.column_schema.data_type))
84        {
85            continue;
86        }
87        for row in &rows.rows {
88            let Some(ValueData::StructValue(value)) =
89                row.values.get(index).and_then(|v| v.value_data.as_ref())
90            else {
91                continue;
92            };
93            let list_items = value
94                .items
95                .iter()
96                .map(|item| match &item.value_data {
97                    Some(ValueData::ListValue(list)) => list.items.len(),
98                    _ => 0,
99                })
100                .sum();
101            histogram::check_sample_size(value.items.len(), list_items)?;
102        }
103    }
104    Ok(())
105}
106
107/// [`check_histogram_rows`] for a bulk write batch.
108pub(crate) fn check_histogram_batch(
109    batch: &datatypes::arrow::record_batch::RecordBatch,
110) -> Result<()> {
111    use datatypes::arrow::array::AsArray;
112
113    batch
114        .columns()
115        .iter()
116        .filter_map(|column| column.as_struct_opt())
117        .try_for_each(histogram::check_array_sample_sizes)
118}
119
120const VERSION: u32 = 1;
121const MANIFEST_LIMIT: usize = 64 * 1024 * 1024;
122const MAX_ROWS: usize = 8192;
123const MAX_FIELDS: usize = 1024;
124const BLOCK_BYTES: usize = 256 * 1024;
125const SEQUENCE: &str = "__sequence";
126const OPERATION: &str = "__op_type";
127/// Output column naming the exact series key that owns each returned sample row.
128const PRIMARY_KEY: &str = store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
129
130/// Internal packing knobs; the backend is disabled unless selected explicitly.
131#[derive(Debug, Clone)]
132pub(crate) struct ColumnarSamplesFormat {
133    pub(crate) block_rows: usize,
134    pub(crate) part_bytes: u64,
135    pub(crate) metadata_bytes: usize,
136    pub(crate) page_bytes: usize,
137    pub(crate) root_capacity: usize,
138}
139impl Default for ColumnarSamplesFormat {
140    fn default() -> Self {
141        Self {
142            block_rows: MAX_ROWS,
143            part_bytes: 512 * 1024 * 1024,
144            metadata_bytes: 4 * 1024 * 1024,
145            page_bytes: metadata::PAGE_LIMIT,
146            root_capacity: metadata::ROOT_CAPACITY,
147        }
148    }
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
152struct TimestampColumn {
153    column_id: u32,
154    name: String,
155    unit: TimestampUnit,
156}
157#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
158#[serde(rename_all = "lowercase")]
159enum TimestampUnit {
160    Second,
161    Millisecond,
162    Microsecond,
163    Nanosecond,
164}
165impl TimestampUnit {
166    fn arrow(self) -> TimeUnit {
167        match self {
168            Self::Second => TimeUnit::Second,
169            Self::Millisecond => TimeUnit::Millisecond,
170            Self::Microsecond => TimeUnit::Microsecond,
171            Self::Nanosecond => TimeUnit::Nanosecond,
172        }
173    }
174    fn from_arrow(unit: &TimeUnit) -> Self {
175        match unit {
176            TimeUnit::Second => Self::Second,
177            TimeUnit::Millisecond => Self::Millisecond,
178            TimeUnit::Microsecond => Self::Microsecond,
179            TimeUnit::Nanosecond => Self::Nanosecond,
180        }
181    }
182}
183#[derive(Debug, Clone, Serialize, Deserialize)]
184struct ValueColumn {
185    column_id: u32,
186    name: String,
187    #[serde(rename = "type")]
188    data_type: String,
189    nullable: bool,
190}
191const FLOAT64_TYPE: &str = "float64";
192const NATIVE_HISTOGRAM_TYPE: &str = "native_histogram";
193/// Sample column encoding ID of a nullable Float64 field.
194const FLOAT64_ENCODING: u16 = 5;
195impl ValueColumn {
196    fn new(column: &store_api::metadata::ColumnMetadata) -> Result<Self> {
197        let data_type = &column.column_schema.data_type;
198        let data_type = if data_type.as_arrow_type() == DataType::Float64 {
199            FLOAT64_TYPE
200        } else if is_native_histogram_value_type(data_type) {
201            NATIVE_HISTOGRAM_TYPE
202        } else {
203            return Err(invalid(
204                "samples support only Float64 and native histogram fields",
205            ));
206        };
207        Ok(Self {
208            column_id: column.column_id,
209            name: column.column_schema.name.clone(),
210            data_type: data_type.to_string(),
211            nullable: true,
212        })
213    }
214
215    fn is_histogram(&self) -> bool {
216        self.data_type == NATIVE_HISTOGRAM_TYPE
217    }
218
219    /// The only column encoding a chunk of this field may carry.
220    fn encoding(&self) -> Result<u16> {
221        match self.data_type.as_str() {
222            FLOAT64_TYPE => Ok(FLOAT64_ENCODING),
223            NATIVE_HISTOGRAM_TYPE => Ok(histogram::ENCODING),
224            _ => Err(invalid("unsupported samples field type")),
225        }
226    }
227
228    fn arrow_type(&self) -> DataType {
229        if self.is_histogram() {
230            native_histogram_value_type().as_arrow_type()
231        } else {
232            DataType::Float64
233        }
234    }
235}
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237struct Part {
238    part_id: u32,
239    directory_bytes: u64,
240    file_size: u64,
241    num_rows: u64,
242    num_blocks: u64,
243    first: MetricSeriesId,
244    last: MetricSeriesId,
245    min_timestamp: i64,
246    max_timestamp: i64,
247}
248impl Part {
249    fn from_groups(part_id: u32, file_size: u64, groups: &[metadata::Group]) -> Result<Self> {
250        let mut bounds = groups
251            .first()
252            .ok_or_else(|| invalid("empty sample part"))?
253            .root
254            .bounds;
255        let mut rows = 0u64;
256        let mut blocks = 0u64;
257        for group in groups {
258            bounds.extend(group.root.bounds);
259            rows = rows
260                .checked_add(group.rows)
261                .ok_or_else(|| invalid("sample part row count overflow"))?;
262            blocks = blocks
263                .checked_add(group.blocks)
264                .ok_or_else(|| invalid("sample part block count overflow"))?;
265        }
266        Ok(Self {
267            part_id,
268            file_size,
269            directory_bytes: (groups.len() * metadata::GROUP_BYTES) as u64,
270            num_rows: rows,
271            num_blocks: blocks,
272            first: bounds.first,
273            last: bounds.last,
274            min_timestamp: bounds.min,
275            max_timestamp: bounds.max,
276        })
277    }
278}
279#[derive(Debug, Clone, Serialize, Deserialize)]
280struct Manifest {
281    /// Resolved from the owning file, not persisted in the codec manifest.
282    #[serde(skip)]
283    prefix: String,
284    format: ArtifactFormat,
285    version: u32,
286    /// Mandatory discriminator; see [`IdentityEncoding`]. Never defaulted on read.
287    identity_encoding: IdentityEncoding,
288    region_id: u64,
289    source_file_id: FileId,
290    generation: FileId,
291    timestamp: TimestampColumn,
292    fields: Vec<ValueColumn>,
293    files: Vec<Part>,
294}
295#[derive(Debug)]
296struct MemoryArtifact {
297    file_id: FileId,
298    manifest: Bytes,
299    parts: Vec<Bytes>,
300    /// Decoded keys addressed by the resident block descriptors.
301    keys: Bytes,
302    blocks: Vec<(usize, metadata::Block)>,
303    fields: Vec<ValueColumn>,
304}
305
306impl Manifest {
307    fn retained_size(&self) -> usize {
308        std::mem::size_of::<Self>()
309            + self.prefix.capacity()
310            + self.timestamp.name.capacity()
311            + self.files.capacity() * std::mem::size_of::<Part>()
312            + self.fields.capacity() * std::mem::size_of::<ValueColumn>()
313            + self
314                .fields
315                .iter()
316                .map(|field| field.name.capacity() + field.data_type.capacity())
317                .sum::<usize>()
318    }
319
320    fn path(&self) -> String {
321        location::narthex_manifest_path(&self.prefix)
322    }
323    fn part_path(&self, id: u32) -> String {
324        location::narthex_part_path(&self.prefix, id as usize, "samples")
325    }
326    fn validate_schema(&self) -> Result<()> {
327        require(
328            (1..=MAX_FIELDS).contains(&self.fields.len()),
329            "invalid samples field count",
330        )?;
331        let mut names = HashSet::from([
332            TABLE_ID_COLUMN,
333            TSID_COLUMN,
334            SEQUENCE,
335            OPERATION,
336            PRIMARY_KEY,
337        ]);
338        require(
339            names.insert(&self.timestamp.name),
340            "duplicate samples timestamp name",
341        )?;
342        let mut ids = HashSet::from([self.timestamp.column_id]);
343        for field in &self.fields {
344            require(
345                field.encoding().is_ok() && field.nullable,
346                "unsupported samples field type/nullability",
347            )?;
348            require(
349                names.insert(&field.name) && ids.insert(field.column_id),
350                "duplicate samples field name/id",
351            )?;
352        }
353        Ok(())
354    }
355    fn schema(&self) -> SchemaRef {
356        let mut fields = vec![
357            Field::new(TABLE_ID_COLUMN, DataType::UInt32, false),
358            Field::new(TSID_COLUMN, DataType::UInt64, false),
359            crate::sst::with_field_id(
360                Field::new(
361                    &self.timestamp.name,
362                    DataType::Timestamp(self.timestamp.unit.arrow(), None),
363                    false,
364                ),
365                self.timestamp.column_id,
366            ),
367            Field::new(SEQUENCE, DataType::UInt64, false),
368            Field::new(OPERATION, DataType::UInt8, false),
369        ];
370        fields.extend(self.fields.iter().map(|f| {
371            crate::sst::with_field_id(Field::new(&f.name, f.arrow_type(), true), f.column_id)
372        }));
373        // Appended after the data fields so stored row indices stay stable. The column is the
374        // artifact's exact-identity marker: readers attribute every row of a batch by the key
375        // they return with it and never project this column.
376        fields.push(Field::new(PRIMARY_KEY, DataType::Binary, false));
377        Arc::new(Schema::new(fields))
378    }
379
380    /// Index of the exact series key column in [`Self::schema`].
381    fn primary_key_index(&self) -> usize {
382        5 + self.fields.len()
383    }
384}
385
386fn valid_rows(rows: usize, fields: usize) -> bool {
387    (1..=MAX_ROWS).contains(&rows)
388        && (1..=MAX_FIELDS).contains(&fields)
389        && rows * (17 + 8 * fields) + fields * rows.div_ceil(8) <= BLOCK_BYTES
390}