This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hudi.git


The following commit(s) were added to refs/heads/master by this push:
     new 07d3bb788ea0 test(trino): add local MOR read benchmarks (#20647)
07d3bb788ea0 is described below

commit 07d3bb788ea08b7509072cbc58d41223eb3160b5
Author: voonhous <[email protected]>
AuthorDate: Fri Nov 20 10:39:52 2026 +0000

    test(trino): add local MOR read benchmarks (#20647)
    
    MOR snapshot read work in the Trino connector had no way to be measured
    without a cluster and an object store. Adds two on-demand benchmarks to
    hudi-trino test scope:
    
    - HudiMergeBufferBenchmark pushes one file group's log records through
      the spillable merge map, with the memory budget, disk map type, spill
      compression, size estimator and serializer the Trino reader context
      uses, and reports estimate per record, spilled count, and put and
      remove cost.
    - HudiMorReadBenchmark runs _ro and _rt queries on a generated
      TPC-DS-shaped MOR table (table version 9, four log files per file
      group, MOR date_dim) behind a file system wrapper that injects
      object-store latency and counts GET/HEAD/LIST per file type, charging
      requests the way Trino's S3 file system sends them.
    
    Both assert their results against the generator's expected values. The
    classes are named *Benchmark, so surefire and CI never run them.
    hudi-trino/README.md gains a Benchmarks section with the run commands
    and the bench.* knobs.
    
    Closes #20626.
---
 hudi-trino/README.md                               |  35 ++
 .../hudi/benchmark/BenchmarkHudiQueryRunner.java   | 134 +++++
 .../hudi/benchmark/HudiMergeBufferBenchmark.java   | 228 ++++++++
 .../hudi/benchmark/HudiMorReadBenchmark.java       | 265 +++++++++
 .../LatencyInjectingFileSystemFactory.java         | 511 ++++++++++++++++++
 .../hudi/benchmark/TpcdsMorTablesInitializer.java  | 598 +++++++++++++++++++++
 6 files changed, 1771 insertions(+)

diff --git a/hudi-trino/README.md b/hudi-trino/README.md
index d9bd21680f9d..8ee8d9c347ec 100644
--- a/hudi-trino/README.md
+++ b/hudi-trino/README.md
@@ -56,6 +56,41 @@ CI follows the same two steps: 
`.github/workflows/hudi_trino_ci.yml` runs `boots
 
 The tests resolve dependency versions from Hudi's root pom, while the shipped 
plugin bundles Trino's. The nightly 
`.github/workflows/hudi_trino_dependency_drift.yml` compares the two classpaths 
with `scripts/trino/check_dependency_drift.py` and files or updates an issue 
when versions differ.
 
+## Benchmarks
+
+Local MOR read benchmarks live in test scope under 
`io.trino.plugin.hudi.benchmark`. They need no cluster and no S3, and are named 
`*Benchmark` so surefire and CI never pick them up. Each one asserts its 
results against the generator's expected values, so a fast but wrong change 
fails the run.
+
+```
+# merge buffer: one file group's log records through the spillable map, sized 
by HudiTrinoReaderContext
+mvn -Phudi-trino,hudi-trino-tests -pl hudi-trino test 
-Dtest=HudiMergeBufferBenchmark \
+    -Dsurefire.failIfNoSpecifiedTests=false
+
+# end to end: _ro vs _rt queries on a generated TPC-DS-shaped MOR table, 
storage behind injected S3 latency
+mvn -Phudi-trino,hudi-trino-tests -pl hudi-trino test 
-Dtest=HudiMorReadBenchmark \
+    -Dsurefire.failIfNoSpecifiedTests=false
+```
+
+Knobs (`-D` system properties):
+
+| Knob | Default | Meaning |
+|---|---|---|
+| `bench.partitions` | 48 | store_sales partitions |
+| `bench.rowsPerPartition` | 60000 | base rows per partition; keep base files 
above Trino's 3 MB `parquet.small-file-threshold` (40000 rows give about 2.9 
MB), or each is read whole |
+| `bench.updateFraction` | 0.10 | fraction of keys updated in each of the 
three update rounds |
+| `bench.deleteFraction` | 0.01 | fraction of keys deleted in the delete round 
|
+| `bench.rounds` | 3 | measured runs after one warmup |
+| `bench.workers` | 1 | extra Trino workers; the coordinator also runs splits |
+| `bench.s3.getMillis` / `headMillis` / `listMillis` | 20 / 15 / 40 | latency 
charged per storage GET / HEAD / LIST |
+| `bench.s3.latency.enabled` | 1 | 0 turns the injected latency off (CPU-bound 
run) |
+| `bench.nativeLogs` | false | true writes table version 10 native logs 
instead of version 9 Avro logs |
+| `bench.metadata` | true | false writes no metadata table and sets 
`hudi.metadata-enabled=false`, so partitions are listed from storage |
+| `bench.s3.samples` | false | true prints one example path per request and 
file type |
+| `bench.logRecords` | 300000 | log records in `HudiMergeBufferBenchmark` |
+
+`HudiMorReadBenchmark` prints one line per query with wall time, CPU, 
base-file input bytes and storage calls per file type, and appends the same to 
`target/hudi-mor-read-benchmark.jsonl` together with the run's start time and 
settings. Log file bytes are not part of the input bytes, so log reads show 
only in the storage calls.
+
+With the metadata table on (the default), planning reads it before the `dpp` 
scenario's date filter is ready, so at the default latencies the filter arrives 
close to the 1 s `hudi.dynamic-filtering.wait-timeout` (about 0.8 s for `_ro` 
and 1.0 s for `_rt`) and `dpp default` can differ from `dpp df_wait_10s` 
between runs. `-Dbench.metadata=false` brings it down to about 0.2 s and 0.4 s. 
To see the scans start before the filter arrives, raise the latencies, for 
example `-Dbench.s3.getMillis [...]
+
 ## End-to-end tests (docker)
 
 The testcontainers E2E suite (`hudi-integ-test`, classes `ITTestTrino*` under
diff --git 
a/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/BenchmarkHudiQueryRunner.java
 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/BenchmarkHudiQueryRunner.java
new file mode 100644
index 000000000000..ff26b06fdaf4
--- /dev/null
+++ 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/BenchmarkHudiQueryRunner.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed 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 io.trino.plugin.hudi.benchmark;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import io.trino.filesystem.Location;
+import io.trino.filesystem.TrinoFileSystemFactory;
+import io.trino.filesystem.local.LocalFileSystemFactory;
+import io.trino.metastore.Database;
+import io.trino.metastore.HiveMetastoreFactory;
+import io.trino.plugin.hive.metastore.file.FileHiveMetastoreConfig;
+import io.trino.plugin.hudi.HudiConnector;
+import io.trino.spi.Plugin;
+import io.trino.spi.connector.Connector;
+import io.trino.spi.connector.ConnectorContext;
+import io.trino.spi.connector.ConnectorFactory;
+import io.trino.spi.security.PrincipalType;
+import io.trino.testing.DistributedQueryRunner;
+
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.Optional;
+
+import static com.google.inject.multibindings.MapBinder.newMapBinder;
+import static io.airlift.configuration.ConfigBinder.configBinder;
+import static io.trino.plugin.hudi.HudiConnectorFactory.createConnector;
+import static io.trino.testing.TestingSession.testSessionBuilder;
+
+/**
+ * A local query runner for the MOR read benchmarks: the {@code hudi} catalog 
reads a local directory through
+ * {@link LatencyInjectingFileSystemFactory}, so every storage request can be 
charged an S3-like latency.
+ */
+final class BenchmarkHudiQueryRunner
+{
+    static final String CATALOG = "hudi";
+    static final String SCHEMA = "tpcds";
+
+    private BenchmarkHudiQueryRunner() {}
+
+    static DistributedQueryRunner create(
+            int workerCount,
+            LatencyInjectingFileSystemFactory.Latency latency,
+            LatencyInjectingFileSystemFactory.Counters counters,
+            TpcdsMorTablesInitializer tables)
+            throws Exception
+    {
+        DistributedQueryRunner queryRunner = 
DistributedQueryRunner.builder(testSessionBuilder()
+                        .setCatalog(CATALOG)
+                        .setSchema(SCHEMA)
+                        .build())
+                .setWorkerCount(workerCount)
+                .build();
+        try {
+            Path dataRoot = 
queryRunner.getCoordinator().getBaseDataDir().resolve("hudi_data");
+            dataRoot.toFile().mkdirs();
+            queryRunner.installPlugin(new BenchmarkHudiPlugin(dataRoot, 
latency, counters));
+            queryRunner.createCatalog(CATALOG, "hudi", ImmutableMap.<String, 
String>builder()
+                    .put("hudi.metadata-enabled", 
String.valueOf(TpcdsMorTablesInitializer.metadataEnabled()))
+                    .put("hudi.table-statistics-enabled", "false")
+                    .put("fs.cache.enabled", "false")
+                    .buildOrThrow());
+            ((HudiConnector) 
queryRunner.getCoordinator().getConnector(CATALOG)).getInjector()
+                    .getInstance(HiveMetastoreFactory.class)
+                    .createMetastore(Optional.empty())
+                    .createDatabase(Database.builder()
+                            .setDatabaseName(SCHEMA)
+                            .setOwnerName(Optional.of("public"))
+                            .setOwnerType(Optional.of(PrincipalType.ROLE))
+                            .build());
+            tables.initializeTables(queryRunner, Location.of("local:///"), 
SCHEMA);
+            return queryRunner;
+        }
+        catch (Throwable e) {
+            queryRunner.close();
+            throw e;
+        }
+    }
+
+    private static final class BenchmarkHudiPlugin
+            implements Plugin
+    {
+        private final Path dataRoot;
+        private final LatencyInjectingFileSystemFactory.Latency latency;
+        private final LatencyInjectingFileSystemFactory.Counters counters;
+
+        private BenchmarkHudiPlugin(Path dataRoot, 
LatencyInjectingFileSystemFactory.Latency latency, 
LatencyInjectingFileSystemFactory.Counters counters)
+        {
+            this.dataRoot = dataRoot;
+            this.latency = latency;
+            this.counters = counters;
+        }
+
+        @Override
+        public Iterable<ConnectorFactory> getConnectorFactories()
+        {
+            return ImmutableList.of(new ConnectorFactory()
+            {
+                @Override
+                public String getName()
+                {
+                    return "hudi";
+                }
+
+                @Override
+                public Connector create(String catalogName, Map<String, 
String> config, ConnectorContext context)
+                {
+                    Map<String, String> fullConfig = ImmutableMap.<String, 
String>builder()
+                            .putAll(config)
+                            .put("bootstrap.quiet", "true")
+                            .put("hive.metastore", "file")
+                            .buildOrThrow();
+                    TrinoFileSystemFactory local = new 
LocalFileSystemFactory(dataRoot);
+                    return createConnector(catalogName, fullConfig, context, 
Optional.of(binder -> {
+                        newMapBinder(binder, String.class, 
TrinoFileSystemFactory.class)
+                                .addBinding("local").toInstance(new 
LatencyInjectingFileSystemFactory(local, latency, counters));
+                        
configBinder(binder).bindConfigDefaults(FileHiveMetastoreConfig.class, 
metastoreConfig -> metastoreConfig.setCatalogDirectory("local:///managed/"));
+                    }));
+                }
+            });
+        }
+    }
+}
diff --git 
a/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/HudiMergeBufferBenchmark.java
 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/HudiMergeBufferBenchmark.java
new file mode 100644
index 000000000000..7f65ea4fcd35
--- /dev/null
+++ 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/HudiMergeBufferBenchmark.java
@@ -0,0 +1,228 @@
+/*
+ * Licensed 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 io.trino.plugin.hudi.benchmark;
+
+import io.trino.plugin.hudi.reader.HudiTrinoReaderContext;
+import io.trino.plugin.hudi.storage.TrinoStorageConfiguration;
+import org.apache.avro.Schema;
+import org.apache.avro.generic.GenericData;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.avro.generic.IndexedRecord;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hudi.common.config.TypedProperties;
+import org.apache.hudi.common.schema.HoodieSchema;
+import org.apache.hudi.common.schema.HoodieSchemaUtils;
+import org.apache.hudi.common.table.HoodieTableConfig;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.common.table.read.BufferedRecord;
+import org.apache.hudi.common.table.read.BufferedRecords;
+import org.apache.hudi.common.table.read.FileGroupReaderSchemaHandler;
+import org.apache.hudi.common.table.read.TableState;
+import org.apache.hudi.common.util.DefaultSizeEstimator;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.common.util.OrderingValues;
+import org.apache.hudi.common.util.SizeEstimator;
+import org.apache.hudi.common.util.collection.ExternalSpillableMap;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration;
+import org.junit.jupiter.api.Test;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Random;
+
+import static com.google.common.io.MoreFiles.deleteRecursively;
+import static com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE;
+import static 
io.trino.plugin.hudi.benchmark.TpcdsMorTablesInitializer.DECIMAL_7_2;
+import static 
io.trino.plugin.hudi.benchmark.TpcdsMorTablesInitializer.DECIMAL_CONVERSION;
+import static 
io.trino.plugin.hudi.benchmark.TpcdsMorTablesInitializer.MEASURES;
+import static 
org.apache.hudi.common.config.HoodieCommonConfig.DISK_MAP_BITCASK_COMPRESSION_ENABLED;
+import static 
org.apache.hudi.common.config.HoodieCommonConfig.SPILLABLE_DISK_MAP_TYPE;
+import static 
org.apache.hudi.common.config.HoodieMemoryConfig.MAX_MEMORY_FOR_MERGE;
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Micro benchmark for the MOR merge buffer of the Trino Hudi connector: one 
file group's log records go through
+ * the same {@link ExternalSpillableMap} that {@code 
FileGroupRecordBuffer#initializeRecordsMap} builds (same memory
+ * budget, disk map type and spill compression), with the size estimator and 
spill serializer taken from a real
+ * {@link HudiTrinoReaderContext}. Changing {@code 
HudiTrinoReaderContext#getRecordSizeEstimator} or
+ * {@code #getRecordSerializer} changes what this measures, with no query 
engine, cluster or S3 involved.
+ *
+ * <p>It measures map put and remove only: every key is unique, records are 
full store_sales width, and no merge
+ * step runs. Per round it reports the estimated bytes per record against the 
merge memory budget, how many entries
+ * spilled to disk, the cost of one {@code sizeEstimate} call, and the put and 
remove cost per record. Every removed
+ * record, spilled or not, must equal the record that was put, so a spill 
serializer that corrupts keys or values
+ * fails the run.
+ *
+ * <p>Run it on JDK 25 without {@code --add-opens}, which is how the Trino 
server runs (the module's surefire
+ * {@code argLine} already matches): the reflection walk of the generic 
estimator only throws there. The first
+ * output line prints the runtime, whether {@code java.base} is open to the 
test, and the estimator and serializer
+ * classes in use.
+ * <pre>
+ * mvn -Phudi-trino,hudi-trino-tests -pl hudi-trino test 
-Dtest=HudiMergeBufferBenchmark \
+ *     -Dsurefire.failIfNoSpecifiedTests=false -Dbench.logRecords=300000
+ * </pre>
+ * The default of 300k log records is about one store_sales file group of a 
1TB-scale TPC-DS MOR table (about 875k
+ * base rows with three 10% update rounds and a 1% delete round).
+ */
+final class HudiMergeBufferBenchmark
+{
+    private static final int LOG_RECORDS = 
Integer.getInteger("bench.logRecords", 300_000);
+    private static final int ROUNDS = Integer.getInteger("bench.rounds", 3);
+
+    @Test
+    void mergeBuffer()
+            throws Exception
+    {
+        Path tableDir = 
Files.createTempDirectory("hudi-trino-merge-buffer-bench");
+        try {
+            Path tablePath = tableDir.resolve("store_sales");
+            TpcdsMorTablesInitializer.initTable(tablePath, "store_sales", 
"ss_item_sk,ss_ticket_number", "ss_sold_date_sk");
+            HoodieTableConfig tableConfig = HoodieTableMetaClient.builder()
+                    .setConf(new HadoopStorageConfiguration(new 
Configuration()))
+                    .setBasePath(tablePath.toUri().toString())
+                    .build()
+                    .getTableConfig();
+            TypedProperties props = new TypedProperties();
+            TypedProperties.putAll(props, tableConfig.getProps());
+
+            HoodieSchema schema = 
HoodieSchemaUtils.addMetadataFields(HoodieSchema.fromAvroSchema(TpcdsMorTablesInitializer.storeSalesSchema()));
+            Schema avroSchema = schema.toAvroSchema();
+            HudiTrinoReaderContext readerContext = readerContext(tableConfig, 
props, schema, tablePath);
+            List<BufferedRecord<IndexedRecord>> records = 
logRecords(readerContext, schema, avroSchema);
+
+            SizeEstimator<BufferedRecord<IndexedRecord>> estimator = 
readerContext.getRecordSizeEstimator();
+            System.out.printf(Locale.ROOT, "runtime=%s java.base opened to 
unnamed=%s estimator=%s serializer=%s logRecords=%s%n",
+                    Runtime.version(), 
Object.class.getModule().isOpen("java.lang", 
HudiMergeBufferBenchmark.class.getModule()),
+                    estimator.getClass().getName(), 
readerContext.getRecordSerializer().getClass().getName(), records.size());
+
+            for (int round = 0; round <= ROUNDS; round++) {
+                runRound(round == 0 ? "warmup" : "round" + round, 
readerContext, props, records, tableDir.resolve("spill-" + round));
+            }
+        }
+        finally {
+            deleteRecursively(tableDir, ALLOW_INSECURE);
+        }
+    }
+
+    private static void runRound(String label, HudiTrinoReaderContext 
readerContext, TypedProperties props, List<BufferedRecord<IndexedRecord>> 
records, Path spillDir)
+            throws Exception
+    {
+        Files.createDirectories(spillDir);
+        SizeEstimator<BufferedRecord<IndexedRecord>> estimator = 
readerContext.getRecordSizeEstimator();
+
+        long estimateStart = System.nanoTime();
+        long estimate = estimator.sizeEstimate(records.getFirst());
+        double estimateMicros = (System.nanoTime() - estimateStart) / 1e3;
+
+        // Same keys and defaults as FileGroupRecordBuffer#initializeRecordsMap
+        long maxMemory = props.getLong(MAX_MEMORY_FOR_MERGE.key(), 
MAX_MEMORY_FOR_MERGE.defaultValue());
+        ExternalSpillableMap.DiskMapType diskMapType = 
ExternalSpillableMap.DiskMapType.valueOf(props.getString(SPILLABLE_DISK_MAP_TYPE.key(),
+                
SPILLABLE_DISK_MAP_TYPE.defaultValue().name()).toUpperCase(Locale.ROOT));
+        boolean compression = 
props.getBoolean(DISK_MAP_BITCASK_COMPRESSION_ENABLED.key(), 
DISK_MAP_BITCASK_COMPRESSION_ENABLED.defaultValue());
+        try (ExternalSpillableMap<Serializable, BufferedRecord<IndexedRecord>> 
map = new ExternalSpillableMap<>(
+                maxMemory,
+                spillDir.toString(),
+                new DefaultSizeEstimator<>(),
+                readerContext.getRecordSizeEstimator(),
+                diskMapType,
+                readerContext.getRecordSerializer(),
+                compression,
+                "HudiMergeBufferBenchmark")) {
+            long putStart = System.nanoTime();
+            for (BufferedRecord<IndexedRecord> record : records) {
+                map.put(record.getRecordKey(), record);
+            }
+            double putNanosPerRecord = (System.nanoTime() - putStart) / 
(double) records.size();
+            int spilled = map.getDiskBasedMapNumEntries();
+            assertThat(map.size()).isEqualTo(records.size());
+
+            List<BufferedRecord<IndexedRecord>> removed = new 
ArrayList<>(records.size());
+            long removeStart = System.nanoTime();
+            for (BufferedRecord<IndexedRecord> record : records) {
+                removed.add(map.remove(record.getRecordKey()));
+            }
+            double removeNanosPerRecord = (System.nanoTime() - removeStart) / 
(double) records.size();
+            assertThat(map.size()).isZero();
+
+            // Outside the timed section. Spilled entries come back through 
the spill serializer, so this compares
+            // the deserialized key and every payload field against the record 
that was put.
+            for (int i = 0; i < records.size(); i++) {
+                BufferedRecord<IndexedRecord> expected = records.get(i);
+                BufferedRecord<IndexedRecord> actual = removed.get(i);
+                assertThat(actual).as("removed record for key %s", 
expected.getRecordKey()).isNotNull();
+                
assertThat(actual.getRecordKey()).isEqualTo(expected.getRecordKey());
+                assertThat(actual.getRecord()).as("payload of key %s", 
expected.getRecordKey()).isEqualTo(expected.getRecord());
+                assertThat(actual).isEqualTo(expected);
+            }
+
+            System.out.printf(Locale.ROOT,
+                    "%-7s estimate=%,d B/record (budget %,d B fits %,d 
records) sizeEstimate=%.0fus put=%.0fns/record spilled=%,d/%,d 
remove=%.0fns/record%n",
+                    label, estimate, maxMemory, estimate == 0 ? 0 : (long) 
(maxMemory * 0.8 / estimate), estimateMicros,
+                    putNanosPerRecord, spilled, records.size(), 
removeNanosPerRecord);
+        }
+    }
+
+    private static HudiTrinoReaderContext readerContext(HoodieTableConfig 
tableConfig, TypedProperties props, HoodieSchema schema, Path tablePath)
+    {
+        // Same initialization order as HoodieFileGroupReader for a split with 
log files.
+        HudiTrinoReaderContext readerContext = new HudiTrinoReaderContext(new 
TrinoStorageConfiguration(), tableConfig, null, List.of(), null, null, props);
+        readerContext.setHasLogFiles(true);
+        
readerContext.getRecordContext().setPartitionPath("ss_sold_date_sk=2451000");
+        readerContext.initRecordMerger(props);
+        readerContext.setTablePath(tablePath.toUri().toString());
+        readerContext.setLatestCommitTime("20260917212448192");
+        readerContext.setShouldMergeUseRecordPosition(false);
+        readerContext.setHasBootstrapBaseFile(false);
+        readerContext.setSchemaHandler(new 
FileGroupReaderSchemaHandler<>(readerContext, schema, schema, Option.empty(), 
props,
+                TableState.of(new StoragePath(tablePath.toUri().toString()), 
tableConfig, Option.empty(), Option.empty())));
+        return readerContext;
+    }
+
+    private static List<BufferedRecord<IndexedRecord>> 
logRecords(HudiTrinoReaderContext readerContext, HoodieSchema schema, Schema 
avroSchema)
+    {
+        Random random = new Random(7);
+        List<BufferedRecord<IndexedRecord>> records = new 
ArrayList<>(LOG_RECORDS);
+        for (int i = 0; i < LOG_RECORDS; i++) {
+            int itemSk = 1 + random.nextInt(300_000);
+            long ticket = 1_000_000L + i;
+            String recordKey = "ss_item_sk:" + itemSk + ",ss_ticket_number:" + 
ticket;
+            GenericRecord record = new GenericData.Record(avroSchema);
+            record.put("_hoodie_commit_time", "20260917212448192");
+            record.put("_hoodie_commit_seqno", "20260917212448192_178_" + i);
+            record.put("_hoodie_record_key", recordKey);
+            record.put("_hoodie_partition_path", "ss_sold_date_sk=2451000");
+            record.put("_hoodie_file_name", 
"d8d5a7a0-5929-44f5-9b6d-336ddfbb33dc-5_178-2744-518159");
+            record.put("ss_sold_time_sk", 28_800 + random.nextInt(36_000));
+            record.put("ss_item_sk", itemSk);
+            record.put("ss_customer_sk", 1 + random.nextInt(12_000_000));
+            record.put("ss_store_sk", 1 + random.nextInt(1_000));
+            record.put("ss_promo_sk", 1 + random.nextInt(1_500));
+            record.put("ss_ticket_number", ticket);
+            record.put("ss_quantity", 1 + random.nextInt(100));
+            for (String measure : MEASURES) {
+                record.put(measure, 
DECIMAL_CONVERSION.toFixed(BigDecimal.valueOf(random.nextInt(2_000_000), 2), 
DECIMAL_7_2, DECIMAL_7_2.getLogicalType()));
+            }
+            record.put("ss_sold_date_sk", 2451000);
+            record.put("__op_ts", 3L);
+            records.add(BufferedRecords.fromEngineRecord(record, schema, 
readerContext.getRecordContext(), OrderingValues.getDefault(), recordKey, 
false));
+        }
+        return records;
+    }
+}
diff --git 
a/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/HudiMorReadBenchmark.java
 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/HudiMorReadBenchmark.java
new file mode 100644
index 000000000000..1c925bd3809b
--- /dev/null
+++ 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/HudiMorReadBenchmark.java
@@ -0,0 +1,265 @@
+/*
+ * Licensed 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 io.trino.plugin.hudi.benchmark;
+
+import io.airlift.units.Duration;
+import io.trino.Session;
+import io.trino.execution.QueryStats;
+import io.trino.server.DynamicFilterService.DynamicFilterDomainStats;
+import io.trino.testing.DistributedQueryRunner;
+import io.trino.testing.MaterializedResult;
+import io.trino.testing.MaterializedRow;
+import io.trino.testing.QueryRunner.MaterializedResultWithPlan;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.math.BigDecimal;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.TreeMap;
+import java.util.function.Consumer;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static 
io.trino.plugin.hudi.benchmark.TpcdsMorTablesInitializer.DATE_DIM;
+import static 
io.trino.plugin.hudi.benchmark.TpcdsMorTablesInitializer.STORE_SALES;
+import static java.lang.String.format;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.Comparator.comparingDouble;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
+
+/**
+ * End-to-end MOR read benchmark for the Trino Hudi connector, runnable on a 
laptop with no cluster and no S3.
+ * It reads a generated TPC-DS-shaped MOR table and reports the numbers each 
read-path fix should move:
+ * <ul>
+ *   <li><b>Merge-path CPU</b> (record size estimation, Page/Avro conversion, 
key-based merge): {@code _rt} vs
+ *   {@code _ro} CPU on the {@code scan} scenario.</li>
+ *   <li><b>Per-split metadata reads</b> (meta client + {@code 
TableSchemaResolver} per split): table-properties,
+ *   timeline and, with the metadata table on, index-definition reads per 
query, which should not grow with the
+ *   number of splits.</li>
+ *   <li><b>Dynamic partition pruning</b> missing its wait window: the {@code 
dpp} scenario reports the date filter's
+ *   collection time against {@code hudi.dynamic-filtering.wait-timeout} 
(session property
+ *   {@code dynamic_filtering_wait_timeout}) and the fact table's base-file 
input.</li>
+ * </ul>
+ *
+ * <p>{@code baseInput} is the query's physical input from {@link QueryStats}, 
which covers the base files only: log
+ * files are read through the Hudi storage layer and their bytes are not 
counted, and show in the storage request
+ * counts instead. {@code _rt} reads more base bytes than {@code _ro} for the 
columns the merge needs, as long as base
+ * files are above Trino's 3 MB {@code parquet.small-file-threshold}; below it 
each base file is read whole and the
+ * two match.
+ *
+ * <p>Named {@code *Benchmark} so surefire never runs it in CI. Run it on 
demand (JDK 25, after the Trino bootstrap
+ * described in the module README):
+ * <pre>
+ * mvn -Phudi-trino,hudi-trino-tests -pl hudi-trino test 
-Dtest=HudiMorReadBenchmark \
+ *     -Dsurefire.failIfNoSpecifiedTests=false \
+ *     -Dbench.partitions=48 -Dbench.rowsPerPartition=60000 -Dbench.rounds=3 \
+ *     -Dbench.s3.getMillis=20 -Dbench.s3.headMillis=15 
-Dbench.s3.listMillis=40
+ * </pre>
+ * {@code -Dbench.s3.latency.enabled=0} turns the injected storage latency off 
(CPU-bound, laptop disk only);
+ * keep it on to see the per-split metadata reads and the dynamic-filter 
timing the way S3 shows them.
+ * Results print to stdout and append to {@code 
target/hudi-mor-read-benchmark.jsonl}, one line per query carrying
+ * the run's start time and settings.
+ */
+@TestInstance(PER_CLASS)
+final class HudiMorReadBenchmark
+{
+    private static final int ROUNDS = Integer.getInteger("bench.rounds", 3);
+    private static final int WORKERS = Integer.getInteger("bench.workers", 1);
+    private static final int TARGET_MONTH = 11;
+
+    private final LatencyInjectingFileSystemFactory.Counters counters = new 
LatencyInjectingFileSystemFactory.Counters();
+    private TpcdsMorTablesInitializer tables;
+    private DistributedQueryRunner queryRunner;
+    private final List<String> report = new ArrayList<>();
+    private final String started = Instant.now().toString();
+    private String settings;
+
+    @BeforeAll
+    void setUp()
+            throws Exception
+    {
+        checkArgument(ROUNDS >= 1, "bench.rounds must be at least 1: %s", 
ROUNDS);
+        tables = TpcdsMorTablesInitializer.fromSystemProperties();
+        // Partition p has d_moy = p % 12 + 1, so the dpp filter d_moy = 
TARGET_MONTH needs partition TARGET_MONTH - 1.
+        checkArgument(tables.partitions() >= TARGET_MONTH, "bench.partitions 
must be at least %s for a d_moy = %s partition: %s",
+                TARGET_MONTH, TARGET_MONTH, tables.partitions());
+        LatencyInjectingFileSystemFactory.Latency latency = 
LatencyInjectingFileSystemFactory.Latency.fromSystemProperties();
+        queryRunner = BenchmarkHudiQueryRunner.create(WORKERS, latency, 
counters, tables);
+        settings = format("tables=%s nativeLogs=%s latency=%s workers=%s 
rounds=%s",
+                tables, Boolean.getBoolean("bench.nativeLogs"), latency, 
WORKERS, ROUNDS);
+        report.add(settings);
+    }
+
+    @AfterAll
+    void tearDown()
+    {
+        report.forEach(System.out::println);
+        if (queryRunner != null) {
+            queryRunner.close();
+        }
+    }
+
+    @Test
+    void scan()
+    {
+        long[] expectedRt = tables.expectedRtTotals();
+        long[] expectedRo = tables.expectedRoTotals();
+        String sql = "SELECT count(*), sum(ss_quantity), sum(ss_net_paid) FROM 
%s";
+        for (Variant variant : Variant.values()) {
+            Measurement ro = measure("scan", "ro", variant, format(sql, 
STORE_SALES + "_ro"), result -> {
+                
assertThat(result.getMaterializedRows().getFirst().getField(0)).isEqualTo(expectedRo[0]);
+                
assertThat(result.getMaterializedRows().getFirst().getField(1)).isEqualTo(expectedRo[1]);
+                
assertThat(result.getMaterializedRows().getFirst().getField(2)).isEqualTo(BigDecimal.valueOf(expectedRo[2],
 2));
+            });
+            Measurement rt = measure("scan", "rt", variant, format(sql, 
STORE_SALES + "_rt"), result -> {
+                
assertThat(result.getMaterializedRows().getFirst().getField(0)).isEqualTo(expectedRt[0]);
+                
assertThat(result.getMaterializedRows().getFirst().getField(1)).isEqualTo(expectedRt[1]);
+                
assertThat(result.getMaterializedRows().getFirst().getField(2)).isEqualTo(BigDecimal.valueOf(expectedRt[2],
 2));
+            });
+            report.add(format("  scan %-18s rt/ro: wall %.1fx, cpu %.1fx, base 
bytes %.1fx",
+                    variant, rt.wallSeconds / ro.wallSeconds, rt.cpuSeconds / 
ro.cpuSeconds, (double) rt.physicalInputBytes / ro.physicalInputBytes));
+        }
+    }
+
+    @Test
+    void dynamicPartitionPruning()
+    {
+        Map<Long, long[]> expectedRo = 
tables.expectedRoByYearForMonth(TARGET_MONTH);
+        Map<Long, long[]> expectedRt = 
tables.expectedRtByYearForMonth(TARGET_MONTH);
+        // min(d_dom) is the date_dim version joined: a _rt query that reads a 
date_dim row without its update fails
+        String sql = "SELECT d.d_year, count(*), sum(ss.ss_quantity), 
min(d.d_dom) FROM %s ss JOIN %s d ON ss.ss_sold_date_sk = d.d_date_sk " +
+                "WHERE d.d_moy = " + TARGET_MONTH + " GROUP BY d.d_year ORDER 
BY 1";
+        for (Variant variant : Variant.values()) {
+            measure("dpp", "ro", variant, format(sql, STORE_SALES + "_ro", 
DATE_DIM + "_ro"), result -> assertByYear(result, expectedRo));
+            measure("dpp", "rt", variant, format(sql, STORE_SALES + "_rt", 
DATE_DIM + "_rt"), result -> assertByYear(result, expectedRt));
+        }
+    }
+
+    private static void assertByYear(MaterializedResult result, Map<Long, 
long[]> expected)
+    {
+        Map<Long, long[]> actual = new TreeMap<>();
+        for (MaterializedRow row : result.getMaterializedRows()) {
+            actual.put(((Number) row.getField(0)).longValue(), new long[] 
{(Long) row.getField(1), (Long) row.getField(2), ((Number) 
row.getField(3)).longValue()});
+        }
+        assertThat(actual.keySet()).isEqualTo(expected.keySet());
+        expected.forEach((year, totals) -> 
assertThat(actual.get(year)).containsExactly(totals));
+    }
+
+    private Measurement measure(String scenario, String table, Variant 
variant, String sql, Consumer<MaterializedResult> verifier)
+    {
+        Session session = variant.apply(queryRunner.getDefaultSession());
+        // Warm up: JIT, metastore and connector caches. Not measured.
+        verifier.accept(queryRunner.executeWithPlan(session, sql).result());
+
+        List<Measurement> runs = new ArrayList<>();
+        for (int round = 0; round < ROUNDS; round++) {
+            counters.reset();
+            long start = System.nanoTime();
+            MaterializedResultWithPlan result = 
queryRunner.executeWithPlan(session, sql);
+            double wall = (System.nanoTime() - start) / 1e9;
+            verifier.accept(result.result());
+            runs.add(Measurement.of(wall, 
queryRunner.getCoordinator().getFullQueryInfo(result.queryId()).getQueryStats(),
 counters));
+        }
+        Measurement median = Measurement.median(runs);
+        if (Boolean.getBoolean("bench.s3.samples")) {
+            report.add(format("    samples %s %s %s:%n%s", scenario, table, 
variant, counters.samples()));
+        }
+        String line = format(Locale.ROOT, "%-5s %-3s %-18s wall=%6.2fs 
cpu=%7.2fs baseInput=%8.1fMB storage[%s] dateDF=%s",
+                scenario, table, variant, median.wallSeconds, 
median.cpuSeconds, median.physicalInputBytes / 1e6,
+                median.storage, median.dateFilterCollection);
+        report.add(line);
+        appendJson(scenario, table, variant, median);
+        return median;
+    }
+
+    private void appendJson(String scenario, String table, Variant variant, 
Measurement m)
+    {
+        String json = format(Locale.ROOT,
+                
"{\"started\":\"%s\",\"settings\":\"%s\",\"scenario\":\"%s\",\"table\":\"%s\",\"variant\":\"%s\",\"wall_s\":%.3f,\"cpu_s\":%.3f,\"base_input_bytes\":%d,\"storage\":\"%s\",\"date_df\":\"%s\"}%n",
+                started, settings, scenario, table, variant, m.wallSeconds, 
m.cpuSeconds, m.physicalInputBytes, m.storage, m.dateFilterCollection);
+        try {
+            Path output = Path.of("target", "hudi-mor-read-benchmark.jsonl");
+            Files.createDirectories(output.getParent());
+            Files.writeString(output, json, UTF_8, StandardOpenOption.CREATE, 
StandardOpenOption.APPEND);
+        }
+        catch (IOException e) {
+            throw new UncheckedIOException(e);
+        }
+    }
+
+    /** Session variants; each isolates one candidate fix that is reachable 
through configuration today. */
+    enum Variant
+    {
+        DEFAULT(Map.of()),
+        /** Resolves the table schema once on the coordinator, which removes 
the per-split {@code TableSchemaResolver}. */
+        SCHEMA_IN_HANDLE(Map.of("resolve_column_name_casing_enabled", "true")),
+        /** Waits long enough for the dimension's dynamic filter, isolating 
the pruning-timing effect. */
+        DF_WAIT_10S(Map.of("dynamic_filtering_wait_timeout", "10s"));
+
+        private final Map<String, String> properties;
+
+        Variant(Map<String, String> properties)
+        {
+            this.properties = properties;
+        }
+
+        Session apply(Session session)
+        {
+            Session.SessionBuilder builder = Session.builder(session);
+            properties.forEach((name, value) -> 
builder.setCatalogSessionProperty(BenchmarkHudiQueryRunner.CATALOG, name, 
value));
+            return builder.build();
+        }
+
+        @Override
+        public String toString()
+        {
+            return name().toLowerCase(Locale.ROOT);
+        }
+    }
+
+    private record Measurement(double wallSeconds, double cpuSeconds, long 
physicalInputBytes, String storage, String dateFilterCollection)
+    {
+        static Measurement of(double wall, QueryStats stats, 
LatencyInjectingFileSystemFactory.Counters counters)
+        {
+            String dateFilter = 
stats.getDynamicFiltersStats().getDynamicFilterDomainStats().stream()
+                    .map(DynamicFilterDomainStats::getCollectionDuration)
+                    .flatMap(Optional::stream)
+                    .map(Duration::toString)
+                    .reduce((a, b) -> a + "," + b)
+                    .orElse("-");
+            return new Measurement(wall, 
stats.getTotalCpuTime().getValue(MILLISECONDS) / 1000.0,
+                    stats.getPhysicalInputDataSize().toBytes(), counters + " | 
" + counters.breakdown(), dateFilter);
+        }
+
+        static Measurement median(List<Measurement> runs)
+        {
+            List<Measurement> sorted = new ArrayList<>(runs);
+            sorted.sort(comparingDouble(Measurement::wallSeconds));
+            return sorted.get(sorted.size() / 2);
+        }
+    }
+}
diff --git 
a/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/LatencyInjectingFileSystemFactory.java
 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/LatencyInjectingFileSystemFactory.java
new file mode 100644
index 000000000000..9fd8c8cf1b35
--- /dev/null
+++ 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/LatencyInjectingFileSystemFactory.java
@@ -0,0 +1,511 @@
+/*
+ * Licensed 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 io.trino.plugin.hudi.benchmark;
+
+import io.trino.filesystem.FileIterator;
+import io.trino.filesystem.Location;
+import io.trino.filesystem.TrinoFileSystem;
+import io.trino.filesystem.TrinoFileSystemFactory;
+import io.trino.filesystem.TrinoInput;
+import io.trino.filesystem.TrinoInputFile;
+import io.trino.filesystem.TrinoInputStream;
+import io.trino.filesystem.TrinoOutputFile;
+import io.trino.spi.security.ConnectorIdentity;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Comparator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.Collectors;
+
+import static java.util.Objects.requireNonNull;
+import static org.apache.hudi.common.fs.FSUtils.isLogFile;
+
+/**
+ * Wraps a local {@link TrinoFileSystemFactory} and charges an 
object-store-like latency on each request a
+ * reader would send to S3: the first read of a stream and each read after a 
seek S3 cannot serve by skipping (one
+ * GET), each positioned or tail read (one ranged GET), an
+ * existence probe or a length or modification time not yet known (one HEAD) 
and each listing call (one LIST).
+ * As Trino's {@code S3InputFile} does, a length or modification time passed 
to {@code newInputFile} or returned
+ * by an earlier HEAD is answered without another request. Local disk answers 
these in
+ * microseconds, which hides any per-split metadata read; the injected latency 
makes those reads cost what
+ * they cost on S3, so a local run shows their effect on wall time and on 
dynamic-filter timing.
+ *
+ * <p>The counters are environment-independent: they count requests regardless 
of the latency setting, so
+ * a change that removes per-split metadata reads shows up as a lower count 
even with zero latency.
+ */
+final class LatencyInjectingFileSystemFactory
+        implements TrinoFileSystemFactory
+{
+    private final TrinoFileSystemFactory delegate;
+    private final Latency latency;
+    private final Counters counters;
+
+    LatencyInjectingFileSystemFactory(TrinoFileSystemFactory delegate, Latency 
latency, Counters counters)
+    {
+        this.delegate = requireNonNull(delegate, "delegate is null");
+        this.latency = requireNonNull(latency, "latency is null");
+        this.counters = requireNonNull(counters, "counters is null");
+    }
+
+    @Override
+    public TrinoFileSystem create(ConnectorIdentity identity)
+    {
+        return new LatencyInjectingFileSystem(delegate.create(identity));
+    }
+
+    /**
+     * Per-request latencies in milliseconds. Defaults approximate same-region 
S3 from EC2: a first-byte GET of
+     * ~20ms, a HEAD of ~15ms, a LIST page of ~40ms.
+     */
+    record Latency(long getMillis, long headMillis, long listMillis)
+    {
+        static Latency fromSystemProperties()
+        {
+            long scale = Long.getLong("bench.s3.latency.enabled", 1) == 0 ? 0 
: 1;
+            return new Latency(
+                    scale * Long.getLong("bench.s3.getMillis", 20),
+                    scale * Long.getLong("bench.s3.headMillis", 15),
+                    scale * Long.getLong("bench.s3.listMillis", 40));
+        }
+    }
+
+    /** Request counts since the last {@link #reset()}, in total and per 
request type and Hudi file type. */
+    static final class Counters
+    {
+        final AtomicLong gets = new AtomicLong();
+        final AtomicLong heads = new AtomicLong();
+        final AtomicLong lists = new AtomicLong();
+        private final Map<String, AtomicLong> byKind = new 
ConcurrentHashMap<>();
+        private final Map<String, String> samples = new ConcurrentHashMap<>();
+
+        void reset()
+        {
+            gets.set(0);
+            heads.set(0);
+            lists.set(0);
+            byKind.clear();
+            samples.clear();
+        }
+
+        void record(AtomicLong counter, Location location)
+        {
+            counter.incrementAndGet();
+            String request = counter == gets ? "GET" : counter == heads ? 
"HEAD" : "LIST";
+            String kind = request + ":" + fileType(location);
+            byKind.computeIfAbsent(kind, key -> new 
AtomicLong()).incrementAndGet();
+            samples.putIfAbsent(kind, location.toString());
+        }
+
+        /** One example location per request and file type, to see which files 
a request type hits. */
+        String samples()
+        {
+            return samples.entrySet().stream()
+                    .sorted(Map.Entry.comparingByKey())
+                    .map(entry -> entry.getKey() + " -> " + entry.getValue())
+                    .collect(Collectors.joining("\n"));
+        }
+
+        /** Per request type and file type, e.g. {@code HEAD:LOG=96}, largest 
first. */
+        String breakdown()
+        {
+            return byKind.entrySet().stream()
+                    .sorted(Map.Entry.<String, 
AtomicLong>comparingByValue(Comparator.comparingLong(AtomicLong::get)).reversed())
+                    .map(entry -> entry.getKey() + "=" + 
entry.getValue().get())
+                    .collect(Collectors.joining(" "));
+        }
+
+        private static String fileType(Location location)
+        {
+            String path = location.toString();
+            if (path.contains("/.hoodie")) {
+                if (path.contains("/.hoodie/metadata")) {
+                    return "METADATA_TABLE";
+                }
+                if (path.contains("/.hoodie/.index_defs")) {
+                    return "INDEX_DEFINITION";
+                }
+                if (path.contains("/.hoodie/timeline")) {
+                    return "TIMELINE";
+                }
+                if (path.endsWith("/.hoodie/hoodie.properties")) {
+                    return "TABLE_PROPERTIES";
+                }
+                return path.endsWith("/.hoodie") ? "HOODIE_DIR" : 
"OTHER_HOODIE";
+            }
+            if (isLogFile(location.fileName())) {
+                return "LOG";
+            }
+            if (path.endsWith(".parquet")) {
+                return "BASE";
+            }
+            if (path.contains(".hoodie_partition_metadata")) {
+                return "PARTITION_METADATA";
+            }
+            return path.contains("=") ? "PARTITION_DIR" : "TABLE_DIR";
+        }
+
+        @Override
+        public String toString()
+        {
+            return "GET=" + gets.get() + " HEAD=" + heads.get() + " LIST=" + 
lists.get();
+        }
+    }
+
+    private void charge(Location location, AtomicLong counter, long millis)
+    {
+        // The file metastore keeps its table definitions on the same 
filesystem; on a cluster the metastore
+        // is a separate service (Glue, HMS), so its files are not charged as 
table storage requests.
+        String path = location.toString();
+        if (path.contains("/.trino") || path.contains("/managed/")) {
+            return;
+        }
+        counters.record(counter, location);
+        if (millis > 0) {
+            try {
+                TimeUnit.MILLISECONDS.sleep(millis);
+            }
+            catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+            }
+        }
+    }
+
+    private final class LatencyInjectingFileSystem
+            implements TrinoFileSystem
+    {
+        private final TrinoFileSystem fileSystem;
+
+        private LatencyInjectingFileSystem(TrinoFileSystem fileSystem)
+        {
+            this.fileSystem = fileSystem;
+        }
+
+        @Override
+        public TrinoInputFile newInputFile(Location location)
+        {
+            return new 
LatencyInjectingInputFile(fileSystem.newInputFile(location), null, null);
+        }
+
+        @Override
+        public TrinoInputFile newInputFile(Location location, long length)
+        {
+            return new 
LatencyInjectingInputFile(fileSystem.newInputFile(location, length), length, 
null);
+        }
+
+        @Override
+        public TrinoInputFile newInputFile(Location location, long length, 
Instant lastModified)
+        {
+            return new 
LatencyInjectingInputFile(fileSystem.newInputFile(location, length, 
lastModified), length, lastModified);
+        }
+
+        @Override
+        public TrinoOutputFile newOutputFile(Location location)
+        {
+            return fileSystem.newOutputFile(location);
+        }
+
+        @Override
+        public void deleteFile(Location location)
+                throws IOException
+        {
+            fileSystem.deleteFile(location);
+        }
+
+        @Override
+        public void deleteDirectory(Location location)
+                throws IOException
+        {
+            fileSystem.deleteDirectory(location);
+        }
+
+        @Override
+        public void renameFile(Location source, Location target)
+                throws IOException
+        {
+            fileSystem.renameFile(source, target);
+        }
+
+        @Override
+        public FileIterator listFiles(Location location)
+                throws IOException
+        {
+            charge(location, counters.lists, latency.listMillis());
+            return fileSystem.listFiles(location);
+        }
+
+        @Override
+        public Optional<Boolean> directoryExists(Location location)
+                throws IOException
+        {
+            charge(location, counters.lists, latency.listMillis());
+            return fileSystem.directoryExists(location);
+        }
+
+        @Override
+        public void createDirectory(Location location)
+                throws IOException
+        {
+            fileSystem.createDirectory(location);
+        }
+
+        @Override
+        public void renameDirectory(Location source, Location target)
+                throws IOException
+        {
+            fileSystem.renameDirectory(source, target);
+        }
+
+        @Override
+        public Set<Location> listDirectories(Location location)
+                throws IOException
+        {
+            charge(location, counters.lists, latency.listMillis());
+            return fileSystem.listDirectories(location);
+        }
+
+        @Override
+        public Optional<Location> createTemporaryDirectory(Location 
targetPath, String temporaryPrefix, String relativePrefix)
+                throws IOException
+        {
+            return fileSystem.createTemporaryDirectory(targetPath, 
temporaryPrefix, relativePrefix);
+        }
+    }
+
+    private final class LatencyInjectingInputFile
+            implements TrinoInputFile
+    {
+        private final TrinoInputFile inputFile;
+        // Null until passed to newInputFile or filled by a HEAD, as 
S3InputFile keeps them
+        private Long length;
+        private Instant lastModified;
+
+        private LatencyInjectingInputFile(TrinoInputFile inputFile, Long 
length, Instant lastModified)
+        {
+            this.inputFile = inputFile;
+            this.length = length;
+            this.lastModified = lastModified;
+        }
+
+        @Override
+        public TrinoInput newInput()
+                throws IOException
+        {
+            return new LatencyInjectingInput(inputFile.location(), 
inputFile.newInput());
+        }
+
+        @Override
+        public TrinoInputStream newStream()
+                throws IOException
+        {
+            return new LatencyInjectingInputStream(inputFile.location(), 
inputFile.newStream());
+        }
+
+        @Override
+        public long length()
+                throws IOException
+        {
+            if (length == null && !head()) {
+                throw new 
FileNotFoundException(inputFile.location().toString());
+            }
+            return length;
+        }
+
+        @Override
+        public Instant lastModified()
+                throws IOException
+        {
+            if (lastModified == null && !head()) {
+                throw new 
FileNotFoundException(inputFile.location().toString());
+            }
+            return lastModified;
+        }
+
+        @Override
+        public boolean exists()
+                throws IOException
+        {
+            return head();
+        }
+
+        /** One HEAD, which fills whichever of length and modification time is 
not yet known. */
+        private boolean head()
+                throws IOException
+        {
+            charge(inputFile.location(), counters.heads, latency.headMillis());
+            if (!inputFile.exists()) {
+                return false;
+            }
+            if (length == null) {
+                length = inputFile.length();
+            }
+            if (lastModified == null) {
+                lastModified = inputFile.lastModified();
+            }
+            return true;
+        }
+
+        @Override
+        public Location location()
+        {
+            return inputFile.location();
+        }
+    }
+
+    /**
+     * Charges GETs as Trino's {@code S3InputStream} sends them: none when the 
stream is opened, one on the first read,
+     * and one on each read that follows a backward seek or a forward seek 
longer than {@link #MAX_SKIP_BYTES}, which
+     * S3 serves by reopening the object at the new position rather than 
skipping on the open connection.
+     * {@code S3InputStream} also skips up to the bytes its connection has 
buffered; that is taken as zero here.
+     */
+    private final class LatencyInjectingInputStream
+            extends TrinoInputStream
+    {
+        private static final long MAX_SKIP_BYTES = 1024 * 1024;
+
+        private final Location location;
+        private final TrinoInputStream stream;
+        private boolean connected;
+        private long streamPosition;
+        private long nextReadPosition;
+
+        private LatencyInjectingInputStream(Location location, 
TrinoInputStream stream)
+        {
+            this.location = location;
+            this.stream = stream;
+        }
+
+        @Override
+        public long getPosition()
+                throws IOException
+        {
+            return stream.getPosition();
+        }
+
+        @Override
+        public void seek(long position)
+                throws IOException
+        {
+            stream.seek(position);
+            nextReadPosition = position;
+        }
+
+        @Override
+        public int read()
+                throws IOException
+        {
+            connect();
+            int value = stream.read();
+            if (value >= 0) {
+                advance(1);
+            }
+            return value;
+        }
+
+        @Override
+        public int read(byte[] buffer, int offset, int length)
+                throws IOException
+        {
+            connect();
+            int read = stream.read(buffer, offset, length);
+            if (read > 0) {
+                advance(read);
+            }
+            return read;
+        }
+
+        @Override
+        public long skip(long n)
+                throws IOException
+        {
+            long skipped = stream.skip(n);
+            nextReadPosition += skipped;
+            return skipped;
+        }
+
+        @Override
+        public int available()
+                throws IOException
+        {
+            return stream.available();
+        }
+
+        @Override
+        public void close()
+                throws IOException
+        {
+            stream.close();
+        }
+
+        private void connect()
+        {
+            long gap = nextReadPosition - streamPosition;
+            if (connected && gap >= 0 && gap <= MAX_SKIP_BYTES) {
+                streamPosition = nextReadPosition;
+                return;
+            }
+            charge(location, counters.gets, latency.getMillis());
+            connected = true;
+            streamPosition = nextReadPosition;
+        }
+
+        private void advance(int bytes)
+        {
+            nextReadPosition += bytes;
+            streamPosition = nextReadPosition;
+        }
+    }
+
+    private final class LatencyInjectingInput
+            implements TrinoInput
+    {
+        private final Location location;
+        private final TrinoInput input;
+
+        private LatencyInjectingInput(Location location, TrinoInput input)
+        {
+            this.location = location;
+            this.input = input;
+        }
+
+        @Override
+        public void readFully(long position, byte[] buffer, int bufferOffset, 
int length)
+                throws IOException
+        {
+            charge(location, counters.gets, latency.getMillis());
+            input.readFully(position, buffer, bufferOffset, length);
+        }
+
+        @Override
+        public int readTail(byte[] buffer, int bufferOffset, int maxLength)
+                throws IOException
+        {
+            charge(location, counters.gets, latency.getMillis());
+            return input.readTail(buffer, bufferOffset, maxLength);
+        }
+
+        @Override
+        public void close()
+                throws IOException
+        {
+            input.close();
+        }
+    }
+}
diff --git 
a/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/TpcdsMorTablesInitializer.java
 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/TpcdsMorTablesInitializer.java
new file mode 100644
index 000000000000..6302617e3ef1
--- /dev/null
+++ 
b/hudi-trino/src/test/java/io/trino/plugin/hudi/benchmark/TpcdsMorTablesInitializer.java
@@ -0,0 +1,598 @@
+/*
+ * Licensed 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 io.trino.plugin.hudi.benchmark;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import io.airlift.log.Logger;
+import io.trino.filesystem.Location;
+import io.trino.filesystem.TrinoFileSystem;
+import io.trino.filesystem.TrinoFileSystemFactory;
+import io.trino.metastore.Column;
+import io.trino.metastore.HiveMetastore;
+import io.trino.metastore.HiveMetastoreFactory;
+import io.trino.metastore.HiveType;
+import io.trino.metastore.Partition;
+import io.trino.metastore.PartitionStatistics;
+import io.trino.metastore.PartitionWithStatistics;
+import io.trino.metastore.PrincipalPrivileges;
+import io.trino.metastore.StorageFormat;
+import io.trino.metastore.Table;
+import io.trino.plugin.hudi.HudiConnector;
+import io.trino.plugin.hudi.testing.HudiTablesInitializer;
+import io.trino.plugin.hudi.testing.ResourceHudiTablesInitializer;
+import io.trino.spi.security.ConnectorIdentity;
+import io.trino.testing.QueryRunner;
+import org.apache.avro.Conversions;
+import org.apache.avro.LogicalTypes;
+import org.apache.avro.Schema;
+import org.apache.avro.SchemaBuilder;
+import org.apache.avro.generic.GenericData;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hudi.client.HoodieJavaWriteClient;
+import org.apache.hudi.client.WriteStatus;
+import org.apache.hudi.client.common.HoodieJavaEngineContext;
+import org.apache.hudi.common.bootstrap.index.NoOpBootstrapIndex;
+import org.apache.hudi.common.config.HoodieMetadataConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieAvroPayload;
+import org.apache.hudi.common.model.HoodieAvroRecord;
+import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.HoodieTableType;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.common.table.HoodieTableVersion;
+import org.apache.hudi.common.table.marker.MarkerType;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieCompactionConfig;
+import org.apache.hudi.config.HoodieIndexConfig;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.index.HoodieIndex;
+import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration;
+
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Random;
+import java.util.Set;
+import java.util.TreeMap;
+
+import static com.google.common.io.MoreFiles.deleteRecursively;
+import static com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE;
+import static io.trino.hive.formats.HiveClassNames.HUDI_PARQUET_INPUT_FORMAT;
+import static 
io.trino.hive.formats.HiveClassNames.HUDI_PARQUET_REALTIME_INPUT_FORMAT;
+import static 
io.trino.hive.formats.HiveClassNames.MAPRED_PARQUET_OUTPUT_FORMAT_CLASS;
+import static io.trino.hive.formats.HiveClassNames.PARQUET_HIVE_SERDE_CLASS;
+import static io.trino.metastore.HiveType.HIVE_INT;
+import static io.trino.metastore.HiveType.HIVE_LONG;
+import static io.trino.metastore.HiveType.HIVE_STRING;
+import static io.trino.plugin.hive.TableType.EXTERNAL_TABLE;
+import static java.lang.String.format;
+import static java.nio.file.Files.createTempDirectory;
+
+/**
+ * Writes two TPC-DS-shaped MOR tables:
+ * <ul>
+ *   <li>{@code store_sales}: partitioned by {@code ss_sold_date_sk} (hive 
style), complex record key
+ *   {@code ss_item_sk,ss_ticket_number}, decimal(7,2) measures, {@code 
COMMIT_TIME_ORDERING}, table version 9.
+ *   One base file per partition, then four delta commits (update, update, 
delete, update) that leave exactly four
+ *   log files in every file group. The last update also writes back the 
deleted keys it samples, so a delete must
+ *   not hide a later update of the same key.</li>
+ *   <li>{@code date_dim}: a small MOR dimension with one update delta commit, 
so the build side of a join merges
+ *   log files too.</li>
+ * </ul>
+ * Each table is registered twice: {@code <name>_ro} (base files only) and 
{@code <name>_rt} (merged snapshot).
+ *
+ * <p>Sizes come from system properties ({@code bench.partitions}, {@code 
bench.rowsPerPartition},
+ * {@code bench.updateFraction}, {@code bench.deleteFraction}). {@code 
bench.metadata} (default true, as in the
+ * connector) writes the metadata table and turns {@code 
hudi.metadata-enabled} on in the benchmark catalog. The
+ * expected query answers are computed in memory from the same generator so 
the benchmark can assert correctness.
+ */
+final class TpcdsMorTablesInitializer
+        implements HudiTablesInitializer
+{
+    static final String STORE_SALES = "store_sales";
+    static final String DATE_DIM = "date_dim";
+    static final int FIRST_DATE_SK = 2450000;
+    /** One partition every 30 days, so each month value holds partitions/12 
partitions. */
+    static final int DAYS_BETWEEN_PARTITIONS = 30;
+
+    private static final Logger log = 
Logger.get(TpcdsMorTablesInitializer.class);
+    static final String[] MEASURES = {
+            "ss_wholesale_cost", "ss_list_price", "ss_sales_price", 
"ss_ext_discount_amt", "ss_ext_sales_price",
+            "ss_ext_wholesale_cost", "ss_ext_list_price", "ss_ext_tax", 
"ss_coupon_amt", "ss_net_paid",
+            "ss_net_paid_inc_tax", "ss_net_profit"};
+    static final Schema DECIMAL_7_2 = LogicalTypes.decimal(7, 
2).addToSchema(Schema.createFixed("decimal_7_2", null, "hoodie.bench", 4));
+    static final Conversions.DecimalConversion DECIMAL_CONVERSION = new 
Conversions.DecimalConversion();
+    /** {@code d_dom} and {@code __op_ts} of a {@code date_dim} row as 
inserted, and after its update. */
+    private static final int DATE_DIM_BASE_VERSION = 1;
+    private static final int DATE_DIM_UPDATED_VERSION = 2;
+
+    private final int partitions;
+    private final int rowsPerPartition;
+    private final double updateFraction;
+    private final double deleteFraction;
+
+    /** Record key -> {@code [ss_sold_date_sk, ss_quantity, unscaled 
ss_net_paid]} of the merged snapshot. */
+    private final Map<String, long[]> finalState = new LinkedHashMap<>();
+    /** {@code ss_sold_date_sk -> [count, sum(ss_quantity)]} of the base files 
alone. */
+    private final Map<Integer, long[]> roByDateSk = new TreeMap<>();
+    /** State of the keys deleted in round 3, for round 4 to write back. */
+    private final Map<String, long[]> deletedState = new HashMap<>();
+    /** {@code d_date_sk} of the {@code date_dim} rows updated to {@link 
#DATE_DIM_UPDATED_VERSION}. */
+    private final Set<Integer> updatedDateSks = new HashSet<>();
+    private long roRowCount;
+    private long roSumQuantity;
+    private long roSumNetPaid;
+
+    TpcdsMorTablesInitializer(int partitions, int rowsPerPartition, double 
updateFraction, double deleteFraction)
+    {
+        this.partitions = partitions;
+        this.rowsPerPartition = rowsPerPartition;
+        this.updateFraction = updateFraction;
+        this.deleteFraction = deleteFraction;
+    }
+
+    static TpcdsMorTablesInitializer fromSystemProperties()
+    {
+        return new TpcdsMorTablesInitializer(
+                Integer.getInteger("bench.partitions", 48),
+                // 60000 rows give base files of about 4.2 MB, above Trino's 3 
MB parquet.small-file-threshold, so
+                // they are read with ranged reads as production-size base 
files are, not loaded whole
+                Integer.getInteger("bench.rowsPerPartition", 60_000),
+                Double.parseDouble(System.getProperty("bench.updateFraction", 
"0.10")),
+                Double.parseDouble(System.getProperty("bench.deleteFraction", 
"0.01")));
+    }
+
+    int partitions()
+    {
+        return partitions;
+    }
+
+    @Override
+    public void initializeTables(QueryRunner queryRunner, Location 
externalLocation, String schemaName)
+            throws Exception
+    {
+        HudiConnector connector = (HudiConnector) 
queryRunner.getCoordinator().getConnector(BenchmarkHudiQueryRunner.CATALOG);
+        TrinoFileSystem fileSystem = 
connector.getInjector().getInstance(TrinoFileSystemFactory.class).create(ConnectorIdentity.ofUser("bench"));
+        HiveMetastore metastore = 
connector.getInjector().getInstance(HiveMetastoreFactory.class).createMetastore(Optional.empty());
+
+        Path stagingDir = createTempDirectory("hudi-trino-bench");
+        try {
+            long start = System.nanoTime();
+            List<String> partitionPaths = 
writeStoreSales(stagingDir.resolve(STORE_SALES));
+            writeDateDim(stagingDir.resolve(DATE_DIM));
+            log.info("Wrote benchmark tables (%s partitions x %s rows) in 
%.1fs", partitions, rowsPerPartition, (System.nanoTime() - start) / 1e9);
+
+            for (String table : List.of(STORE_SALES, DATE_DIM)) {
+                Location tableLocation = externalLocation.appendPath(table);
+                
ResourceHudiTablesInitializer.copyDir(stagingDir.resolve(table), fileSystem, 
tableLocation);
+            }
+            Location storeSales = externalLocation.appendPath(STORE_SALES);
+            Location dateDim = externalLocation.appendPath(DATE_DIM);
+            for (boolean rt : new boolean[] {false, true}) {
+                String suffix = rt ? "_rt" : "_ro";
+                registerTable(metastore, schemaName, STORE_SALES + suffix, 
storeSales, storeSalesColumns(),
+                        List.of(new Column("ss_sold_date_sk", HIVE_INT, 
Optional.empty(), Map.of())), partitionPaths, rt);
+                registerTable(metastore, schemaName, DATE_DIM + suffix, 
dateDim, dateDimColumns(), List.of(), List.of(), rt);
+            }
+        }
+        finally {
+            deleteRecursively(stagingDir, ALLOW_INSECURE);
+        }
+    }
+
+    /** Row count, {@code sum(ss_quantity)} and unscaled {@code 
sum(ss_net_paid)} of the merged snapshot. */
+    long[] expectedRtTotals()
+    {
+        long sum = 0;
+        long netPaid = 0;
+        for (long[] row : finalState.values()) {
+            sum += row[1];
+            netPaid += row[2];
+        }
+        return new long[] {finalState.size(), sum, netPaid};
+    }
+
+    /** Row count, {@code sum(ss_quantity)} and unscaled {@code 
sum(ss_net_paid)} of the base files alone. */
+    long[] expectedRoTotals()
+    {
+        return new long[] {roRowCount, roSumQuantity, roSumNetPaid};
+    }
+
+    /**
+     * {@code d_year -> [count, sum(ss_quantity), min(d_dom)]} of the merged 
snapshot joined to the merged
+     * {@code date_dim} on {@code d_moy = month}.
+     */
+    Map<Long, long[]> expectedRtByYearForMonth(int month)
+    {
+        Map<Long, long[]> result = new TreeMap<>();
+        for (long[] row : finalState.values()) {
+            int dateSk = (int) row[0];
+            if (moy(dateSk) == month) {
+                long[] acc = result.computeIfAbsent((long) year(dateSk), y -> 
new long[] {0, 0, Long.MAX_VALUE});
+                acc[0]++;
+                acc[1] += row[1];
+                acc[2] = Math.min(acc[2], updatedDateSks.contains(dateSk) ? 
DATE_DIM_UPDATED_VERSION : DATE_DIM_BASE_VERSION);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * {@code d_year -> [count, sum(ss_quantity), min(d_dom)]} of the base 
files alone joined to the base files of
+     * {@code date_dim} on {@code d_moy = month}.
+     */
+    Map<Long, long[]> expectedRoByYearForMonth(int month)
+    {
+        Map<Long, long[]> result = new TreeMap<>();
+        roByDateSk.forEach((dateSk, totals) -> {
+            if (moy(dateSk) == month) {
+                long[] acc = result.computeIfAbsent((long) year(dateSk), y -> 
new long[] {0, 0, DATE_DIM_BASE_VERSION});
+                acc[0] += totals[0];
+                acc[1] += totals[1];
+            }
+        });
+        return result;
+    }
+
+    /** {@code bench.metadata}: whether the tables carry a metadata table and 
the catalog reads it (default true). */
+    static boolean metadataEnabled()
+    {
+        return Boolean.parseBoolean(System.getProperty("bench.metadata", 
"true"));
+    }
+
+    static int dateSk(int partition)
+    {
+        return FIRST_DATE_SK + partition * DAYS_BETWEEN_PARTITIONS;
+    }
+
+    static int moy(int dateSk)
+    {
+        return ((dateSk - FIRST_DATE_SK) / DAYS_BETWEEN_PARTITIONS) % 12 + 1;
+    }
+
+    static int year(int dateSk)
+    {
+        return 1998 + (dateSk - FIRST_DATE_SK) / (DAYS_BETWEEN_PARTITIONS * 
12);
+    }
+
+    private List<String> writeStoreSales(Path tablePath)
+            throws IOException
+    {
+        Schema schema = storeSalesSchema();
+        initTable(tablePath, STORE_SALES, "ss_item_sk,ss_ticket_number", 
"ss_sold_date_sk");
+        Random random = new Random(42);
+        List<String> partitionPaths = new ArrayList<>();
+        Map<String, HoodieKey> keys = new LinkedHashMap<>();
+
+        try (HoodieJavaWriteClient<HoodieAvroPayload> client = 
writeClient(tablePath, STORE_SALES, schema)) {
+            List<HoodieRecord<HoodieAvroPayload>> inserts = new 
ArrayList<>(partitions * rowsPerPartition);
+            long ticket = 0;
+            for (int p = 0; p < partitions; p++) {
+                int dateSk = dateSk(p);
+                String partitionPath = "ss_sold_date_sk=" + dateSk;
+                partitionPaths.add(partitionPath);
+                for (int r = 0; r < rowsPerPartition; r++) {
+                    int itemSk = 1 + random.nextInt(300_000);
+                    ticket++;
+                    String recordKey = "ss_item_sk:" + itemSk + 
",ss_ticket_number:" + ticket;
+                    HoodieKey key = new HoodieKey(recordKey, partitionPath);
+                    int quantity = 1 + random.nextInt(100);
+                    long[] state = new long[] {dateSk, quantity, 0};
+                    inserts.add(record(schema, key, itemSk, ticket, state, 
random, 0));
+                    keys.put(recordKey, key);
+                    finalState.put(recordKey, state);
+                    long[] partitionTotals = 
roByDateSk.computeIfAbsent(dateSk, sk -> new long[2]);
+                    partitionTotals[0]++;
+                    partitionTotals[1] += quantity;
+                    roSumQuantity += quantity;
+                    roSumNetPaid += state[2];
+                }
+            }
+            roRowCount = inserts.size();
+            commit(client, "bulk_insert", inserts, null);
+
+            List<String> recordKeys = new ArrayList<>(keys.keySet());
+            for (int round = 1; round <= 4; round++) {
+                if (round == 3) {
+                    List<HoodieKey> deletes = new ArrayList<>();
+                    for (String recordKey : sample(recordKeys, deleteFraction, 
random)) {
+                        long[] deleted = finalState.remove(recordKey);
+                        if (deleted != null) {
+                            deletes.add(keys.get(recordKey));
+                            deletedState.put(recordKey, deleted);
+                        }
+                    }
+                    commit(client, "delete", null, deletes);
+                    continue;
+                }
+                List<HoodieRecord<HoodieAvroPayload>> updates = new 
ArrayList<>();
+                for (String recordKey : sample(recordKeys, updateFraction, 
random)) {
+                    long[] state = finalState.get(recordKey);
+                    if (state == null) {
+                        // Deleted in round 3: writing it again checks that 
the delete does not hide this later update
+                        state = deletedState.remove(recordKey);
+                        if (state == null) {
+                            continue;
+                        }
+                        finalState.put(recordKey, state);
+                    }
+                    HoodieKey key = keys.get(recordKey);
+                    int quantity = 1 + random.nextInt(100);
+                    state[1] = quantity;
+                    String[] parts = recordKey.split(",");
+                    int itemSk = 
Integer.parseInt(parts[0].substring("ss_item_sk:".length()));
+                    long ticketNumber = 
Long.parseLong(parts[1].substring("ss_ticket_number:".length()));
+                    updates.add(record(schema, key, itemSk, ticketNumber, 
state, random, round));
+                }
+                commit(client, "upsert", updates, null);
+            }
+        }
+        return partitionPaths;
+    }
+
+    private void writeDateDim(Path tablePath)
+            throws IOException
+    {
+        Schema schema = 
SchemaBuilder.record("date_dim_record").namespace("hoodie.bench").fields()
+                .requiredInt("d_date_sk")
+                .requiredInt("d_year")
+                .requiredInt("d_moy")
+                .requiredInt("d_dom")
+                .requiredLong("__op_ts")
+                .endRecord();
+        initTable(tablePath, DATE_DIM, "d_date_sk", "");
+        try (HoodieJavaWriteClient<HoodieAvroPayload> client = 
writeClient(tablePath, DATE_DIM, schema)) {
+            int days = Math.max(partitions * DAYS_BETWEEN_PARTITIONS, 3650);
+            List<HoodieRecord<HoodieAvroPayload>> rows = new ArrayList<>();
+            List<HoodieRecord<HoodieAvroPayload>> updates = new ArrayList<>();
+            for (int d = 0; d < days; d++) {
+                int dateSk = FIRST_DATE_SK + d;
+                rows.add(dateDimRecord(schema, dateSk, DATE_DIM_BASE_VERSION));
+                if (d % 10 == 0) {
+                    updates.add(dateDimRecord(schema, dateSk, 
DATE_DIM_UPDATED_VERSION));
+                    updatedDateSks.add(dateSk);
+                }
+            }
+            commit(client, "bulk_insert", rows, null);
+            commit(client, "upsert", updates, null);
+        }
+    }
+
+    private static HoodieRecord<HoodieAvroPayload> dateDimRecord(Schema 
schema, int dateSk, int version)
+    {
+        GenericRecord record = new GenericData.Record(schema);
+        record.put("d_date_sk", dateSk);
+        // d_moy and d_year follow the store_sales partition spacing so a 
d_moy filter selects whole partitions.
+        record.put("d_year", year(dateSk));
+        record.put("d_moy", moy(dateSk));
+        record.put("d_dom", version);
+        record.put("__op_ts", (long) version);
+        HoodieKey key = new HoodieKey(String.valueOf(dateSk), "");
+        return new HoodieAvroRecord<>(key, new 
HoodieAvroPayload(Option.of(record)), null);
+    }
+
+    private static void commit(HoodieJavaWriteClient<HoodieAvroPayload> 
client, String operation, List<HoodieRecord<HoodieAvroPayload>> records, 
List<HoodieKey> deletes)
+    {
+        String instant = client.startCommit();
+        List<WriteStatus> statuses = switch (operation) {
+            case "bulk_insert" -> client.bulkInsert(records, instant);
+            case "upsert" -> client.upsert(records, instant);
+            case "delete" -> client.delete(deletes, instant);
+            default -> throw new IllegalArgumentException(operation);
+        };
+        client.commit(instant, statuses);
+    }
+
+    private static List<String> sample(List<String> keys, double fraction, 
Random random)
+    {
+        List<String> sample = new ArrayList<>();
+        for (String key : keys) {
+            if (random.nextDouble() < fraction) {
+                sample.add(key);
+            }
+        }
+        return sample;
+    }
+
+    /**
+     * Builds one store_sales row from {@code state = [ss_sold_date_sk, 
ss_quantity, -]} and stores the generated
+     * {@code ss_net_paid} (unscaled, scale 2) in {@code state[2]}.
+     */
+    private static HoodieRecord<HoodieAvroPayload> record(Schema schema, 
HoodieKey key, int itemSk, long ticket, long[] state, Random random, long opTs)
+    {
+        GenericRecord record = new GenericData.Record(schema);
+        record.put("ss_sold_time_sk", 28_800 + random.nextInt(36_000));
+        record.put("ss_item_sk", itemSk);
+        record.put("ss_customer_sk", 1 + random.nextInt(12_000_000));
+        record.put("ss_store_sk", 1 + random.nextInt(1_000));
+        record.put("ss_promo_sk", 1 + random.nextInt(1_500));
+        record.put("ss_ticket_number", ticket);
+        record.put("ss_quantity", (int) state[1]);
+        for (String measure : MEASURES) {
+            int unscaled = random.nextInt(2_000_000);
+            if (measure.equals("ss_net_paid")) {
+                state[2] = unscaled;
+            }
+            record.put(measure, 
DECIMAL_CONVERSION.toFixed(BigDecimal.valueOf(unscaled, 2), DECIMAL_7_2, 
DECIMAL_7_2.getLogicalType()));
+        }
+        record.put("ss_sold_date_sk", (int) state[0]);
+        record.put("__op_ts", opTs);
+        return new HoodieAvroRecord<>(key, new 
HoodieAvroPayload(Option.of(record)), null);
+    }
+
+    static Schema storeSalesSchema()
+    {
+        SchemaBuilder.FieldAssembler<Schema> fields = 
SchemaBuilder.record("store_sales_record").namespace("hoodie.bench").fields()
+                .requiredInt("ss_sold_time_sk")
+                .requiredInt("ss_item_sk")
+                .requiredInt("ss_customer_sk")
+                .requiredInt("ss_store_sk")
+                .requiredInt("ss_promo_sk")
+                .requiredLong("ss_ticket_number")
+                .requiredInt("ss_quantity");
+        for (String measure : MEASURES) {
+            fields = fields.name(measure).type(DECIMAL_7_2).noDefault();
+        }
+        return 
fields.requiredInt("ss_sold_date_sk").requiredLong("__op_ts").endRecord();
+    }
+
+    private static List<Column> storeSalesColumns()
+    {
+        ImmutableList.Builder<Column> columns = ImmutableList.<Column>builder()
+                .addAll(metaColumns())
+                .add(column("ss_sold_time_sk", HIVE_INT))
+                .add(column("ss_item_sk", HIVE_INT))
+                .add(column("ss_customer_sk", HIVE_INT))
+                .add(column("ss_store_sk", HIVE_INT))
+                .add(column("ss_promo_sk", HIVE_INT))
+                .add(column("ss_ticket_number", HIVE_LONG))
+                .add(column("ss_quantity", HIVE_INT));
+        for (String measure : MEASURES) {
+            columns.add(column(measure, HiveType.valueOf("decimal(7,2)")));
+        }
+        return columns.add(column("__op_ts", HIVE_LONG)).build();
+    }
+
+    private static List<Column> dateDimColumns()
+    {
+        return ImmutableList.<Column>builder()
+                .addAll(metaColumns())
+                .add(column("d_date_sk", HIVE_INT))
+                .add(column("d_year", HIVE_INT))
+                .add(column("d_moy", HIVE_INT))
+                .add(column("d_dom", HIVE_INT))
+                .add(column("__op_ts", HIVE_LONG))
+                .build();
+    }
+
+    private static List<Column> metaColumns()
+    {
+        return List.of(
+                column("_hoodie_commit_time", HIVE_STRING),
+                column("_hoodie_commit_seqno", HIVE_STRING),
+                column("_hoodie_record_key", HIVE_STRING),
+                column("_hoodie_partition_path", HIVE_STRING),
+                column("_hoodie_file_name", HIVE_STRING));
+    }
+
+    private static Column column(String name, HiveType type)
+    {
+        return new Column(name, type, Optional.empty(), Map.of());
+    }
+
+    static void initTable(Path tablePath, String tableName, String 
recordKeyFields, String partitionFields)
+            throws IOException
+    {
+        HoodieTableMetaClient.newTableBuilder()
+                .setTableType(HoodieTableType.MERGE_ON_READ)
+                .setTableName(tableName)
+                .setTableVersion(Boolean.getBoolean("bench.nativeLogs") ? 
HoodieTableVersion.TEN : HoodieTableVersion.NINE)
+                .setTimelineLayoutVersion(2)
+                .setBootstrapIndexClass(NoOpBootstrapIndex.class.getName())
+                .setRecordKeyFields(recordKeyFields)
+                .setPartitionFields(partitionFields)
+                .setKeyGeneratorType(partitionFields.isEmpty() ? 
"NON_PARTITION" : "COMPLEX")
+                .setHiveStylePartitioningEnable(true)
+                .setRecordMergeMode(RecordMergeMode.COMMIT_TIME_ORDERING)
+                .initTable(new HadoopStorageConfiguration(new 
Configuration()), tablePath.toUri().toString());
+    }
+
+    private static HoodieJavaWriteClient<HoodieAvroPayload> writeClient(Path 
tablePath, String tableName, Schema schema)
+    {
+        // Write version 9 writes legacy log files (.log.N with inline data 
blocks), as a version-9 Spark writer does;
+        // -Dbench.nativeLogs=true writes the version-10 native log files 
(<file>.log.parquet) instead.
+        int writeVersion = Boolean.getBoolean("bench.nativeLogs") ? 10 : 9;
+        HoodieWriteConfig config = HoodieWriteConfig.newBuilder()
+                .withPath(tablePath.toUri().toString())
+                .withWriteTableVersion(writeVersion)
+                .withSchema(schema.toString())
+                .withParallelism(4, 4)
+                .withBulkInsertParallelism(1)
+                .withDeleteParallelism(4)
+                .forTable(tableName)
+                .withRecordMergeMode(RecordMergeMode.COMMIT_TIME_ORDERING)
+                
.withIndexConfig(HoodieIndexConfig.newBuilder().withIndexType(HoodieIndex.IndexType.INMEMORY).build())
+                .withCompactionConfig(HoodieCompactionConfig.newBuilder()
+                        .withInlineCompaction(false)
+                        .withMaxNumDeltaCommitsBeforeCompaction(100)
+                        .build())
+                .withEmbeddedTimelineServerEnabled(false)
+                .withMarkersType(MarkerType.DIRECT.name())
+                
.withMetadataConfig(HoodieMetadataConfig.newBuilder().enable(metadataEnabled()).build())
+                .build();
+        return new HoodieJavaWriteClient<>(new HoodieJavaEngineContext(new 
HadoopStorageConfiguration(new Configuration())), config);
+    }
+
+    private static void registerTable(
+            HiveMetastore metastore,
+            String schemaName,
+            String tableName,
+            Location tableLocation,
+            List<Column> dataColumns,
+            List<Column> partitionColumns,
+            List<String> partitionPaths,
+            boolean rt)
+    {
+        StorageFormat storageFormat = StorageFormat.create(
+                PARQUET_HIVE_SERDE_CLASS,
+                rt ? HUDI_PARQUET_REALTIME_INPUT_FORMAT : 
HUDI_PARQUET_INPUT_FORMAT,
+                MAPRED_PARQUET_OUTPUT_FORMAT_CLASS);
+        metastore.createTable(Table.builder()
+                        .setDatabaseName(schemaName)
+                        .setTableName(tableName)
+                        .setTableType(EXTERNAL_TABLE.name())
+                        .setOwner(Optional.of("public"))
+                        .setDataColumns(dataColumns)
+                        .setPartitionColumns(partitionColumns)
+                        .setParameters(ImmutableMap.of("serialization.format", 
"1", "EXTERNAL", "TRUE"))
+                        .withStorage(storage -> 
storage.setStorageFormat(storageFormat).setLocation(tableLocation.toString()))
+                        .build(),
+                PrincipalPrivileges.NO_PRIVILEGES);
+        if (partitionPaths.isEmpty()) {
+            return;
+        }
+        List<PartitionWithStatistics> partitions = new ArrayList<>();
+        for (String partitionPath : partitionPaths) {
+            String value = partitionPath.substring(partitionPath.indexOf('=') 
+ 1);
+            partitions.add(new PartitionWithStatistics(
+                    Partition.builder()
+                            .setDatabaseName(schemaName)
+                            .setTableName(tableName)
+                            .setValues(List.of(value))
+                            .withStorage(storage -> 
storage.setStorageFormat(storageFormat).setLocation(tableLocation.appendPath(partitionPath).toString()))
+                            .setColumns(dataColumns)
+                            .build(),
+                    partitionPath,
+                    PartitionStatistics.empty()));
+        }
+        metastore.addPartitions(schemaName, tableName, partitions);
+    }
+
+    @Override
+    public String toString()
+    {
+        return format("TpcdsMorTables[partitions=%s, rowsPerPartition=%s, 
updateFraction=%s, deleteFraction=%s, metadata=%s]",
+                partitions, rowsPerPartition, updateFraction, deleteFraction, 
metadataEnabled());
+    }
+}

Reply via email to