You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@asterixdb.apache.org by AsterixDB Code Review <do...@asterix-gerrit.ics.uci.edu> on 2026/09/29 23:20:15 UTC
[XL] Change in asterixdb[master]: [ASTERIXDB-3912][EXT] Cut Iceberg read round trips
From Hussain Towaileb <hu...@gmail.com>:
Hussain Towaileb has uploaded this change for review. ( https://asterix-gerrit.ics.uci.edu/c/asterixdb/+/21945?usp=email )
Change subject: [ASTERIXDB-3912][EXT] Cut Iceberg read round trips
......................................................................
[ASTERIXDB-3912][EXT] Cut Iceberg read round trips
Readers loaded the Iceberg table from the catalog in their constructor,
which runs inside the synchronized createAdapter that every partition on
a node shares, so each partition's catalog round trips waited for the
previous partition's, repeating work the compiler had already done. The
compiler now ships the schema at the pinned snapshot and a description
of the table's FileIO to the readers, which open their own FileIO under
a registry id of their own and make no catalog calls. The compiler also
loads the table once rather than checking for it first, which was itself
a full load.
Data and delete files are opened with the length their manifest records,
sparing a storage request per file, and an equality delete file is
loaded once per scan on a node rather than once for every data file it
applies to.
Also release the catalog clients that initializeCatalog registered
before failing, and close the catalog that snapshot validation opened,
which was never closed.
Added test cases covering reader construction and cleanup, per-reader
FileIO isolation, the shared delete cache and snapshot validation
cleanup.
Ext-ref: MB-74257
Generated-by: Claude Opus 5.5 <no...@anthropic.com>
Change-Id: I5179221ef913ef8d5236a0c44c9e761f24e880d8
---
A asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergDeleteCache.java
A asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileIoDescriptor.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileRecordReader.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergParquetRecordReaderFactory.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/PositionlessGenericDeleteFilter.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergSnapshotUtils.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergUtils.java
A asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergDeleteCacheTest.java
A asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileRecordReaderLifecycleTest.java
M asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergVariantReadRoutingTest.java
A asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/util/iceberg/IcebergSnapshotValidationCleanupTest.java
11 files changed, 1,173 insertions(+), 52 deletions(-)
git pull ssh://asterix-gerrit.ics.uci.edu:29418/asterixdb refs/changes/45/21945/1
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergDeleteCache.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergDeleteCache.java
new file mode 100644
index 0000000..ed11ef1
--- /dev/null
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergDeleteCache.java
@@ -0,0 +1,108 @@
+/*
+ * 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.asterix.external.input.record.reader.iceberg;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.data.BaseDeleteLoader;
+import org.apache.iceberg.data.DeleteLoader;
+import org.apache.iceberg.io.InputFile;
+
+/**
+ * Delete files loaded once per scan on a node rather than once per data file they apply to.
+ * <p>
+ * An equality delete applies to every data file of its partition written before it, so without a cache each of those
+ * data files reloads it: a table with a handful of delete files costs a remote read and a rebuilt set per data file.
+ * One instance is shared by every reader of a scan on a node, the same way Iceberg's executor-wide delete cache is
+ * shared by concurrently running tasks: the loaded values are only read after they are built.
+ * <p>
+ * Entries are kept for the lifetime of the scan. A delete file whose estimated in-memory size exceeds
+ * {@link #MAX_ENTRY_SIZE}, or that would take the scan past {@link #MAX_TOTAL_SIZE}, is loaded the uncached way.
+ */
+final class IcebergDeleteCache {
+
+ static final long MAX_ENTRY_SIZE = 64L * 1024 * 1024;
+ static final long MAX_TOTAL_SIZE = 128L * 1024 * 1024;
+
+ private final ConcurrentMap<String, FutureTask<Object>> entries = new ConcurrentHashMap<>();
+ private final AtomicLong cachedSize = new AtomicLong();
+
+ /**
+ * @return a delete loader reading through this cache, opening delete files with {@code loadInputFile}
+ */
+ DeleteLoader newLoader(Function<DeleteFile, InputFile> loadInputFile) {
+ return new BaseDeleteLoader(loadInputFile) {
+ @Override
+ protected boolean canCache(long size) {
+ return size <= MAX_ENTRY_SIZE && cachedSize.get() + size <= MAX_TOTAL_SIZE;
+ }
+
+ @Override
+ protected <V> V getOrLoad(String key, Supplier<V> valueSupplier, long valueSize) {
+ return IcebergDeleteCache.this.getOrLoad(key, valueSupplier, valueSize);
+ }
+ };
+ }
+
+ int size() {
+ return entries.size();
+ }
+
+ // The load runs outside any map lock so that readers of other delete files are not held up, and a reader asking
+ // for a file another reader is loading waits for that load instead of repeating it. A failed load is not kept,
+ // so the next reader retries it.
+ @SuppressWarnings("unchecked")
+ private <V> V getOrLoad(String key, Supplier<V> valueSupplier, long valueSize) {
+ FutureTask<Object> task = entries.get(key);
+ if (task == null) {
+ FutureTask<Object> created = new FutureTask<>(valueSupplier::get);
+ task = entries.putIfAbsent(key, created);
+ if (task == null) {
+ task = created;
+ cachedSize.addAndGet(valueSize);
+ created.run();
+ }
+ }
+ try {
+ return (V) task.get();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("interrupted while loading delete file " + key, e);
+ } catch (ExecutionException e) {
+ if (entries.remove(key, task)) {
+ cachedSize.addAndGet(-valueSize);
+ }
+ Throwable cause = e.getCause();
+ if (cause instanceof RuntimeException runtime) {
+ throw runtime;
+ }
+ if (cause instanceof Error error) {
+ throw error;
+ }
+ throw new IllegalStateException("failed to load delete file " + key, cause);
+ }
+ }
+}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileIoDescriptor.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileIoDescriptor.java
new file mode 100644
index 0000000..8cd989c
--- /dev/null
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileIoDescriptor.java
@@ -0,0 +1,91 @@
+/*
+ * 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.asterix.external.input.record.reader.iceberg;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import org.apache.asterix.external.util.aws.EnsureCloseClientsFactoryRegistry;
+import org.apache.iceberg.CatalogUtil;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.StorageCredential;
+import org.apache.iceberg.io.SupportsStorageCredentials;
+
+/**
+ * Everything needed to open a table's {@link FileIO} without its catalog: the implementation, its properties, and any
+ * storage credentials the catalog vended. Captured from the table loaded at compile time and shipped to the readers,
+ * so a reader can open the data files without contacting the catalog again.
+ * <p>
+ * Iceberg's {@code SerializableTable} is not used for this because it reloads the table metadata through the shipped
+ * FileIO the first time a snapshot or schema is asked for, and that FileIO registers its clients under the compile-time
+ * registry id: every copy would share the id, and closing any one of them would shut down the clients of all of them.
+ */
+final class IcebergFileIoDescriptor implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String implementation;
+ private final HashMap<String, String> properties;
+ private final ArrayList<StorageCredential> credentials;
+
+ private IcebergFileIoDescriptor(String implementation, Map<String, String> properties,
+ List<StorageCredential> credentials) {
+ this.implementation = implementation;
+ this.properties = new HashMap<>(properties);
+ this.credentials = new ArrayList<>(credentials);
+ }
+
+ /**
+ * @return the descriptor of {@code io}, or {@code null} when that FileIO does not expose its properties, in which
+ * case readers have to load the table from the catalog themselves
+ */
+ static IcebergFileIoDescriptor capture(FileIO io) {
+ Map<String, String> properties;
+ try {
+ properties = io.properties();
+ } catch (UnsupportedOperationException e) {
+ return null;
+ }
+ List<StorageCredential> credentials =
+ io instanceof SupportsStorageCredentials withCredentials ? withCredentials.credentials() : List.of();
+ return new IcebergFileIoDescriptor(io.getClass().getName(), properties, credentials);
+ }
+
+ /**
+ * @return the properties to open a new FileIO with, carrying a registry id of their own so that the clients the
+ * FileIO creates can be released without touching those of any other reader
+ */
+ Map<String, String> newProperties() {
+ Map<String, String> copy = new HashMap<>(properties);
+ copy.put(EnsureCloseClientsFactoryRegistry.FACTORY_INSTANCE_ID_KEY, UUID.randomUUID().toString());
+ return copy;
+ }
+
+ /**
+ * Opens a FileIO with properties obtained from {@link #newProperties()}; the caller owns it and must close it, and
+ * then release the registry id in those properties.
+ */
+ FileIO open(Map<String, String> ioProperties) {
+ return CatalogUtil.loadFileIO(implementation, ioProperties, null, credentials);
+ }
+}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileRecordReader.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileRecordReader.java
index e25ab06..853d532 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileRecordReader.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileRecordReader.java
@@ -49,6 +49,7 @@
import org.apache.iceberg.catalog.Catalog;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.data.DeleteLoader;
import org.apache.iceberg.data.GenericDeleteFilter;
import org.apache.iceberg.data.Record;
import org.apache.iceberg.data.parquet.GenericParquetReaders;
@@ -74,6 +75,10 @@
private final IRawRecord<Record> record;
private Map<String, String> catalogProperties;
+ private final IcebergFileIoDescriptor fileIoDescriptor;
+ private final IcebergDeleteCache deleteCache;
+ private Map<String, String> fileIoProperties;
+ private boolean tableInitialized;
private int nextTaskIndex = 0;
private Catalog catalog;
private FileIO tableFileIo;
@@ -90,19 +95,24 @@
private final boolean variantProjectionPushdownWithDeletes;
private final IWarningCollector warningCollector;
- public IcebergFileRecordReader(List<FileScanTask> fileScanTasks, Schema projectedSchema,
- Map<String, String> configuration, IWarningCollector warningCollector) throws HyracksDataException {
+ /**
+ * @param schemaAtSnapshot the table schema at the pinned snapshot, and {@code fileIoDescriptor} the table's FileIO,
+ * both as the compiler loaded them. When both are given the reader opens the data files directly and never
+ * contacts the catalog; when either is {@code null} it loads the table from the catalog itself.
+ * @param deleteCache the scan's delete files already loaded on this node, shared with the scan's other readers;
+ * {@code null} loads every delete file for each data file it applies to
+ */
+ public IcebergFileRecordReader(List<FileScanTask> fileScanTasks, Schema projectedSchema, Schema schemaAtSnapshot,
+ IcebergFileIoDescriptor fileIoDescriptor, IcebergDeleteCache deleteCache, Map<String, String> configuration,
+ IWarningCollector warningCollector) throws HyracksDataException {
this.fileScanTasks = fileScanTasks;
this.projectedSchema = projectedSchema;
+ this.schemaAtSnapshot = schemaAtSnapshot;
+ this.fileIoDescriptor = fileIoDescriptor;
+ this.deleteCache = deleteCache;
this.originalConfiguration = configuration;
this.warningCollector = warningCollector;
this.record = new GenericRecord<>();
- try {
- initializeTable();
- } catch (CompilationException e) {
- Throwable throwable = closeResources(e);
- throw HyracksDataException.create(throwable);
- }
this.variantProjectionPlan = buildVariantProjectionPlan();
this.variantProjectionPushdownWithDeletes = Boolean.parseBoolean(configuration.getOrDefault(
ExternalDataConstants.IcebergOptions.VARIANT_PROJECTION_PUSHDOWN_WITH_DELETES, Boolean.toString(
@@ -153,6 +163,11 @@
if (fileScanTasks.isEmpty()) {
return;
}
+ if (fileIoDescriptor != null && schemaAtSnapshot != null) {
+ fileIoProperties = fileIoDescriptor.newProperties();
+ tableFileIo = fileIoDescriptor.open(fileIoProperties);
+ return;
+ }
String namespace = IcebergUtils.getNamespace(originalConfiguration);
String tableName = originalConfiguration.get(IcebergConstants.ICEBERG_TABLE_NAME_PROPERTY_KEY);
@@ -160,10 +175,7 @@
catalog = IcebergUtils.initializeCatalog(catalogProperties, namespace);
Namespace parsedNamespace = IcebergUtils.parseNamespace(namespace);
TableIdentifier tableIdentifier = TableIdentifier.of(parsedNamespace, tableName);
- if (!catalog.tableExists(tableIdentifier)) {
- throw CompilationException.create(ErrorCode.ICEBERG_TABLE_DOES_NOT_EXIST, tableName);
- }
- Table table = catalog.loadTable(tableIdentifier);
+ Table table = IcebergUtils.loadExistingTable(catalog, tableIdentifier, tableName);
tableFileIo = table.io();
// we always have a snapshot id since we pin it at compile time
@@ -183,6 +195,14 @@
@Override
public boolean hasNext() throws Exception {
+ // Loaded here rather than in the constructor: readers are constructed inside GenericAdapterFactory's
+ // synchronized createAdapter, which every partition on a node shares, so loading the table there (catalog
+ // clients, namespace check, metadata reads) would run each partition's remote calls one after another.
+ if (!tableInitialized) {
+ tableInitialized = true;
+ initializeTable();
+ }
+
// iterator has more records
if (recordsIterator != null && recordsIterator.hasNext()) {
return true;
@@ -233,6 +253,9 @@
if (catalog != null) {
IcebergUtils.closeAndCleanup(catalog, catalogProperties);
}
+ if (fileIoProperties != null) {
+ IcebergUtils.closeAndCleanup(null, fileIoProperties);
+ }
} catch (Exception ex) {
throwable = ExceptionUtils.suppress(throwable, ex);
}
@@ -258,12 +281,13 @@
private void setNextRecordsIterator() {
FileScanTask task = fileScanTasks.get(nextTaskIndex++);
- InputFile inFile = tableFileIo.newInputFile(task.file().location());
+ // the manifest records the length, and not passing it costs a storage request per file to find it out
+ InputFile inFile = tableFileIo.newInputFile(task.file().location(), task.file().fileSizeInBytes());
CloseableIterable<Record> prunedRead = null;
try {
prunedRead = openPrunedReadIfEligible(tableFileIo, inFile, task, schemaAtSnapshot, projectedSchema,
- variantProjectionPlan, variantProjectionPushdownWithDeletes);
+ variantProjectionPlan, variantProjectionPushdownWithDeletes, deleteCache);
if (prunedRead != null) {
iterable = prunedRead;
recordsIterator = prunedRead.iterator();
@@ -277,7 +301,7 @@
warnProjectionNotPushed(e);
}
- iterable = openStandardRead(tableFileIo, inFile, task, schemaAtSnapshot, projectedSchema);
+ iterable = openStandardRead(tableFileIo, inFile, task, schemaAtSnapshot, projectedSchema, deleteCache);
recordsIterator = iterable.iterator();
}
@@ -295,6 +319,11 @@
*/
static CloseableIterable<Record> openStandardRead(FileIO io, InputFile inFile, FileScanTask task,
Schema schemaAtSnapshot, Schema projectedSchema) {
+ return openStandardRead(io, inFile, task, schemaAtSnapshot, projectedSchema, null);
+ }
+
+ static CloseableIterable<Record> openStandardRead(FileIO io, InputFile inFile, FileScanTask task,
+ Schema schemaAtSnapshot, Schema projectedSchema, IcebergDeleteCache deleteCache) {
int deletesCount = (task.deletes() == null) ? 0 : task.deletes().size();
if (deletesCount == 0) {
// No deletes: read only projected schema
@@ -304,7 +333,7 @@
}
// Has deletes: read required schema, then apply delete filter
- GenericDeleteFilter deleteFilter = new GenericDeleteFilter(io, task, schemaAtSnapshot, projectedSchema);
+ GenericDeleteFilter deleteFilter = newDeleteFilter(io, task, schemaAtSnapshot, projectedSchema, deleteCache);
Schema requiredSchema = deleteFilter.requiredSchema();
CloseableIterable<Record> rows =
@@ -356,12 +385,19 @@
static CloseableIterable<Record> openPrunedReadIfEligible(FileIO io, InputFile inFile, FileScanTask task,
Schema tableSchema, Schema projectedSchema, VariantProjectionPlan plan, boolean pushdownWithDeletes)
throws IOException {
+ return openPrunedReadIfEligible(io, inFile, task, tableSchema, projectedSchema, plan, pushdownWithDeletes,
+ null);
+ }
+
+ static CloseableIterable<Record> openPrunedReadIfEligible(FileIO io, InputFile inFile, FileScanTask task,
+ Schema tableSchema, Schema projectedSchema, VariantProjectionPlan plan, boolean pushdownWithDeletes,
+ IcebergDeleteCache deleteCache) throws IOException {
if (!shouldTryPrunedVariantRead(plan, task.deletes(), pushdownWithDeletes)) {
return null;
}
boolean hasDeletes = task.deletes() != null && !task.deletes().isEmpty();
if (hasDeletes) {
- return openPrunedDeleteAwareRead(io, inFile, task, tableSchema, projectedSchema, plan);
+ return openPrunedDeleteAwareRead(io, inFile, task, tableSchema, projectedSchema, plan, deleteCache);
}
VariantProjectedParquetReader prunedReader = VariantProjectedParquetReader.open(inFile, projectedSchema,
task.residual(), task.start(), task.length(), true, plan);
@@ -386,8 +422,14 @@
*/
static CloseableIterable<Record> openPrunedDeleteAwareRead(FileIO io, InputFile inFile, FileScanTask task,
Schema tableSchema, Schema projectedSchema, VariantProjectionPlan plan) throws IOException {
+ return openPrunedDeleteAwareRead(io, inFile, task, tableSchema, projectedSchema, plan, null);
+ }
+
+ static CloseableIterable<Record> openPrunedDeleteAwareRead(FileIO io, InputFile inFile, FileScanTask task,
+ Schema tableSchema, Schema projectedSchema, VariantProjectionPlan plan, IcebergDeleteCache deleteCache)
+ throws IOException {
PositionlessGenericDeleteFilter deleteFilter =
- new PositionlessGenericDeleteFilter(io, task, tableSchema, projectedSchema);
+ new PositionlessGenericDeleteFilter(io, task, tableSchema, projectedSchema, deleteCache);
// Open first, load deletes second. Both the clip being a no-op and a missing row-index offset are decided at
// open time, and either sends this task to the standard delete path, which loads its own copy of every
@@ -424,6 +466,25 @@
}
}
+ /**
+ * Iceberg's delete filter, opening delete files with the length their manifest records and loading them through
+ * {@code deleteCache} when one is given.
+ */
+ static GenericDeleteFilter newDeleteFilter(FileIO io, FileScanTask task, Schema tableSchema, Schema requestedSchema,
+ IcebergDeleteCache deleteCache) {
+ return new GenericDeleteFilter(io, task, tableSchema, requestedSchema) {
+ @Override
+ protected InputFile loadInputFile(DeleteFile deleteFile) {
+ return io.newInputFile(deleteFile.location(), deleteFile.fileSizeInBytes());
+ }
+
+ @Override
+ protected DeleteLoader newDeleteLoader() {
+ return deleteCache != null ? deleteCache.newLoader(this::loadInputFile) : super.newDeleteLoader();
+ }
+ };
+ }
+
private long getSnapshotId(Map<String, String> configuration) {
String snapshotStr = configuration.get(IcebergConstants.ICEBERG_SNAPSHOT_ID_PROPERTY_KEY);
if (snapshotStr != null) {
@@ -431,18 +492,4 @@
}
throw new IllegalStateException("Snapshot must've been pinned during compilation phase");
}
-
- private Throwable closeResources(Throwable throwable) {
- if (tableFileIo != null) {
- throwable = CleanupUtils.closeSilently(tableFileIo, throwable);
- }
- if (catalog != null) {
- try {
- IcebergUtils.closeAndCleanup(catalog, catalogProperties);
- } catch (Exception ex) {
- throwable = ExceptionUtils.suppress(throwable, ex);
- }
- }
- return throwable;
- }
}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergParquetRecordReaderFactory.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergParquetRecordReaderFactory.java
index cedc5f0..7abb1e7 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergParquetRecordReaderFactory.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergParquetRecordReaderFactory.java
@@ -91,10 +91,15 @@
private final List<PartitionWorkLoadBasedOnSize> partitionWorkLoadsBasedOnSize = new ArrayList<>();
private Schema projectedSchema;
+ // Shipped to the readers so that they read the planned files without loading the table from the catalog again
+ private Schema schemaAtSnapshot;
+ private IcebergFileIoDescriptor fileIoDescriptor;
private Map<String, String> originalConfiguration;
private Map<String, String> catalogProperties;
private transient AlgebricksAbsolutePartitionConstraint partitionConstraint;
+ // Every reader of this scan on a node is created from this one deserialized factory, so they share it
+ private transient volatile IcebergDeleteCache deleteCache;
public IcebergParquetRecordReaderFactory() {
}
@@ -114,6 +119,20 @@
return partitionConstraint;
}
+ private IcebergDeleteCache deleteCache() {
+ IcebergDeleteCache cache = deleteCache;
+ if (cache == null) {
+ synchronized (this) {
+ cache = deleteCache;
+ if (cache == null) {
+ cache = new IcebergDeleteCache();
+ deleteCache = cache;
+ }
+ }
+ }
+ return cache;
+ }
+
private int getPartitionsCount() {
return getPartitionConstraint().getLocations().length;
}
@@ -123,8 +142,8 @@
try {
int partition = context.getPartition();
return new IcebergFileRecordReader(partitionWorkLoadsBasedOnSize.get(partition).getFileScanTasks(),
- projectedSchema, new HashMap<>(originalConfiguration),
- context.getTaskContext().getWarningCollector());
+ projectedSchema, schemaAtSnapshot, fileIoDescriptor, deleteCache(),
+ new HashMap<>(originalConfiguration), context.getTaskContext().getWarningCollector());
} catch (Exception e) {
throw HyracksDataException.create(e);
}
@@ -256,15 +275,12 @@
catalog = IcebergUtils.initializeCatalog(catalogProperties, namespace);
Namespace parsedNamespace = IcebergUtils.parseNamespace(namespace);
TableIdentifier tableIdentifier = TableIdentifier.of(parsedNamespace, tableName);
- if (!catalog.tableExists(tableIdentifier)) {
- throw CompilationException.create(ErrorCode.ICEBERG_TABLE_DOES_NOT_EXIST, tableName);
- }
-
- Table table = catalog.loadTable(tableIdentifier);
+ Table table = IcebergUtils.loadExistingTable(catalog, tableIdentifier, tableName);
TableScan scan = table.newScan();
scan = setAndPinScanSnapshot(originalConfiguration, table, scan);
long snapshotId = Long.parseLong(originalConfiguration.get(ICEBERG_SNAPSHOT_ID_PROPERTY_KEY));
- Schema schemaAtSnapshot = table.schemas().get(table.snapshot(snapshotId).schemaId());
+ schemaAtSnapshot = table.schemas().get(table.snapshot(snapshotId).schemaId());
+ fileIoDescriptor = IcebergFileIoDescriptor.capture(table.io());
projectedSchema = selectRequestedColumns(schemaAtSnapshot, configuration);
ensureTypesSupported(projectedSchema, appCtx.getExternalProperties().isIcebergVariantEnabled());
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/PositionlessGenericDeleteFilter.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/PositionlessGenericDeleteFilter.java
index bd764b6..c730617 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/PositionlessGenericDeleteFilter.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/iceberg/PositionlessGenericDeleteFilter.java
@@ -18,9 +18,11 @@
*/
package org.apache.asterix.external.input.record.reader.iceberg;
+import org.apache.iceberg.DeleteFile;
import org.apache.iceberg.FileScanTask;
import org.apache.iceberg.Schema;
import org.apache.iceberg.StructLike;
+import org.apache.iceberg.data.DeleteLoader;
import org.apache.iceberg.data.InternalRecordWrapper;
import org.apache.iceberg.data.Record;
import org.apache.iceberg.deletes.DeleteCounter;
@@ -51,11 +53,21 @@
private final FileIO io;
private final InternalRecordWrapper asStructLike;
+ private final IcebergDeleteCache deleteCache;
PositionlessGenericDeleteFilter(FileIO io, FileScanTask task, Schema tableSchema, Schema requestedSchema) {
+ this(io, task, tableSchema, requestedSchema, null);
+ }
+
+ /**
+ * @param deleteCache the scan's delete files already loaded on this node; {@code null} loads them afresh
+ */
+ PositionlessGenericDeleteFilter(FileIO io, FileScanTask task, Schema tableSchema, Schema requestedSchema,
+ IcebergDeleteCache deleteCache) {
super(task.file().location(), task.deletes(), tableSchema, requestedSchema, new DeleteCounter(), false);
this.io = io;
this.asStructLike = new InternalRecordWrapper(requiredSchema().asStruct());
+ this.deleteCache = deleteCache;
}
@Override
@@ -73,4 +85,14 @@
protected InputFile getInputFile(String location) {
return io.newInputFile(location);
}
+
+ @Override
+ protected InputFile loadInputFile(DeleteFile deleteFile) {
+ return io.newInputFile(deleteFile.location(), deleteFile.fileSizeInBytes());
+ }
+
+ @Override
+ protected DeleteLoader newDeleteLoader() {
+ return deleteCache != null ? deleteCache.newLoader(this::loadInputFile) : super.newDeleteLoader();
+ }
}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergSnapshotUtils.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergSnapshotUtils.java
index b2a2cdf..f801527 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergSnapshotUtils.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergSnapshotUtils.java
@@ -125,16 +125,32 @@
String tableName = catalogAndCollectionProperties.get(IcebergConstants.ICEBERG_TABLE_NAME_PROPERTY_KEY);
Map<String, String> catalogProperties =
IcebergUtils.filterCatalogProperties(catalogAndCollectionProperties);
- Catalog icebergCatalog = IcebergUtils.initializeCatalog(catalogProperties, namespace, true);
+ Catalog icebergCatalog = null;
+ Throwable throwable = null;
+ try {
+ icebergCatalog = IcebergUtils.initializeCatalog(catalogProperties, namespace, true);
- Namespace parsedNamespace = IcebergUtils.parseNamespace(namespace);
- TableIdentifier tableIdentifier = TableIdentifier.of(parsedNamespace, tableName);
- Table table = icebergCatalog.loadTable(tableIdentifier);
+ Namespace parsedNamespace = IcebergUtils.parseNamespace(namespace);
+ TableIdentifier tableIdentifier = TableIdentifier.of(parsedNamespace, tableName);
+ Table table = icebergCatalog.loadTable(tableIdentifier);
- Optional<Long> snapshotIdOptional = getSnapshotId(catalogAndCollectionProperties, table);
- if (snapshotIdOptional.isPresent() && !snapshotIdExists(table, snapshotIdOptional.get())) {
- throw CompilationException.create(ErrorCode.ICEBERG_SNAPSHOT_ID_NOT_FOUND, snapshotIdOptional.get(),
- tableIdentifier.toString());
+ Optional<Long> snapshotIdOptional = getSnapshotId(catalogAndCollectionProperties, table);
+ if (snapshotIdOptional.isPresent() && !snapshotIdExists(table, snapshotIdOptional.get())) {
+ throw CompilationException.create(ErrorCode.ICEBERG_SNAPSHOT_ID_NOT_FOUND, snapshotIdOptional.get(),
+ tableIdentifier.toString());
+ }
+ } catch (Throwable th) {
+ throwable = th;
+ throw th;
+ } finally {
+ try {
+ IcebergUtils.closeAndCleanup(icebergCatalog, catalogProperties);
+ } catch (CompilationException ex) {
+ if (throwable == null) {
+ throw ex;
+ }
+ throwable.addSuppressed(ex);
+ }
}
}
}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergUtils.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergUtils.java
index 40e0c51..4a01378 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergUtils.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/iceberg/IcebergUtils.java
@@ -66,6 +66,7 @@
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.SupportsNamespaces;
import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.NoSuchTableException;
import org.apache.iceberg.gcp.gcs.GCSFileIO;
import org.apache.iceberg.nessie.NessieCatalog;
import org.apache.iceberg.rest.RESTCatalog;
@@ -403,7 +404,7 @@
IcebergCatalogSource catalogSource = validateAndGetCatalogSource(source);
// remove null values to avoid failures in internal checks
- Catalog catalog;
+ Catalog catalog = null;
catalogProperties.values().removeIf(Objects::isNull);
try {
@@ -418,13 +419,26 @@
validateNamespacePresence((SupportsNamespaces) catalog, namespace);
}
} catch (CompilationException ex) {
- throw ex;
+ throw closeOnFailure(catalog, catalogProperties, ex);
} catch (Throwable ex) {
- throw CompilationException.create(ErrorCode.EXTERNAL_SOURCE_ERROR, ex, ex.getMessage());
+ throw closeOnFailure(catalog, catalogProperties,
+ CompilationException.create(ErrorCode.EXTERNAL_SOURCE_ERROR, ex, ex.getMessage()));
}
return catalog;
}
+ // The caller never receives a catalog that failed here, so it cannot close it: initCatalog has already registered
+ // the catalog's clients, and nothing else would release them.
+ private static CompilationException closeOnFailure(Catalog catalog, Map<String, String> catalogProperties,
+ CompilationException failure) {
+ try {
+ closeAndCleanup(catalog, catalogProperties);
+ } catch (Exception ex) {
+ failure.addSuppressed(ex);
+ }
+ return failure;
+ }
+
private static Catalog createAndSetCatalogProperties(Map<String, String> properties, IcebergCatalogSource source)
throws CompilationException {
Catalog catalog;
@@ -654,6 +668,21 @@
};
}
+ /**
+ * Loads the table, reporting one the catalog does not have as {@link ErrorCode#ICEBERG_TABLE_DOES_NOT_EXIST}.
+ * <p>
+ * Asking {@code tableExists} first is not a cheaper probe: for the metastore catalogs it is a full load itself, so
+ * the table would be fetched and its metadata file read twice.
+ */
+ public static Table loadExistingTable(Catalog catalog, TableIdentifier tableIdentifier, String tableName)
+ throws CompilationException {
+ try {
+ return catalog.loadTable(tableIdentifier);
+ } catch (NoSuchTableException e) {
+ throw CompilationException.create(ErrorCode.ICEBERG_TABLE_DOES_NOT_EXIST, e, tableName);
+ }
+ }
+
public static Table loadTable(Catalog catalog, TableIdentifier tableIdentifier, CatalogConfig.IcebergCatalogSource source) {
return switch (source) {
case AWS_GLUE -> {
diff --git a/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergDeleteCacheTest.java b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergDeleteCacheTest.java
new file mode 100644
index 0000000..9e4739e
--- /dev/null
+++ b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergDeleteCacheTest.java
@@ -0,0 +1,335 @@
+/*
+ * 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.asterix.external.input.record.reader.iceberg;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.data.GenericRecord;
+import org.apache.iceberg.data.Record;
+import org.apache.iceberg.data.parquet.GenericParquetWriter;
+import org.apache.iceberg.deletes.EqualityDeleteWriter;
+import org.apache.iceberg.hadoop.HadoopTables;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.parquet.Parquet;
+import org.apache.iceberg.types.Types;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * An equality delete applies to every data file written before it in its partition. These tests pin down that a scan's
+ * readers load such a delete file once, shared through {@link IcebergDeleteCache}, that they open it with the length
+ * its manifest records, and that the rows it deletes stay deleted.
+ */
+public class IcebergDeleteCacheTest {
+
+ private static final Schema SCHEMA = new Schema(Types.NestedField.required(1, "id", Types.IntegerType.get()),
+ Types.NestedField.required(2, "bucket", Types.IntegerType.get()));
+ private static final int DATA_FILES = 3;
+ private static final int ROWS_PER_FILE = 10;
+ private static final Set<Integer> DELETED_BUCKETS = Set.of(1, 2);
+
+ private File warehouse;
+ private Table table;
+ private DeleteFile deleteFile;
+ private List<FileScanTask> tasks;
+ private CountingFileIO io;
+
+ @Before
+ public void createTable() throws Exception {
+ warehouse = Files.createTempDirectory("iceberg-delete-cache").toFile();
+ HadoopTables tables = new HadoopTables(new org.apache.hadoop.conf.Configuration());
+ table = tables.create(SCHEMA, PartitionSpec.unpartitioned(), Map.of(TableProperties.FORMAT_VERSION, "2"),
+ warehouse.toString());
+ for (int f = 0; f < DATA_FILES; f++) {
+ table.newAppend().appendFile(writeDataFile(f)).commit();
+ }
+ deleteFile = writeEqualityDelete();
+ table.newRowDelta().addDeletes(deleteFile).commit();
+ tasks = new ArrayList<>();
+ try (CloseableIterable<FileScanTask> planned = table.newScan().planFiles()) {
+ planned.forEach(tasks::add);
+ }
+ Assert.assertEquals(DATA_FILES, tasks.size());
+ for (FileScanTask task : tasks) {
+ Assert.assertEquals("the equality delete must apply to every data file", 1, task.deletes().size());
+ }
+ io = new CountingFileIO(table.io());
+ }
+
+ @After
+ public void deleteWarehouse() throws Exception {
+ org.apache.commons.io.FileUtils.deleteDirectory(warehouse);
+ }
+
+ @Test
+ public void withoutCacheEveryDataFileReloadsTheDeleteFile() throws Exception {
+ Assert.assertEquals(expectedIds(), readAll(null));
+ Assert.assertEquals(DATA_FILES, io.opens(deleteFile.location()));
+ }
+
+ @Test
+ public void withCacheTheDeleteFileIsLoadedOnce() throws Exception {
+ IcebergDeleteCache cache = new IcebergDeleteCache();
+ Assert.assertEquals(expectedIds(), readAll(cache));
+ Assert.assertEquals("one load must serve every data file", 1, io.opens(deleteFile.location()));
+ Assert.assertEquals(0, io.opensWithoutLength(deleteFile.location()));
+ }
+
+ /** Partitions on a node read concurrently through one cache; they must not load the file once each. */
+ @Test
+ public void concurrentReadersShareOneLoad() throws Exception {
+ IcebergDeleteCache cache = new IcebergDeleteCache();
+ int readers = 8;
+ ExecutorService pool = Executors.newFixedThreadPool(readers);
+ try {
+ List<Future<Set<Integer>>> results = new ArrayList<>();
+ for (int r = 0; r < readers; r++) {
+ results.add(pool.submit(() -> readAll(cache)));
+ }
+ for (Future<Set<Integer>> result : results) {
+ Assert.assertEquals(expectedIds(), result.get());
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+ Assert.assertEquals(1, io.opens(deleteFile.location()));
+ }
+
+ /** A load that fails must not be remembered: the reader sees the failure, and the next reader loads again. */
+ @Test
+ public void failedLoadIsNotKeptAndTheNextReaderRetriesIt() throws Exception {
+ IcebergDeleteCache cache = new IcebergDeleteCache();
+ io.failNextOpens(deleteFile.location(), 1);
+ try {
+ readAll(cache);
+ Assert.fail("the failed delete load must surface, not be swallowed");
+ } catch (RuntimeException expected) {
+ // the injected failure
+ }
+ Assert.assertEquals("a failed load must not stay in the cache", 0, cache.size());
+ Assert.assertEquals(expectedIds(), readAll(cache));
+ Assert.assertEquals("one failed attempt, then one load that serves every data file", 2,
+ io.opens(deleteFile.location()));
+ }
+
+ /**
+ * Readers waiting on a load that fails share its failure; none of them may go on without the deletes and return
+ * rows that should have been deleted, and once the failure is gone the cache serves the right rows.
+ */
+ @Test
+ public void readersRacingOnAFailedLoadNeverReturnDeletedRows() throws Exception {
+ IcebergDeleteCache cache = new IcebergDeleteCache();
+ io.failNextOpens(deleteFile.location(), 1);
+ int readers = 8;
+ ExecutorService pool = Executors.newFixedThreadPool(readers);
+ int failures = 0;
+ try {
+ List<Future<Set<Integer>>> results = new ArrayList<>();
+ for (int r = 0; r < readers; r++) {
+ results.add(pool.submit(() -> readAll(cache)));
+ }
+ for (Future<Set<Integer>> result : results) {
+ try {
+ Assert.assertEquals("a reader that succeeds must return exactly the live rows", expectedIds(),
+ result.get());
+ } catch (java.util.concurrent.ExecutionException e) {
+ failures++;
+ }
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+ Assert.assertTrue("the injected failure must reach at least one reader", failures >= 1);
+ Assert.assertEquals(expectedIds(), readAll(cache));
+ }
+
+ private Set<Integer> readAll(IcebergDeleteCache cache) throws Exception {
+ Set<Integer> ids = new TreeSet<>();
+ for (FileScanTask task : tasks) {
+ InputFile inFile = io.newInputFile(task.file().location(), task.file().fileSizeInBytes());
+ try (CloseableIterable<Record> rows =
+ IcebergFileRecordReader.openStandardRead(io, inFile, task, SCHEMA, SCHEMA, cache)) {
+ for (Record row : rows) {
+ ids.add((Integer) row.getField("id"));
+ }
+ }
+ }
+ return ids;
+ }
+
+ private static Set<Integer> expectedIds() {
+ Set<Integer> ids = new TreeSet<>();
+ for (int id = 0; id < DATA_FILES * ROWS_PER_FILE; id++) {
+ if (!DELETED_BUCKETS.contains(bucket(id))) {
+ ids.add(id);
+ }
+ }
+ return ids;
+ }
+
+ private static int bucket(int id) {
+ return id % 5;
+ }
+
+ private DataFile writeDataFile(int fileIndex) throws Exception {
+ File file = new File(warehouse, "data/part-" + fileIndex + ".parquet");
+ Assert.assertTrue(file.getParentFile().mkdirs() || file.getParentFile().exists());
+ FileAppender<Record> appender = Parquet.write(org.apache.iceberg.Files.localOutput(file)).schema(SCHEMA)
+ .createWriterFunc(GenericParquetWriter::create).build();
+ GenericRecord template = GenericRecord.create(SCHEMA);
+ try (FileAppender<Record> writer = appender) {
+ for (int i = 0; i < ROWS_PER_FILE; i++) {
+ int id = fileIndex * ROWS_PER_FILE + i;
+ Record record = template.copy();
+ record.setField("id", id);
+ record.setField("bucket", bucket(id));
+ writer.add(record);
+ }
+ }
+ return DataFiles.builder(PartitionSpec.unpartitioned()).withInputFile(org.apache.iceberg.Files.localInput(file))
+ .withMetrics(appender.metrics()).withFormat(FileFormat.PARQUET).build();
+ }
+
+ private DeleteFile writeEqualityDelete() throws Exception {
+ Schema deleteSchema = SCHEMA.select("bucket");
+ File file = new File(warehouse, "data/eq-delete.parquet");
+ EqualityDeleteWriter<Record> writer = Parquet.writeDeletes(org.apache.iceberg.Files.localOutput(file))
+ .forTable(table).rowSchema(deleteSchema).createWriterFunc(GenericParquetWriter::create)
+ .equalityFieldIds(Collections.singletonList(SCHEMA.findField("bucket").fieldId())).overwrite()
+ .buildEqualityWriter();
+ GenericRecord template = GenericRecord.create(deleteSchema);
+ try (EqualityDeleteWriter<Record> open = writer) {
+ for (int bucket : DELETED_BUCKETS) {
+ Record row = template.copy();
+ row.setField("bucket", bucket);
+ open.write(row);
+ }
+ }
+ return writer.toDeleteFile();
+ }
+
+ /** Counts the files opened for reading, and whether they were opened without their length. */
+ private static final class CountingFileIO implements FileIO {
+ private final FileIO delegate;
+ private final Map<String, AtomicInteger> opens = new ConcurrentHashMap<>();
+ private final Map<String, AtomicInteger> opensWithoutLength = new ConcurrentHashMap<>();
+ private final Map<String, AtomicInteger> failuresLeft = new ConcurrentHashMap<>();
+
+ CountingFileIO(FileIO delegate) {
+ this.delegate = delegate;
+ }
+
+ /** The next {@code count} opens of {@code location} yield a file whose stream cannot be opened. */
+ void failNextOpens(String location, int count) {
+ failuresLeft.put(location, new AtomicInteger(count));
+ }
+
+ private InputFile maybeFailing(String path, InputFile file) {
+ AtomicInteger left = failuresLeft.get(path);
+ if (left == null || left.getAndUpdate(n -> Math.max(0, n - 1)) <= 0) {
+ return file;
+ }
+ return new InputFile() {
+ @Override
+ public long getLength() {
+ return file.getLength();
+ }
+
+ @Override
+ public org.apache.iceberg.io.SeekableInputStream newStream() {
+ throw new org.apache.iceberg.exceptions.RuntimeIOException("injected failure opening %s", path);
+ }
+
+ @Override
+ public String location() {
+ return file.location();
+ }
+
+ @Override
+ public boolean exists() {
+ return file.exists();
+ }
+ };
+ }
+
+ int opens(String location) {
+ return opens.getOrDefault(location, new AtomicInteger()).get();
+ }
+
+ int opensWithoutLength(String location) {
+ return opensWithoutLength.getOrDefault(location, new AtomicInteger()).get();
+ }
+
+ @Override
+ public InputFile newInputFile(String path) {
+ opens.computeIfAbsent(path, p -> new AtomicInteger()).incrementAndGet();
+ opensWithoutLength.computeIfAbsent(path, p -> new AtomicInteger()).incrementAndGet();
+ return maybeFailing(path, delegate.newInputFile(path));
+ }
+
+ @Override
+ public InputFile newInputFile(String path, long length) {
+ opens.computeIfAbsent(path, p -> new AtomicInteger()).incrementAndGet();
+ return maybeFailing(path, delegate.newInputFile(path, length));
+ }
+
+ @Override
+ public OutputFile newOutputFile(String path) {
+ return delegate.newOutputFile(path);
+ }
+
+ @Override
+ public void deleteFile(String path) {
+ delegate.deleteFile(path);
+ }
+
+ @Override
+ public Map<String, String> properties() {
+ return new HashMap<>(delegate.properties());
+ }
+ }
+}
diff --git a/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileRecordReaderLifecycleTest.java b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileRecordReaderLifecycleTest.java
new file mode 100644
index 0000000..cf14e0d
--- /dev/null
+++ b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergFileRecordReaderLifecycleTest.java
@@ -0,0 +1,268 @@
+/*
+ * 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.asterix.external.input.record.reader.iceberg;
+
+import static org.apache.asterix.external.util.iceberg.IcebergConstants.ICEBERG_CATALOG_PROPERTY_PREFIX_INTERNAL;
+
+import java.lang.reflect.Field;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.asterix.common.exceptions.CompilationException;
+import org.apache.asterix.common.exceptions.ErrorCode;
+import org.apache.asterix.external.awsclient.EnsureCloseAWSClientFactory;
+import org.apache.asterix.external.util.ExternalDataConstants;
+import org.apache.asterix.external.util.aws.AwsConstants;
+import org.apache.asterix.external.util.aws.EnsureCloseClientsFactoryRegistry;
+import org.apache.asterix.external.util.iceberg.IcebergConstants;
+import org.apache.iceberg.CatalogUtil;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.aws.AwsProperties;
+import org.apache.iceberg.aws.s3.S3FileIO;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.types.Types;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import com.sun.net.httpserver.HttpServer;
+
+/**
+ * The reader is constructed inside {@code GenericAdapterFactory.createAdapter}, which is synchronized and shared by
+ * every partition on a node, so it must not reach the catalog until it is read from. These tests pin that down, and
+ * that a table load failing on the read path still releases the catalog's clients — whether it fails inside
+ * catalog initialization, which never hands the catalog back, or after it, when only the reader holds it.
+ * <p>
+ * The catalog is a Glue catalog pointed at a local stand-in for the Glue endpoint that counts requests. It answers
+ * {@code GetDatabase} as {@link #databaseExists} says, and reports every table as missing.
+ */
+public class IcebergFileRecordReaderLifecycleTest {
+
+ private HttpServer glue;
+ private final AtomicInteger glueRequests = new AtomicInteger();
+ private final AtomicInteger storageRequests = new AtomicInteger();
+ private final AtomicInteger storageHeadRequests = new AtomicInteger();
+ private volatile boolean databaseExists;
+
+ @Before
+ public void startGlue() throws Exception {
+ glue = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ glue.createContext("/", exchange -> {
+ String target = exchange.getRequestHeaders().getFirst("X-Amz-Target");
+ (target != null ? glueRequests : storageRequests).incrementAndGet();
+ if (target == null && "HEAD".equals(exchange.getRequestMethod())) {
+ storageHeadRequests.incrementAndGet();
+ }
+ boolean found = "AWSGlue.GetDatabase".equals(target) && databaseExists;
+ byte[] body = (found ? "{\"Database\":{\"Name\":\"ns\"}}"
+ : "{\"__type\":\"EntityNotFoundException\",\"Message\":\"not found\"}")
+ .getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("Content-Type", "application/x-amz-json-1.1");
+ if (!found) {
+ exchange.getResponseHeaders().add("x-amzn-ErrorType", "EntityNotFoundException");
+ }
+ exchange.sendResponseHeaders(found ? 200 : 400, body.length);
+ exchange.getResponseBody().write(body);
+ exchange.close();
+ });
+ glue.start();
+ }
+
+ @After
+ public void stopGlue() {
+ glue.stop(0);
+ }
+
+ @Test
+ public void constructorDoesNotContactCatalog() throws Exception {
+ IcebergFileRecordReader reader = newReader();
+ try {
+ Assert.assertEquals("constructing the reader must not reach the catalog", 0, glueRequests.get());
+ } finally {
+ reader.close();
+ }
+ }
+
+ @Test
+ public void missingNamespaceReleasesClientsBeforeReaderIsClosed() throws Exception {
+ databaseExists = false;
+ int registeredBefore = registeredFactoryCount();
+ IcebergFileRecordReader reader = newReader();
+
+ assertHasNextFails(reader, ErrorCode.ICEBERG_NAMESPACE_DOES_NOT_EXIST);
+ Assert.assertEquals(
+ "a catalog that failed to initialize is never handed back, so it must release its own" + " clients",
+ registeredBefore, registeredFactoryCount());
+ reader.close();
+ }
+
+ @Test
+ public void missingTableReleasesClientsWhenReaderIsClosed() throws Exception {
+ databaseExists = true;
+ int registeredBefore = registeredFactoryCount();
+ IcebergFileRecordReader reader = newReader();
+
+ assertHasNextFails(reader, ErrorCode.ICEBERG_TABLE_DOES_NOT_EXIST);
+ Assert.assertEquals("the catalog is still open after the failed load", registeredBefore + 1,
+ registeredFactoryCount());
+
+ reader.close();
+ Assert.assertEquals("closing the reader must release the clients of a catalog whose table load failed",
+ registeredBefore, registeredFactoryCount());
+ }
+
+ @Test
+ public void shippedFileIoReadsWithoutCatalogAndCloseReleasesItsClients() throws Exception {
+ IcebergFileIoDescriptor descriptor = shippedFileIo();
+ int registeredBefore = registeredFactoryCount();
+ IcebergFileRecordReader reader = readerOverShippedFileIo(descriptor);
+
+ attemptRead(reader);
+ Assert.assertEquals("a reader given the table's FileIO must not contact the catalog", 0, glueRequests.get());
+ Assert.assertTrue("the reader must have read through the shipped FileIO", storageRequests.get() > 0);
+ Assert.assertEquals("the data file's length is in the manifest, so the reader must not ask storage for it", 0,
+ storageHeadRequests.get());
+ Assert.assertEquals("the reader's own FileIO holds its clients until the reader is closed",
+ registeredBefore + 1, registeredFactoryCount());
+
+ reader.close();
+ Assert.assertEquals("closing the reader must release the clients of the FileIO it opened", registeredBefore,
+ registeredFactoryCount());
+ }
+
+ /**
+ * Every partition on a node reads from one deserialized factory, so its readers open FileIOs from the same
+ * descriptor. Were those FileIOs to share a registry id, the first reader to close would shut down the clients of
+ * the others while they are still reading.
+ */
+ @Test
+ public void readersOverOneDescriptorReleaseOnlyTheirOwnClients() throws Exception {
+ IcebergFileIoDescriptor descriptor = shippedFileIo();
+ int registeredBefore = registeredFactoryCount();
+ IcebergFileRecordReader first = readerOverShippedFileIo(descriptor);
+ IcebergFileRecordReader second = readerOverShippedFileIo(descriptor);
+
+ attemptRead(first);
+ attemptRead(second);
+ Assert.assertEquals("each reader must register its FileIO's clients under an id of its own",
+ registeredBefore + 2, registeredFactoryCount());
+
+ first.close();
+ Assert.assertEquals("closing one reader must leave the other reader's clients alone", registeredBefore + 1,
+ registeredFactoryCount());
+ second.close();
+ Assert.assertEquals(registeredBefore, registeredFactoryCount());
+ }
+
+ private IcebergFileIoDescriptor shippedFileIo() {
+ Map<String, String> ioProperties = new HashMap<>();
+ ioProperties.put(AwsProperties.CLIENT_FACTORY, EnsureCloseAWSClientFactory.class.getName());
+ ioProperties.put(EnsureCloseClientsFactoryRegistry.FACTORY_INSTANCE_ID_KEY, "compile-time-id");
+ putCollectionProperty(ioProperties, AwsConstants.REGION_FIELD_NAME, "us-east-1");
+ putCollectionProperty(ioProperties, AwsConstants.SERVICE_END_POINT_FIELD_NAME, endpoint());
+ putCollectionProperty(ioProperties, AwsConstants.ACCESS_KEY_ID_FIELD_NAME, "test-access-key");
+ putCollectionProperty(ioProperties, AwsConstants.SECRET_ACCESS_KEY_FIELD_NAME, "test-secret-key");
+ return IcebergFileIoDescriptor.capture(CatalogUtil.loadFileIO(S3FileIO.class.getName(), ioProperties, null));
+ }
+
+ private IcebergFileRecordReader readerOverShippedFileIo(IcebergFileIoDescriptor descriptor) throws Exception {
+ DataFile dataFile = Mockito.mock(DataFile.class);
+ Mockito.when(dataFile.location()).thenReturn("s3://test_bucket/data/f.parquet");
+ Mockito.when(dataFile.fileSizeInBytes()).thenReturn(1024L);
+ FileScanTask task = Mockito.mock(FileScanTask.class);
+ Mockito.when(task.file()).thenReturn(dataFile);
+ Mockito.when(task.deletes()).thenReturn(List.of());
+ Mockito.when(task.residual()).thenReturn(Expressions.alwaysTrue());
+ Mockito.when(task.length()).thenReturn(10L);
+ Schema schema = new Schema(Types.NestedField.required(1, "id", Types.LongType.get()));
+ return new IcebergFileRecordReader(List.of(task), schema, schema, descriptor, null, configuration(), null);
+ }
+
+ // the stand-in serves no data file, so the read fails; what is under test is what the attempt touched
+ private static void attemptRead(IcebergFileRecordReader reader) {
+ try {
+ reader.hasNext();
+ Assert.fail("the stand-in serves no data file, so the read must fail");
+ } catch (Exception expected) {
+ // expected
+ }
+ }
+
+ private void assertHasNextFails(IcebergFileRecordReader reader, ErrorCode expected) throws Exception {
+ try {
+ reader.hasNext();
+ Assert.fail("hasNext must fail with " + expected);
+ } catch (CompilationException e) {
+ Assert.assertEquals(expected.intValue(), e.getErrorCode());
+ }
+ Assert.assertTrue("the failed load must have reached the catalog", glueRequests.get() > 0);
+ }
+
+ private IcebergFileRecordReader newReader() throws Exception {
+ // any non-empty task list: a reader with nothing to read never loads the table at all
+ List<FileScanTask> tasks = List.of(Mockito.mock(FileScanTask.class));
+ Schema schema = new Schema(Types.NestedField.required(1, "id", Types.LongType.get()));
+ return new IcebergFileRecordReader(tasks, schema, null, null, null, configuration(), null);
+ }
+
+ private String endpoint() {
+ return "http://127.0.0.1:" + glue.getAddress().getPort();
+ }
+
+ private Map<String, String> configuration() {
+ String region = "us-east-1";
+ Map<String, String> configuration = new HashMap<>();
+ configuration.put(ExternalDataConstants.KEY_EXTERNAL_SOURCE_TYPE,
+ ExternalDataConstants.KEY_ADAPTER_NAME_AWS_S3);
+ configuration.put(IcebergConstants.ICEBERG_NAMESPACE_PROPERTY_KEY, "ns");
+ configuration.put(IcebergConstants.ICEBERG_TABLE_NAME_PROPERTY_KEY, "users");
+ configuration.put(IcebergConstants.ICEBERG_SNAPSHOT_ID_PROPERTY_KEY, "1");
+ configuration.put(AwsConstants.REGION_FIELD_NAME, region);
+ configuration.put(AwsConstants.ACCESS_KEY_ID_FIELD_NAME, "test-access-key");
+ configuration.put(AwsConstants.SECRET_ACCESS_KEY_FIELD_NAME, "test-secret-key");
+ putCatalogProperty(configuration, IcebergConstants.ICEBERG_SOURCE_PROPERTY_KEY, "AWS_GLUE");
+ putCatalogProperty(configuration, AwsConstants.REGION_FIELD_NAME, region);
+ putCatalogProperty(configuration, AwsConstants.SERVICE_END_POINT_FIELD_NAME, endpoint());
+ putCatalogProperty(configuration, AwsConstants.ACCESS_KEY_ID_FIELD_NAME, "test-access-key");
+ putCatalogProperty(configuration, AwsConstants.SECRET_ACCESS_KEY_FIELD_NAME, "test-secret-key");
+ return configuration;
+ }
+
+ private static void putCollectionProperty(Map<String, String> properties, String key, String value) {
+ properties.put(IcebergConstants.ICEBERG_COLLECTION_PROPERTY_PREFIX_INTERNAL + key, value);
+ }
+
+ private static void putCatalogProperty(Map<String, String> configuration, String key, String value) {
+ configuration.put(ICEBERG_CATALOG_PROPERTY_PREFIX_INTERNAL + key, value);
+ }
+
+ private static int registeredFactoryCount() throws Exception {
+ Field registry = EnsureCloseClientsFactoryRegistry.class.getDeclaredField("REGISTRY");
+ registry.setAccessible(true);
+ return ((Map<?, ?>) registry.get(null)).size();
+ }
+}
diff --git a/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergVariantReadRoutingTest.java b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergVariantReadRoutingTest.java
index c17d9b5..38f3477 100644
--- a/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergVariantReadRoutingTest.java
+++ b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/iceberg/IcebergVariantReadRoutingTest.java
@@ -251,7 +251,7 @@
public void projectionFallback_raisesOneConstantWarning() throws Exception {
WarningCollector warnings = new WarningCollector();
IcebergFileRecordReader reader =
- new IcebergFileRecordReader(List.of(), filterSchema(), new HashMap<>(), warnings);
+ new IcebergFileRecordReader(List.of(), filterSchema(), null, null, null, new HashMap<>(), warnings);
reader.warnProjectionNotPushed(new RuntimeException("first file blew up"));
reader.warnProjectionNotPushed(new IllegalStateException("a completely different failure"));
diff --git a/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/util/iceberg/IcebergSnapshotValidationCleanupTest.java b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/util/iceberg/IcebergSnapshotValidationCleanupTest.java
new file mode 100644
index 0000000..5bc6e02
--- /dev/null
+++ b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/util/iceberg/IcebergSnapshotValidationCleanupTest.java
@@ -0,0 +1,189 @@
+/*
+ * 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.asterix.external.util.iceberg;
+
+import static org.apache.asterix.external.util.iceberg.IcebergConstants.ICEBERG_CATALOG_PROPERTY_PREFIX_INTERNAL;
+
+import java.lang.reflect.Field;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.asterix.common.exceptions.CompilationException;
+import org.apache.asterix.common.exceptions.ErrorCode;
+import org.apache.asterix.external.util.ExternalDataConstants;
+import org.apache.asterix.external.util.aws.AwsConstants;
+import org.apache.asterix.external.util.aws.EnsureCloseClientsFactoryRegistry;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+
+/**
+ * {@link IcebergSnapshotUtils#validateSnapshotExists} builds its own catalog to look the snapshot up, and the catalog's
+ * AWS clients are held by the static {@link EnsureCloseClientsFactoryRegistry} until they are released, so every exit
+ * from it has to release them: a leaked entry is never collected and costs one set of clients per validated DDL.
+ * <p>
+ * A local server stands in for both Glue and S3. Glue requests are told apart by their {@code X-Amz-Target} header;
+ * anything else is an S3 GET for the table's metadata file. The bucket name is not a valid host name, which makes the
+ * S3 client address it path-style on the local endpoint.
+ */
+public class IcebergSnapshotValidationCleanupTest {
+
+ private static final String BUCKET = "test_bucket";
+ private static final String METADATA_KEY = "tbl/metadata/v1.metadata.json";
+ private static final long SNAPSHOT_ID = 42L;
+
+ private HttpServer server;
+ private volatile boolean tableExists = true;
+ private final AtomicInteger metadataReads = new AtomicInteger();
+
+ @Before
+ public void startServer() throws Exception {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext("/", this::handle);
+ server.start();
+ }
+
+ @After
+ public void stopServer() {
+ server.stop(0);
+ }
+
+ @Test
+ public void existingSnapshotReleasesClients() throws Exception {
+ int registeredBefore = registeredFactoryCount();
+ IcebergSnapshotUtils.validateSnapshotExists(properties(SNAPSHOT_ID));
+ Assert.assertTrue("the validation must have loaded the table's metadata", metadataReads.get() > 0);
+ Assert.assertEquals("a successful validation must release its catalog's clients", registeredBefore,
+ registeredFactoryCount());
+ }
+
+ @Test
+ public void missingSnapshotReleasesClients() throws Exception {
+ int registeredBefore = registeredFactoryCount();
+ try {
+ IcebergSnapshotUtils.validateSnapshotExists(properties(7L));
+ Assert.fail("a snapshot the table does not have must be rejected");
+ } catch (CompilationException e) {
+ Assert.assertEquals(ErrorCode.ICEBERG_SNAPSHOT_ID_NOT_FOUND.intValue(), e.getErrorCode());
+ }
+ Assert.assertEquals("a rejected snapshot must still release the catalog's clients", registeredBefore,
+ registeredFactoryCount());
+ }
+
+ @Test
+ public void missingTableReleasesClients() throws Exception {
+ tableExists = false;
+ int registeredBefore = registeredFactoryCount();
+ try {
+ IcebergSnapshotUtils.validateSnapshotExists(properties(SNAPSHOT_ID));
+ Assert.fail("a table the catalog does not have must be rejected");
+ } catch (Exception expected) {
+ // the failure itself is not what is under test here
+ }
+ Assert.assertEquals("a failed table load must still release the catalog's clients", registeredBefore,
+ registeredFactoryCount());
+ }
+
+ private Map<String, String> properties(long snapshotId) {
+ String region = "us-east-1";
+ String endpoint = "http://127.0.0.1:" + server.getAddress().getPort();
+ Map<String, String> properties = new HashMap<>();
+ properties.put(ExternalDataConstants.KEY_EXTERNAL_SOURCE_TYPE, ExternalDataConstants.KEY_ADAPTER_NAME_AWS_S3);
+ properties.put(IcebergConstants.ICEBERG_NAMESPACE_PROPERTY_KEY, "ns");
+ properties.put(IcebergConstants.ICEBERG_TABLE_NAME_PROPERTY_KEY, "tbl");
+ properties.put(IcebergConstants.ICEBERG_SNAPSHOT_ID_PROPERTY_KEY, Long.toString(snapshotId));
+ properties.put(AwsConstants.REGION_FIELD_NAME, region);
+ properties.put(AwsConstants.SERVICE_END_POINT_FIELD_NAME, endpoint);
+ properties.put(AwsConstants.ACCESS_KEY_ID_FIELD_NAME, "test-access-key");
+ properties.put(AwsConstants.SECRET_ACCESS_KEY_FIELD_NAME, "test-secret-key");
+ putCatalogProperty(properties, IcebergConstants.ICEBERG_SOURCE_PROPERTY_KEY, "AWS_GLUE");
+ putCatalogProperty(properties, AwsConstants.REGION_FIELD_NAME, region);
+ putCatalogProperty(properties, AwsConstants.SERVICE_END_POINT_FIELD_NAME, endpoint);
+ putCatalogProperty(properties, AwsConstants.ACCESS_KEY_ID_FIELD_NAME, "test-access-key");
+ putCatalogProperty(properties, AwsConstants.SECRET_ACCESS_KEY_FIELD_NAME, "test-secret-key");
+ return properties;
+ }
+
+ private void handle(HttpExchange exchange) throws java.io.IOException {
+ String target = exchange.getRequestHeaders().getFirst("X-Amz-Target");
+ if ("AWSGlue.GetDatabase".equals(target)) {
+ respond(exchange, 200, "{\"Database\":{\"Name\":\"ns\"}}", null);
+ } else if ("AWSGlue.GetTable".equals(target) && tableExists) {
+ respond(exchange, 200,
+ "{\"Table\":{\"Name\":\"tbl\",\"DatabaseName\":\"ns\",\"Parameters\":{"
+ + "\"table_type\":\"ICEBERG\",\"metadata_location\":\"s3://" + BUCKET + "/" + METADATA_KEY
+ + "\"}}}",
+ null);
+ } else if (target != null) {
+ respond(exchange, 400, "{\"__type\":\"EntityNotFoundException\",\"Message\":\"not found\"}",
+ "EntityNotFoundException");
+ } else if (exchange.getRequestURI().getPath().equals("/" + BUCKET + "/" + METADATA_KEY)) {
+ metadataReads.incrementAndGet();
+ respond(exchange, 200, metadataJson(), null);
+ } else {
+ respond(exchange, 404, "", null);
+ }
+ }
+
+ private static void respond(HttpExchange exchange, int status, String body, String errorType)
+ throws java.io.IOException {
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("Content-Type", "application/x-amz-json-1.1");
+ if (errorType != null) {
+ exchange.getResponseHeaders().add("x-amzn-ErrorType", errorType);
+ }
+ exchange.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length);
+ if (bytes.length > 0) {
+ exchange.getResponseBody().write(bytes);
+ }
+ exchange.close();
+ }
+
+ private static String metadataJson() {
+ String location = "s3://" + BUCKET + "/tbl";
+ return "{\"format-version\":2,\"table-uuid\":\"9c12d441-03fe-4693-9a96-a0705ddf69c1\",\"location\":\""
+ + location + "\",\"last-sequence-number\":1,\"last-updated-ms\":1700000000000,\"last-column-id\":1,"
+ + "\"current-schema-id\":0,\"schemas\":[{\"type\":\"struct\",\"schema-id\":0,\"fields\":[{\"id\":1,"
+ + "\"name\":\"id\",\"required\":true,\"type\":\"long\"}]}],\"default-spec-id\":0,"
+ + "\"partition-specs\":[{\"spec-id\":0,\"fields\":[]}],\"last-partition-id\":999,"
+ + "\"default-sort-order-id\":0,\"sort-orders\":[{\"order-id\":0,\"fields\":[]}],\"properties\":{},"
+ + "\"current-snapshot-id\":" + SNAPSHOT_ID + ",\"snapshots\":[{\"sequence-number\":1,"
+ + "\"snapshot-id\":" + SNAPSHOT_ID + ",\"timestamp-ms\":1700000000000,\"summary\":{\"operation\":"
+ + "\"append\"},\"manifest-list\":\"" + location + "/metadata/snap-42.avro\",\"schema-id\":0}],"
+ + "\"snapshot-log\":[{\"timestamp-ms\":1700000000000,\"snapshot-id\":" + SNAPSHOT_ID + "}],"
+ + "\"metadata-log\":[]}";
+ }
+
+ private static void putCatalogProperty(Map<String, String> properties, String key, String value) {
+ properties.put(ICEBERG_CATALOG_PROPERTY_PREFIX_INTERNAL + key, value);
+ }
+
+ private static int registeredFactoryCount() throws Exception {
+ Field registry = EnsureCloseClientsFactoryRegistry.class.getDeclaredField("REGISTRY");
+ registry.setAccessible(true);
+ return ((Map<?, ?>) registry.get(null)).size();
+ }
+}
--
To view, visit https://asterix-gerrit.ics.uci.edu/c/asterixdb/+/21945?usp=email
To unsubscribe, or for help writing mail filters, visit https://asterix-gerrit.ics.uci.edu/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: asterixdb
Gerrit-Branch: master
Gerrit-Change-Id: I5179221ef913ef8d5236a0c44c9e761f24e880d8
Gerrit-Change-Number: 21945
Gerrit-PatchSet: 1
Gerrit-Owner: Hussain Towaileb <hu...@gmail.com>