hello-stephen commented on code in PR #71239: URL: https://github.com/apache/doris/pull/71239#discussion_r4780095598
########## fe/fe-iceberg-common/src/main/java/org/apache/iceberg/DorisMetadataRows.java: ########## @@ -0,0 +1,156 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.iceberg; + +import org.apache.iceberg.types.Type; +import org.apache.iceberg.types.Types; +import org.apache.iceberg.util.ByteBuffers; + +import java.io.Serializable; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Keyless, self-contained metadata batches; no IO or encryption manager is serialized to a backend. */ +public final class DorisMetadataRows { + public static final long MAX_ROW_BYTES = 4L << 20; + + private DorisMetadataRows() { + } + + public static DataTask task(Schema schema, List<StructLike> rows) { + return task(schema, rows, 0); + } + + /** Keep batch ordinals in task identity even when projected row values are identical. */ + public static DataTask task(Schema schema, List<StructLike> rows, long batchOrdinal) { + DataFile file = DataFiles.builder(PartitionSpec.unpartitioned()) + .withPath("iceberg-metadata-batch-" + batchOrdinal) + .withFileSizeInBytes(0).withRecordCount(rows.size()).withFormat(FileFormat.METADATA).build(); + return new StaticDataTask(file, schema, schema, rows.toArray(new StructLike[0])); + } + + public static CopiedRow copy(StructLike row, Schema schema) { + Budget budget = new Budget(); + return new CopiedRow(copyStruct(row, schema.asStruct(), budget), MAX_ROW_BYTES - budget.remaining); + } + + /** A detached row and its conservative allocation charge for bounded metadata batching. */ + public static final class CopiedRow { + private final StructLike row; + private final long bytes; + + private CopiedRow(StructLike row, long bytes) { + this.row = row; + this.bytes = bytes; + } + + public StructLike row() { + return row; + } + + public long bytes() { + return bytes; + } + } + + private static StructLike copyStruct(StructLike row, Types.StructType type, Budget budget) { + budget.charge(32L + 8L * type.fields().size()); + Object[] values = new Object[type.fields().size()]; + for (int index = 0; index < values.length; index++) { + Types.NestedField field = type.fields().get(index); + // These Iceberg IDs identify key carriers even inside entries.data_file. A user field + // with the same name in readable_metrics must retain its ordinary statistics. + if (field.fieldId() != DataFile.KEY_METADATA.fieldId() + && field.fieldId() != ManifestFile.KEY_METADATA.fieldId()) { + values[index] = copyValue(row.get(index, Object.class), field.type(), budget); + } + } + return StaticDataTask.Row.of(values); + } + + private static Object copyValue(Object value, Type type, Budget budget) { + if (value == null) { + return null; + } + switch (type.typeId()) { + case STRUCT: + return copyStruct((StructLike) value, type.asStructType(), budget); + case LIST: + List<?> list = (List<?>) value; + budget.charge(32L + 8L * list.size()); + List<Object> copiedList = new ArrayList<>(list.size()); + for (Object element : list) { + copiedList.add(copyValue(element, type.asListType().elementType(), budget)); + } + return copiedList; + case MAP: + Map<?, ?> map = (Map<?, ?>) value; + budget.charge(64L + 48L * map.size()); + Map<Object, Object> copiedMap = new LinkedHashMap<>(); + for (Map.Entry<?, ?> entry : map.entrySet()) { + copiedMap.put(copyValue(entry.getKey(), type.asMapType().keyType(), budget), + copyValue(entry.getValue(), type.asMapType().valueType(), budget)); + } + return copiedMap; + case STRING: + budget.charge(24L + 4L * ((CharSequence) value).length()); + return value.toString(); + case BINARY: + case FIXED: + if (value instanceof ByteBuffer) { + ByteBuffer binary = (ByteBuffer) value; + budget.charge(32L + binary.remaining()); + return new SerializedBinary(ByteBuffers.toByteArray(binary)); Review Comment: [P2] Copy binary metadata before advancing the manifest iterator `ByteBuffers.toByteArray` can return a writable buffer's own array. The Iceberg 1.12 Parquet manifest reader reuses these buffers between entries, and `$entries` projects those entries directly. If two entries in one batch carry different same-width lower or upper bounds, reading the second can overwrite the first row's array before serialization. Copy the remaining bytes into storage owned by the detached row and test two entries that reuse a writable buffer. [Iceberg buffer conversion](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/api/src/main/java/org/apache/iceberg/util/ByteBuffers.java#L28-L47) · [Iceberg entries reader](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/core/src/main/java/org/apache/iceberg/BaseEntriesTable.java#L310-L354) · [Iceberg Parquet buffer reuse](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/parquet/src/main/java/org/apache/iceberg/parquet/ParquetValueReaders.java#L715-L732) ########## fe/fe-iceberg-common/src/main/java/org/apache/iceberg/DorisMetadataRows.java: ########## @@ -0,0 +1,156 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.iceberg; + +import org.apache.iceberg.types.Type; +import org.apache.iceberg.types.Types; +import org.apache.iceberg.util.ByteBuffers; + +import java.io.Serializable; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Keyless, self-contained metadata batches; no IO or encryption manager is serialized to a backend. */ +public final class DorisMetadataRows { + public static final long MAX_ROW_BYTES = 4L << 20; + + private DorisMetadataRows() { + } + + public static DataTask task(Schema schema, List<StructLike> rows) { + return task(schema, rows, 0); + } + + /** Keep batch ordinals in task identity even when projected row values are identical. */ + public static DataTask task(Schema schema, List<StructLike> rows, long batchOrdinal) { + DataFile file = DataFiles.builder(PartitionSpec.unpartitioned()) + .withPath("iceberg-metadata-batch-" + batchOrdinal) + .withFileSizeInBytes(0).withRecordCount(rows.size()).withFormat(FileFormat.METADATA).build(); + return new StaticDataTask(file, schema, schema, rows.toArray(new StructLike[0])); + } + + public static CopiedRow copy(StructLike row, Schema schema) { + Budget budget = new Budget(); + return new CopiedRow(copyStruct(row, schema.asStruct(), budget), MAX_ROW_BYTES - budget.remaining); + } + + /** A detached row and its conservative allocation charge for bounded metadata batching. */ + public static final class CopiedRow { + private final StructLike row; + private final long bytes; + + private CopiedRow(StructLike row, long bytes) { + this.row = row; + this.bytes = bytes; + } + + public StructLike row() { + return row; + } + + public long bytes() { + return bytes; + } + } + + private static StructLike copyStruct(StructLike row, Types.StructType type, Budget budget) { + budget.charge(32L + 8L * type.fields().size()); + Object[] values = new Object[type.fields().size()]; + for (int index = 0; index < values.length; index++) { + Types.NestedField field = type.fields().get(index); + // These Iceberg IDs identify key carriers even inside entries.data_file. A user field + // with the same name in readable_metrics must retain its ordinary statistics. + if (field.fieldId() != DataFile.KEY_METADATA.fieldId() + && field.fieldId() != ManifestFile.KEY_METADATA.fieldId()) { Review Comment: [P2] Preserve readable metrics whose IDs match key fields Iceberg assigns `$files.readable_metrics` IDs after the base file schema. On an unpartitioned table with 54 scalar columns, field 519 is the `value_count` for the 54th primitive column visited by the SDK. This recursive check equates 519 with `ManifestFile.KEY_METADATA` in every struct, so a populated count is returned as NULL in the encrypted metadata scan. Identify the key field within its metadata-table schema and path, and cover a wide `$files` projection. [Iceberg metric IDs](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/core/src/main/java/org/apache/iceberg/MetricsUtil.java#L334-L367) · [Iceberg file schema](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/api/src/main/java/org/apache/iceberg/DataFile.java#L112-L146) ########## fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergScanPlanProvider.java: ########## @@ -591,6 +598,16 @@ public ConnectorSplitSource streamSplits(ConnectorSession session, ConnectorScan // preserve that boundary instead of interpreting Iceberg's sentinel as the latest snapshot. return emptySplitSource(); } + if (iceHandle.isSystemTable()) { + Table metadataTable = resolveSysTable(session, iceHandle); + if (isPositionDeletesSysTable(iceHandle) || IcebergLabelsSysTable.isLabels(iceHandle) + || !IcebergEncryptionRead.isEncrypted(((BaseMetadataTable) metadataTable).table())) { + throw new UnsupportedOperationException("This Iceberg metadata table requires synchronous planning"); + } + TableScan metadataScan = projectedMetadataScan(metadataTable, iceHandle, columns, filter, session); + return new IcebergMetadataSplitSource(metadataScan::planFiles, metadataScan.schema(), Review Comment: [P2] Bound encrypted partition metadata before materialization For `$partitions`, Iceberg's `planFiles()` reads all matching manifest entries into a partition map and materializes the result as one `StaticDataTask` before returning. This happens before `IcebergMetadataSplitSource` can enforce its per-row or per-batch limits. A high-cardinality encrypted table can therefore exhaust FE memory or time out before the first split even in batch mode. Bound aggregation before building the SDK result, or apply a size fence specific to `$partitions` before starting it. [Iceberg partition aggregation](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/core/src/main/java/org/apache/iceberg/PartitionsTable.java#L141-L205) · [Iceberg static task materialization](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/core/src/main/java/org/apache/iceberg/StaticDataTask.java#L33-L44) ########## fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergParquetColumnKeys.java: ########## @@ -0,0 +1,199 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.iceberg; + +import org.apache.doris.connector.spi.ConnectorConf; +import org.apache.doris.connector.spi.ConnectorContext; + +import org.apache.iceberg.ContentFile; +import org.apache.iceberg.DataFile; +import org.apache.iceberg.DeleteFile; +import org.apache.iceberg.encryption.EncryptionUtil; +import org.apache.iceberg.encryption.KeyManagementClient; +import org.apache.iceberg.encryption.NativeEncryptionInputFile; +import org.apache.iceberg.encryption.NativeEncryptionKeyMetadata; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.util.ByteBuffers; +import org.apache.parquet.format.ColumnChunk; +import org.apache.parquet.format.ColumnMetaData; +import org.apache.parquet.format.EncryptionWithColumnKey; +import org.apache.parquet.format.RowGroup; + +import java.nio.ByteBuffer; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** Optional producer-specific column DEKs, resolved only inside the admitted statement's IO scope. */ +final class IcebergParquetColumnKeys { + static final String PROVIDER_CONFIG = "parquet_column_key_provider_class"; + static final int MAX_COLUMN_KEYS = 65536; + + private IcebergParquetColumnKeys() { + } + + static Map<Integer, byte[]> read(FileIO io, ContentFile<?> file, ConnectorContext context) { + // Operator configuration is a separate namespace. Catalog/table/vended properties cannot load code. + String implementation = context == null ? null : ConnectorConf.get(context, PROVIDER_CONFIG, null, null); + if (implementation == null || implementation.isBlank()) { + return Collections.emptyMap(); + } + try (IcebergParquetColumnKeyProvider provider = Class.forName(implementation, true, + IcebergParquetColumnKeys.class.getClassLoader()).asSubclass(IcebergParquetColumnKeyProvider.class) + .getDeclaredConstructor().newInstance(); + KeyUnwrapper kms = new KeyUnwrapper(io.properties())) { Review Comment: [P2] Pass the effective HMS KMS configuration to the column-key provider Without an explicit `io-impl`, the HMS SDK creates `HadoopFileIO(conf)` with an empty `properties()` map. It initializes the table's working KMS separately from catalog properties. The native footer can open, but a provider that calls the supplied `unwrap` callback tries to create a second KMS client from the empty map and fails with `COLUMN_KEY_RESOLUTION_FAILED`. Use the effective KMS context for this table and test the default HMS FileIO path. The integration fixture selects `S3FileIO` explicitly. [Iceberg HMS initialization](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/hive-metastore/src/main/java/org/apache/iceberg/hive/HiveCatalog.java#L119-L130) · [Iceberg HadoopFileIO](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/core/src/main/java/org/apache/iceberg/hadoop/HadoopFileIO.java#L53-L72) ########## docker/thirdparties/docker-compose/iceberg/encryption/IcebergEncryptionFixture.java: ########## @@ -245,6 +399,26 @@ private void proxyKms(HttpExchange request) throws IOException { + "\"message\":\"Fixture decrypt permission revoked\"}"); return; } + // One immutable snapshot prevents concurrent requests from mixing modes and budgets. + KmsFault fault = kmsFault.getAndUpdate(value -> value.remaining() > 0 + ? new KmsFault(value.mode(), value.delayMillis(), value.remaining() - 1) : value); + if (fault.delayMillis() > 0) { Review Comment: [P3] Stop delaying healthy requests after the fault budget is used After the final injected fault, the atomic state still contains `delayMillis`. A one-fault throttle therefore sleeps on the successful retry and on every subsequent decrypt until the fixture is cleared. Apply the delay only to requests that consume a fault. ########## fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergProcedureOps.java: ########## @@ -324,6 +328,8 @@ private ProcedureTableOperations(TableOperations delegate, int admittedFormat) { private TableMetadata validate(TableMetadata metadata) { Objects.requireNonNull(metadata, "Procedure table no longer exists"); + // A concurrent encryption change also revokes maintenance on refresh and CAS replay. + IcebergEncryptionRead.checkWrite(metadata); Review Comment: [P2] Fence encryption state at REST maintenance commit `validate` checks the client metadata. If another writer enables encryption after that check without changing the format or snapshot reference, the Iceberg REST server can still apply the staged `rewrite_manifests` update to its latest metadata. The request's requirements and Doris's same-format fence do not check the encryption state. This can publish plaintext manifests staged before the switch. Use a server-side metadata-generation or encryption-state precondition for this operation and cover the REST apply path. [Iceberg REST requirements](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/core/src/main/java/org/apache/iceberg/UpdateRequirements.java#L45-L113) · [Iceberg REST commit](https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.12.0/core/src/main/java/org/apache/iceberg/rest/CatalogHandlers.java#L556-L598) ########## regression-test/suites/external_table_p0/iceberg/test_iceberg_encryption_native_read_integration.groovy: ########## @@ -197,11 +360,44 @@ suite("test_iceberg_encryption_native_read_integration", "p0,external,nonConcurr assertEquals([1, 2, 3, 4], (sql "SELECT id FROM ${encrypted} ORDER BY id").collect { it[0] as Integer }) assertEquals(4L, (sql "SELECT COUNT(*) FROM ${encrypted}")[0][0] as Long) } + long beforeRestart = fixture("/kms/access", "GET").decryptRequests as Long + restartFrontend.call() Review Comment: [P3] Preserve the original frontend restart failure The restart helper closes the thread-local JDBC connection before requesting restart and replaces it after reconnecting. A restart timeout or failed reconnect leaves the suite's `finally` block sending `SET` and `DROP` on the closed connection, which can replace the restart error. Restore the shared KMS fixture state and guard SQL cleanup on a live child connection. ########## be/src/format_v2/parquet/parquet_crypto.cpp: ########## @@ -302,32 +310,60 @@ ParquetColumnCrypto::~ParquetColumnCrypto() = default; Status ParquetFileCrypto::create(const TFileEncryptionInfo& info, const tparquet::FileCryptoMetaData& metadata, std::shared_ptr<ParquetFileCrypto>* crypto) { - if (!info.__isset.version || info.version != 1 || !info.__isset.key || + if (!info.__isset.version || (info.version != 1 && info.version != 2) || !info.__isset.key || (info.key.size() != 16 && info.key.size() != 24 && info.key.size() != 32) || !info.__isset.aad_prefix || info.aad_prefix.size() > 65536) { return Status::InvalidArgument("File encryption [INVALID_DESCRIPTOR]"); } + if (info.__isset.column_keys) { + if (info.version != 2 || info.column_keys.size() > 65536) { + return Status::InvalidArgument("File encryption [INVALID_COLUMN_KEYS]"); + } + for (const auto& [ordinal, key] : info.column_keys) { + if (ordinal < 0 || (ordinal & 65535) > 32767 || + (key.size() != 16 && key.size() != 24 && key.size() != 32)) { + return Status::InvalidArgument("File encryption [INVALID_COLUMN_KEYS]"); + } + } + } const auto& algorithm = metadata.encryption_algorithm; - if (!algorithm.__isset.AES_GCM_V1 || algorithm.__isset.AES_GCM_CTR_V1) { + if (algorithm.__isset.AES_GCM_V1 == algorithm.__isset.AES_GCM_CTR_V1) { return Status::NotSupported("File encryption [UNSUPPORTED_CIPHER]"); } - const auto& aes = algorithm.AES_GCM_V1; - if (!aes.__isset.aad_file_unique || aes.aad_file_unique.size() != 8) { - return Status::Corruption("File encryption [INVALID_FILE_AAD]"); - } - if (aes.supply_aad_prefix && info.aad_prefix.empty()) { - return Status::InvalidArgument("File encryption [MISSING_AAD]"); - } - if ((!aes.aad_prefix.empty() && aes.aad_prefix != info.aad_prefix) || - (aes.aad_prefix.empty() && !aes.supply_aad_prefix && !info.aad_prefix.empty())) { - return Status::InvalidArgument("File encryption [AAD_MISMATCH]"); - } + std::string file_aad; + const auto validate_aad = [&](const auto& aes) -> Status { + if (!aes.__isset.aad_file_unique || aes.aad_file_unique.size() != 8) { + return Status::Corruption("File encryption [INVALID_FILE_AAD]"); + } + if (aes.supply_aad_prefix && info.aad_prefix.empty()) { + return Status::InvalidArgument("File encryption [MISSING_AAD]"); + } + if ((!aes.aad_prefix.empty() && aes.aad_prefix != info.aad_prefix) || + (aes.aad_prefix.empty() && !aes.supply_aad_prefix && !info.aad_prefix.empty())) { + return Status::InvalidArgument("File encryption [AAD_MISMATCH]"); + } + file_aad = info.aad_prefix + aes.aad_file_unique; + return Status::OK(); + }; + RETURN_IF_ERROR(algorithm.__isset.AES_GCM_V1 ? validate_aad(algorithm.AES_GCM_V1) + : validate_aad(algorithm.AES_GCM_CTR_V1)); #if __has_include(<parquet/encryption/encryption_internal.h>) auto impl = std::make_unique<Impl>(); auto key = std::make_shared<crypto_detail::FileKey>(); key->key = ::arrow::util::SecureString(std::string(info.key)); - key->file_aad = info.aad_prefix + aes.aad_file_unique; - impl->key = std::move(key); + key->file_aad = std::make_shared<const std::string>(std::move(file_aad)); + impl->cipher = algorithm.__isset.AES_GCM_CTR_V1 ? ::parquet::ParquetCipher::AES_GCM_CTR_V1 + : ::parquet::ParquetCipher::AES_GCM_V1; + impl->key = key; + if (info.__isset.column_keys) { + for (const auto& [ordinal, bytes] : info.column_keys) { + auto column_key = std::make_shared<crypto_detail::FileKey>(); + column_key->key = ::arrow::util::SecureString(std::string(bytes)); Review Comment: [P3] Wipe temporary copies of independent column keys `TableReader` passes `ParquetReader` an owned copy of the wire descriptor. Once the file context has moved its own keys into `SecureString`, `ParquetReader::_clear_decryption_parameters()` wipes the temporary footer key and resets the descriptor. Apply the same `SecureClear` to each `column_keys` value before reset so temporary column keys are cleared on footer success, failure and close. ########## fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergMetadataSplitSource.java: ########## @@ -0,0 +1,212 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.iceberg; + +import org.apache.doris.connector.spi.ConnectorContext; +import org.apache.doris.connector.spi.scan.ConnectorScanContext; +import org.apache.doris.connector.spi.scan.ConnectorScanRange; +import org.apache.doris.connector.spi.scan.ConnectorSplitSource; + +import org.apache.iceberg.DorisMetadataRows; +import org.apache.iceberg.FileScanTask; +import org.apache.iceberg.Schema; +import org.apache.iceberg.StructLike; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.CloseableIterator; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.concurrent.Callable; +import java.util.function.Supplier; + +/** Pulls authenticated metadata on the FE and publishes only bounded, sanitized row batches. */ +final class IcebergMetadataSplitSource implements ConnectorSplitSource { + private static final int MAX_BATCH_ROWS = 256; + private static final long TARGET_BATCH_BYTES = 1L << 20; + private static final int MAX_SERIALIZED_BYTES = 6 << 20; + private final Supplier<CloseableIterable<FileScanTask>> loader; + private final Schema schema; + private final ConnectorScanContext scanContext; + private final ConnectorContext context; + private CloseableIterable<FileScanTask> tasks; + private CloseableIterator<FileScanTask> taskIterator; + private CloseableIterable<StructLike> rows; + private CloseableIterator<StructLike> rowIterator; + private DorisMetadataRows.CopiedRow pending; + private ConnectorScanRange next; + private long batchOrdinal; + private boolean closed; + + IcebergMetadataSplitSource(Supplier<CloseableIterable<FileScanTask>> loader, Schema schema, + ConnectorScanContext scanContext, ConnectorContext context) { + this.loader = loader; + this.schema = schema; + this.scanContext = scanContext; + this.context = context; + } + + @Override + public boolean hasNext() { + if (closed) { + return false; + } + try { + return authenticated(this::advance); + } catch (RuntimeException failure) { + try { + close(); + } catch (IOException cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + private boolean advance() throws IOException { + scanContext.checkCancelled(); + if (next != null) { + return true; + } + if (tasks == null) { + tasks = loader.get(); + taskIterator = tasks.iterator(); + } + List<StructLike> batch = new ArrayList<>(); + long bytes = 0; + while (batch.size() < MAX_BATCH_ROWS) { + scanContext.checkCancelled(); + if (pending == null) { + while (rowIterator == null || !rowIterator.hasNext()) { + closeRows(); + if (!taskIterator.hasNext()) { + break; + } + rows = taskIterator.next().asDataTask().rows(); Review Comment: [P3] Check cancellation before opening the next metadata task If an encrypted `$files` scan has consecutive manifests with no live rows, this inner loop can keep opening them after cancellation. The producer defers closing a running source, and the table FileIO decorator uses a no-op cancellation callback. Check cancellation on each task advance and pass the scan's cancellation check into metadata FileIO so the producer can release the worker promptly. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
