Skip to main content

mito2/sst/
narthex.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 sample and series-index writers.
16
17use std::cmp::Reverse;
18use std::collections::BinaryHeap;
19use std::sync::Arc;
20
21use datatypes::arrow::array::{Array, BinaryArray, DictionaryArray};
22use datatypes::arrow::compute::{cast, max, min};
23use datatypes::arrow::datatypes::{DataType, UInt32Type};
24use futures::stream::BoxStream;
25use futures::{StreamExt, TryStreamExt};
26use snafu::ResultExt;
27use store_api::metadata::RegionMetadata;
28use store_api::storage::FileId;
29
30use crate::access_layer::{AccessLayer, SstWriteRequest};
31use crate::access_layer::{OperationType, SstInfoArray};
32use crate::cache::file_cache::{FileType, IndexKey};
33use crate::cache::write_cache::{NarthexUpload, WriteCacheRef};
34use crate::error::{ComputeArrowSnafu, InvalidRecordBatchSnafu, Result};
35use crate::series_index::columnar::reader::ColumnarReader;
36use crate::series_index::columnar::{ColumnarSeriesFormat, invalid, require};
37use crate::series_index::format::{FormatWriter, SamplesFormatReader};
38use crate::series_index::identity::ExactSeriesKey;
39use crate::series_index::samples::ColumnarSamplesFormat;
40use crate::series_index::samples::reader::SamplesReader;
41use crate::sst::file::{
42    FileFormat, FileHandle, FileMeta, NarthexPartMeta, NarthexSamplesMeta, NarthexSeriesIndexMeta,
43    RegionFileId,
44};
45use crate::sst::location;
46use crate::sst::parquet::SstInfo;
47use crate::sst::parquet::writer::SstWriteGuard;
48
49/// Counts changes in a sorted key stream, including across independent Arrow dictionaries.
50fn count_series(keys: &dyn Array, previous_key: &mut Vec<u8>) -> Result<u64> {
51    let mut count = 0;
52    let mut count_key = |key: &[u8]| {
53        if key != previous_key.as_slice() {
54            count += 1;
55            previous_key.clear();
56            previous_key.extend_from_slice(key);
57        }
58    };
59    if let Some(dictionary) = keys.as_any().downcast_ref::<DictionaryArray<UInt32Type>>()
60        && let Some(values) = dictionary.values().as_any().downcast_ref::<BinaryArray>()
61    {
62        // Indices only carry meaning within this batch. Distinct indices may also hold
63        // equal bytes, so check the bytes at each transition.
64        let mut previous_index = None;
65        for index in dictionary.keys().iter().flatten() {
66            if previous_index == Some(index) {
67                continue;
68            }
69            previous_index = Some(index);
70            let index = index as usize;
71            if index >= values.len() {
72                return Err(invalid("invalid narthex dictionary key index"));
73            }
74            if values.is_valid(index) {
75                count_key(values.value(index));
76            }
77        }
78    } else if let Some(keys) = keys.as_any().downcast_ref::<BinaryArray>() {
79        keys.iter().flatten().for_each(count_key);
80    } else {
81        let binary = cast(keys, &DataType::Binary).context(ComputeArrowSnafu)?;
82        let keys = binary
83            .as_any()
84            .downcast_ref::<BinaryArray>()
85            .ok_or_else(|| {
86                InvalidRecordBatchSnafu {
87                    reason: "invalid narthex primary key".to_string(),
88                }
89                .build()
90            })?;
91        keys.iter().flatten().for_each(count_key);
92    }
93    Ok(count)
94}
95
96/// Reuses the narthex codec and the caller's merged, sequence-normalized source.
97pub(crate) async fn write_samples(
98    layer: &AccessLayer,
99    mut request: SstWriteRequest,
100    guard: Option<Arc<dyn SstWriteGuard>>,
101    cancellation: Option<tokio_util::sync::CancellationToken>,
102) -> Result<SstInfoArray> {
103    let id = FileId::random();
104    let region_id = request.metadata.region_id;
105    if let Some(guard) = guard {
106        guard
107            .before_create_narthex(RegionFileId::new(region_id, id))
108            .await?;
109    }
110    let prefix = location::narthex_file_dir(&layer.build_region_dir(region_id), id);
111    let cache = request.cache_manager.write_cache();
112    let store = cache.map_or_else(
113        || layer.object_store().clone(),
114        |cache| cache.file_cache().local_store(),
115    );
116    let mut writer = Box::new(crate::series_index::samples::writer::SamplesWriter::new(
117        ColumnarSamplesFormat::default(),
118        request.metadata.clone(),
119        store,
120        &prefix,
121        id,
122        id,
123    )?);
124    if let Some(cache) = cache {
125        writer.set_upload(NarthexUpload::new(
126            cache,
127            layer.object_store(),
128            prefix,
129            IndexKey::new(region_id, id, FileType::Samples(None)),
130            request.op_type,
131            cancellation.clone(),
132        ));
133    }
134    let mut rows = 0;
135    let mut series = 0;
136    let mut previous_key = Vec::new();
137    let mut lower = i64::MAX;
138    let mut upper = i64::MIN;
139    let timestamp = &request.metadata.time_index_column().column_schema.name;
140    let write_result: Result<()> = async {
141        loop {
142            let next = request.source.next_batch();
143            let batch = if let Some(signal) = &cancellation {
144                tokio::select! {
145                    biased;
146                    _ = signal.cancelled() => return crate::error::CompactionCancelledSnafu.fail(),
147                    batch = next => batch?,
148                }
149            } else {
150                next.await?
151            };
152            let Some(batch) = batch else {
153                break;
154            };
155
156            if batch.num_rows() == 0 {
157                continue;
158            }
159            let ts = batch.column_by_name(timestamp).ok_or_else(|| {
160                InvalidRecordBatchSnafu {
161                    reason: "narthex samples lack timestamp".to_string(),
162                }
163                .build()
164            })?;
165            let (values, _) =
166                datatypes::timestamp::timestamp_array_to_primitive(ts).ok_or_else(|| {
167                    InvalidRecordBatchSnafu {
168                        reason: "invalid narthex timestamp".to_string(),
169                    }
170                    .build()
171                })?;
172            lower = lower.min(min(&values).unwrap_or(lower));
173            upper = upper.max(max(&values).unwrap_or(upper));
174            let keys = batch.column_by_name("__primary_key").ok_or_else(|| {
175                InvalidRecordBatchSnafu {
176                    reason: "narthex samples lack primary key".to_string(),
177                }
178                .build()
179            })?;
180            series += count_series(keys.as_ref(), &mut previous_key)?;
181            rows += batch.num_rows();
182            // Narthex files always retain row sequences; import barriers are applied by readers.
183            writer.write(&batch).await?;
184        }
185        Ok(())
186    }
187    .await;
188    if let Err(error) = write_result {
189        return Err(abort_narthex_write(writer, error).await);
190    }
191    if rows == 0 {
192        writer.abort().await?;
193        return Ok(Default::default());
194    }
195    let artifact = writer.finish().await?;
196    // The samples codec returns its manifest first, then parts in ID order.
197    let (manifest, parts) = artifact.objects.split_first().ok_or_else(|| {
198        InvalidRecordBatchSnafu {
199            reason: "missing Narthex samples manifest",
200        }
201        .build()
202    })?;
203    let unit = request.metadata.time_index_type().unit();
204    let info = SstInfo {
205        file_id: id,
206        time_range: (
207            common_time::Timestamp::new(lower, unit),
208            common_time::Timestamp::new(upper, unit),
209        ),
210        file_size: artifact.file_size,
211        num_rows: rows,
212        num_series: series,
213        num_row_groups: 0,
214        max_row_group_uncompressed_size: 0,
215        max_row_group_decoded_size: 0,
216        file_metadata: None,
217        index_metadata: Default::default(),
218        format: FileFormat::NarthexSamples(Box::new(NarthexSamplesMeta {
219            manifest_size: manifest.file_size,
220            parts: parts
221                .iter()
222                .map(|part| NarthexPartMeta {
223                    file_size: part.file_size,
224                })
225                .collect(),
226        })),
227    };
228    Ok(smallvec::smallvec![info])
229}
230
231/// Reconstruct the canonical sparse key from a Narthex series row, in SST order.
232async fn series_keys(
233    layer: &AccessLayer,
234    cache: Option<&WriteCacheRef>,
235    source: &FileHandle,
236    metadata: &RegionMetadata,
237) -> Result<BoxStream<'static, Result<(ExactSeriesKey, u64)>>> {
238    let mut reader = ColumnarReader::open_cached(
239        layer.object_store().clone(),
240        source.clone(),
241        &layer.build_region_dir(source.region_id()),
242        crate::cache::columnar::MetadataCache::maintenance(cache),
243    )
244    .await?;
245    reader.adapt_tags(metadata)?;
246    Ok(reader.read_full_keys())
247}
248
249/// Merge sorted sample keys or stored index rows. A separate manifest edit publishes the index.
250pub(crate) async fn write_series(
251    layer: &AccessLayer,
252    cache: Option<&WriteCacheRef>,
253    metadata: store_api::metadata::RegionMetadataRef,
254    sources: &[FileHandle],
255    window: crate::sst::file::WindowSequence,
256) -> Result<crate::sst::file::FileMeta> {
257    require(!sources.is_empty(), "narthex series index requires inputs")?;
258    let id = FileId::random();
259    let prefix = location::narthex_file_dir(&layer.build_region_dir(metadata.region_id), id);
260    let mut file = FileMeta {
261        region_id: metadata.region_id,
262        file_id: id,
263        time_range: sources
264            .iter()
265            .map(|file| file.meta_ref().time_range)
266            .reduce(|left, right| (left.0.min(right.0), left.1.max(right.1)))
267            .ok_or_else(|| {
268                crate::series_index::columnar::invalid("empty narthex index source set")
269            })?,
270        format: FileFormat::NarthexSeriesIndex(Box::new(NarthexSeriesIndexMeta {
271            manifest_size: 0,
272            parts: Default::default(),
273            window,
274        })),
275        ..Default::default()
276    };
277    let mut writer = ColumnarSeriesFormat::default().narthex_writer(
278        metadata.clone(),
279        cache.map_or_else(
280            || layer.object_store().clone(),
281            |cache| cache.file_cache().local_store(),
282        ),
283        &file,
284        prefix.clone(),
285    )?;
286    if let Some(cache) = cache {
287        writer.set_upload(NarthexUpload::new(
288            cache,
289            layer.object_store(),
290            prefix,
291            IndexKey::new(metadata.region_id, id, FileType::Series(None)),
292            OperationType::Compact,
293            None,
294        ));
295    }
296    let write_result: Result<()> = async {
297        let mut streams = Vec::with_capacity(sources.len());
298        let mut heads = BinaryHeap::new();
299        for source in sources {
300            let mut stream = match &source.meta_ref().format {
301                FileFormat::NarthexSeriesIndex(_) => {
302                    series_keys(layer, cache, source, &metadata).await?
303                }
304                FileFormat::NarthexSamples(_) => SamplesReader::open_cached(
305                    layer.object_store().clone(),
306                    source.clone(),
307                    &layer.build_region_dir(source.region_id()),
308                    crate::cache::columnar::MetadataCache::maintenance(cache),
309                )
310                .await?
311                .read(Default::default())?
312                .map_ok(|block| (block.key, block.batch.num_rows() as u64))
313                .boxed(),
314                FileFormat::Parquet => {
315                    return Err(invalid("expected Narthex series or samples"));
316                }
317            };
318            if let Some((key, rows)) = stream.try_next().await? {
319                heads.push(Reverse((key, streams.len(), rows)));
320            }
321            streams.push(stream);
322        }
323        while let Some(Reverse((key, index, rows))) = heads.pop() {
324            writer.append_key(key.bytes(), rows).await?;
325            if let Some((key, rows)) = streams[index].try_next().await? {
326                heads.push(Reverse((key, index, rows)));
327            }
328        }
329        Ok(())
330    }
331    .await;
332    if let Err(error) = write_result {
333        return Err(abort_narthex_write(writer, error).await);
334    }
335    let artifact = writer.finish().await?;
336    file.file_size = artifact.file_size;
337    if let FileFormat::NarthexSeriesIndex(index) = &mut file.format {
338        // The series codec returns its manifest after the ordered parts.
339        let (manifest, parts) = artifact.objects.split_last().ok_or_else(|| {
340            crate::series_index::columnar::invalid("missing Narthex series manifest")
341        })?;
342        index.manifest_size = manifest.file_size;
343        index.parts = parts
344            .iter()
345            .map(|part| NarthexPartMeta {
346                file_size: part.file_size,
347            })
348            .collect();
349    }
350    Ok(file)
351}
352
353/// Complete cleanup before reporting a failed write. Drop cleanup remains a fallback
354/// for cancellation, but can race runtime shutdown after an ordinary returned error.
355pub(crate) async fn abort_narthex_write(
356    writer: Box<dyn crate::series_index::format::FormatWriter>,
357    error: crate::error::Error,
358) -> crate::error::Error {
359    if let Err(cleanup_error) = writer.abort().await {
360        common_telemetry::warn!(cleanup_error; "Failed to abort unpublished narthex artifact");
361    }
362    error
363}
364
365#[cfg(test)]
366mod key_count_tests {
367    use datatypes::arrow::array::UInt32Array;
368
369    use super::*;
370
371    #[test]
372    fn counts_runs_across_dictionary_changes() {
373        let first = DictionaryArray::<UInt32Type>::new(
374            UInt32Array::from(vec![0, 0, 1, 2, 2]),
375            Arc::new(BinaryArray::from_vec(vec![b"a", b"a", b"b"])),
376        );
377        let second = DictionaryArray::<UInt32Type>::new(
378            UInt32Array::from(vec![0, 0, 1]),
379            Arc::new(BinaryArray::from_vec(vec![b"b", b"c"])),
380        );
381        let mut previous = Vec::new();
382        assert_eq!(count_series(&first, &mut previous).unwrap(), 2);
383        assert_eq!(count_series(&second, &mut previous).unwrap(), 1);
384        assert_eq!(previous, b"c");
385    }
386}