Skip to main content

iceberg/scan/
task.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use futures::stream::BoxStream;
21use serde::{Deserialize, Serialize, Serializer};
22use typed_builder::TypedBuilder;
23
24use crate::Result;
25use crate::expr::BoundPredicate;
26use crate::spec::{
27    DataContentType, DataFileFormat, ManifestEntryRef, NameMapping, PartitionSpec, Schema,
28    SchemaRef, Struct,
29};
30
31/// A stream of [`FileScanTask`].
32pub type FileScanTaskStream = BoxStream<'static, Result<FileScanTask>>;
33
34/// Serialization helper that always returns NotImplementedError.
35/// Used for fields that should not be serialized but we want to be explicit about it.
36fn serialize_not_implemented<S, T>(_: &T, _: S) -> std::result::Result<S::Ok, S::Error>
37where S: Serializer {
38    Err(serde::ser::Error::custom(
39        "Serialization not implemented for this field",
40    ))
41}
42
43/// Deserialization helper that always returns NotImplementedError.
44/// Used for fields that should not be deserialized but we want to be explicit about it.
45fn deserialize_not_implemented<'de, D, T>(_: D) -> std::result::Result<T, D::Error>
46where D: serde::Deserializer<'de> {
47    Err(serde::de::Error::custom(
48        "Deserialization not implemented for this field",
49    ))
50}
51
52/// A task to scan part of file.
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TypedBuilder)]
54#[builder(field_defaults(setter(prefix = "with_")))]
55pub struct FileScanTask {
56    /// The total size of the data file in bytes, from the manifest entry.
57    /// Used to skip a stat/HEAD request when reading Parquet footers.
58    pub file_size_in_bytes: u64,
59    /// The start offset of the file to scan.
60    pub start: u64,
61    /// The length of the file to scan.
62    pub length: u64,
63    /// The number of records in the file to scan.
64    ///
65    /// This is an optional field, and only available if we are
66    /// reading the entire data file.
67    #[builder(default)]
68    pub record_count: Option<u64>,
69
70    /// The data file path corresponding to the task.
71    pub data_file_path: String,
72
73    /// The format of the file to scan.
74    pub data_file_format: DataFileFormat,
75
76    /// The schema of the file to scan.
77    pub schema: SchemaRef,
78    /// The field ids to project.
79    pub project_field_ids: Vec<i32>,
80    /// The predicate to filter.
81    #[serde(skip_serializing_if = "Option::is_none")]
82    #[builder(default)]
83    pub predicate: Option<BoundPredicate>,
84
85    /// The list of delete files that may need to be applied to this data file
86    #[builder(default)]
87    pub deletes: Vec<FileScanTaskDeleteFile>,
88
89    /// Partition data from the manifest entry, used to identify which columns can use
90    /// constant values from partition metadata vs. reading from the data file.
91    /// Per the Iceberg spec, only identity-transformed partition fields should use constants.
92    #[serde(default)]
93    #[serde(skip_serializing_if = "Option::is_none")]
94    #[serde(serialize_with = "serialize_not_implemented")]
95    #[serde(deserialize_with = "deserialize_not_implemented")]
96    #[builder(default)]
97    pub partition: Option<Struct>,
98
99    /// The partition spec for this file, used to distinguish identity transforms
100    /// (which use partition metadata constants) from non-identity transforms like
101    /// bucket/truncate (which must read source columns from the data file).
102    #[serde(default)]
103    #[serde(skip_serializing_if = "Option::is_none")]
104    #[serde(serialize_with = "serialize_not_implemented")]
105    #[serde(deserialize_with = "deserialize_not_implemented")]
106    #[builder(default)]
107    pub partition_spec: Option<Arc<PartitionSpec>>,
108
109    /// Name mapping from table metadata (property: schema.name-mapping.default),
110    /// used to resolve field IDs from column names when Parquet files lack field IDs
111    /// or have field ID conflicts.
112    #[serde(default)]
113    #[serde(skip_serializing_if = "Option::is_none")]
114    #[serde(serialize_with = "serialize_not_implemented")]
115    #[serde(deserialize_with = "deserialize_not_implemented")]
116    #[builder(default)]
117    pub name_mapping: Option<Arc<NameMapping>>,
118
119    /// Whether this scan task should treat column names as case-sensitive when binding predicates.
120    pub case_sensitive: bool,
121
122    /// Key metadata for encrypted data files (Parquet Modular Encryption).
123    /// When present, the reader uses this to build `FileDecryptionProperties`.
124    ///
125    /// Note on the trust boundary: for the standard encryption scheme this
126    /// carries `StandardKeyMetadata`, whose payload is the *plaintext* DEK.
127    /// Because `FileScanTask` derives `Serialize`, that plaintext DEK is part
128    /// of the serialized scan plan should these tasks ever be serialized and sent
129    /// over the network.
130    #[serde(default)]
131    #[serde(skip_serializing_if = "Option::is_none")]
132    #[builder(default)]
133    pub key_metadata: Option<Box<[u8]>>,
134}
135
136impl FileScanTask {
137    /// Returns the data file path of this file scan task.
138    pub fn data_file_path(&self) -> &str {
139        &self.data_file_path
140    }
141
142    /// Returns the project field id of this file scan task.
143    pub fn project_field_ids(&self) -> &[i32] {
144        &self.project_field_ids
145    }
146
147    /// Returns the predicate of this file scan task.
148    pub fn predicate(&self) -> Option<&BoundPredicate> {
149        self.predicate.as_ref()
150    }
151
152    /// Returns the schema of this file scan task as a reference
153    pub fn schema(&self) -> &Schema {
154        &self.schema
155    }
156
157    /// Returns the schema of this file scan task as a SchemaRef
158    pub fn schema_ref(&self) -> SchemaRef {
159        self.schema.clone()
160    }
161}
162
163#[derive(Debug)]
164pub(crate) struct DeleteFileContext {
165    pub(crate) manifest_entry: ManifestEntryRef,
166    pub(crate) partition_spec_id: i32,
167}
168
169impl From<&DeleteFileContext> for FileScanTaskDeleteFile {
170    fn from(ctx: &DeleteFileContext) -> Self {
171        FileScanTaskDeleteFile::builder()
172            .with_file_path(ctx.manifest_entry.file_path().to_string())
173            .with_file_size_in_bytes(ctx.manifest_entry.file_size_in_bytes())
174            .with_file_type(ctx.manifest_entry.content_type())
175            .with_partition_spec_id(ctx.partition_spec_id)
176            .with_equality_ids(ctx.manifest_entry.data_file.equality_ids.clone())
177            .with_key_metadata(
178                ctx.manifest_entry
179                    .data_file
180                    .key_metadata
181                    .as_deref()
182                    .map(Box::from),
183            )
184            .build()
185    }
186}
187
188/// A task to scan part of file.
189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TypedBuilder)]
190#[builder(field_defaults(setter(prefix = "with_")))]
191pub struct FileScanTaskDeleteFile {
192    /// The delete file path
193    pub file_path: String,
194
195    /// The total size of the delete file in bytes, from the manifest entry.
196    pub file_size_in_bytes: u64,
197
198    /// delete file type
199    pub file_type: DataContentType,
200
201    /// partition id
202    pub partition_spec_id: i32,
203
204    /// equality ids for equality deletes (null for anything other than equality-deletes)
205    #[builder(default)]
206    pub equality_ids: Option<Vec<i32>>,
207
208    /// Key metadata for encrypted delete files (Parquet Modular Encryption).
209    /// When present, the reader uses this to build `FileDecryptionProperties`.
210    ///
211    /// Same plaintext-DEK trust boundary as [`FileScanTask::key_metadata`]:
212    /// this is serialized into the scan plan and crosses the planner -> worker
213    /// channel in the clear for the standard encryption scheme.
214    #[serde(default)]
215    #[serde(skip_serializing_if = "Option::is_none")]
216    #[builder(default)]
217    pub key_metadata: Option<Box<[u8]>>,
218}