Skip to main content

operator/statement/
import_packed.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
15use std::collections::HashMap;
16use std::sync::Arc;
17
18use common_datasource::file_format::Format;
19use common_datasource::file_format::parquet::packed_reader::{
20    PackReadWindows, PackedParquetReader, WINDOW_SIZE,
21};
22use common_datasource::object_store::{BuiltBackend, build_backend_with_path};
23use common_datasource::packed_snapshot::{ObjectKind, PACK_INDEX_FILE, PackIndex};
24use common_error::ext::BoxedError;
25use common_query::Output;
26use futures::stream::FuturesUnordered;
27use futures::{FutureExt, StreamExt};
28use session::context::QueryContextRef;
29use snafu::ResultExt;
30use table::TableRef;
31use table::requests::CopyDatabaseRequest;
32use tokio_util::compat::FuturesAsyncReadCompatExt;
33use tokio_util::sync::CancellationToken;
34
35use crate::error::{self, Result};
36use crate::statement::StatementExecutor;
37use crate::statement::database_copy::validate_database_directory;
38
39/// All table identities are resolved before the frontend authorizes any write.
40pub struct PreparedPackedImport {
41    backend: BuiltBackend,
42    index: PackIndex,
43    parallelism: usize,
44    pub tables: Vec<TableRef>,
45}
46
47impl StatementExecutor {
48    pub async fn prepare_packed_import(
49        &self,
50        req: CopyDatabaseRequest,
51        ctx: &QueryContextRef,
52    ) -> Result<PreparedPackedImport> {
53        validate_database_directory(&req.location)?;
54        if req.with.get("metric_data_layout").map(String::as_str) != Some("packed")
55            || !matches!(
56                Format::try_from(&req.with).context(error::ParseFileFormatSnafu)?,
57                Format::Parquet(_)
58            )
59            || req
60                .with
61                .get("continue_on_error")
62                .is_some_and(|v| v != "false")
63        {
64            return error::InvalidCopyParameterSnafu {
65                key: "metric_data_layout",
66                value: "packed requires parquet and continue_on_error=false",
67            }
68            .fail();
69        }
70        let backend = build_backend_with_path(
71            &req.location,
72            &req.connection,
73            &self.local_file_access,
74            &self.remote_storage_access,
75        )
76        .await
77        .context(error::BuildBackendSnafu)?;
78        if !backend
79            .is_file(PACK_INDEX_FILE)
80            .await
81            .context(error::ReadObjectSnafu {
82                path: PACK_INDEX_FILE,
83            })?
84        {
85            return error::InvalidCopyParameterSnafu {
86                key: "index",
87                value: "not a regular file",
88            }
89            .fail();
90        }
91        let bytes = backend
92            .object_store
93            .read(PACK_INDEX_FILE)
94            .await
95            .context(error::ReadObjectSnafu {
96                path: PACK_INDEX_FILE,
97            })?
98            .to_bytes();
99        let mut index: PackIndex = serde_json::from_slice(&bytes).map_err(|e| {
100            error::InvalidCopyParameterSnafu {
101                key: "pack_index",
102                value: e.to_string(),
103            }
104            .build()
105        })?;
106        index
107            .validate()
108            .map_err(BoxedError::new)
109            .context(error::ExternalSnafu)?;
110        index
111            .tables
112            .sort_by(|a, b| (&a.object, a.offset).cmp(&(&b.object, b.offset)));
113        let names: Vec<_> = index.tables.iter().map(|t| t.table_name.clone()).collect();
114        let mut tables = self
115            .capture_database_export_tables(&req, Some(&names), ctx)
116            .await?;
117        if tables.len() != names.len() {
118            return error::InvalidCopyParameterSnafu {
119                key: "index",
120                value: "physical tables and views are not data targets",
121            }
122            .fail();
123        }
124        let positions: HashMap<_, _> = names
125            .iter()
126            .enumerate()
127            .map(|(i, n)| (n.as_str(), i))
128            .collect();
129        tables.sort_by_key(|table| positions.get(table.table_info().name.as_str()).copied());
130        for object in &index.objects {
131            let meta = backend
132                .object_store
133                .stat(&object.path)
134                .await
135                .context(error::ReadObjectSnafu { path: &object.path })?;
136            if !backend
137                .is_file_with_mode(&object.path, meta.mode())
138                .await
139                .context(error::ReadObjectSnafu { path: &object.path })?
140            {
141                return error::InvalidCopyParameterSnafu {
142                    key: "object",
143                    value: &object.path,
144                }
145                .fail();
146            }
147            if meta.content_length() != object.length {
148                return error::InvalidCopyParameterSnafu {
149                    key: "object_length",
150                    value: &object.path,
151                }
152                .fail();
153            }
154        }
155        Ok(PreparedPackedImport {
156            backend,
157            index,
158            tables,
159            parallelism: crate::statement::database_copy::parse_parallelism_from_option_map(
160                &req.with,
161            ),
162        })
163    }
164
165    pub async fn import_packed(
166        &self,
167        plan: PreparedPackedImport,
168        cancellation: &CancellationToken,
169        ctx: QueryContextRef,
170    ) -> Result<Output> {
171        let windows = PackReadWindows::new(plan.backend.object_store.clone());
172        let mut pending = PendingPackedInserts::new(plan.parallelism);
173        let objects: HashMap<_, _> = plan
174            .index
175            .objects
176            .iter()
177            .map(|o| (o.path.as_str(), o))
178            .collect();
179        let result: Result<()> = async {
180            for (entry, table) in plan.index.tables.iter().zip(plan.tables) {
181                if cancellation.is_cancelled() {
182                    return error::PackedImportCancelledSnafu.fail();
183                }
184                let object = objects.get(entry.object.as_str()).ok_or_else(|| {
185                    error::InvalidCopyParameterSnafu {
186                        key: "object",
187                        value: &entry.object,
188                    }
189                    .build()
190                })?;
191                match object.kind {
192                    ObjectKind::Pack if entry.length <= WINDOW_SIZE as u64 => {
193                        let reader = PackedParquetReader::new(
194                            Arc::clone(&windows),
195                            object.path.clone(),
196                            object.length,
197                            entry.offset,
198                            entry.length,
199                        )
200                        .context(error::ReadParquetMetadataSnafu)?;
201                        self.copy_indexed_parquet(
202                            reader,
203                            table,
204                            entry.row_count,
205                            &mut pending,
206                            cancellation,
207                            ctx.clone(),
208                        )
209                        .await?
210                    }
211                    ObjectKind::Pack | ObjectKind::Parquet => {
212                        // The virtual file keeps footer/column offsets relative to this
213                        // stream. Parquet decoder allocations are separate from the cache.
214                        let reader = plan
215                            .backend
216                            .object_store
217                            .reader_with(&object.path)
218                            .chunk(256 * 1024)
219                            .await
220                            .context(error::ReadObjectSnafu { path: &object.path })?
221                            .into_futures_async_read(entry.offset..entry.offset + entry.length)
222                            .await
223                            .context(error::ReadObjectSnafu { path: &object.path })?
224                            .compat();
225                        self.copy_indexed_parquet(
226                            reader,
227                            table,
228                            entry.row_count,
229                            &mut pending,
230                            cancellation,
231                            ctx.clone(),
232                        )
233                        .await?
234                    }
235                };
236            }
237            Ok(())
238        }
239        .await;
240        let drained = pending.drain().await;
241        common_telemetry::debug!(
242            peak_pending_bytes = pending.peak_pending_bytes,
243            peak_batch_bytes = pending.peak_batch_bytes,
244            "Packed import insertion payloads; codec and compressed windows accounted separately"
245        );
246        result?;
247        drained?;
248        Ok(Output::new(
249            common_query::OutputData::AffectedRows(pending.rows),
250            common_query::OutputMeta::new_with_cost(pending.cost),
251        ))
252    }
253}
254
255/// Retains all started writes until completion, including after the first error.
256pub(crate) struct PendingPackedInserts {
257    tasks: FuturesUnordered<tokio::task::JoinHandle<(usize, Result<Output>)>>,
258    bytes: usize,
259    parallelism: usize,
260    rows: usize,
261    cost: usize,
262    peak_pending_bytes: usize,
263    peak_batch_bytes: usize,
264}
265
266impl PendingPackedInserts {
267    fn new(parallelism: usize) -> Self {
268        Self {
269            tasks: FuturesUnordered::new(),
270            bytes: 0,
271            parallelism,
272            rows: 0,
273            cost: 0,
274            peak_pending_bytes: 0,
275            peak_batch_bytes: 0,
276        }
277    }
278
279    /// Backpressure before decoding, while allowing one current batch outside the queue.
280    pub(crate) async fn before_decode(&mut self) -> Result<()> {
281        while let Some(Some(output)) = self.tasks.next().now_or_never() {
282            self.complete(output)?;
283        }
284        while self.tasks.len() >= self.parallelism || self.bytes >= 32 * 1024 * 1024 {
285            self.complete_one().await?;
286        }
287        Ok(())
288    }
289
290    pub(crate) async fn admit(
291        &mut self,
292        bytes: usize,
293        insert: impl std::future::Future<Output = Result<Output>> + Send + 'static,
294        cancellation: &CancellationToken,
295    ) -> Result<()> {
296        while let Some(Some(output)) = self.tasks.next().now_or_never() {
297            self.complete(output)?;
298        }
299        self.peak_batch_bytes = self.peak_batch_bytes.max(bytes);
300        const BUDGET: usize = 32 * 1024 * 1024;
301        if bytes > BUDGET {
302            self.drain().await?;
303            if cancellation.is_cancelled() {
304                return error::PackedImportCancelledSnafu.fail();
305            }
306            let (rows, cost) = insert.await?.extract_rows_and_cost();
307            self.rows += rows;
308            self.cost += cost;
309            return Ok(());
310        }
311        while self.tasks.len() >= self.parallelism || self.bytes + bytes > BUDGET {
312            self.complete_one().await?;
313        }
314        if cancellation.is_cancelled() {
315            return error::PackedImportCancelledSnafu.fail();
316        }
317        self.bytes += bytes;
318        self.peak_pending_bytes = self.peak_pending_bytes.max(self.bytes);
319        self.tasks.push(common_runtime::spawn_query(
320            async move { (bytes, insert.await) },
321        ));
322        Ok(())
323    }
324
325    async fn complete_one(&mut self) -> Result<()> {
326        if let Some(output) = self.tasks.next().await {
327            self.complete(output)?;
328        }
329        Ok(())
330    }
331
332    fn complete(
333        &mut self,
334        output: std::result::Result<(usize, Result<Output>), common_runtime::JoinError>,
335    ) -> Result<()> {
336        let (bytes, output) = output.context(error::JoinTaskSnafu)?;
337        self.bytes -= bytes;
338        let (rows, cost) = output?.extract_rows_and_cost();
339        self.rows += rows;
340        self.cost += cost;
341        Ok(())
342    }
343
344    async fn drain(&mut self) -> Result<()> {
345        let mut first = None;
346        while !self.tasks.is_empty() {
347            if let Err(error) = self.complete_one().await {
348                first.get_or_insert(error);
349            }
350        }
351        first.map_or(Ok(()), Err)
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use std::sync::atomic::{AtomicUsize, Ordering};
358
359    use super::*;
360
361    #[tokio::test]
362    async fn oversized_batch_drains_and_runs_exclusively() {
363        let cancellation = CancellationToken::new();
364        let mut queue = PendingPackedInserts::new(4);
365        let completed = Arc::new(AtomicUsize::new(0));
366        for _ in 0..2 {
367            let completed = completed.clone();
368            queue
369                .admit(
370                    1024,
371                    async move {
372                        completed.fetch_add(1, Ordering::SeqCst);
373                        Ok(Output::new_with_affected_rows(1))
374                    },
375                    &cancellation,
376                )
377                .await
378                .unwrap();
379        }
380        let observed = completed.clone();
381        queue
382            .admit(
383                40 * 1024 * 1024,
384                async move {
385                    assert_eq!(observed.load(Ordering::SeqCst), 2);
386                    Ok(Output::new_with_affected_rows(3))
387                },
388                &cancellation,
389            )
390            .await
391            .unwrap();
392        assert_eq!(queue.rows, 5);
393        assert!(queue.tasks.is_empty());
394        assert!(queue.peak_pending_bytes <= 32 * 1024 * 1024);
395        assert_eq!(queue.peak_batch_bytes, 40 * 1024 * 1024);
396    }
397
398    #[tokio::test]
399    async fn concurrent_insert_queue_drains_after_error_and_cancel() {
400        let cancellation = CancellationToken::new();
401        let mut queue = PendingPackedInserts::new(2);
402        let barrier = Arc::new(tokio::sync::Barrier::new(2));
403        let completed = Arc::new(AtomicUsize::new(0));
404        for fail in [true, false] {
405            let barrier = barrier.clone();
406            let completed = completed.clone();
407            queue
408                .admit(
409                    16 * 1024 * 1024,
410                    async move {
411                        barrier.wait().await;
412                        completed.fetch_add(1, Ordering::SeqCst);
413                        if fail {
414                            error::InvalidCopyParameterSnafu {
415                                key: "test",
416                                value: "failure",
417                            }
418                            .fail()
419                        } else {
420                            Ok(Output::new_with_affected_rows(1))
421                        }
422                    },
423                    &cancellation,
424                )
425                .await
426                .unwrap();
427        }
428        cancellation.cancel();
429        assert!(
430            queue
431                .admit(1, async { panic!("must not start") }, &cancellation)
432                .await
433                .is_err()
434        );
435        let _ = queue.drain().await;
436        assert_eq!(completed.load(Ordering::SeqCst), 2);
437        assert_eq!(queue.bytes, 0);
438        assert!(queue.tasks.is_empty());
439    }
440}