Skip to main content

mito2/series_index/samples/
writer.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//! Streaming sample writing with bounded blocks and owned outputs.
16
17use std::sync::Arc;
18
19use async_trait::async_trait;
20use bytes::Bytes;
21use datatypes::arrow::array::{
22    Array, ArrayRef, AsArray, BinaryArray, DictionaryArray, Float64Array, StructArray, UInt8Array,
23    UInt64Array,
24};
25use datatypes::arrow::compute::concat;
26use datatypes::arrow::datatypes::{DataType, UInt32Type};
27use datatypes::arrow::record_batch::RecordBatch;
28use datatypes::prelude::DataType as _;
29use datatypes::timestamp::timestamp_array_to_primitive;
30use futures::FutureExt;
31use object_store::ObjectStore;
32use snafu::ResultExt;
33use store_api::metadata::RegionMetadataRef;
34use store_api::storage::{FileId, consts};
35
36use crate::error::{ComputeArrowSnafu, Result, SerdeJsonSnafu};
37use crate::series_index::artifact::{ArtifactFormat, ArtifactMetadata, ArtifactObject};
38use crate::series_index::artifact_writer::Outputs;
39use crate::series_index::format::FormatWriter;
40use crate::series_index::identity::{ExactSeriesKey, IdentityEncoding};
41use crate::series_index::samples::bulk::NarthexBulkPart;
42use crate::series_index::samples::histogram::ChunkBound;
43use crate::series_index::samples::metadata::{self, Block, Column, KeyRef, Page, PageReference};
44use crate::series_index::samples::{
45    ColumnarSamplesFormat, FLOAT64_ENCODING, MANIFEST_LIMIT, MAX_ROWS, Manifest, MemoryArtifact,
46    MetricSeriesId, Part, TimestampColumn, TimestampUnit, VERSION, ValueColumn, codec, histogram,
47    invalid, require, valid_rows, validate_narthex_metadata,
48};
49
50use crate::sst::DEFAULT_WRITE_BUFFER_SIZE;
51
52/// Both destinations receive exactly the same file framing and codec output.
53enum Destination {
54    Store(Outputs),
55    Memory {
56        current: Option<Vec<u8>>,
57        objects: Vec<Bytes>,
58        blocks: Vec<(usize, Block)>,
59        keys: Vec<u8>,
60    },
61}
62
63impl Destination {
64    fn is_open(&self) -> bool {
65        match self {
66            Self::Store(outputs) => outputs.active.is_some(),
67            Self::Memory { current, .. } => current.is_some(),
68        }
69    }
70
71    async fn open(&mut self, path: String) -> Result<()> {
72        match self {
73            Self::Store(outputs) => outputs.open(path).await,
74            Self::Memory { current, .. } => {
75                *current = Some(Vec::new());
76                Ok(())
77            }
78        }
79    }
80
81    async fn write(&mut self, bytes: Vec<u8>) -> Result<()> {
82        match self {
83            Self::Store(outputs) => outputs.write(bytes).await,
84            Self::Memory { current, .. } => {
85                current.as_mut().expect("open memory object").extend(bytes);
86                Ok(())
87            }
88        }
89    }
90
91    async fn close(&mut self) -> Result<()> {
92        match self {
93            Self::Store(outputs) => outputs.close().await,
94            Self::Memory {
95                current, objects, ..
96            } => {
97                objects.push(Bytes::from(
98                    current
99                        .take()
100                        .expect("open memory object")
101                        .into_boxed_slice(),
102                ));
103                Ok(())
104            }
105        }
106    }
107
108    async fn cleanup(&mut self) -> Result<()> {
109        if let Self::Store(outputs) = self {
110            outputs.cleanup().await?;
111        }
112        Ok(())
113    }
114}
115
116/// Coalesces encoded columns across blocks before handing them to OpenDAL.
117#[derive(Default)]
118struct SampleBuffer {
119    bytes: Vec<u8>,
120}
121
122impl SampleBuffer {
123    async fn write(&mut self, outputs: &mut Destination, mut bytes: &[u8]) -> Result<()> {
124        if let Destination::Memory { current, .. } = outputs {
125            current
126                .as_mut()
127                .expect("open memory part")
128                .extend_from_slice(bytes);
129            return Ok(());
130        }
131        let capacity = DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize;
132        while !bytes.is_empty() {
133            if self.bytes.capacity() == 0 {
134                self.bytes.reserve_exact(capacity);
135            }
136            let count = bytes.len().min(capacity - self.bytes.len());
137            self.bytes.extend_from_slice(&bytes[..count]);
138            bytes = &bytes[count..];
139            if self.bytes.len() == capacity {
140                self.flush(outputs).await?;
141            }
142        }
143        Ok(())
144    }
145
146    async fn flush(&mut self, outputs: &mut Destination) -> Result<()> {
147        if !self.bytes.is_empty() {
148            outputs.write(std::mem::take(&mut self.bytes)).await?;
149        }
150        Ok(())
151    }
152}
153
154#[derive(Default)]
155struct BlockScratch {
156    timestamps: Vec<i64>,
157    sequences: Vec<u64>,
158    operations: Vec<u8>,
159    encoded: Vec<u8>,
160    compressed: Vec<u8>,
161}
162
163#[derive(Default)]
164struct DescriptorScratch {
165    raw: Vec<u8>,
166    compressed: Vec<u8>,
167}
168
169struct Row {
170    id: MetricSeriesId,
171    time: i64,
172    sequence: u64,
173    operation: u8,
174}
175/// One field's values for the rows of the pending block, in row order.
176enum PendingField {
177    Float(Vec<Option<u64>>),
178    /// Runs of rows borrowed from input batches, concatenated once when the block is encoded.
179    Histogram {
180        runs: Vec<(ArrayRef, usize, usize)>,
181        bound: ChunkBound,
182    },
183}
184impl PendingField {
185    fn clear(&mut self) {
186        match self {
187            Self::Float(values) => values.clear(),
188            Self::Histogram { runs, bound } => {
189                runs.clear();
190                *bound = ChunkBound::default();
191            }
192        }
193    }
194
195    fn new(field: &ValueColumn) -> Self {
196        if field.is_histogram() {
197            Self::Histogram {
198                runs: Vec::new(),
199                bound: ChunkBound::default(),
200            }
201        } else {
202            Self::Float(Vec::new())
203        }
204    }
205}
206/// One input batch's column for a field.
207enum FieldInput<'a> {
208    Float(&'a Float64Array),
209    Histogram(&'a ArrayRef, &'a StructArray),
210}
211pub(crate) struct SamplesWriter {
212    options: ColumnarSamplesFormat,
213    manifest: Manifest,
214    outputs: Destination,
215    compressor: zstd::bulk::Compressor<'static>,
216    output_buffer: SampleBuffer,
217    scratch: BlockScratch,
218    descriptor: DescriptorScratch,
219    /// Canonical sparse key of the series that owns `rows` and `last`.
220    series_key: Option<ExactSeriesKey>,
221    rows: Vec<Row>,
222    /// Field values of `rows`, one entry per manifest field.
223    fields: Vec<PendingField>,
224    last: Option<(MetricSeriesId, i64, u64)>,
225    ordinal: u64,
226    leaves: Vec<Vec<Block>>,
227    leaf_bytes: usize,
228    descriptor_bytes: usize,
229    position: u64,
230    groups: Vec<metadata::Group>,
231    group_rows: u64,
232    group_blocks: u64,
233    /// Exact keys for the active group. Pending blocks reference offsets
234    /// within this buffer until the final payload position is known.
235    keys: Vec<u8>,
236    manifest_bytes: usize,
237    failed: bool,
238}
239impl SamplesWriter {
240    pub(crate) fn set_upload(&mut self, upload: crate::cache::write_cache::NarthexUpload) {
241        if let Destination::Store(outputs) = &mut self.outputs {
242            outputs.upload = Some(upload);
243        }
244    }
245
246    pub fn new(
247        options: ColumnarSamplesFormat,
248        metadata: RegionMetadataRef,
249        store: ObjectStore,
250        prefix: &str,
251        source_file_id: FileId,
252        generation: FileId,
253    ) -> Result<Self> {
254        Self::with_destination(
255            options,
256            metadata,
257            Destination::Store(Outputs {
258                store,
259                active: None,
260                paths: Vec::new(),
261                committed: false,
262                upload: None,
263            }),
264            prefix,
265            source_file_id,
266            generation,
267        )
268    }
269
270    fn with_destination(
271        options: ColumnarSamplesFormat,
272        metadata: RegionMetadataRef,
273        outputs: Destination,
274        prefix: &str,
275        source_file_id: FileId,
276        generation: FileId,
277    ) -> Result<Self> {
278        validate_narthex_metadata(&metadata)?;
279        require(
280            (1..=MAX_ROWS).contains(&options.block_rows)
281                && (1..=metadata::ROOT_CAPACITY).contains(&options.root_capacity)
282                && (188..=metadata::PAGE_LIMIT).contains(&options.page_bytes)
283                && options.part_bytes > 0
284                && options.metadata_bytes > 0,
285            "invalid samples packing options",
286        )?;
287        let timestamp = metadata.time_index_column();
288        let DataType::Timestamp(unit, None) = timestamp.column_schema.data_type.as_arrow_type()
289        else {
290            return Err(invalid("samples require a timestamp time index"));
291        };
292        let fields = metadata
293            .field_columns()
294            .map(ValueColumn::new)
295            .collect::<Result<Vec<_>>>()?;
296        let pending_fields = fields.iter().map(PendingField::new).collect();
297        let manifest = Manifest {
298            prefix: prefix.to_string(),
299            format: ArtifactFormat::ColumnarSamples,
300            version: VERSION,
301            identity_encoding: IdentityEncoding::CURRENT_SAMPLES,
302            region_id: metadata.region_id.as_u64(),
303            source_file_id,
304            generation,
305            timestamp: TimestampColumn {
306                column_id: timestamp.column_id,
307                name: timestamp.column_schema.name.clone(),
308                unit: TimestampUnit::from_arrow(&unit),
309            },
310            fields,
311            files: Vec::new(),
312        };
313        manifest.validate_schema()?;
314        require(
315            prefix.ends_with('/') && !prefix.split('/').any(|part| part == ".."),
316            "invalid samples output prefix",
317        )?;
318        let manifest_bytes = serde_json::to_vec(&manifest).context(SerdeJsonSnafu)?.len();
319        require(
320            manifest_bytes <= MANIFEST_LIMIT,
321            "samples schema exceeds manifest limit",
322        )?;
323        Ok(Self {
324            options,
325            manifest,
326            outputs,
327            compressor: zstd::bulk::Compressor::new(1)
328                .map_err(|e| invalid(format!("sample compression: {e}")))?,
329            output_buffer: SampleBuffer::default(),
330            scratch: BlockScratch::default(),
331            descriptor: DescriptorScratch::default(),
332            series_key: None,
333            rows: Vec::new(),
334            fields: pending_fields,
335            last: None,
336            ordinal: 0,
337            leaves: Vec::new(),
338            leaf_bytes: 12,
339            descriptor_bytes: 0,
340            position: 0,
341            groups: Vec::new(),
342            group_rows: 0,
343            group_blocks: 0,
344            keys: Vec::new(),
345            manifest_bytes,
346            failed: false,
347        })
348    }
349    pub(crate) fn memory(
350        metadata: RegionMetadataRef,
351        options: ColumnarSamplesFormat,
352    ) -> Result<Self> {
353        let id = FileId::random();
354        Self::with_destination(
355            options,
356            metadata,
357            Destination::Memory {
358                current: None,
359                objects: Vec::new(),
360                blocks: Vec::new(),
361                keys: Vec::new(),
362            },
363            "memory/",
364            id,
365            id,
366        )
367    }
368
369    pub(crate) fn push_memory(&mut self, batch: &RecordBatch) -> Result<()> {
370        // The memory destination has no asynchronous I/O or task dependencies.
371        self.write_batch(batch)
372            .now_or_never()
373            .expect("memory writer is synchronous")
374    }
375
376    pub(crate) fn finish_memory(mut self) -> Result<NarthexBulkPart> {
377        self.complete()
378            .now_or_never()
379            .expect("memory writer is synchronous")?;
380        let Destination::Memory {
381            mut objects,
382            keys,
383            blocks,
384            ..
385        } = self.outputs
386        else {
387            unreachable!()
388        };
389        let manifest = objects.pop().expect("completed samples manifest");
390        Ok(NarthexBulkPart::new(MemoryArtifact {
391            file_id: self.manifest.source_file_id,
392            manifest,
393            parts: objects,
394            keys: Bytes::from(keys.into_boxed_slice()),
395            blocks,
396            fields: self.manifest.fields,
397        }))
398    }
399
400    async fn write_batch(&mut self, batch: &RecordBatch) -> Result<()> {
401        require(batch.num_columns() >= 4, "samples require flat batches")?;
402        let column = |name: &str| {
403            batch
404                .column_by_name(name)
405                .ok_or_else(|| invalid(format!("missing sample input column {name}")))
406        };
407        let time = column(&self.manifest.timestamp.name)?;
408        require(
409            time.data_type() == &DataType::Timestamp(self.manifest.timestamp.unit.arrow(), None)
410                && time.null_count() == 0,
411            "samples timestamp type/null mismatch",
412        )?;
413        let (times, _) = timestamp_array_to_primitive(time)
414            .ok_or_else(|| invalid("invalid sample timestamp array"))?;
415        let sequence = column(consts::SEQUENCE_COLUMN_NAME)?
416            .as_any()
417            .downcast_ref::<UInt64Array>()
418            .ok_or_else(|| invalid("invalid sample sequence type"))?;
419        let operations = column(consts::OP_TYPE_COLUMN_NAME)?
420            .as_any()
421            .downcast_ref::<UInt8Array>()
422            .ok_or_else(|| invalid("invalid sample operation type"))?;
423        require(
424            sequence.null_count() == 0 && operations.null_count() == 0,
425            "null sample sequence/operation",
426        )?;
427        let fields = self
428            .manifest
429            .fields
430            .iter()
431            .map(|field| {
432                let array = column(&field.name)?;
433                let input = if field.is_histogram() {
434                    array
435                        .as_struct_opt()
436                        .map(|s| FieldInput::Histogram(array, s))
437                } else {
438                    array.as_any().downcast_ref().map(FieldInput::Float)
439                };
440                input.ok_or_else(|| invalid("invalid sample field array"))
441            })
442            .collect::<Result<Vec<_>>>()?;
443        let keys = column(consts::PRIMARY_KEY_COLUMN_NAME)?;
444        require(keys.null_count() == 0, "null sample primary key")?;
445        let binary = keys.as_any().downcast_ref::<BinaryArray>();
446        let dictionary = keys.as_any().downcast_ref::<DictionaryArray<UInt32Type>>();
447        let values = dictionary.and_then(|d| d.values().as_any().downcast_ref::<BinaryArray>());
448        require(
449            binary.is_some() || values.is_some(),
450            "samples require binary or UInt32 dictionary primary keys",
451        )?;
452        for i in 0..batch.num_rows() {
453            let key = if let Some(binary) = binary {
454                binary.value(i)
455            } else {
456                let dictionary = dictionary.ok_or_else(|| invalid("missing sample dictionary"))?;
457                let values = values.ok_or_else(|| invalid("invalid sample dictionary values"))?;
458                let index = dictionary.keys().value(i) as usize;
459                require(
460                    index < values.len() && !values.is_null(index),
461                    "invalid sample dictionary key",
462                )?;
463                values.value(index)
464            };
465            let time = times.value(i);
466            let seq = sequence.value(i);
467            let op = operations.value(i);
468            require(op <= 1, "unknown sample operation")?;
469            // Identity is the exact sparse key, not `(table_id, tsid)`: two distinct
470            // series may share a `tsid`, and every block records which exact key owns it.
471            let new_series = self
472                .series_key
473                .as_ref()
474                .is_none_or(|current| current.bytes() != key);
475            if new_series {
476                let exact = ExactSeriesKey::from_prevalidated_sparse_key(key)
477                    .ok_or_else(|| invalid("truncated sample key prefix"))?;
478                if self.last.is_some() {
479                    // Rows arrive in canonical sparse-key order.
480                    let previous = self
481                        .series_key
482                        .as_ref()
483                        .ok_or_else(|| invalid("missing sample series key"))?;
484                    require(
485                        exact > *previous,
486                        "sample input is not sorted by primary key",
487                    )?;
488                    // A different key that shares `(table_id, tsid)` is a different
489                    // series: it opens its own block, which records its exact key, so
490                    // timestamps and ordinals may restart.
491                    self.flush_block().await?;
492                    self.ordinal = 0;
493                }
494                self.series_key = Some(exact);
495            }
496            let id = match self.last {
497                Some((id, last_time, last_seq)) if !new_series => {
498                    // The same exact series continues: the existing monotonic rules hold.
499                    require(
500                        time > last_time || (time == last_time && seq <= last_seq),
501                        "sample input is not sorted",
502                    )?;
503                    id
504                }
505                _ => self
506                    .series_key
507                    .as_ref()
508                    .ok_or_else(|| invalid("missing series key"))?
509                    .id(),
510            };
511            let mut bounds = self.histogram_bounds(&fields, i);
512            if self.rows.len() == self.options.block_rows
513                || !valid_rows(self.rows.len() + 1, fields.len())
514                || bounds.is_none()
515            {
516                self.flush_block().await?;
517                bounds = self.histogram_bounds(&fields, i);
518            }
519            let mut bounds = bounds
520                .ok_or_else(|| invalid("native histogram sample exceeds the chunk limit"))?
521                .into_iter();
522            self.rows.push(Row {
523                id,
524                time,
525                sequence: seq,
526                operation: op,
527            });
528            for (pending, input) in self.fields.iter_mut().zip(&fields) {
529                match (pending, input) {
530                    (PendingField::Float(values), FieldInput::Float(array)) => {
531                        values.push(array.is_valid(i).then(|| array.value(i).to_bits()));
532                    }
533                    (PendingField::Histogram { runs, bound }, FieldInput::Histogram(array, _)) => {
534                        *bound = bounds
535                            .next()
536                            .ok_or_else(|| invalid("missing native histogram bound"))?;
537                        match runs.last_mut() {
538                            Some((run, start, len))
539                                if Arc::ptr_eq(run, array) && *start + *len == i =>
540                            {
541                                *len += 1
542                            }
543                            _ => runs.push(((*array).clone(), i, 1)),
544                        }
545                    }
546                    _ => return Err(invalid("sample field kind changed between rows")),
547                }
548            }
549            self.last = Some((id, time, seq));
550        }
551        Ok(())
552    }
553    /// Each histogram field's chunk bound with row `i` appended to the pending block, in field
554    /// order, or `None` when one of those chunks would no longer fit.
555    fn histogram_bounds(&self, fields: &[FieldInput<'_>], i: usize) -> Option<Vec<ChunkBound>> {
556        self.fields
557            .iter()
558            .zip(fields)
559            .filter_map(|(pending, input)| match (pending, input) {
560                (PendingField::Histogram { bound, .. }, FieldInput::Histogram(_, array)) => {
561                    Some(bound.with_row(array, i))
562                }
563                _ => None,
564            })
565            .collect()
566    }
567    async fn flush_block(&mut self) -> Result<()> {
568        if self.rows.is_empty() {
569            return Ok(());
570        }
571        let key = self
572            .series_key
573            .as_ref()
574            .ok_or_else(|| invalid("sample block has no series key"))?;
575        let mut block = encode_block(
576            &self.rows,
577            &self.fields,
578            key,
579            &self.manifest,
580            self.ordinal,
581            &mut self.compressor,
582            &mut self.scratch,
583        )?;
584        self.rows.clear();
585        self.fields.iter_mut().for_each(PendingField::clear);
586        let key_len = key.bytes().len() as u64;
587        self.ordinal = self
588            .ordinal
589            .checked_add(1)
590            .ok_or_else(|| invalid("sample ordinal overflow"))?;
591        let size = metadata::descriptor_bytes(block.columns.len());
592        // The descriptor carries a fixed-size key reference, not the key, so this bound is a
593        // function of the field count only: a key longer than a whole metadata page is no
594        // longer a build failure, and only a narrower configured page can reject a descriptor.
595        require(
596            size + 12 <= self.options.page_bytes,
597            "sample descriptor exceeds leaf limit",
598        )?;
599        let budget = self.options.metadata_bytes as u64;
600        let new_series = block.ordinal == 0;
601        let pending = self.descriptor_bytes as u64 + self.keys.len() as u64;
602        // Prefer a series boundary after three quarters of the budget; a long series
603        // may continue into the next group when the hard budget or leaf fanout is reached.
604        let projected = pending + size as u64 + if new_series { key_len } else { 0 };
605        if !self.leaves.is_empty()
606            && ((new_series && pending >= budget - budget / 4)
607                || projected > budget
608                || (self.leaf_bytes + size > self.options.page_bytes
609                    && self.leaves.len() == self.options.root_capacity))
610        {
611            self.finish_group().await?;
612            if self.groups.len() == metadata::MAX_GROUPS {
613                self.finish_part().await?;
614            }
615        }
616        if !self.outputs.is_open() {
617            let id = u32::try_from(self.manifest.files.len())
618                .map_err(|_| invalid("too many sample parts"))?;
619            self.outputs.open(self.manifest.part_path(id)).await?;
620            self.output_buffer
621                .write(&mut self.outputs, &metadata::header())
622                .await?;
623            self.position = metadata::HEADER_SIZE;
624        }
625        for column in &mut block.columns {
626            column.payload.offset = self.position;
627            self.position = column.payload.end()?;
628        }
629        self.output_buffer
630            .write(&mut self.outputs, &self.scratch.encoded)
631            .await?;
632        if !new_series && let Some(previous) = self.leaves.last().and_then(|leaf| leaf.last()) {
633            block.key = previous.key;
634        } else {
635            let key = self
636                .series_key
637                .as_ref()
638                .ok_or_else(|| invalid("sample block has no series key"))?
639                .bytes();
640            block.key.offset = self.keys.len() as u64;
641            self.keys.extend_from_slice(key);
642        }
643        if self.leaves.is_empty() || self.leaf_bytes + size > self.options.page_bytes {
644            self.leaves.push(Vec::new());
645            self.leaf_bytes = 12;
646        }
647        self.leaf_bytes += size;
648        self.descriptor_bytes += size;
649        self.group_rows = self
650            .group_rows
651            .checked_add(u64::from(block.rows))
652            .ok_or_else(|| invalid("sample row count overflow"))?;
653        self.group_blocks += 1;
654        self.leaves
655            .last_mut()
656            .ok_or_else(|| invalid("missing sample leaf"))?
657            .push(block);
658        if self.position.saturating_add(self.keys.len() as u64) >= self.options.part_bytes {
659            self.finish_part().await?;
660        }
661        Ok(())
662    }
663    async fn write_page(&mut self, page: Page) -> Result<PageReference> {
664        let bounds = page.bounds()?;
665        page.encode_into(&mut self.descriptor.raw);
666        let (payload, bytes) = metadata::pack_page_into(
667            &mut self.compressor,
668            &self.descriptor.raw,
669            &mut self.descriptor.compressed,
670            self.position,
671        )?;
672        self.position = payload.end()?;
673        self.output_buffer.write(&mut self.outputs, bytes).await?;
674        Ok(PageReference { bounds, payload })
675    }
676    async fn finish_group(&mut self) -> Result<()> {
677        if self.leaves.is_empty() {
678            return Ok(());
679        }
680        let payload_end = self.position;
681        let logical_key_end = payload_end
682            .checked_add(self.keys.len() as u64)
683            .ok_or_else(|| invalid("sample key offset overflow"))?;
684        let frames = super::key_pages::encode(&self.keys, &mut self.compressor)?;
685        if let Destination::Memory {
686            blocks,
687            objects,
688            keys,
689            ..
690        } = &mut self.outputs
691        {
692            // Resident descriptors index the concatenated decoded keys across all groups.
693            let base = keys.len() as u64;
694            keys.extend_from_slice(&self.keys);
695            blocks.extend(self.leaves.iter().flatten().cloned().map(|mut block| {
696                block.key.offset += base;
697                (objects.len(), block)
698            }));
699        }
700        self.keys.clear();
701        let key_end = payload_end
702            .checked_add(frames.len() as u64)
703            .ok_or_else(|| invalid("sample key area overflow"))?;
704        self.output_buffer.write(&mut self.outputs, &frames).await?;
705        self.position = key_end;
706        let mut children = Vec::with_capacity(self.leaves.len());
707        for mut leaf in std::mem::take(&mut self.leaves) {
708            for block in &mut leaf {
709                // All relative offsets lie within the key buffer whose end was checked above.
710                block.key.offset += payload_end;
711            }
712            children.push(self.write_page(Page::Leaf(leaf)).await?);
713        }
714        let depth = if children.len() == 1 { 1 } else { 2 };
715        let root = if depth == 1 {
716            children.remove(0)
717        } else {
718            self.write_page(Page::Internal(children)).await?
719        };
720        let start = match self.groups.last() {
721            Some(group) => group.root.payload.end()?,
722            None => metadata::HEADER_SIZE,
723        };
724        self.groups.push(metadata::Group {
725            start,
726            rows: self.group_rows,
727            blocks: self.group_blocks,
728            root,
729            depth,
730            payload_end,
731            key_end,
732            logical_key_end,
733        });
734        self.group_rows = 0;
735        self.group_blocks = 0;
736        self.descriptor_bytes = 0;
737        self.leaf_bytes = 12;
738        Ok(())
739    }
740    async fn finish_part(&mut self) -> Result<()> {
741        self.finish_group().await?;
742        let groups = std::mem::take(&mut self.groups);
743        if groups.is_empty() {
744            return Ok(());
745        }
746        let bytes = metadata::encode_directory(&groups);
747        let file_length = self
748            .position
749            .checked_add(bytes.len() as u64)
750            .ok_or_else(|| invalid("sample part length overflow"))?;
751        self.output_buffer.write(&mut self.outputs, &bytes).await?;
752        self.output_buffer.flush(&mut self.outputs).await?;
753        self.outputs.close().await?;
754        let part_id = u32::try_from(self.manifest.files.len())
755            .map_err(|_| invalid("too many sample parts"))?;
756        let part = Part::from_groups(part_id, file_length, &groups)?;
757        self.manifest_bytes += serde_json::to_vec(&part).context(SerdeJsonSnafu)?.len()
758            + usize::from(!self.manifest.files.is_empty());
759        require(
760            self.manifest_bytes <= MANIFEST_LIMIT,
761            "samples manifest exceeds size limit",
762        )?;
763        self.manifest.files.push(part);
764        self.position = 0;
765        Ok(())
766    }
767    async fn complete(&mut self) -> Result<ArtifactMetadata> {
768        require(!self.failed, "sample writer failed previously")?;
769        self.flush_block().await?;
770        self.finish_part().await?;
771        let bytes = serde_json::to_vec(&self.manifest).context(SerdeJsonSnafu)?;
772        require(
773            bytes.len() <= MANIFEST_LIMIT,
774            "samples manifest exceeds limit",
775        )?;
776        let mut file_size = bytes.len() as u64;
777        let mut objects = vec![ArtifactObject {
778            path: self.manifest.path(),
779            file_size,
780        }];
781        for part in &self.manifest.files {
782            objects.push(ArtifactObject {
783                path: self.manifest.part_path(part.part_id),
784                file_size: part.file_size,
785            });
786            file_size = file_size
787                .checked_add(part.file_size)
788                .ok_or_else(|| invalid("sample artifact size overflow"))?;
789        }
790        self.outputs.open(self.manifest.path()).await?;
791        self.outputs.write(bytes).await?;
792        self.outputs.close().await?;
793        if let Destination::Store(outputs) = &mut self.outputs {
794            outputs.commit().await;
795        }
796        Ok(ArtifactMetadata {
797            format: ArtifactFormat::ColumnarSamples,
798            generation: self.manifest.generation,
799            objects,
800            file_size,
801        })
802    }
803}
804
805#[cfg(test)]
806impl SamplesWriter {
807    /// The current part's accounting, for the rollover tests: `(position, counted key bytes,
808    /// blocks in the current group, finished parts)`.
809    ///
810    /// A key copy that is not counted defers the part boundary silently, and the parts it makes
811    /// are still readable, so only the accounting itself shows the difference.
812    pub(super) fn part_accounting(&self) -> (u64, u64, u64, usize) {
813        (
814            self.position,
815            self.keys.len() as u64,
816            self.group_blocks,
817            self.manifest.files.len(),
818        )
819    }
820}
821#[async_trait]
822impl FormatWriter for SamplesWriter {
823    async fn write(&mut self, batch: &RecordBatch) -> Result<()> {
824        require(!self.failed, "sample writer failed previously")?;
825        self.failed = true;
826        let result = self.write_batch(batch).await;
827        if result.is_ok() {
828            self.failed = false;
829        }
830        result
831    }
832    async fn finish(mut self: Box<Self>) -> Result<ArtifactMetadata> {
833        let result = self.complete().await;
834        if result.is_err()
835            && let Err(error) = self.outputs.cleanup().await
836        {
837            common_telemetry::warn!(error; "Cleaning failed samples build");
838        }
839        result
840    }
841    async fn abort(mut self: Box<Self>) -> Result<()> {
842        self.outputs.cleanup().await
843    }
844}
845fn encode_block(
846    rows: &[Row],
847    fields: &[PendingField],
848    key: &ExactSeriesKey,
849    manifest: &Manifest,
850    ordinal: u64,
851    compressor: &mut zstd::bulk::Compressor<'_>,
852    scratch: &mut BlockScratch,
853) -> Result<Block> {
854    let first = rows.first().ok_or_else(|| invalid("empty sample block"))?;
855    let last = rows.last().ok_or_else(|| invalid("empty sample block"))?;
856    require(
857        rows.iter().all(|row| row.id == key.id()),
858        "sample block mixes series",
859    )?;
860    let mut block = Block {
861        id: key.id(),
862        key: KeyRef {
863            offset: 0,
864            length: u32::try_from(key.bytes().len())
865                .map_err(|_| invalid("sample series key exceeds 4 GiB"))?,
866        },
867        min: first.time,
868        max: last.time,
869        ordinal,
870        rows: rows.len() as u32,
871        columns: Vec::new(),
872    };
873    let mut push = |role,
874                    id,
875                    encoding,
876                    bytes: &mut Vec<u8>,
877                    nulls,
878                    start,
879                    compressed: &mut Vec<u8>|
880     -> Result<()> {
881        let payload = metadata::pack_chunk_tail(compressor, bytes, compressed, start, encoding)?;
882        block.columns.push(Column {
883            role,
884            id,
885            payload,
886            nulls,
887        });
888        Ok(())
889    };
890    scratch.timestamps.clear();
891    scratch.sequences.clear();
892    scratch.operations.clear();
893    for row in rows {
894        scratch.timestamps.push(row.time);
895        scratch.sequences.push(row.sequence);
896        scratch.operations.push(row.operation);
897    }
898    let out = &mut scratch.encoded;
899    out.clear();
900    let start = out.len();
901    let encoding = codec::append_time(&scratch.timestamps, out);
902    push(
903        1,
904        manifest.timestamp.column_id,
905        encoding,
906        out,
907        0,
908        start,
909        &mut scratch.compressed,
910    )?;
911    let start = out.len();
912    let encoding = codec::append_sequence(&scratch.sequences, out);
913    push(2, 0, encoding, out, 0, start, &mut scratch.compressed)?;
914    let start = out.len();
915    let encoding = codec::append_operations(&scratch.operations, out);
916    push(3, 0, encoding, out, 0, start, &mut scratch.compressed)?;
917    for (field, pending) in manifest.fields.iter().zip(fields) {
918        match pending {
919            PendingField::Float(values) => {
920                require(
921                    values.len() == rows.len(),
922                    "sample field row count mismatch",
923                )?;
924                let nulls = values.iter().filter(|v| v.is_none()).count();
925                if nulls != rows.len() {
926                    let start = scratch.encoded.len();
927                    codec::append_float(values, &mut scratch.encoded);
928                    push(
929                        4,
930                        field.column_id,
931                        FLOAT64_ENCODING,
932                        &mut scratch.encoded,
933                        nulls as u32,
934                        start,
935                        &mut scratch.compressed,
936                    )?;
937                }
938            }
939            PendingField::Histogram { runs, .. } => {
940                let slices = runs
941                    .iter()
942                    .map(|(array, start, len)| array.slice(*start, *len))
943                    .collect::<Vec<_>>();
944                let array = concat(&slices.iter().map(|a| a.as_ref()).collect::<Vec<_>>())
945                    .context(ComputeArrowSnafu)?;
946                let array = array
947                    .as_struct_opt()
948                    .ok_or_else(|| invalid("invalid native histogram sample array"))?;
949                require(array.len() == rows.len(), "sample field row count mismatch")?;
950                // An all-null field has no chunk, as for Float64 fields.
951                if array.null_count() != rows.len() {
952                    let encoded = histogram::encode(array)?;
953
954                    let start = scratch.encoded.len();
955                    scratch.encoded.extend_from_slice(&encoded);
956                    push(
957                        4,
958                        field.column_id,
959                        histogram::ENCODING,
960                        &mut scratch.encoded,
961                        array.null_count() as u32,
962                        start,
963                        &mut scratch.compressed,
964                    )?;
965                }
966            }
967        }
968    }
969    Ok(block)
970}
971
972#[cfg(test)]
973mod tests {
974    use super::*;
975
976    fn outputs() -> (Destination, ObjectStore) {
977        let store = ObjectStore::new(object_store::services::Memory::default()).unwrap();
978        (
979            Destination::Store(Outputs {
980                store: store.clone(),
981                active: None,
982                paths: Vec::new(),
983                committed: false,
984                upload: None,
985            }),
986            store,
987        )
988    }
989
990    #[tokio::test]
991    async fn buffered_output_boundaries_and_parts() {
992        let capacity = DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize;
993        let (mut outputs, store) = outputs();
994        let mut buffer = SampleBuffer::default();
995        for size in [0, capacity - 1, capacity, capacity + 1, capacity * 2 + 13] {
996            let path = format!("part-{size}");
997            outputs.open(path.clone()).await.unwrap();
998            let bytes: Vec<_> = (0..size).map(|i| (i % 251) as u8).collect();
999            // Exercise both tiny fragments and an input larger than the staging buffer.
1000            let split = size.min(1000);
1001            for chunk in bytes[..split].chunks(7) {
1002                buffer.write(&mut outputs, chunk).await.unwrap();
1003            }
1004            buffer.write(&mut outputs, &bytes[split..]).await.unwrap();
1005            assert_eq!(buffer.bytes.len(), size % capacity);
1006            buffer.flush(&mut outputs).await.unwrap();
1007            outputs.close().await.unwrap();
1008            assert!(buffer.bytes.is_empty());
1009            assert_eq!(store.read(&path).await.unwrap().to_vec(), bytes);
1010        }
1011        outputs.cleanup().await.unwrap();
1012    }
1013
1014    #[tokio::test]
1015    async fn abort_discards_pending_bytes() {
1016        let (mut outputs, store) = outputs();
1017        let mut buffer = SampleBuffer::default();
1018        outputs.open("part".into()).await.unwrap();
1019        buffer.write(&mut outputs, b"pending").await.unwrap();
1020        outputs.cleanup().await.unwrap();
1021        drop(buffer);
1022        assert!(!store.exists("part").await.unwrap());
1023    }
1024
1025    /// Synthetic small-write benchmark; run explicitly with --ignored --nocapture.
1026    #[tokio::test]
1027    #[ignore]
1028    async fn benchmark_small_sample_writes() {
1029        common_telemetry::init_default_ut_logging();
1030        let capacity = DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize;
1031        let fragment = vec![42; 100];
1032        let count = capacity / fragment.len() + 1;
1033        for buffered in [false, true] {
1034            let (mut outputs, store) = outputs();
1035            outputs.open("bench".into()).await.unwrap();
1036            let mut buffer = SampleBuffer::default();
1037            let started = std::time::Instant::now();
1038            for _ in 0..count {
1039                if buffered {
1040                    buffer.write(&mut outputs, &fragment).await.unwrap();
1041                } else {
1042                    outputs.write(fragment.clone()).await.unwrap();
1043                }
1044            }
1045            buffer.flush(&mut outputs).await.unwrap();
1046            outputs.close().await.unwrap();
1047            common_telemetry::info!(
1048                "buffered={buffered}, elapsed={:?}, submitted_fragments={}",
1049                started.elapsed(),
1050                if buffered { 2 } else { count }
1051            );
1052            assert_eq!(
1053                store.read("bench").await.unwrap().len(),
1054                count * fragment.len()
1055            );
1056            outputs.cleanup().await.unwrap();
1057        }
1058    }
1059}