You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fluss.apache.org by ip...@apache.org on 2026/10/15 07:19:19 UTC
(fluss) branch main updated: [trino] Add initial connector build and plugin skeleton (#4207)
This is an automated email from the ASF dual-hosted git repository.
polyzos pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fluss.git
The following commit(s) were added to refs/heads/main by this push:
new 79ca19ac12 [trino] Add initial connector build and plugin skeleton (#4207)
79ca19ac12 is described below
commit 79ca19ac129bd760aee8846363cf1292ed113185
Author: yangshangqing <50...@users.noreply.github.com>
AuthorDate: Thu Oct 15 03:19:13 2026 -0400
[trino] Add initial connector build and plugin skeleton (#4207)
* [trino] Add initial connector build and plugin skeleton
* [trino] Add metadata support for Fluss tables
* [trino] Add initial tests
* [trino] Add bounded log table reads and tests
* [trino] Refactor scan readers and add partitioned table reads
* [Trino] fix ci, Clarified that SASL authentication for Fluss is not supported in Trino connector for now.
* [trino] Improve connector robustness and error handling
* [trino] Fix lock held across table open, tighten SASL config validation and CI triggers
* [trino] Restore CI trigger paths for core modules
---------
Co-authored-by: Giannis Polyzos <ip...@gmail.com>
---
.github/workflows/ci-trino.yaml | 94 +++
fluss-trino/.mvn/wrapper/maven-wrapper.properties | 3 +
fluss-trino/README.md | 213 ++++++
fluss-trino/mvnw | 295 +++++++++
fluss-trino/mvnw.cmd | 189 ++++++
fluss-trino/pom.xml | 365 +++++++++++
.../org/apache/fluss/trino/FlussBucketHandle.java | 124 ++++
.../org/apache/fluss/trino/FlussClientManager.java | 155 +++++
.../org/apache/fluss/trino/FlussColumnHandle.java | 76 +++
.../fluss/trino/FlussColumnsSystemTable.java | 144 +++++
.../java/org/apache/fluss/trino/FlussConfig.java | 113 ++++
.../org/apache/fluss/trino/FlussConnector.java | 89 +++
.../apache/fluss/trino/FlussConnectorFactory.java | 65 ++
.../apache/fluss/trino/FlussConnectorModule.java | 70 ++
.../org/apache/fluss/trino/FlussErrorCode.java | 46 ++
.../org/apache/fluss/trino/FlussKvSplitReader.java | 172 +++++
.../java/org/apache/fluss/trino/FlussLogRange.java | 89 +++
.../apache/fluss/trino/FlussLogSplitReader.java | 253 ++++++++
.../java/org/apache/fluss/trino/FlussMetadata.java | 336 ++++++++++
.../apache/fluss/trino/FlussMetadataAccess.java | 560 ++++++++++++++++
.../org/apache/fluss/trino/FlussPageSource.java | 318 +++++++++
.../fluss/trino/FlussPageSourceProvider.java | 74 +++
.../apache/fluss/trino/FlussPhysicalBucket.java | 63 ++
.../java/org/apache/fluss/trino/FlussPlugin.java | 32 +
.../org/apache/fluss/trino/FlussRowDecoder.java | 273 ++++++++
.../java/org/apache/fluss/trino/FlussScanType.java | 25 +
.../java/org/apache/fluss/trino/FlussSplit.java | 110 ++++
.../org/apache/fluss/trino/FlussSplitManager.java | 62 ++
.../org/apache/fluss/trino/FlussSplitPlanner.java | 129 ++++
.../org/apache/fluss/trino/FlussSplitReader.java | 82 +++
.../fluss/trino/FlussSplitReaderFactory.java | 44 ++
.../org/apache/fluss/trino/FlussTableHandle.java | 132 ++++
.../apache/fluss/trino/FlussTableProperties.java | 123 ++++
.../fluss/trino/FlussTableScanValidator.java | 79 +++
.../apache/fluss/trino/FlussTransactionHandle.java | 26 +
.../org/apache/fluss/trino/FlussTypeConverter.java | 154 +++++
.../org/apache/fluss/trino/ResolvedSchemaName.java | 48 ++
.../org/apache/fluss/trino/ResolvedTableName.java | 49 ++
.../fluss/trino/TrinoVersionCompatibility.java | 103 +++
.../apache/fluss/trino/FlussBucketHandleTest.java | 77 +++
.../apache/fluss/trino/FlussClientManagerTest.java | 308 +++++++++
.../apache/fluss/trino/FlussColumnHandleTest.java | 54 ++
.../fluss/trino/FlussColumnsSystemTableTest.java | 129 ++++
.../org/apache/fluss/trino/FlussConfigTest.java | 126 ++++
.../fluss/trino/FlussConnectorFactoryTest.java | 155 +++++
.../org/apache/fluss/trino/FlussConnectorTest.java | 82 +++
.../fluss/trino/FlussKvScannerLifecycleITCase.java | 380 +++++++++++
.../apache/fluss/trino/FlussKvSplitReaderTest.java | 81 +++
.../org/apache/fluss/trino/FlussLogRangeTest.java | 50 ++
.../org/apache/fluss/trino/FlussLogReadITCase.java | 713 +++++++++++++++++++++
.../fluss/trino/FlussLogSplitReaderTest.java | 192 ++++++
.../fluss/trino/FlussMetadataAccessTest.java | 312 +++++++++
.../org/apache/fluss/trino/FlussMetadataTest.java | 358 +++++++++++
.../fluss/trino/FlussPageSourceProviderTest.java | 60 ++
.../apache/fluss/trino/FlussPageSourceTest.java | 616 ++++++++++++++++++
.../org/apache/fluss/trino/FlussPluginTest.java | 35 +
.../fluss/trino/FlussPrimaryKeyReadITCase.java | 699 ++++++++++++++++++++
.../org/apache/fluss/trino/FlussQueryRunner.java | 261 ++++++++
.../apache/fluss/trino/FlussRowDecoderTest.java | 404 ++++++++++++
.../apache/fluss/trino/FlussSplitManagerTest.java | 642 +++++++++++++++++++
.../org/apache/fluss/trino/FlussSplitTest.java | 98 +++
.../apache/fluss/trino/FlussTableHandleTest.java | 74 +++
.../fluss/trino/FlussTablePropertiesTest.java | 103 +++
.../fluss/trino/FlussTableScanValidatorTest.java | 122 ++++
.../apache/fluss/trino/FlussTypeConverterTest.java | 124 ++++
.../apache/fluss/trino/TestingFlussMetadata.java | 60 ++
.../apache/fluss/trino/TestingKvScanControl.java | 136 ++++
tools/maven/checkstyle.xml | 8 +
68 files changed, 11836 insertions(+)
diff --git a/.github/workflows/ci-trino.yaml b/.github/workflows/ci-trino.yaml
new file mode 100644
index 0000000000..eeec81d6cf
--- /dev/null
+++ b/.github/workflows/ci-trino.yaml
@@ -0,0 +1,94 @@
+################################################################################
+# 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.
+################################################################################
+
+name: Trino Connector CI
+
+permissions:
+ contents: read
+
+on:
+ push:
+ branches:
+ - main
+ - release-**
+ paths:
+ - 'fluss-trino/**'
+ - 'fluss-client/**'
+ - 'fluss-common/**'
+ - 'fluss-rpc/**'
+ - 'fluss-server/**'
+ - 'fluss-test-utils/**'
+ - 'fluss-metrics/**'
+ - 'fluss-protogen/**'
+ - 'pom.xml'
+ - '.mvn/**'
+ - 'mvnw'
+ - 'tools/maven/**'
+ - '.github/workflows/ci-trino.yaml'
+
+ pull_request:
+ paths:
+ - 'fluss-trino/**'
+ - 'fluss-client/**'
+ - 'fluss-common/**'
+ - 'fluss-rpc/**'
+ - 'fluss-server/**'
+ - 'fluss-test-utils/**'
+ - 'fluss-metrics/**'
+ - 'fluss-protogen/**'
+ - 'pom.xml'
+ - '.mvn/**'
+ - 'mvnw'
+ - 'tools/maven/**'
+ - '.github/workflows/ci-trino.yaml'
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.number || github.run_id }}
+ cancel-in-progress: true
+
+jobs:
+ build:
+ name: "Trino Connector"
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Set up JDK 17
+ uses: actions/setup-java@v5
+ with:
+ distribution: 'temurin'
+ java-version: '17'
+ cache: 'maven'
+
+ - name: Install Fluss dependencies
+ run: >-
+ ./mvnw -B --no-transfer-progress
+ -pl fluss-client,fluss-server,fluss-test-utils
+ -am install -DskipTests
+
+ - name: Set up JDK 25
+ uses: actions/setup-java@v5
+ with:
+ distribution: 'temurin'
+ java-version: '25'
+
+ - name: Build and verify Trino connector
+ working-directory: fluss-trino
+ run: ./mvnw -B --no-transfer-progress clean verify
diff --git a/fluss-trino/.mvn/wrapper/maven-wrapper.properties b/fluss-trino/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000000..216df05897
--- /dev/null
+++ b/fluss-trino/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,3 @@
+wrapperVersion=3.3.4
+distributionType=only-script
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
diff --git a/fluss-trino/README.md b/fluss-trino/README.md
new file mode 100644
index 0000000000..a3934ff941
--- /dev/null
+++ b/fluss-trino/README.md
@@ -0,0 +1,213 @@
+<!--
+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.
+-->
+
+# Fluss Trino connector
+
+This read-only connector targets **Trino 483 and JDK 25**. It is built as a
+standalone Maven module. Source conventions follow Fluss, including Java 8 syntax
+and collection idioms; the resulting plugin requires JDK 25 and is not a Java 8
+binary.
+
+## Supported operations
+
+| Capability | Support |
+| --- | --- |
+| Database, table and column discovery | Supported |
+| `DESCRIBE`, `SHOW CREATE TABLE`, `"table$columns"` | Supported |
+| Non-partitioned and partitioned Log Table reads | Supported, with bounded offset ranges |
+| Non-partitioned and partitioned Primary Key Table reads | Supported, using bucket snapshots |
+| Lakehouse table reads | Not supported; metadata remains available |
+| Writes, DDL, lookup and Union Read | Not supported |
+| Predicate, aggregation, limit and partition pruning pushdown | Not implemented |
+| Task retries / fault-tolerant execution | Not supported |
+| SASL authentication on JDK 25 | Not supported; configuration properties are retained |
+
+Ordinary `SELECT`, column selection and ordering, `COUNT(*)`, `WHERE`, `ORDER BY`
+and `LIMIT` use Trino's execution engine. Filters and other operations without
+pushdown are evaluated by Trino. Partitioned scans enumerate physical buckets;
+a partition predicate does not currently avoid scanning other partitions.
+
+Trino-visible database and table names are normalized to lowercase. When multiple
+Fluss names differ only by case, resolving the ambiguous name fails rather than
+arbitrarily choosing a physical table. Case-colliding column names are rejected.
+
+Supported values include BOOLEAN, integer types, FLOAT/DOUBLE, CHAR/STRING,
+BINARY/BYTES, DECIMAL, DATE/TIME, TIMESTAMP, TIMESTAMP_LTZ, and recursively
+ARRAY/MAP/ROW, subject to Trino's map-key type constraints. Decimal conversion
+preserves decimal precision. TIMESTAMP_LTZ preserves the instant using UTC;
+TIMESTAMP has no timezone conversion. Fluss TIME values contain milliseconds of
+the day, even when their schema declares a higher precision. Null map keys and
+keys that become duplicates under Trino semantics are rejected.
+
+## Build
+
+First install the matching Fluss dependencies from the repository root using
+JDK 17, as in the connector CI workflow:
+
+```sh
+JAVA_HOME=/path/to/jdk-17 ./mvnw -B \
+ -pl fluss-client,fluss-server,fluss-test-utils -am install -DskipTests
+```
+
+The standalone connector build does not build sibling modules automatically.
+This step installs the current checkout's Fluss artifacts and test JARs into the
+local Maven repository. It is required in a fresh environment.
+
+Then build the connector with its own Maven wrapper and JDK 25:
+
+```sh
+cd fluss-trino
+JAVA_HOME=/path/to/jdk-25 ./mvnw clean package -DskipTests
+```
+
+## Install and configure
+
+Copy the contents of the assembled `target/fluss-trino-<version>/` directory,
+including its dependency JARs, into a dedicated `plugin/fluss/` directory on every
+Trino coordinator and worker. Use the assembled plugin, not just the connector
+JAR, and deploy the same version on all nodes.
+
+Create `etc/catalog/fluss.properties` on the Trino nodes:
+
+```properties
+connector.name=fluss
+bootstrap.servers=localhost:9123
+```
+
+Replace the bootstrap address with Fluss endpoints reachable from every Trino
+node. The current connector supports only unauthenticated `PLAINTEXT` connections.
+
+### SASL limitation on JDK 25
+
+**SASL authentication is currently unsupported.** The Fluss client's SASL callback
+uses `Subject.getSubject()`, which is unsupported on JDK 25. A separate Fluss
+client compatibility fix is planned.
+
+The properties `client.security.protocol`, `client.security.sasl.mechanism`,
+`client.security.sasl.username`, and `client.security.sasl.password` remain
+recognized configuration keys for future compatibility. Retaining them does not
+enable authentication: catalog creation fails with a configuration error if a
+protocol other than `PLAINTEXT`, or any SASL property, is configured. Leave SASL
+properties unset, even when explicitly selecting `PLAINTEXT`.
+
+Unsupported authentication configurations are rejected during catalog creation,
+while the Fluss connection itself remains lazily initialized. This allows the
+catalog to be created without requiring a running Fluss cluster.
+
+Upgrading the Fluss client alone will not enable SASL support. The connector's
+explicit restriction must also be removed once compatibility has been verified.
+
+The Arrow JVM option below does not resolve the SASL incompatibility.
+
+### Required JVM option for Arrow reads
+
+Add this line to **Trino's `etc/jvm.config` on every coordinator and worker**:
+
+```text
+--add-opens=java.base/java.nio=ALL-UNNAMED
+```
+
+Fluss uses Arrow for Arrow-backed data reads. On JDK 25, Arrow needs reflective
+access to `java.nio` internals; without this option, data reads can fail even when
+metadata queries work. Applying it to all nodes also covers coordinators that
+execute queries. Restart the Trino processes after updating their JVM settings.
+
+This is a **server JVM option**, not a catalog property or a Trino CLI option.
+Setting it only in Maven, an IDE test runner, or the CLI does not configure the
+Trino server. If your deployment manages JVM arguments outside `etc/jvm.config`,
+add it to the equivalent server JVM configuration.
+
+Retain the other JVM options required by your Trino 483 distribution. The
+connector's integration-test JVM uses the following options in its POM:
+
+```text
+--add-modules=jdk.incubator.vector
+--enable-native-access=ALL-UNNAMED
+--add-opens=java.base/java.nio=ALL-UNNAMED
+```
+
+These test options are not a complete replacement for Trino's server JVM
+configuration, and Maven does not install them into the server configuration.
+
+### Example queries
+
+For an existing Fluss database `trino_test` and table `users`:
+
+```sql
+SHOW SCHEMAS FROM fluss;
+SHOW TABLES FROM fluss.trino_test;
+DESCRIBE fluss.trino_test.users;
+SHOW CREATE TABLE fluss.trino_test.users;
+SELECT * FROM fluss.trino_test."users$columns";
+SELECT * FROM fluss.trino_test.users LIMIT 10;
+SELECT count(*) FROM fluss.trino_test.users;
+```
+
+The catalog name `fluss` comes from the catalog properties filename.
+`SHOW CREATE TABLE` describes the existing table; it does not imply that the
+connector supports executing `CREATE TABLE`.
+
+## Read semantics
+
+### Log Tables
+
+For non-partitioned tables, planning performs two sequential bulk Admin API
+lookups: earliest offsets, then latest offsets, each covering the selected
+buckets. For partitioned tables, each phase issues one bulk lookup per selected
+partition, covering that partition's buckets. The client may distribute these
+API calls across multiple network RPCs.
+
+Each nonempty bucket becomes a split with a fixed `[startOffset, stoppingOffset)`
+range. These are per-bucket boundaries, not a global transactional snapshot.
+Records appended beyond a split's stopping offset do not extend the query.
+
+An empty poll is not EOF. The reader uses records and consumed-offset progress to
+detect completion, including progress without rows. An expired start offset fails
+instead of silently resetting to a later offset. Records below the planned start
+are treated as an invariant failure; records at or beyond the stop are discarded.
+
+### Primary Key Tables
+
+Planning creates one KV split per physical bucket, without offset or statistics
+lookups. Each worker uses a single-bucket BatchScanner to read the live rows in
+that bucket's snapshot. Updates and deletes are reflected as of that snapshot.
+
+A snapshot opens when the server processes its initial scan request, not when
+Trino plans the query. Different buckets can open at different times, so a query
+does not provide a globally consistent snapshot across buckets or partitions.
+
+An empty batch yields; only a null batch means EOF. Unconsumed rows remain in the
+current iterator across page requests. The connector does not reopen a failed
+scanner and combine rows from different snapshots. Limited open retries belong
+to the Fluss client; continuation failures fail the query.
+
+Remote scanner closure is best effort. A lost open response or failed close RPC
+can leave a server session until its idle TTL expires. A slow consumer can also
+exceed the session TTL; the connector does not add keepalive requests.
+
+### Resource ownership and cancellation
+
+Workers validate table identity, schema identity and split compatibility before
+reading. Each PageSource owns its Table and reader; each reader owns its scanner
+and buffered batch. The connector owns the shared Connection and Admin client.
+
+Reads are synchronous. Each page request makes at most one scanner poll with a
+100 ms timeout argument. That argument does not bound initialization, metadata
+RPCs or all client retry behavior. Reads occupy a Trino driver thread;
+cancellation relies on Trino's serialized PageSource close contract and the
+underlying calls returning. Cancellation within 100 ms is not guaranteed.
diff --git a/fluss-trino/mvnw b/fluss-trino/mvnw
new file mode 100755
index 0000000000..bd8896bf22
--- /dev/null
+++ b/fluss-trino/mvnw
@@ -0,0 +1,295 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# 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.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Apache Maven Wrapper startup batch script, version 3.3.4
+#
+# Optional ENV vars
+# -----------------
+# JAVA_HOME - location of a JDK home dir, required when download maven via java source
+# MVNW_REPOURL - repo url base for downloading maven distribution
+# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
+# ----------------------------------------------------------------------------
+
+set -euf
+[ "${MVNW_VERBOSE-}" != debug ] || set -x
+
+# OS specific support.
+native_path() { printf %s\\n "$1"; }
+case "$(uname)" in
+CYGWIN* | MINGW*)
+ [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
+ native_path() { cygpath --path --windows "$1"; }
+ ;;
+esac
+
+# set JAVACMD and JAVACCMD
+set_java_home() {
+ # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
+ if [ -n "${JAVA_HOME-}" ]; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ]; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ JAVACCMD="$JAVA_HOME/jre/sh/javac"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ JAVACCMD="$JAVA_HOME/bin/javac"
+
+ if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
+ echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
+ echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
+ return 1
+ fi
+ fi
+ else
+ JAVACMD="$(
+ 'set' +e
+ 'unset' -f command 2>/dev/null
+ 'command' -v java
+ )" || :
+ JAVACCMD="$(
+ 'set' +e
+ 'unset' -f command 2>/dev/null
+ 'command' -v javac
+ )" || :
+
+ if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
+ echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
+ return 1
+ fi
+ fi
+}
+
+# hash string like Java String::hashCode
+hash_string() {
+ str="${1:-}" h=0
+ while [ -n "$str" ]; do
+ char="${str%"${str#?}"}"
+ h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
+ str="${str#?}"
+ done
+ printf %x\\n $h
+}
+
+verbose() { :; }
+[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
+
+die() {
+ printf %s\\n "$1" >&2
+ exit 1
+}
+
+trim() {
+ # MWRAPPER-139:
+ # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
+ # Needed for removing poorly interpreted newline sequences when running in more
+ # exotic environments such as mingw bash on Windows.
+ printf "%s" "${1}" | tr -d '[:space:]'
+}
+
+scriptDir="$(dirname "$0")"
+scriptName="$(basename "$0")"
+
+# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
+while IFS="=" read -r key value; do
+ case "${key-}" in
+ distributionUrl) distributionUrl=$(trim "${value-}") ;;
+ distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
+ esac
+done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
+[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+
+case "${distributionUrl##*/}" in
+maven-mvnd-*bin.*)
+ MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
+ case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
+ *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
+ :Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
+ :Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
+ :Linux*x86_64*) distributionPlatform=linux-amd64 ;;
+ *)
+ echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
+ distributionPlatform=linux-amd64
+ ;;
+ esac
+ distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
+ ;;
+maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
+*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
+esac
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
+[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
+distributionUrlName="${distributionUrl##*/}"
+distributionUrlNameMain="${distributionUrlName%.*}"
+distributionUrlNameMain="${distributionUrlNameMain%-bin}"
+MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
+MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
+
+exec_maven() {
+ unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
+ exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
+}
+
+if [ -d "$MAVEN_HOME" ]; then
+ verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+ exec_maven "$@"
+fi
+
+case "${distributionUrl-}" in
+*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
+*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
+esac
+
+# prepare tmp dir
+if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
+ clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
+ trap clean HUP INT TERM EXIT
+else
+ die "cannot create temp dir"
+fi
+
+mkdir -p -- "${MAVEN_HOME%/*}"
+
+# Download and Install Apache Maven
+verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+verbose "Downloading from: $distributionUrl"
+verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+# select .zip or .tar.gz
+if ! command -v unzip >/dev/null; then
+ distributionUrl="${distributionUrl%.zip}.tar.gz"
+ distributionUrlName="${distributionUrl##*/}"
+fi
+
+# verbose opt
+__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
+[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
+
+# normalize http auth
+case "${MVNW_PASSWORD:+has-password}" in
+'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+esac
+
+if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
+ verbose "Found wget ... using wget"
+ wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
+elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
+ verbose "Found curl ... using curl"
+ curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
+elif set_java_home; then
+ verbose "Falling back to use Java to download"
+ javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
+ targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
+ cat >"$javaSource" <<-END
+ public class Downloader extends java.net.Authenticator
+ {
+ protected java.net.PasswordAuthentication getPasswordAuthentication()
+ {
+ return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
+ }
+ public static void main( String[] args ) throws Exception
+ {
+ setDefault( new Downloader() );
+ java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
+ }
+ }
+ END
+ # For Cygwin/MinGW, switch paths to Windows format before running javac and java
+ verbose " - Compiling Downloader.java ..."
+ "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
+ verbose " - Running Downloader.java ..."
+ "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
+fi
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+if [ -n "${distributionSha256Sum-}" ]; then
+ distributionSha256Result=false
+ if [ "$MVN_CMD" = mvnd.sh ]; then
+ echo "Checksum validation is not supported for maven-mvnd." >&2
+ echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+ exit 1
+ elif command -v sha256sum >/dev/null; then
+ if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
+ distributionSha256Result=true
+ fi
+ elif command -v shasum >/dev/null; then
+ if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
+ distributionSha256Result=true
+ fi
+ else
+ echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
+ echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+ exit 1
+ fi
+ if [ $distributionSha256Result = false ]; then
+ echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
+ echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
+ exit 1
+ fi
+fi
+
+# unzip and move
+if command -v unzip >/dev/null; then
+ unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
+else
+ tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
+fi
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+actualDistributionDir=""
+
+# First try the expected directory name (for regular distributions)
+if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
+ if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
+ actualDistributionDir="$distributionUrlNameMain"
+ fi
+fi
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if [ -z "$actualDistributionDir" ]; then
+ # enable globbing to iterate over items
+ set +f
+ for dir in "$TMP_DOWNLOAD_DIR"/*; do
+ if [ -d "$dir" ]; then
+ if [ -f "$dir/bin/$MVN_CMD" ]; then
+ actualDistributionDir="$(basename "$dir")"
+ break
+ fi
+ fi
+ done
+ set -f
+fi
+
+if [ -z "$actualDistributionDir" ]; then
+ verbose "Contents of $TMP_DOWNLOAD_DIR:"
+ verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
+ die "Could not find Maven distribution directory in extracted archive"
+fi
+
+verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
+mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
+
+clean || :
+exec_maven "$@"
diff --git a/fluss-trino/mvnw.cmd b/fluss-trino/mvnw.cmd
new file mode 100644
index 0000000000..5761d94892
--- /dev/null
+++ b/fluss-trino/mvnw.cmd
@@ -0,0 +1,189 @@
+<# : batch portion
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM http://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Apache Maven Wrapper startup batch script, version 3.3.4
+@REM
+@REM Optional ENV vars
+@REM MVNW_REPOURL - repo url base for downloading maven distribution
+@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
+@REM ----------------------------------------------------------------------------
+
+@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
+@SET __MVNW_CMD__=
+@SET __MVNW_ERROR__=
+@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
+@SET PSModulePath=
+@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
+ IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
+)
+@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
+@SET __MVNW_PSMODULEP_SAVE=
+@SET __MVNW_ARG0_NAME__=
+@SET MVNW_USERNAME=
+@SET MVNW_PASSWORD=
+@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
+@echo Cannot start maven from wrapper >&2 && exit /b 1
+@GOTO :EOF
+: end batch / begin powershell #>
+
+$ErrorActionPreference = "Stop"
+if ($env:MVNW_VERBOSE -eq "true") {
+ $VerbosePreference = "Continue"
+}
+
+# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
+$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
+if (!$distributionUrl) {
+ Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+}
+
+switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
+ "maven-mvnd-*" {
+ $USE_MVND = $true
+ $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
+ $MVN_CMD = "mvnd.cmd"
+ break
+ }
+ default {
+ $USE_MVND = $false
+ $MVN_CMD = $script -replace '^mvnw','mvn'
+ break
+ }
+}
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
+if ($env:MVNW_REPOURL) {
+ $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
+ $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
+}
+$distributionUrlName = $distributionUrl -replace '^.*/',''
+$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
+
+$MAVEN_M2_PATH = "$HOME/.m2"
+if ($env:MAVEN_USER_HOME) {
+ $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
+}
+
+if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
+ New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
+}
+
+$MAVEN_WRAPPER_DISTS = $null
+if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
+ $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
+} else {
+ $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
+}
+
+$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
+$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
+$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
+
+if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
+ Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+ Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+ exit $?
+}
+
+if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
+ Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
+}
+
+# prepare tmp dir
+$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
+$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
+$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
+trap {
+ if ($TMP_DOWNLOAD_DIR.Exists) {
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+ }
+}
+
+New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
+
+# Download and Install Apache Maven
+Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+Write-Verbose "Downloading from: $distributionUrl"
+Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+$webclient = New-Object System.Net.WebClient
+if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
+ $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
+}
+[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
+if ($distributionSha256Sum) {
+ if ($USE_MVND) {
+ Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
+ }
+ Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
+ if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
+ Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
+ }
+}
+
+# unzip and move
+Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+$actualDistributionDir = ""
+
+# First try the expected directory name (for regular distributions)
+$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
+$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
+if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
+ $actualDistributionDir = $distributionUrlNameMain
+}
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if (!$actualDistributionDir) {
+ Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
+ $testPath = Join-Path $_.FullName "bin/$MVN_CMD"
+ if (Test-Path -Path $testPath -PathType Leaf) {
+ $actualDistributionDir = $_.Name
+ }
+ }
+}
+
+if (!$actualDistributionDir) {
+ Write-Error "Could not find Maven distribution directory in extracted archive"
+}
+
+Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
+try {
+ Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
+} catch {
+ if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
+ Write-Error "fail to move MAVEN_HOME"
+ }
+} finally {
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+}
+
+Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
diff --git a/fluss-trino/pom.xml b/fluss-trino/pom.xml
new file mode 100644
index 0000000000..b974012394
--- /dev/null
+++ b/fluss-trino/pom.xml
@@ -0,0 +1,365 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>org.apache.fluss</groupId>
+ <artifactId>fluss-trino</artifactId>
+ <version>1.1-SNAPSHOT</version>
+
+ <name>Apache Fluss : Trino</name>
+ <packaging>trino-plugin</packaging>
+ <description>Trino connector for Apache Fluss</description>
+
+ <properties>
+ <!-- Build -->
+ <maven.compiler.release>25</maven.compiler.release>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+
+ <!-- Runtime dependencies -->
+ <trino.version>483</trino.version>
+ <dep.airlift.version>439</dep.airlift.version>
+ <dep.slice.version>2.8</dep.slice.version>
+ <dep.opentelemetry.version>1.63.0</dep.opentelemetry.version>
+ <jackson.version>2.22</jackson.version>
+
+ <!-- Test dependencies -->
+ <!-- Match the Jupiter/Platform API used by Trino 483 testing. -->
+ <junit.version>6.1.2</junit.version>
+ <curator.version>5.4.0</curator.version>
+ <assertj.version>3.27.7</assertj.version>
+ <mockito.version>5.20.0</mockito.version>
+
+ <!-- Build plugins and tools -->
+ <trino.maven.plugin.version>20</trino.maven.plugin.version>
+ <maven.enforcer.plugin.version>3.6.1</maven.enforcer.plugin.version>
+ <maven.checkstyle.plugin.version>3.6.0</maven.checkstyle.plugin.version>
+ <checkstyle.version>9.3</checkstyle.version>
+ <spotless.version>2.27.1</spotless.version>
+ <!-- google-java-format 1.15.0 used by the root build is incompatible with JDK 25. -->
+ <google.java.format.version>1.34.0</google.java.format.version>
+ <apache.rat.plugin.version>0.16.1</apache.rat.plugin.version>
+ <maven.compiler.plugin.version>3.15.0</maven.compiler.plugin.version>
+ <maven.surefire.plugin.version>3.5.6</maven.surefire.plugin.version>
+ </properties>
+
+ <dependencies>
+ <!-- Connector implementation -->
+ <dependency>
+ <groupId>org.apache.fluss</groupId>
+ <artifactId>fluss-client</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>io.trino</groupId>
+ <artifactId>trino-plugin-toolkit</artifactId>
+ <version>${trino.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>io.airlift</groupId>
+ <artifactId>bootstrap</artifactId>
+ <version>${dep.airlift.version}</version>
+ </dependency>
+
+ <!-- Dependencies provided by Trino -->
+ <dependency>
+ <groupId>io.trino</groupId>
+ <artifactId>trino-spi</artifactId>
+ <version>${trino.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
+ <version>${jackson.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>io.airlift</groupId>
+ <artifactId>slice</artifactId>
+ <version>${dep.slice.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>io.opentelemetry</groupId>
+ <artifactId>opentelemetry-api</artifactId>
+ <version>${dep.opentelemetry.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>io.opentelemetry</groupId>
+ <artifactId>opentelemetry-context</artifactId>
+ <version>${dep.opentelemetry.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- Test dependencies (Trino, Fluss and Curator: Apache License 2.0). -->
+ <dependency>
+ <groupId>io.trino</groupId>
+ <artifactId>trino-testing</artifactId>
+ <version>${trino.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.fluss</groupId>
+ <artifactId>fluss-server</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.fluss</groupId>
+ <artifactId>fluss-server</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.fluss</groupId>
+ <artifactId>fluss-test-utils</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.fluss</groupId>
+ <artifactId>fluss-common</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.fluss</groupId>
+ <artifactId>fluss-rpc</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-test</artifactId>
+ <version>${curator.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>io.airlift</groupId>
+ <artifactId>json</artifactId>
+ <version>${dep.airlift.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>io.airlift</groupId>
+ <artifactId>configuration-testing</artifactId>
+ <version>${dep.airlift.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>${mockito.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <version>${junit.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <version>${assertj.version}</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>io.trino</groupId>
+ <artifactId>trino-maven-plugin</artifactId>
+ <version>${trino.maven.plugin.version}</version>
+ <extensions>true</extensions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-enforcer-plugin</artifactId>
+ <version>${maven.enforcer.plugin.version}</version>
+ <executions>
+ <execution>
+ <id>enforce-build-environment</id>
+ <goals>
+ <goal>enforce</goal>
+ </goals>
+ <configuration>
+ <rules>
+ <requireJavaVersion>
+ <version>[25,26)</version>
+ </requireJavaVersion>
+ <requireMavenVersion>
+ <version>[3.9.16,4.0.0)</version>
+ </requireMavenVersion>
+ </rules>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>${maven.checkstyle.plugin.version}</version>
+ <dependencies>
+ <dependency>
+ <groupId>com.puppycrawl.tools</groupId>
+ <artifactId>checkstyle</artifactId>
+ <version>${checkstyle.version}</version>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <configLocation>
+ ${project.basedir}/../tools/maven/checkstyle.xml
+ </configLocation>
+ <suppressionsLocation>
+ ${project.basedir}/../tools/maven/suppressions.xml
+ </suppressionsLocation>
+ <includeTestSourceDirectory>true</includeTestSourceDirectory>
+ <failOnViolation>true</failOnViolation>
+ </configuration>
+ <executions>
+ <execution>
+ <id>checkstyle</id>
+ <phase>validate</phase>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>com.diffplug.spotless</groupId>
+ <artifactId>spotless-maven-plugin</artifactId>
+ <version>${spotless.version}</version>
+ <configuration>
+ <java>
+ <googleJavaFormat>
+ <version>${google.java.format.version}</version>
+ <style>AOSP</style>
+ </googleJavaFormat>
+ <importOrder>
+ <order>org.apache.fluss,,javax,java,scala,\#</order>
+ </importOrder>
+ <removeUnusedImports/>
+ </java>
+ </configuration>
+ <executions>
+ <execution>
+ <id>spotless-check</id>
+ <phase>validate</phase>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.rat</groupId>
+ <artifactId>apache-rat-plugin</artifactId>
+ <version>${apache.rat.plugin.version}</version>
+ <configuration>
+ <consoleOutput>true</consoleOutput>
+ <numUnapprovedLicenses>0</numUnapprovedLicenses>
+ <excludes>
+ <exclude>**/.*/**</exclude>
+ <exclude>**/target/**</exclude>
+ <exclude>**/*.iml</exclude>
+ </excludes>
+ </configuration>
+ <executions>
+ <execution>
+ <id>rat-check</id>
+ <phase>validate</phase>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>${maven.compiler.plugin.version}</version>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>${maven.surefire.plugin.version}</version>
+ <configuration>
+ <!-- Explicit instrumentation avoids dynamic agent attachment -->
+ <argLine>-javaagent:"${settings.localRepository}/org/mockito/mockito-core/${mockito.version}/mockito-core-${mockito.version}.jar"</argLine>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-failsafe-plugin</artifactId>
+ <version>${maven.surefire.plugin.version}</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>integration-test</goal>
+ <goal>verify</goal>
+ </goals>
+ </execution>
+ </executions>
+ <configuration>
+ <argLine>--add-modules=jdk.incubator.vector --enable-native-access=ALL-UNNAMED --add-opens=java.base/java.nio=ALL-UNNAMED</argLine>
+ <systemPropertyVariables>
+ <junit.jupiter.execution.timeout.default>2 m</junit.jupiter.execution.timeout.default>
+ </systemPropertyVariables>
+ <includes>
+ <include>**/*ITCase.java</include>
+ </includes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussBucketHandle.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussBucketHandle.java
new file mode 100644
index 0000000000..5d0287d7fe
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussBucketHandle.java
@@ -0,0 +1,124 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.metadata.TableBucket;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.Objects;
+import java.util.Optional;
+
+import static io.airlift.slice.SizeOf.LONG_INSTANCE_SIZE;
+import static io.airlift.slice.SizeOf.instanceSize;
+import static io.airlift.slice.SizeOf.sizeOf;
+import static org.apache.fluss.utils.Preconditions.checkArgument;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Immutable Fluss bucket handle. */
+public final class FlussBucketHandle {
+ private static final int INSTANCE_SIZE = instanceSize(FlussBucketHandle.class);
+ private final long tableId;
+ private final Optional<Long> partitionId;
+ private final int bucketId;
+
+ public FlussBucketHandle(long tableId, Optional<Long> partitionId, int bucketId) {
+ checkArgument(tableId >= 0, "tableId must be non-negative");
+ this.partitionId = checkNotNull(partitionId, "partitionId is null");
+ partitionId.ifPresent(
+ value -> checkArgument(value >= 0, "partitionId must be non-negative"));
+ checkArgument(bucketId >= 0, "bucketId must be non-negative");
+
+ this.tableId = tableId;
+ this.bucketId = bucketId;
+ }
+
+ /** Creates a bucket handle from JSON with its table and bucket IDs required. */
+ @JsonCreator
+ public static FlussBucketHandle fromJson(
+ @JsonProperty("tableId") Long tableId,
+ @JsonProperty("partitionId") Optional<Long> partitionId,
+ @JsonProperty("bucketId") Integer bucketId) {
+ checkArgument(tableId != null, "tableId is required");
+ checkArgument(bucketId != null, "bucketId is required");
+
+ return new FlussBucketHandle(tableId, partitionId, bucketId);
+ }
+
+ @JsonProperty
+ public long getTableId() {
+ return tableId;
+ }
+
+ @JsonProperty
+ public Optional<Long> getPartitionId() {
+ return partitionId;
+ }
+
+ @JsonProperty
+ public int getBucketId() {
+ return bucketId;
+ }
+
+ boolean isPartitioned() {
+ return partitionId.isPresent();
+ }
+
+ long getRequiredPartitionId() {
+ return partitionId.orElseThrow(
+ () -> new IllegalStateException("Bucket does not belong to a partition"));
+ }
+
+ TableBucket toTableBucket() {
+ return new TableBucket(tableId, partitionId.orElse(null), bucketId);
+ }
+
+ long getRetainedSizeInBytes() {
+ return INSTANCE_SIZE + sizeOf(partitionId, ignored -> LONG_INSTANCE_SIZE);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ FlussBucketHandle that = (FlussBucketHandle) o;
+ return tableId == that.tableId
+ && bucketId == that.bucketId
+ && Objects.equals(partitionId, that.partitionId);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(tableId, partitionId, bucketId);
+ }
+
+ @Override
+ public String toString() {
+ return "FlussBucketHandle{"
+ + "tableId="
+ + tableId
+ + ", partitionId="
+ + partitionId
+ + ", bucketId="
+ + bucketId
+ + '}';
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussClientManager.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussClientManager.java
new file mode 100644
index 0000000000..6a4dcde45e
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussClientManager.java
@@ -0,0 +1,155 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.Connection;
+import org.apache.fluss.client.ConnectionFactory;
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.TablePath;
+
+import com.google.inject.Inject;
+import jakarta.annotation.PreDestroy;
+
+import static org.apache.fluss.utils.ExceptionUtils.firstOrSuppressed;
+import static org.apache.fluss.utils.ExceptionUtils.rethrowException;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+import static org.apache.fluss.utils.Preconditions.checkState;
+
+/** Lazily initializes and owns the shared Fluss connection and Admin client. */
+public final class FlussClientManager {
+
+ private static final String BOOTSTRAP_SERVERS = "bootstrap.servers";
+ private static final String SECURITY_PROTOCOL = "client.security.protocol";
+
+ private final Object lock = new Object();
+ private final Configuration configuration;
+
+ // All mutable state is guarded by lock.
+ private Connection connection;
+ private Admin admin;
+ private boolean closed;
+
+ /** Captures connector configuration without connecting to Fluss. */
+ @Inject
+ public FlussClientManager(FlussConfig config) {
+ checkNotNull(config, "config is null");
+
+ this.configuration = new Configuration();
+ configuration.setString(BOOTSTRAP_SERVERS, config.getBootstrapServers());
+
+ config.getSecurityProtocol()
+ .ifPresent(value -> configuration.setString(SECURITY_PROTOCOL, value));
+ }
+
+ /** Closes initialized resources without triggering initialization. */
+ @PreDestroy
+ public void close() throws Exception {
+ Admin adminToClose;
+ Connection connectionToClose;
+
+ synchronized (lock) {
+ if (closed) {
+ return;
+ }
+
+ closed = true;
+ adminToClose = admin;
+ connectionToClose = connection;
+
+ admin = null;
+ connection = null;
+ }
+
+ Throwable failure = null;
+
+ if (adminToClose != null) {
+ try {
+ adminToClose.close();
+ } catch (Exception | Error e) {
+ failure = firstOrSuppressed(e, failure);
+ }
+ }
+
+ if (connectionToClose != null) {
+ try {
+ connectionToClose.close();
+ } catch (Exception | Error e) {
+ failure = firstOrSuppressed(e, failure);
+ }
+ }
+
+ if (failure != null) {
+ rethrowException(failure, "Failed closing Fluss client resources");
+ }
+ }
+
+ /** Returns the shared Admin client. Callers must not close it. */
+ Admin getAdmin() {
+ synchronized (lock) {
+ initializeIfNeeded();
+ return admin;
+ }
+ }
+
+ /** Opens an independently owned table that the caller must close. */
+ Table openTable(TablePath tablePath) {
+ checkNotNull(tablePath, "tablePath is null");
+
+ Connection currentConnection;
+ synchronized (lock) {
+ initializeIfNeeded();
+ currentConnection = connection;
+ }
+
+ // Opening a table issues blocking metadata RPCs; holding the lock here would block Admin
+ // callers and other splits behind them.
+ return currentConnection.getTable(tablePath);
+ }
+
+ /** Initializes both resources while holding lock. */
+ private void initializeIfNeeded() {
+ checkState(!closed, "Fluss client manager is closed");
+
+ if (connection != null) {
+ return;
+ }
+
+ Connection newConnection = null;
+
+ try {
+ newConnection = ConnectionFactory.createConnection(configuration);
+ Admin newAdmin = newConnection.getAdmin();
+
+ connection = newConnection;
+ admin = newAdmin;
+ } catch (RuntimeException | Error failure) {
+ if (newConnection != null) {
+ try {
+ newConnection.close();
+ } catch (Exception | Error closeFailure) {
+ firstOrSuppressed(closeFailure, failure);
+ }
+ }
+
+ throw failure;
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussColumnHandle.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussColumnHandle.java
new file mode 100644
index 0000000000..cefb851ffa
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussColumnHandle.java
@@ -0,0 +1,76 @@
+/*
+ * 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.fluss.trino;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.trino.spi.connector.ColumnHandle;
+
+import java.util.Objects;
+
+import static org.apache.fluss.utils.Preconditions.checkArgument;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Immutable Fluss column handle. */
+public final class FlussColumnHandle implements ColumnHandle {
+
+ private final String name;
+ private final int ordinalPosition;
+
+ @JsonCreator
+ public FlussColumnHandle(
+ @JsonProperty("name") String name,
+ @JsonProperty("ordinalPosition") int ordinalPosition) {
+ this.name = checkNotNull(name, "name is null");
+ checkArgument(ordinalPosition >= 0, "ordinalPosition must be non-negative");
+ this.ordinalPosition = ordinalPosition;
+ }
+
+ @JsonProperty
+ public String getName() {
+ return name;
+ }
+
+ @JsonProperty
+ public int getOrdinalPosition() {
+ return ordinalPosition;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!(obj instanceof FlussColumnHandle)) {
+ return false;
+ }
+ FlussColumnHandle that = (FlussColumnHandle) obj;
+ return ordinalPosition == that.ordinalPosition && name.equals(that.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, ordinalPosition);
+ }
+
+ @Override
+ public String toString() {
+ return name + ":" + ordinalPosition;
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussColumnsSystemTable.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussColumnsSystemTable.java
new file mode 100644
index 0000000000..3bb7a52468
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussColumnsSystemTable.java
@@ -0,0 +1,144 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.metadata.Schema;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList;
+
+import io.trino.spi.connector.ColumnMetadata;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.ConnectorTableMetadata;
+import io.trino.spi.connector.ConnectorTransactionHandle;
+import io.trino.spi.connector.InMemoryRecordSet;
+import io.trino.spi.connector.RecordCursor;
+import io.trino.spi.connector.SchemaTableName;
+import io.trino.spi.connector.SystemTable;
+import io.trino.spi.predicate.TupleDomain;
+import io.trino.spi.type.Type;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import static io.trino.spi.type.BigintType.BIGINT;
+import static io.trino.spi.type.BooleanType.BOOLEAN;
+import static io.trino.spi.type.VarcharType.VARCHAR;
+
+/** Coordinator-local snapshot of the columns of a Fluss table. */
+final class FlussColumnsSystemTable implements SystemTable {
+
+ static final String SUFFIX = "$columns";
+
+ private static final String COLUMN_NAME = "column_name";
+ private static final String ORDINAL_POSITION = "ordinal_position";
+ private static final String FLUSS_TYPE = "fluss_type";
+ private static final String TRINO_TYPE = "trino_type";
+ private static final String IS_NULLABLE = "is_nullable";
+ private static final String PRIMARY_KEY_POSITION = "primary_key_position";
+ private static final String PARTITION_KEY_POSITION = "partition_key_position";
+ private static final String BUCKET_KEY_POSITION = "bucket_key_position";
+ private static final String COMMENT = "comment";
+
+ private final ConnectorTableMetadata metadata;
+ private final InMemoryRecordSet records;
+
+ FlussColumnsSystemTable(SchemaTableName name, TableInfo tableInfo) {
+ metadata =
+ new ConnectorTableMetadata(
+ name,
+ ImmutableList.of(
+ requiredColumn(COLUMN_NAME, VARCHAR),
+ requiredColumn(ORDINAL_POSITION, BIGINT),
+ requiredColumn(FLUSS_TYPE, VARCHAR),
+ requiredColumn(TRINO_TYPE, VARCHAR),
+ requiredColumn(IS_NULLABLE, BOOLEAN),
+ nullableColumn(PRIMARY_KEY_POSITION, BIGINT),
+ nullableColumn(PARTITION_KEY_POSITION, BIGINT),
+ nullableColumn(BUCKET_KEY_POSITION, BIGINT),
+ nullableColumn(COMMENT, VARCHAR)));
+
+ Map<String, Long> primaryKeyPositions = positionsByColumnName(tableInfo.getPrimaryKeys());
+ Map<String, Long> partitionKeyPositions =
+ positionsByColumnName(tableInfo.getPartitionKeys());
+ Map<String, Long> bucketKeyPositions = positionsByColumnName(tableInfo.getBucketKeys());
+
+ InMemoryRecordSet.Builder builder = InMemoryRecordSet.builder(metadata);
+ List<Schema.Column> columns = tableInfo.getSchema().getColumns();
+
+ for (int i = 0; i < columns.size(); i++) {
+ Schema.Column column = columns.get(i);
+
+ builder.addRow(
+ column.getName(),
+ (long) i + 1,
+ column.getDataType().toString(),
+ FlussTypeConverter.toTrinoType(column.getDataType()).getDisplayName(),
+ column.getDataType().isNullable(),
+ primaryKeyPositions.get(column.getName()),
+ partitionKeyPositions.get(column.getName()),
+ bucketKeyPositions.get(column.getName()),
+ column.getComment().orElse(null));
+ }
+
+ records = builder.build();
+ }
+
+ @Override
+ public Distribution getDistribution() {
+ return Distribution.SINGLE_COORDINATOR;
+ }
+
+ @Override
+ public ConnectorTableMetadata getTableMetadata() {
+ return metadata;
+ }
+
+ @Override
+ public RecordCursor cursor(
+ ConnectorTransactionHandle transactionHandle,
+ ConnectorSession session,
+ TupleDomain<Integer> constraint) {
+ if (constraint.isNone()) {
+ return InMemoryRecordSet.builder(metadata).build().cursor();
+ }
+
+ // Constraint pushdown is intentionally not implemented for this small
+ // coordinator-local metadata snapshot.
+ return records.cursor();
+ }
+
+ private static ColumnMetadata requiredColumn(String name, Type type) {
+ return ColumnMetadata.builder().setName(name).setType(type).setNullable(false).build();
+ }
+
+ private static ColumnMetadata nullableColumn(String name, Type type) {
+ return ColumnMetadata.builder().setName(name).setType(type).setNullable(true).build();
+ }
+
+ private static Map<String, Long> positionsByColumnName(List<String> columnNames) {
+ Map<String, Long> positions = new LinkedHashMap<>();
+
+ for (int i = 0; i < columnNames.size(); i++) {
+ positions.put(columnNames.get(i), (long) i + 1);
+ }
+
+ return positions;
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConfig.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConfig.java
new file mode 100644
index 0000000000..172fb08874
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConfig.java
@@ -0,0 +1,113 @@
+/*
+ * 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.fluss.trino;
+
+import io.airlift.configuration.Config;
+import io.airlift.configuration.ConfigDescription;
+import io.airlift.configuration.ConfigSecuritySensitive;
+import jakarta.validation.constraints.AssertTrue;
+import jakarta.validation.constraints.NotEmpty;
+import jakarta.validation.constraints.NotNull;
+
+import java.util.Optional;
+
+/** Configuration for the Fluss connector. */
+public class FlussConfig {
+
+ private static final String PLAINTEXT = "PLAINTEXT";
+
+ private String bootstrapServers;
+ private String securityProtocol;
+ private String saslMechanism;
+ private String saslUsername;
+ private String saslPassword;
+
+ @NotEmpty
+ public String getBootstrapServers() {
+ return bootstrapServers;
+ }
+
+ @Config("bootstrap.servers")
+ @ConfigDescription("Bootstrap servers of the Fluss cluster")
+ public FlussConfig setBootstrapServers(String bootstrapServers) {
+ this.bootstrapServers = bootstrapServers;
+ return this;
+ }
+
+ @NotNull
+ public Optional<String> getSecurityProtocol() {
+ return Optional.ofNullable(securityProtocol);
+ }
+
+ @Config("client.security.protocol")
+ @ConfigDescription("Security protocol used by the Fluss client")
+ public FlussConfig setSecurityProtocol(String securityProtocol) {
+ this.securityProtocol = securityProtocol;
+ return this;
+ }
+
+ @NotNull
+ public Optional<String> getSaslMechanism() {
+ return Optional.ofNullable(saslMechanism);
+ }
+
+ @Config("client.security.sasl.mechanism")
+ @ConfigDescription("SASL mechanism used by the Fluss client")
+ public FlussConfig setSaslMechanism(String saslMechanism) {
+ this.saslMechanism = saslMechanism;
+ return this;
+ }
+
+ @NotNull
+ public Optional<String> getSaslUsername() {
+ return Optional.ofNullable(saslUsername);
+ }
+
+ @Config("client.security.sasl.username")
+ @ConfigDescription("SASL username used by the Fluss client")
+ public FlussConfig setSaslUsername(String saslUsername) {
+ this.saslUsername = saslUsername;
+ return this;
+ }
+
+ @NotNull
+ public Optional<String> getSaslPassword() {
+ return Optional.ofNullable(saslPassword);
+ }
+
+ @Config("client.security.sasl.password")
+ @ConfigDescription("SASL password used by the Fluss client")
+ @ConfigSecuritySensitive
+ public FlussConfig setSaslPassword(String saslPassword) {
+ this.saslPassword = saslPassword;
+ return this;
+ }
+
+ /** Rejects authentication settings during catalog creation until SASL is supported. */
+ @AssertTrue(
+ message =
+ "Authentication is not supported by the Fluss Trino connector; "
+ + "only PLAINTEXT connections are currently supported")
+ public boolean isPlaintextOnly() {
+ return (securityProtocol == null || PLAINTEXT.equalsIgnoreCase(securityProtocol))
+ && saslMechanism == null
+ && saslUsername == null
+ && saslPassword == null;
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConnector.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConnector.java
new file mode 100644
index 0000000000..6a473b2fe1
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConnector.java
@@ -0,0 +1,89 @@
+/*
+ * 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.fluss.trino;
+
+import com.google.inject.Inject;
+import io.airlift.bootstrap.LifeCycleManager;
+import io.trino.spi.connector.Connector;
+import io.trino.spi.connector.ConnectorMetadata;
+import io.trino.spi.connector.ConnectorPageSourceProvider;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.ConnectorSplitManager;
+import io.trino.spi.connector.ConnectorTransactionHandle;
+import io.trino.spi.session.PropertyMetadata;
+import io.trino.spi.transaction.IsolationLevel;
+
+import java.util.List;
+
+import static io.trino.spi.transaction.IsolationLevel.READ_COMMITTED;
+import static io.trino.spi.transaction.IsolationLevel.checkConnectorSupports;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Trino connector for Apache Fluss. */
+public class FlussConnector implements Connector {
+
+ private final LifeCycleManager lifeCycleManager;
+ private final ConnectorMetadata metadata;
+ private final ConnectorSplitManager splitManager;
+ private final ConnectorPageSourceProvider pageSourceProvider;
+
+ @Inject
+ public FlussConnector(
+ LifeCycleManager lifeCycleManager,
+ ConnectorMetadata metadata,
+ ConnectorSplitManager splitManager,
+ ConnectorPageSourceProvider pageSourceProvider) {
+ this.lifeCycleManager = checkNotNull(lifeCycleManager, "lifeCycleManager is null");
+ this.metadata = checkNotNull(metadata, "metadata is null");
+ this.splitManager = checkNotNull(splitManager, "splitManager is null");
+ this.pageSourceProvider = checkNotNull(pageSourceProvider, "pageSourceProvider is null");
+ }
+
+ @Override
+ public ConnectorTransactionHandle beginTransaction(
+ IsolationLevel isolationLevel, boolean readOnly, boolean autoCommit) {
+ checkConnectorSupports(READ_COMMITTED, isolationLevel);
+ return FlussTransactionHandle.INSTANCE;
+ }
+
+ @Override
+ public ConnectorMetadata getMetadata(
+ ConnectorSession session, ConnectorTransactionHandle transactionHandle) {
+ return metadata;
+ }
+
+ @Override
+ public ConnectorSplitManager getSplitManager() {
+ return splitManager;
+ }
+
+ @Override
+ public ConnectorPageSourceProvider getPageSourceProvider() {
+ return pageSourceProvider;
+ }
+
+ @Override
+ public List<PropertyMetadata<?>> getTableProperties() {
+ return FlussTableProperties.getTableProperties();
+ }
+
+ @Override
+ public void shutdown() {
+ lifeCycleManager.stop();
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConnectorFactory.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConnectorFactory.java
new file mode 100644
index 0000000000..64e7ebaa0b
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConnectorFactory.java
@@ -0,0 +1,65 @@
+/*
+ * 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.fluss.trino;
+
+import com.google.inject.Injector;
+import io.airlift.bootstrap.Bootstrap;
+import io.trino.plugin.base.ConnectorContextModule;
+import io.trino.spi.connector.Connector;
+import io.trino.spi.connector.ConnectorContext;
+import io.trino.spi.connector.ConnectorFactory;
+
+import java.util.Map;
+
+import static org.apache.fluss.trino.TrinoVersionCompatibility.verifyCompatibleVersion;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Factory for creating Fluss connectors. */
+public class FlussConnectorFactory implements ConnectorFactory {
+ @Override
+ public String getName() {
+ return "fluss";
+ }
+
+ @Override
+ public Connector create(
+ String catalogName, Map<String, String> config, ConnectorContext context) {
+ checkNotNull(catalogName, "catalogName is null");
+ checkNotNull(config, "config is null");
+ checkNotNull(context, "context is null");
+
+ verifyCompatibleVersion(context.getSpiVersion());
+
+ Bootstrap app =
+ new Bootstrap(
+ "io.trino.bootstrap.catalog." + catalogName,
+ new ConnectorContextModule(catalogName, context),
+ new FlussConnectorModule(),
+ binder ->
+ binder.bind(ClassLoader.class)
+ .toInstance(FlussConnectorFactory.class.getClassLoader()));
+
+ Injector injector =
+ app.doNotInitializeLogging()
+ .disableSystemProperties()
+ .setRequiredConfigurationProperties(config)
+ .initialize();
+
+ return injector.getInstance(FlussConnector.class);
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConnectorModule.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConnectorModule.java
new file mode 100644
index 0000000000..9a24760644
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussConnectorModule.java
@@ -0,0 +1,70 @@
+/*
+ * 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.fluss.trino;
+
+import com.google.inject.Binder;
+import com.google.inject.Scopes;
+import io.airlift.configuration.AbstractConfigurationAwareModule;
+import io.trino.plugin.base.classloader.ClassLoaderSafeConnectorMetadata;
+import io.trino.plugin.base.classloader.ClassLoaderSafeConnectorPageSourceProvider;
+import io.trino.plugin.base.classloader.ClassLoaderSafeConnectorSplitManager;
+import io.trino.plugin.base.classloader.ForClassLoaderSafe;
+import io.trino.spi.connector.ConnectorMetadata;
+import io.trino.spi.connector.ConnectorPageSourceProvider;
+import io.trino.spi.connector.ConnectorSplitManager;
+
+import static io.airlift.configuration.ConfigBinder.configBinder;
+
+/** Guice bindings for the Fluss connector. */
+public class FlussConnectorModule extends AbstractConfigurationAwareModule {
+
+ @Override
+ public void setup(Binder binder) {
+ configBinder(binder).bindConfig(FlussConfig.class);
+
+ binder.bind(FlussConnector.class).in(Scopes.SINGLETON);
+ binder.bind(FlussClientManager.class).in(Scopes.SINGLETON);
+ binder.bind(ConnectorPageSourceProvider.class)
+ .annotatedWith(ForClassLoaderSafe.class)
+ .to(FlussPageSourceProvider.class)
+ .in(Scopes.SINGLETON);
+ binder.bind(ConnectorPageSourceProvider.class)
+ .to(ClassLoaderSafeConnectorPageSourceProvider.class)
+ .in(Scopes.SINGLETON);
+
+ binder.bind(FlussMetadataAccess.class).in(Scopes.SINGLETON);
+
+ binder.bind(ConnectorMetadata.class)
+ .annotatedWith(ForClassLoaderSafe.class)
+ .to(FlussMetadata.class)
+ .in(Scopes.SINGLETON);
+ binder.bind(ConnectorMetadata.class)
+ .to(ClassLoaderSafeConnectorMetadata.class)
+ .in(Scopes.SINGLETON);
+
+ binder.bind(ConnectorSplitManager.class)
+ .annotatedWith(ForClassLoaderSafe.class)
+ .to(FlussSplitManager.class)
+ .in(Scopes.SINGLETON);
+ binder.bind(ConnectorSplitManager.class)
+ .to(ClassLoaderSafeConnectorSplitManager.class)
+ .in(Scopes.SINGLETON);
+
+ binder.bind(FlussSplitPlanner.class).in(Scopes.SINGLETON);
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussErrorCode.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussErrorCode.java
new file mode 100644
index 0000000000..dcc93516ef
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussErrorCode.java
@@ -0,0 +1,46 @@
+/*
+ * 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.fluss.trino;
+
+import io.trino.spi.ErrorCode;
+import io.trino.spi.ErrorCodeSupplier;
+import io.trino.spi.ErrorType;
+
+import static io.trino.spi.ErrorType.EXTERNAL;
+
+/** Error codes reported by the Fluss connector. */
+enum FlussErrorCode implements ErrorCodeSupplier {
+ FLUSS_METADATA_ERROR(1, EXTERNAL),
+ FLUSS_SPLIT_ERROR(2, EXTERNAL),
+ FLUSS_READ_ERROR(3, EXTERNAL),
+ FLUSS_METADATA_CHANGED(4, EXTERNAL);
+
+ private static final int ERROR_CODE_BASE = 0x7F00_0000;
+
+ private final ErrorCode errorCode;
+
+ FlussErrorCode(int code, ErrorType type) {
+ errorCode = new ErrorCode(ERROR_CODE_BASE + code, name(), type);
+ }
+
+ @Override
+ public ErrorCode toErrorCode() {
+ return errorCode;
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussKvSplitReader.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussKvSplitReader.java
new file mode 100644
index 0000000000..2be55f45a2
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussKvSplitReader.java
@@ -0,0 +1,172 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.client.table.scanner.batch.BatchScanner;
+import org.apache.fluss.row.InternalRow;
+import org.apache.fluss.utils.CloseableIterator;
+
+import io.trino.spi.TrinoException;
+
+import java.io.IOException;
+import java.time.Duration;
+
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_READ_ERROR;
+import static org.apache.fluss.utils.ExceptionUtils.firstOrSuppressed;
+import static org.apache.fluss.utils.ExceptionUtils.rethrowException;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/**
+ * Bounded current-state reader for one primary-key table bucket.
+ *
+ * <p>The Fluss batch scanner establishes a bucket snapshot lazily. An empty batch yields to Trino,
+ * while a null batch marks the end of the snapshot.
+ */
+final class FlussKvSplitReader implements FlussSplitReader {
+
+ private final FlussBucketHandle bucket;
+ private final BatchScanner scanner;
+
+ private CloseableIterator<InternalRow> records;
+
+ private boolean finished;
+ private boolean closed;
+
+ FlussKvSplitReader(Table table, FlussBucketHandle bucket) {
+ checkNotNull(table, "table is null");
+ this.bucket = checkNotNull(bucket, "bucket is null");
+ scanner = table.newScan().createBatchScanner(bucket.toTableBucket());
+ }
+
+ @Override
+ public PollResult poll(Duration timeout) {
+ checkNotNull(timeout, "timeout is null");
+
+ if (closed || finished) {
+ return PollResult.FINISHED;
+ }
+
+ if (records != null) {
+ throw new IllegalStateException(
+ "Cannot poll Fluss KV scanner while the current batch is not consumed");
+ }
+
+ try {
+ records = scanner.pollBatch(timeout);
+ } catch (IOException e) {
+ throw new TrinoException(
+ FLUSS_READ_ERROR, "Failed reading Fluss KV snapshot for " + bucket, e);
+ }
+
+ if (records == null) {
+ finished = true;
+ return PollResult.FINISHED;
+ }
+
+ if (!records.hasNext()) {
+ closeBatch();
+ return PollResult.YIELD;
+ }
+
+ return PollResult.AVAILABLE;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return records != null;
+ }
+
+ @Override
+ public InternalRow next() {
+ if (records == null) {
+ throw new IllegalStateException("No buffered Fluss KV row");
+ }
+
+ InternalRow row = records.next();
+
+ // Keep records non-null iff another row can be consumed without polling.
+ if (!records.hasNext()) {
+ closeBatch();
+ }
+
+ return row;
+ }
+
+ @Override
+ public boolean isFinished() {
+ return finished && records == null;
+ }
+
+ @Override
+ public long getRetainedSizeInBytes() {
+ /*
+ * BatchScanner does not expose the retained size of its materialized row batch or
+ * in-flight continuation request. PageBuilder memory is accounted separately by
+ * FlussPageSource.
+ */
+ return 0;
+ }
+
+ @Override
+ public long getCompletedBytes() {
+ // The KV batch API does not expose encoded byte counts for consumed rows.
+ return 0;
+ }
+
+ @Override
+ public void close() throws Exception {
+ if (closed) {
+ return;
+ }
+
+ closed = true;
+ finished = true;
+ CloseableIterator<InternalRow> recordsToClose = records;
+ records = null;
+ Throwable failure = null;
+
+ if (recordsToClose != null) {
+ try {
+ recordsToClose.close();
+ } catch (Exception | Error e) {
+ failure = firstOrSuppressed(e, failure);
+ }
+ }
+
+ try {
+ scanner.close();
+ } catch (Exception | Error e) {
+ failure = firstOrSuppressed(e, failure);
+ }
+
+ if (failure != null) {
+ rethrowException(failure, "Failed closing Fluss KV reader for " + bucket);
+ }
+ }
+
+ private void closeBatch() {
+ CloseableIterator<InternalRow> recordsToClose = records;
+ records = null;
+
+ if (recordsToClose != null) {
+ recordsToClose.close();
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussLogRange.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussLogRange.java
new file mode 100644
index 0000000000..233c2da19b
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussLogRange.java
@@ -0,0 +1,89 @@
+/*
+ * 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.fluss.trino;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.Objects;
+
+import static io.airlift.slice.SizeOf.instanceSize;
+import static org.apache.fluss.utils.Preconditions.checkArgument;
+
+/** Immutable range of Fluss log offsets. */
+public final class FlussLogRange {
+ private static final int INSTANCE_SIZE = instanceSize(FlussLogRange.class);
+
+ private final long startOffset;
+ private final long stoppingOffset;
+
+ public FlussLogRange(long startOffset, long stoppingOffset) {
+ checkArgument(startOffset >= 0, "startOffset must be non-negative");
+ checkArgument(stoppingOffset >= startOffset, "stoppingOffset must not precede startOffset");
+ this.startOffset = startOffset;
+ this.stoppingOffset = stoppingOffset;
+ }
+
+ /** Creates a log offset range from JSON with both offsets required. */
+ @JsonCreator
+ public static FlussLogRange fromJson(
+ @JsonProperty("startOffset") Long startOffset,
+ @JsonProperty("stoppingOffset") Long stoppingOffset) {
+ checkArgument(startOffset != null, "startOffset is required");
+ checkArgument(stoppingOffset != null, "stoppingOffset is required");
+ return new FlussLogRange(startOffset, stoppingOffset);
+ }
+
+ @JsonProperty
+ public long getStartOffset() {
+ return startOffset;
+ }
+
+ @JsonProperty
+ public long getStoppingOffset() {
+ return stoppingOffset;
+ }
+
+ boolean isEmpty() {
+ return startOffset == stoppingOffset;
+ }
+
+ long getRetainedSizeInBytes() {
+ return INSTANCE_SIZE;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ FlussLogRange that = (FlussLogRange) o;
+ return startOffset == that.startOffset && stoppingOffset == that.stoppingOffset;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(startOffset, stoppingOffset);
+ }
+
+ @Override
+ public String toString() {
+ return "[" + startOffset + "," + stoppingOffset + ")";
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussLogSplitReader.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussLogSplitReader.java
new file mode 100644
index 0000000000..9725699fa4
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussLogSplitReader.java
@@ -0,0 +1,253 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.client.table.scanner.ScanRecord;
+import org.apache.fluss.client.table.scanner.log.LogScanner;
+import org.apache.fluss.client.table.scanner.log.ScanRecords;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.row.InternalRow;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList;
+
+import io.trino.spi.TrinoException;
+
+import java.time.Duration;
+import java.util.List;
+
+import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_READ_ERROR;
+import static org.apache.fluss.utils.ExceptionUtils.firstOrSuppressed;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/**
+ * Bounded log reader for one physical Fluss bucket.
+ *
+ * <p>The underlying {@link LogScanner} is unbounded. This reader restricts it to the split's
+ * exclusive-end offset range and reports {@link PollResult#FINISHED} once that range is consumed.
+ */
+final class FlussLogSplitReader implements FlussSplitReader {
+
+ private static final long ESTIMATED_RECORD_OVERHEAD_BYTES = 128;
+
+ private final FlussBucketHandle bucket;
+ private final TableBucket tableBucket;
+ private final FlussLogRange range;
+
+ private final LogScanner scanner;
+
+ private List<ScanRecord> records = ImmutableList.of();
+ private int recordIndex;
+ private int recordLimit;
+
+ private long estimatedRetainedBytes;
+ private long completedBytes;
+
+ private boolean stopReached;
+ private boolean finished;
+ private boolean closed;
+
+ FlussLogSplitReader(Table table, FlussBucketHandle bucket, FlussLogRange range) {
+ checkNotNull(table, "table is null");
+ this.bucket = checkNotNull(bucket, "bucket is null");
+ this.range = checkNotNull(range, "range is null");
+ this.tableBucket = bucket.toTableBucket();
+
+ if (range.isEmpty()) {
+ scanner = null;
+ finished = true;
+ return;
+ }
+
+ LogScanner scanner = table.newScan().createLogScanner();
+
+ try {
+ if (bucket.isPartitioned()) {
+ scanner.subscribe(
+ bucket.getRequiredPartitionId(),
+ bucket.getBucketId(),
+ range.getStartOffset());
+ } else {
+ scanner.subscribe(bucket.getBucketId(), range.getStartOffset());
+ }
+ } catch (RuntimeException | Error failure) {
+ try {
+ scanner.close();
+ } catch (Throwable closeFailure) {
+ firstOrSuppressed(closeFailure, failure);
+ }
+ throw failure;
+ }
+
+ this.scanner = scanner;
+ }
+
+ @Override
+ public PollResult poll(Duration timeout) {
+ checkNotNull(timeout, "timeout is null");
+
+ if (closed || finished) {
+ return PollResult.FINISHED;
+ }
+
+ if (hasNext()) {
+ throw new IllegalStateException(
+ "Cannot poll Fluss log scanner while the current batch is not consumed");
+ }
+
+ ScanRecords batch;
+ try {
+ batch = scanner.poll(timeout);
+ } catch (RuntimeException e) {
+ throw new TrinoException(FLUSS_READ_ERROR, "Failed reading Fluss log for " + bucket, e);
+ }
+ List<ScanRecord> batchRecords = batch.records(tableBucket);
+
+ long retainedBytes = 0;
+ int validRecordCount = 0;
+ boolean reachesStop = false;
+
+ for (ScanRecord record : batchRecords) {
+ long recordBytes = Math.max(0, record.getSizeInBytes());
+
+ // This is an estimate. LogScanner does not expose all client-side retained buffers.
+ retainedBytes += ESTIMATED_RECORD_OVERHEAD_BYTES + recordBytes;
+ long offset = record.logOffset();
+ if (offset < range.getStartOffset()) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Fluss offset invariant failed for "
+ + bucket
+ + ": offset "
+ + offset
+ + " precedes "
+ + range);
+ }
+
+ /*
+ * Scan records are ordered for a bucket. Once the exclusive stopping offset is
+ * reached, no later record belongs to this split.
+ */
+ if (!reachesStop) {
+ if (offset >= range.getStoppingOffset()) {
+ reachesStop = true;
+ } else {
+ validRecordCount++;
+
+ if (offset == range.getStoppingOffset() - 1) {
+ reachesStop = true;
+ }
+ }
+ }
+ }
+
+ /*
+ * The scanner may make progress through the stopping offset without returning a record at
+ * exactly stoppingOffset - 1. Preserve the progress-based termination used by the existing
+ * reader.
+ */
+ Long progress = batch.consumedUpToOffset(tableBucket);
+ if (progress != null && progress >= range.getStoppingOffset()) {
+ reachesStop = true;
+ }
+
+ records = batchRecords;
+ recordIndex = 0;
+ recordLimit = validRecordCount;
+ estimatedRetainedBytes = retainedBytes;
+ stopReached = stopReached || reachesStop;
+
+ if (recordLimit == 0) {
+ clearBatch();
+
+ if (stopReached) {
+ finished = true;
+ return PollResult.FINISHED;
+ }
+
+ return PollResult.YIELD;
+ }
+
+ return PollResult.AVAILABLE;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return recordIndex < recordLimit;
+ }
+
+ @Override
+ public InternalRow next() {
+ if (!hasNext()) {
+ throw new IllegalStateException("No buffered Fluss log row");
+ }
+
+ ScanRecord record = records.get(recordIndex++);
+ completedBytes += Math.max(0, record.getSizeInBytes());
+
+ InternalRow row = record.getRow();
+
+ if (recordIndex == recordLimit) {
+ clearBatch();
+
+ if (stopReached) {
+ finished = true;
+ }
+ }
+
+ return row;
+ }
+
+ @Override
+ public boolean isFinished() {
+ return finished && !hasNext();
+ }
+
+ @Override
+ public long getRetainedSizeInBytes() {
+ return estimatedRetainedBytes;
+ }
+
+ @Override
+ public long getCompletedBytes() {
+ return completedBytes;
+ }
+
+ @Override
+ public void close() throws Exception {
+ if (closed) {
+ return;
+ }
+
+ closed = true;
+ finished = true;
+ clearBatch();
+
+ if (scanner != null) {
+ scanner.close();
+ }
+ }
+
+ private void clearBatch() {
+ records = ImmutableList.of();
+ recordIndex = 0;
+ recordLimit = 0;
+ estimatedRetainedBytes = 0;
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussMetadata.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussMetadata.java
new file mode 100644
index 0000000000..32ab1223c3
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussMetadata.java
@@ -0,0 +1,336 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.metadata.Schema;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList;
+
+import com.google.inject.Inject;
+import io.trino.spi.TrinoException;
+import io.trino.spi.connector.ColumnHandle;
+import io.trino.spi.connector.ColumnMetadata;
+import io.trino.spi.connector.ConnectorMetadata;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.ConnectorTableHandle;
+import io.trino.spi.connector.ConnectorTableMetadata;
+import io.trino.spi.connector.ConnectorTableVersion;
+import io.trino.spi.connector.RelationColumnsMetadata;
+import io.trino.spi.connector.RelationCommentMetadata;
+import io.trino.spi.connector.SchemaTableName;
+import io.trino.spi.connector.SystemTable;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.UnaryOperator;
+import java.util.stream.Collectors;
+
+import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Provides Trino metadata backed by the Fluss catalog. */
+public final class FlussMetadata implements ConnectorMetadata {
+
+ private final FlussMetadataAccess metadataAccess;
+
+ @Inject
+ FlussMetadata(FlussMetadataAccess metadataAccess) {
+ this.metadataAccess = checkNotNull(metadataAccess, "metadataAccess is null");
+ }
+
+ @Override
+ public List<String> listSchemaNames(ConnectorSession session) {
+ return metadataAccess.listSchemaNames();
+ }
+
+ @Override
+ public List<SchemaTableName> listTables(ConnectorSession session, Optional<String> schemaName) {
+ ImmutableList.Builder<SchemaTableName> tables = ImmutableList.builder();
+
+ for (FlussMetadataAccess.TableNameMapping tableNameMapping :
+ metadataAccess.listTableNameMappings(schemaName)) {
+ tables.addAll(tableNameMapping.listTableNames());
+ }
+
+ return tables.build();
+ }
+
+ @Override
+ public ConnectorTableHandle getTableHandle(
+ ConnectorSession session,
+ SchemaTableName tableName,
+ Optional<ConnectorTableVersion> startVersion,
+ Optional<ConnectorTableVersion> endVersion) {
+
+ if (startVersion.isPresent() || endVersion.isPresent()) {
+ throw new TrinoException(
+ NOT_SUPPORTED, "Fluss connector does not support table versioning");
+ }
+
+ Optional<ResolvedTableName> resolvedTable = metadataAccess.resolveTable(tableName);
+
+ if (!resolvedTable.isPresent()) {
+ return null;
+ }
+
+ ResolvedTableName resolved = resolvedTable.get();
+
+ Optional<TableInfo> tableInfo = metadataAccess.findTableInfo(resolved);
+
+ if (!tableInfo.isPresent()) {
+ return null;
+ }
+
+ TableInfo info = tableInfo.get();
+
+ return new FlussTableHandle(
+ resolved.getTrinoName().getSchemaName(),
+ resolved.getTrinoName().getTableName(),
+ resolved.getFlussDatabaseName(),
+ resolved.getFlussTableName(),
+ info.getTableId(),
+ info.getSchemaId());
+ }
+
+ @Override
+ public Optional<SystemTable> getSystemTable(
+ ConnectorSession session, SchemaTableName tableName) {
+ String name = tableName.getTableName();
+ if (!isColumnsSystemTable(name)) {
+ return Optional.empty();
+ }
+
+ Optional<ResolvedSchemaName> schema =
+ metadataAccess.resolveSchema(tableName.getSchemaName());
+ if (!schema.isPresent()) {
+ return Optional.empty();
+ }
+
+ FlussMetadataAccess.TableNameMapping tables =
+ metadataAccess.loadTableNameMapping(schema.get());
+
+ // Physical tables take precedence over connector-defined system tables.
+ if (tables.containsTable(name)) {
+ return Optional.empty();
+ }
+
+ Optional<ResolvedTableName> baseTable = tables.resolveTable(getColumnsBaseTableName(name));
+ return baseTable.flatMap(
+ resolvedTableName ->
+ metadataAccess
+ .findTableInfo(resolvedTableName)
+ .map(info -> new FlussColumnsSystemTable(tableName, info)));
+ }
+
+ @Override
+ public SchemaTableName getTableName(ConnectorSession session, ConnectorTableHandle table) {
+ FlussTableHandle handle = (FlussTableHandle) table;
+
+ return new SchemaTableName(handle.getSchemaName(), handle.getTableName());
+ }
+
+ @Override
+ public ConnectorTableMetadata getTableMetadata(
+ ConnectorSession session, ConnectorTableHandle table) {
+
+ TableInfo info = metadataAccess.getTableInfo((FlussTableHandle) table);
+
+ return new ConnectorTableMetadata(
+ getTableName(session, table),
+ getColumns(info),
+ FlussTableProperties.fromTableInfo(info),
+ getTableComment(info));
+ }
+
+ @Override
+ public Map<String, ColumnHandle> getColumnHandles(
+ ConnectorSession session, ConnectorTableHandle table) {
+
+ TableInfo info = metadataAccess.getTableInfo((FlussTableHandle) table);
+
+ List<String> names = info.getSchema().getColumnNames();
+ validateColumnNames(names);
+
+ Map<String, ColumnHandle> handles = new LinkedHashMap<>();
+
+ for (int position = 0; position < names.size(); position++) {
+ String name = names.get(position);
+
+ handles.put(name.toLowerCase(Locale.ROOT), new FlussColumnHandle(name, position));
+ }
+
+ return Collections.unmodifiableMap(handles);
+ }
+
+ @Override
+ public ColumnMetadata getColumnMetadata(
+ ConnectorSession session, ConnectorTableHandle table, ColumnHandle columnHandle) {
+
+ FlussColumnHandle column = (FlussColumnHandle) columnHandle;
+
+ List<Schema.Column> columns =
+ metadataAccess.getTableInfo((FlussTableHandle) table).getSchema().getColumns();
+
+ int ordinalPosition = column.getOrdinalPosition();
+
+ if (ordinalPosition < 0 || ordinalPosition >= columns.size()) {
+ throw new IllegalArgumentException(
+ "Invalid column ordinal: " + column.getOrdinalPosition());
+ }
+
+ Schema.Column field = columns.get(column.getOrdinalPosition());
+
+ if (!field.getName().equals(column.getName())) {
+ throw new IllegalArgumentException(
+ "Column handle does not match current table schema: " + column.getName());
+ }
+
+ return toColumnMetadata(field);
+ }
+
+ @Override
+ public Iterator<RelationColumnsMetadata> streamRelationColumns(
+ ConnectorSession session,
+ Optional<String> schemaName,
+ UnaryOperator<Set<SchemaTableName>> relationFilter) {
+
+ List<RelationColumnsMetadata> relations = new ArrayList<>();
+
+ for (ResolvedTableName table : getFilteredRelations(schemaName, relationFilter)) {
+
+ Optional<TableInfo> tableInfo = metadataAccess.findTableInfo(table);
+
+ if (!tableInfo.isPresent()) {
+ continue;
+ }
+
+ relations.add(
+ RelationColumnsMetadata.forTable(
+ table.getTrinoName(), getColumns(tableInfo.get())));
+ }
+
+ return relations.iterator();
+ }
+
+ @Override
+ public Iterator<RelationCommentMetadata> streamRelationComments(
+ ConnectorSession session,
+ Optional<String> schemaName,
+ UnaryOperator<Set<SchemaTableName>> relationFilter) {
+
+ List<RelationCommentMetadata> relations = new ArrayList<>();
+
+ for (ResolvedTableName table : getFilteredRelations(schemaName, relationFilter)) {
+
+ Optional<TableInfo> tableInfo = metadataAccess.findTableInfo(table);
+
+ if (!tableInfo.isPresent()) {
+ continue;
+ }
+
+ relations.add(
+ RelationCommentMetadata.forRelation(
+ table.getTrinoName(), getTableComment(tableInfo.get())));
+ }
+
+ return relations.iterator();
+ }
+
+ private List<ResolvedTableName> getFilteredRelations(
+ Optional<String> schemaName, UnaryOperator<Set<SchemaTableName>> relationFilter) {
+ Map<SchemaTableName, FlussMetadataAccess.TableNameMapping> mappingsByTable =
+ new LinkedHashMap<>();
+
+ for (FlussMetadataAccess.TableNameMapping mapping :
+ metadataAccess.listTableNameMappings(schemaName)) {
+ for (SchemaTableName tableName : mapping.listTableNames()) {
+ mappingsByTable.put(tableName, mapping);
+ }
+ }
+
+ Set<SchemaTableName> filteredNames =
+ relationFilter.apply(new LinkedHashSet<>(mappingsByTable.keySet()));
+
+ ImmutableList.Builder<ResolvedTableName> tables = ImmutableList.builder();
+
+ for (SchemaTableName tableName : filteredNames) {
+ FlussMetadataAccess.TableNameMapping mapping = mappingsByTable.get(tableName);
+ if (mapping == null) {
+ continue;
+ }
+
+ mapping.resolveTable(tableName.getTableName()).ifPresent(tables::add);
+ }
+
+ return tables.build();
+ }
+
+ private static ColumnMetadata toColumnMetadata(Schema.Column column) {
+ return ColumnMetadata.builder()
+ .setName(column.getName())
+ .setType(FlussTypeConverter.toTrinoType(column.getDataType()))
+ .setNullable(column.getDataType().isNullable())
+ .setComment(column.getComment())
+ .build();
+ }
+
+ private static List<ColumnMetadata> getColumns(TableInfo info) {
+ validateColumnNames(info.getSchema().getColumnNames());
+
+ return info.getSchema().getColumns().stream()
+ .map(FlussMetadata::toColumnMetadata)
+ .collect(Collectors.toList());
+ }
+
+ private static Optional<String> getTableComment(TableInfo info) {
+ return info.getComment().filter(comment -> !comment.isEmpty());
+ }
+
+ private static boolean isColumnsSystemTable(String tableName) {
+ return tableName.endsWith(FlussColumnsSystemTable.SUFFIX)
+ && tableName.length() > FlussColumnsSystemTable.SUFFIX.length();
+ }
+
+ private static String getColumnsBaseTableName(String tableName) {
+ return tableName.substring(0, tableName.length() - FlussColumnsSystemTable.SUFFIX.length());
+ }
+
+ private static void validateColumnNames(List<String> names) {
+ Map<String, String> canonicalNames = new LinkedHashMap<>();
+
+ for (String name : names) {
+ String canonicalName = name.toLowerCase(Locale.ROOT);
+
+ String previous = canonicalNames.putIfAbsent(canonicalName, name);
+
+ if (previous != null) {
+ throw new TrinoException(
+ NOT_SUPPORTED, "Ambiguous Fluss columns: " + previous + " and " + name);
+ }
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussMetadataAccess.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussMetadataAccess.java
new file mode 100644
index 0000000000..7834c73194
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussMetadataAccess.java
@@ -0,0 +1,560 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.client.admin.OffsetSpec;
+import org.apache.fluss.exception.DatabaseNotExistException;
+import org.apache.fluss.exception.PartitionNotExistException;
+import org.apache.fluss.exception.TableNotExistException;
+import org.apache.fluss.metadata.BucketInfo;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metadata.TablePath;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableMap;
+
+import com.google.inject.Inject;
+import io.trino.spi.ErrorCodeSupplier;
+import io.trino.spi.TrinoException;
+import io.trino.spi.connector.SchemaTableName;
+import io.trino.spi.connector.TableNotFoundException;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+
+import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
+import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_METADATA_ERROR;
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_SPLIT_ERROR;
+import static org.apache.fluss.trino.FlussTableScanValidator.validateIdentity;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/**
+ * Provides access to Fluss catalog metadata.
+ *
+ * <p>This class handles physical name resolution, Admin RPC calls, and translation of Fluss
+ * metadata failures. Name discovery preserves ambiguous names; resolution rejects them only when
+ * the requested name is ambiguous.
+ */
+final class FlussMetadataAccess {
+ private final FlussClientManager clientManager;
+
+ @Inject
+ FlussMetadataAccess(FlussClientManager clientManager) {
+ this.clientManager = checkNotNull(clientManager, "clientManager is null");
+ }
+
+ List<String> listSchemaNames() {
+ return ImmutableList.copyOf(loadSchemaNameMapping().keySet());
+ }
+
+ Optional<ResolvedSchemaName> resolveSchema(String schemaName) {
+ checkNotNull(schemaName, "schemaName is null");
+
+ String canonicalName = canonicalize(schemaName);
+ return resolveName(loadSchemaNameMapping(), canonicalName, "database")
+ .map(physicalName -> new ResolvedSchemaName(canonicalName, physicalName));
+ }
+
+ TableNameMapping loadTableNameMapping(ResolvedSchemaName schema) {
+ checkNotNull(schema, "schema is null");
+
+ try {
+ return new TableNameMapping(
+ schema,
+ buildNameMapping(
+ await(
+ getAdmin().listTables(schema.getFlussName()),
+ FLUSS_METADATA_ERROR,
+ "Failed to list Fluss tables in database "
+ + schema.getFlussName())));
+ } catch (DatabaseNotExistException e) {
+ // The database may have been dropped after resolving its name.
+ return new TableNameMapping(schema, ImmutableMap.of());
+ }
+ }
+
+ /**
+ * Returns table-name mappings for the requested schema or the whole catalog.
+ *
+ * <p>Because Trino identifiers are case-insensitive, a catalog-wide listing fails if any
+ * logical schema maps to multiple case-distinct Fluss databases.
+ */
+ List<TableNameMapping> listTableNameMappings(Optional<String> schemaName) {
+ checkNotNull(schemaName, "schemaName is null");
+
+ if (schemaName.isPresent()) {
+ Optional<ResolvedSchemaName> schema = resolveSchema(schemaName.get());
+ if (!schema.isPresent()) {
+ return ImmutableList.of();
+ }
+ return ImmutableList.of(loadTableNameMapping(schema.get()));
+ }
+
+ Map<String, List<String>> schemas = loadSchemaNameMapping();
+ ImmutableList.Builder<TableNameMapping> tableNameMappingBuilder = ImmutableList.builder();
+
+ for (String name : schemas.keySet()) {
+ String physicalName =
+ resolveName(schemas, name, "database")
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Missing database in name mapping: " + name));
+ tableNameMappingBuilder.add(
+ loadTableNameMapping(new ResolvedSchemaName(name, physicalName)));
+ }
+
+ return tableNameMappingBuilder.build();
+ }
+
+ /**
+ * Resolves case-insensitive Trino identifiers to physical Fluss names.
+ *
+ * <p>Both schema and table discovery are required to detect ambiguous names that differ only in
+ * case.
+ */
+ Optional<ResolvedTableName> resolveTable(SchemaTableName tableName) {
+ checkNotNull(tableName, "tableName is null");
+
+ Optional<ResolvedSchemaName> schema = resolveSchema(tableName.getSchemaName());
+ if (!schema.isPresent()) {
+ return Optional.empty();
+ }
+
+ return loadTableNameMapping(schema.get()).resolveTable(tableName.getTableName());
+ }
+
+ /**
+ * Returns table information if the table still exists.
+ *
+ * <p>This method is intended for metadata discovery, where the table may disappear between
+ * listing and lookup.
+ */
+ Optional<TableInfo> findTableInfo(ResolvedTableName table) {
+ try {
+ return Optional.of(
+ loadTableInfo(table.getFlussDatabaseName(), table.getFlussTableName()));
+ } catch (TableNotExistException | DatabaseNotExistException e) {
+ return Optional.empty();
+ }
+ }
+
+ /**
+ * Returns table information for an existing Trino table handle and validates its physical table
+ * identity.
+ */
+ TableInfo getTableInfo(FlussTableHandle table) {
+ checkNotNull(table, "table is null");
+ try {
+ TableInfo info = loadTableInfo(table.getFlussDatabaseName(), table.getFlussTableName());
+ validateIdentity(table, info);
+ return info;
+ } catch (TableNotExistException | DatabaseNotExistException e) {
+ throw tableNotFound(table, e);
+ }
+ }
+
+ List<FlussPhysicalBucket> listScanBuckets(FlussTableHandle table) {
+ checkNotNull(table, "table is null");
+ TablePath tablePath = TablePath.of(table.getFlussDatabaseName(), table.getFlussTableName());
+ try {
+ List<BucketInfo> bucketInfos =
+ await(
+ getAdmin().describeBuckets(tablePath),
+ FLUSS_SPLIT_ERROR,
+ "Failed to describe Fluss buckets for " + table);
+
+ ImmutableList.Builder<FlussPhysicalBucket> buckets = ImmutableList.builder();
+
+ for (BucketInfo info : bucketInfos) {
+ if (info.getTableId() != table.getTableId()) {
+ throw new TrinoException(
+ FLUSS_SPLIT_ERROR,
+ "Fluss bucket metadata refers to an unexpected table ID");
+ }
+
+ Optional<Long> partitionId =
+ info.getPartitionId().isPresent()
+ ? Optional.of(info.getPartitionId().getAsLong())
+ : Optional.empty();
+
+ buckets.add(
+ new FlussPhysicalBucket(
+ new FlussBucketHandle(
+ info.getTableId(), partitionId, info.getBucketId()),
+ Optional.ofNullable(info.getPartitionName())));
+ }
+
+ return buckets.build();
+ } catch (TableNotExistException | DatabaseNotExistException e) {
+ throw tableNotFound(table, e);
+ }
+ }
+
+ Map<FlussBucketHandle, Long> resolveOffsets(
+ FlussTableHandle table, List<FlussPhysicalBucket> buckets, OffsetSpec offsetSpec) {
+ checkNotNull(table, "table is null");
+ checkNotNull(buckets, "buckets is null");
+ checkNotNull(offsetSpec, "offsetSpec is null");
+
+ if (buckets.isEmpty()) {
+ return ImmutableMap.of();
+ }
+
+ validatePhysicalBuckets(table, buckets);
+ TablePath tablePath = TablePath.of(table.getFlussDatabaseName(), table.getFlussTableName());
+
+ try {
+ if (!buckets.get(0).getBucket().isPartitioned()) {
+ return listNonPartitionedOffsets(tablePath, table, buckets, offsetSpec);
+ }
+ return listPartitionedOffsets(tablePath, table, buckets, offsetSpec);
+ } catch (TableNotExistException | DatabaseNotExistException e) {
+ throw tableNotFound(table, e);
+ }
+ }
+
+ List<FlussPhysicalBucket> retainCurrentBuckets(
+ FlussTableHandle table, List<FlussPhysicalBucket> expectedBuckets) {
+ Set<FlussPhysicalBucket> currentBuckets = new HashSet<>(listScanBuckets(table));
+ Set<Long> currentPartitionIds = new HashSet<>();
+ for (FlussPhysicalBucket current : currentBuckets) {
+ FlussBucketHandle bucket = current.getBucket();
+ if (bucket.isPartitioned()) {
+ currentPartitionIds.add(bucket.getRequiredPartitionId());
+ }
+ }
+ ImmutableList.Builder<FlussPhysicalBucket> remaining = ImmutableList.builder();
+ for (FlussPhysicalBucket expected : expectedBuckets) {
+ if (currentBuckets.contains(expected)) {
+ remaining.add(expected);
+ continue;
+ }
+ FlussBucketHandle bucket = expected.getBucket();
+ if (bucket.isPartitioned()
+ && !currentPartitionIds.contains(bucket.getRequiredPartitionId())) {
+ // The original physical partition no longer exists.
+ continue;
+ }
+ throw new TrinoException(
+ FLUSS_SPLIT_ERROR,
+ "Fluss bucket topology changed during split planning; retry the query: missing "
+ + expected);
+ }
+
+ return remaining.build();
+ }
+
+ private Admin getAdmin() {
+ try {
+ return clientManager.getAdmin();
+ } catch (TrinoException e) {
+ throw e;
+ } catch (RuntimeException e) {
+ throw new TrinoException(
+ FLUSS_METADATA_ERROR, "Failed to initialize the Fluss client", e);
+ }
+ }
+
+ private Map<FlussBucketHandle, Long> listNonPartitionedOffsets(
+ TablePath tablePath,
+ FlussTableHandle table,
+ List<FlussPhysicalBucket> buckets,
+ OffsetSpec offsetSpec) {
+ List<Integer> bucketIds =
+ buckets.stream()
+ .map(FlussPhysicalBucket::getBucket)
+ .map(FlussBucketHandle::getBucketId)
+ .collect(ImmutableList.toImmutableList());
+
+ Map<Integer, Long> rawOffsets =
+ await(
+ getAdmin().listOffsets(tablePath, bucketIds, offsetSpec).all(),
+ FLUSS_SPLIT_ERROR,
+ "Failed to list Fluss offsets for " + table);
+
+ ImmutableMap.Builder<FlussBucketHandle, Long> result = ImmutableMap.builder();
+
+ for (FlussPhysicalBucket physicalBucket : buckets) {
+ FlussBucketHandle bucket = physicalBucket.getBucket();
+ result.put(bucket, requireOffset(table, bucket, rawOffsets));
+ }
+
+ return result.buildOrThrow();
+ }
+
+ private Map<FlussBucketHandle, Long> listPartitionedOffsets(
+ TablePath tablePath,
+ FlussTableHandle table,
+ List<FlussPhysicalBucket> buckets,
+ OffsetSpec offsetSpec) {
+ Map<String, List<FlussPhysicalBucket>> bucketsByPartition = groupByPartition(buckets);
+ Map<String, CompletableFuture<Map<Integer, Long>>> futures = new LinkedHashMap<>();
+
+ Admin admin = getAdmin();
+
+ for (Map.Entry<String, List<FlussPhysicalBucket>> entry : bucketsByPartition.entrySet()) {
+ String partitionName = entry.getKey();
+ List<Integer> bucketIds =
+ entry.getValue().stream()
+ .map(FlussPhysicalBucket::getBucket)
+ .map(FlussBucketHandle::getBucketId)
+ .collect(ImmutableList.toImmutableList());
+ try {
+ futures.put(
+ partitionName,
+ admin.listOffsets(tablePath, partitionName, bucketIds, offsetSpec).all());
+ } catch (PartitionNotExistException e) {
+ // The partition may have expired since bucket discovery.
+ }
+ }
+
+ ImmutableMap.Builder<FlussBucketHandle, Long> result = ImmutableMap.builder();
+ for (Map.Entry<String, List<FlussPhysicalBucket>> entry : bucketsByPartition.entrySet()) {
+ String partitionName = entry.getKey();
+ CompletableFuture<Map<Integer, Long>> future = futures.get(partitionName);
+ if (future == null) {
+ continue;
+ }
+ Map<Integer, Long> rawOffsets;
+ try {
+ rawOffsets =
+ await(
+ future,
+ FLUSS_SPLIT_ERROR,
+ "Failed to list Fluss offsets for "
+ + table
+ + " partition "
+ + partitionName);
+ } catch (PartitionNotExistException e) {
+ // The partition disappeared while fetching offsets.
+ continue;
+ }
+
+ for (FlussPhysicalBucket physicalBucket : entry.getValue()) {
+ FlussBucketHandle bucket = physicalBucket.getBucket();
+ result.put(bucket, requireOffset(table, bucket, rawOffsets));
+ }
+ }
+
+ return result.buildOrThrow();
+ }
+
+ private Map<String, List<String>> loadSchemaNameMapping() {
+ return buildNameMapping(
+ await(
+ getAdmin().listDatabases(),
+ FLUSS_METADATA_ERROR,
+ "Failed to list Fluss databases"));
+ }
+
+ private TableInfo loadTableInfo(String databaseName, String tableName) {
+ TablePath tablePath = TablePath.of(databaseName, tableName);
+ return await(
+ getAdmin().getTableInfo(tablePath),
+ FLUSS_METADATA_ERROR,
+ "Failed to get Fluss table metadata for " + tablePath);
+ }
+
+ private static Map<String, List<FlussPhysicalBucket>> groupByPartition(
+ List<FlussPhysicalBucket> buckets) {
+ Map<String, List<FlussPhysicalBucket>> result = new LinkedHashMap<>();
+
+ for (FlussPhysicalBucket bucket : buckets) {
+ result.computeIfAbsent(bucket.getRequiredPartitionName(), ignored -> new ArrayList<>())
+ .add(bucket);
+ }
+
+ return result;
+ }
+
+ private static TableNotFoundException tableNotFound(FlussTableHandle table, Throwable cause) {
+ return new TableNotFoundException(
+ new SchemaTableName(table.getSchemaName(), table.getTableName()), cause);
+ }
+
+ private static long requireOffset(
+ FlussTableHandle table, FlussBucketHandle bucket, Map<Integer, Long> offsets) {
+ Long offset = offsets.get(bucket.getBucketId());
+ if (offset == null || offset < 0) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Missing or invalid Fluss offset for "
+ + table
+ + " bucket "
+ + bucket
+ + ": "
+ + offset);
+ }
+ return offset;
+ }
+
+ private static void validatePhysicalBuckets(
+ FlussTableHandle table, List<FlussPhysicalBucket> buckets) {
+ boolean partitioned = buckets.get(0).getBucket().isPartitioned();
+
+ Set<FlussBucketHandle> seen = new HashSet<>();
+
+ for (FlussPhysicalBucket physicalBucket : buckets) {
+ FlussBucketHandle bucket = physicalBucket.getBucket();
+
+ if (bucket.getTableId() != table.getTableId()) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Fluss bucket " + bucket + " does not belong to table " + table);
+ }
+
+ if (bucket.isPartitioned() != partitioned) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Fluss bucket list mixes partitioned and non-partitioned buckets");
+ }
+
+ if (!seen.add(bucket)) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Duplicate Fluss bucket in scan planning: " + bucket);
+ }
+ }
+ }
+
+ private static String canonicalize(String name) {
+ return name.toLowerCase(Locale.ROOT);
+ }
+
+ private static Map<String, List<String>> buildNameMapping(List<String> names) {
+ Map<String, List<String>> candidates = new LinkedHashMap<>();
+
+ for (String name : names) {
+ candidates.computeIfAbsent(canonicalize(name), ignored -> new ArrayList<>()).add(name);
+ }
+
+ ImmutableMap.Builder<String, List<String>> nameMapping = ImmutableMap.builder();
+ for (Map.Entry<String, List<String>> entry : candidates.entrySet()) {
+ List<String> physicalNames = new ArrayList<>(entry.getValue());
+ Collections.sort(physicalNames);
+ nameMapping.put(entry.getKey(), ImmutableList.copyOf(physicalNames));
+ }
+
+ return nameMapping.build();
+ }
+
+ private static Optional<String> resolveName(
+ Map<String, List<String>> mapping, String name, String objectType) {
+ List<String> candidates = mapping.get(canonicalize(name));
+ if (candidates == null) {
+ return Optional.empty();
+ }
+
+ if (candidates.size() > 1) {
+ throw new TrinoException(
+ NOT_SUPPORTED,
+ "Ambiguous Fluss "
+ + objectType
+ + " '"
+ + name
+ + "': "
+ + String.join(", ", candidates));
+ }
+
+ return Optional.of(candidates.get(0));
+ }
+
+ private static <T> T await(
+ CompletableFuture<T> future, ErrorCodeSupplier errorCode, String message) {
+ try {
+ return future.join();
+ } catch (CompletionException e) {
+ Throwable cause = unwrapCompletionException(e);
+
+ if (cause instanceof TableNotExistException) {
+ throw (TableNotExistException) cause;
+ }
+ if (cause instanceof DatabaseNotExistException) {
+ throw (DatabaseNotExistException) cause;
+ }
+ if (cause instanceof TrinoException) {
+ throw (TrinoException) cause;
+ }
+ if (cause instanceof Error) {
+ throw (Error) cause;
+ }
+ if (cause instanceof PartitionNotExistException) {
+ throw (PartitionNotExistException) cause;
+ }
+
+ throw new TrinoException(errorCode, message, cause);
+ }
+ }
+
+ private static Throwable unwrapCompletionException(Throwable failure) {
+ while (failure instanceof CompletionException && failure.getCause() != null) {
+ failure = failure.getCause();
+ }
+ return failure;
+ }
+
+ /** Immutable table-name snapshot that resolves physical names without additional RPC calls. */
+ static final class TableNameMapping {
+
+ private final ResolvedSchemaName schema;
+ private final Map<String, List<String>> candidates;
+
+ private TableNameMapping(ResolvedSchemaName schema, Map<String, List<String>> candidates) {
+ this.schema = checkNotNull(schema, "schema is null");
+ this.candidates = checkNotNull(candidates, "candidates is null");
+ }
+
+ /**
+ * Returns distinct logical table names, including names with ambiguous physical matches.
+ */
+ List<SchemaTableName> listTableNames() {
+ ImmutableList.Builder<SchemaTableName> tables = ImmutableList.builder();
+
+ for (String name : candidates.keySet()) {
+ tables.add(new SchemaTableName(schema.getTrinoName(), name));
+ }
+
+ return tables.build();
+ }
+
+ /** Returns whether any physical table has the requested logical name. */
+ boolean containsTable(String tableName) {
+ return candidates.containsKey(canonicalize(tableName));
+ }
+
+ /** Resolves one logical table name and rejects ambiguity for that name only. */
+ Optional<ResolvedTableName> resolveTable(String tableName) {
+ String canonicalName = canonicalize(tableName);
+
+ return resolveName(candidates, canonicalName, "table")
+ .map(physicalName -> schema.table(canonicalName, physicalName));
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPageSource.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPageSource.java
new file mode 100644
index 0000000000..40ecad73af
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPageSource.java
@@ -0,0 +1,318 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metadata.TablePath;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList;
+
+import io.trino.spi.Page;
+import io.trino.spi.PageBuilder;
+import io.trino.spi.TrinoException;
+import io.trino.spi.block.DuplicateMapKeyException;
+import io.trino.spi.classloader.ThreadContextClassLoader;
+import io.trino.spi.connector.ConnectorPageSource;
+import io.trino.spi.connector.MemoryContext;
+import io.trino.spi.connector.SourcePage;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.OptionalLong;
+
+import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_READ_ERROR;
+import static org.apache.fluss.trino.FlussTableScanValidator.validateSplit;
+import static org.apache.fluss.trino.FlussTableScanValidator.validateTable;
+import static org.apache.fluss.utils.ExceptionUtils.firstOrSuppressed;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/**
+ * Synchronous bounded page source for one physical Fluss split.
+ *
+ * <p>The page source owns table and reader lifecycle, converts Fluss rows into Trino pages, and
+ * reports reader and page-builder memory. Storage-specific LOG/KV semantics are encapsulated by
+ * {@link FlussSplitReader}.
+ *
+ * <p>Each page request polls the underlying Fluss scanner at most once. A poll may yield without
+ * completing the split.
+ */
+final class FlussPageSource implements ConnectorPageSource {
+
+ private static final Duration POLL_TIMEOUT = Duration.ofMillis(100);
+
+ private static final int MAX_PAGE_ROWS = 1024;
+ private static final int MAX_PAGE_BYTES = 1024 * 1024;
+
+ private final FlussClientManager clients;
+ private final FlussTableHandle handle;
+ private final FlussSplit split;
+ private final List<FlussColumnHandle> columns;
+ private final MemoryContext memory;
+
+ private Table table;
+ private FlussRowDecoder decoder;
+ private FlussSplitReader reader;
+
+ private boolean closed;
+
+ private long completedBytes;
+ private long completedPositions;
+ private long readNanos;
+
+ FlussPageSource(
+ FlussClientManager clients,
+ FlussTableHandle handle,
+ FlussSplit split,
+ List<FlussColumnHandle> columns,
+ MemoryContext memory) {
+ this.clients = checkNotNull(clients, "clients is null");
+ this.handle = checkNotNull(handle, "handle is null");
+ this.split = checkNotNull(split, "split is null");
+ this.columns = ImmutableList.copyOf(checkNotNull(columns, "columns is null"));
+ this.memory = checkNotNull(memory, "memory is null");
+ }
+
+ @Override
+ public SourcePage getNextSourcePage() {
+ if (closed) {
+ return null;
+ }
+ try (ThreadContextClassLoader ignored =
+ new ThreadContextClassLoader(FlussPageSource.class.getClassLoader())) {
+ initialize();
+ if (!reader.hasNext()) {
+ if (reader.isFinished()) {
+ close();
+ return null;
+ }
+ FlussSplitReader.PollResult pollResult = pollReader();
+ // Polling may acquire or release reader-owned input buffers.
+ memory.setBytes(reader.getRetainedSizeInBytes());
+ switch (pollResult) {
+ case AVAILABLE:
+ if (!reader.hasNext()) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Fluss reader reported available data without a buffered row");
+ }
+ break;
+ case YIELD:
+ if (reader.hasNext() || reader.isFinished()) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Fluss reader returned an invalid yield state");
+ }
+ return null;
+ case FINISHED:
+ if (!reader.isFinished()) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Fluss reader reported completion without being finished");
+ }
+ close();
+ return null;
+ default:
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Unknown Fluss reader poll result: " + pollResult);
+ }
+ }
+
+ PageBuilder builder = PageBuilder.withMaxPageSize(MAX_PAGE_BYTES, decoder.getTypes());
+ reportMemory(builder);
+ /*
+ * Consume only the currently buffered Fluss scanner batch. If the batch is exhausted
+ * before the page is full, the next scanner poll happens on the next Trino page-source
+ * request.
+ */
+ while (!builder.isFull()
+ && builder.getPositionCount() < MAX_PAGE_ROWS
+ && reader.hasNext()) {
+ decoder.append(reader.next(), builder);
+ // Report allocation growth as rows are appended instead of only after page build.
+ reportMemory(builder);
+ }
+ // reader.next() may have released the exhausted scanner batch.
+ reportMemory(builder);
+
+ if (builder.isEmpty()) {
+ // The PageBuilder becomes unreachable when this method returns.
+ memory.setBytes(reader.getRetainedSizeInBytes());
+ if (reader.isFinished()) {
+ close();
+ }
+ return null;
+ }
+ Page page;
+ try {
+ page = builder.build();
+ } catch (DuplicateMapKeyException e) {
+ throw new TrinoException(
+ FLUSS_READ_ERROR,
+ "Fluss map contains duplicate keys under Trino semantics for "
+ + handle
+ + ", split "
+ + split,
+ e);
+ }
+ completedPositions += page.getPositionCount();
+ /*
+ * Ownership of the built page transfers to Trino. Only reader-owned input memory
+ * remains attributable to this page source.
+ */
+ memory.setBytes(reader.getRetainedSizeInBytes());
+ if (reader.isFinished()) {
+ close();
+ }
+ return SourcePage.create(page);
+ } catch (RuntimeException | Error failure) {
+ closeWithSuppression(failure);
+ throw failure;
+ }
+ }
+
+ @Override
+ public void close() {
+ if (closed) {
+ return;
+ }
+ try (ThreadContextClassLoader ignored =
+ new ThreadContextClassLoader(FlussPageSource.class.getClassLoader())) {
+ closed = true;
+
+ FlussSplitReader readerToClose = reader;
+ Table tableToClose = table;
+
+ reader = null;
+ table = null;
+ decoder = null;
+
+ Throwable failure = null;
+
+ if (readerToClose != null) {
+ try {
+ completedBytes = readerToClose.getCompletedBytes();
+ } catch (RuntimeException | Error e) {
+ failure = firstOrSuppressed(e, failure);
+ }
+ try {
+ readerToClose.close();
+ } catch (Exception | Error e) {
+ failure = firstOrSuppressed(e, failure);
+ }
+ }
+
+ if (tableToClose != null) {
+ try {
+ tableToClose.close();
+ } catch (Exception | Error e) {
+ failure = firstOrSuppressed(e, failure);
+ }
+ }
+
+ try {
+ memory.setBytes(0);
+ } catch (RuntimeException | Error e) {
+ failure = firstOrSuppressed(e, failure);
+ }
+
+ if (failure instanceof Error) {
+ throw (Error) failure;
+ }
+
+ if (failure != null) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Failed closing Fluss reader for " + handle + ", split " + split,
+ failure);
+ }
+ }
+ }
+
+ @Override
+ public boolean isFinished() {
+ return closed;
+ }
+
+ @Override
+ public long getCompletedBytes() {
+ if (reader != null) {
+ return reader.getCompletedBytes();
+ }
+
+ return completedBytes;
+ }
+
+ @Override
+ public OptionalLong getCompletedPositions() {
+ return OptionalLong.of(completedPositions);
+ }
+
+ @Override
+ public long getReadTimeNanos() {
+ return readNanos;
+ }
+
+ private void initialize() {
+ if (reader != null) {
+ return;
+ }
+
+ table =
+ clients.openTable(
+ TablePath.of(handle.getFlussDatabaseName(), handle.getFlussTableName()));
+
+ TableInfo tableInfo = table.getTableInfo();
+
+ validateTable(handle, tableInfo);
+ validateSplit(split, tableInfo);
+
+ decoder = new FlussRowDecoder(tableInfo.getSchema(), columns);
+
+ reader = FlussSplitReaderFactory.create(table, split);
+ }
+
+ private FlussSplitReader.PollResult pollReader() {
+ long started = System.nanoTime();
+
+ try {
+ return reader.poll(POLL_TIMEOUT);
+ } finally {
+ readNanos += System.nanoTime() - started;
+ }
+ }
+
+ private void reportMemory(PageBuilder builder) {
+ long retainedBytes =
+ Math.addExact(reader.getRetainedSizeInBytes(), builder.getRetainedSizeInBytes());
+
+ memory.setBytes(retainedBytes);
+ }
+
+ private void closeWithSuppression(Throwable failure) {
+ try {
+ close();
+ } catch (RuntimeException | Error closeFailure) {
+ if (failure != closeFailure) {
+ failure.addSuppressed(closeFailure);
+ }
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPageSourceProvider.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPageSourceProvider.java
new file mode 100644
index 0000000000..6f77f2154c
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPageSourceProvider.java
@@ -0,0 +1,74 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList;
+
+import com.google.inject.Inject;
+import io.trino.spi.connector.ColumnHandle;
+import io.trino.spi.connector.ConnectorPageSource;
+import io.trino.spi.connector.ConnectorPageSourceProvider;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.ConnectorSplit;
+import io.trino.spi.connector.ConnectorTableCredentials;
+import io.trino.spi.connector.ConnectorTableHandle;
+import io.trino.spi.connector.ConnectorTransactionHandle;
+import io.trino.spi.connector.DynamicFilter;
+import io.trino.spi.connector.MemoryContext;
+
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList.toImmutableList;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Creates an independent bounded page source for each scheduled Fluss split. */
+public final class FlussPageSourceProvider implements ConnectorPageSourceProvider {
+
+ private final FlussClientManager clients;
+
+ @Inject
+ FlussPageSourceProvider(FlussClientManager clients) {
+ this.clients = checkNotNull(clients, "clients is null");
+ }
+
+ @Override
+ public ConnectorPageSource createPageSource(
+ ConnectorTransactionHandle transaction,
+ ConnectorSession session,
+ ConnectorSplit split,
+ ConnectorTableHandle table,
+ Optional<ConnectorTableCredentials> credentials,
+ List<ColumnHandle> columns,
+ DynamicFilter dynamicFilter,
+ MemoryContext memoryContext) {
+ FlussTableHandle handle = (FlussTableHandle) table;
+ FlussSplit flussSplit = (FlussSplit) split;
+
+ ImmutableList<FlussColumnHandle> projectedColumns =
+ columns.stream().map(FlussColumnHandle.class::cast).collect(toImmutableList());
+
+ return new FlussPageSource(
+ clients,
+ handle,
+ flussSplit,
+ projectedColumns,
+ checkNotNull(memoryContext, "memoryContext is null"));
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPhysicalBucket.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPhysicalBucket.java
new file mode 100644
index 0000000000..efbd1bc1d2
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPhysicalBucket.java
@@ -0,0 +1,63 @@
+/*
+ * 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.fluss.trino;
+
+import java.util.Objects;
+import java.util.Optional;
+
+import static org.apache.fluss.utils.Preconditions.checkArgument;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+final class FlussPhysicalBucket {
+ private final FlussBucketHandle bucket;
+ private final Optional<String> partitionName;
+
+ FlussPhysicalBucket(FlussBucketHandle bucket, Optional<String> partitionName) {
+ this.bucket = checkNotNull(bucket, "bucket is null");
+ this.partitionName = checkNotNull(partitionName, "partitionName is null");
+
+ checkArgument(
+ bucket.isPartitioned() == partitionName.isPresent(),
+ "partition ID and partition name must either both be present or both be absent");
+ }
+
+ FlussBucketHandle getBucket() {
+ return bucket;
+ }
+
+ String getRequiredPartitionName() {
+ return partitionName.orElseThrow(
+ () -> new IllegalStateException("Bucket does not belong to a partition"));
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ FlussPhysicalBucket that = (FlussPhysicalBucket) o;
+ return Objects.equals(bucket, that.bucket)
+ && Objects.equals(partitionName, that.partitionName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(bucket, partitionName);
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPlugin.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPlugin.java
new file mode 100644
index 0000000000..6f9c3f5e7e
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussPlugin.java
@@ -0,0 +1,32 @@
+/*
+ * 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.fluss.trino;
+
+import io.trino.spi.Plugin;
+import io.trino.spi.connector.ConnectorFactory;
+
+import java.util.Collections;
+
+/** Apache Fluss connector plugin for Trino. */
+public class FlussPlugin implements Plugin {
+
+ @Override
+ public Iterable<ConnectorFactory> getConnectorFactories() {
+ return Collections.singletonList(new FlussConnectorFactory());
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussRowDecoder.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussRowDecoder.java
new file mode 100644
index 0000000000..838b6f3bfa
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussRowDecoder.java
@@ -0,0 +1,273 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.metadata.Schema;
+import org.apache.fluss.row.DataGetters;
+import org.apache.fluss.row.Decimal;
+import org.apache.fluss.row.InternalArray;
+import org.apache.fluss.row.InternalMap;
+import org.apache.fluss.row.InternalRow;
+import org.apache.fluss.row.TimestampLtz;
+import org.apache.fluss.row.TimestampNtz;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList;
+import org.apache.fluss.types.ArrayType;
+import org.apache.fluss.types.BinaryType;
+import org.apache.fluss.types.CharType;
+import org.apache.fluss.types.DataType;
+import org.apache.fluss.types.DecimalType;
+import org.apache.fluss.types.LocalZonedTimestampType;
+import org.apache.fluss.types.MapType;
+import org.apache.fluss.types.RowType;
+import org.apache.fluss.types.TimestampType;
+
+import io.airlift.slice.Slice;
+import io.trino.spi.PageBuilder;
+import io.trino.spi.TrinoException;
+import io.trino.spi.block.ArrayBlockBuilder;
+import io.trino.spi.block.BlockBuilder;
+import io.trino.spi.block.MapBlockBuilder;
+import io.trino.spi.block.RowBlockBuilder;
+import io.trino.spi.type.Chars;
+import io.trino.spi.type.Int128;
+import io.trino.spi.type.LongTimestamp;
+import io.trino.spi.type.LongTimestampWithTimeZone;
+import io.trino.spi.type.Type;
+
+import java.util.List;
+
+import static io.airlift.slice.Slices.wrappedBuffer;
+import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
+import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
+import static io.trino.spi.type.DateTimeEncoding.packDateTimeWithZone;
+import static io.trino.spi.type.TimeZoneKey.UTC_KEY;
+import static org.apache.fluss.utils.Preconditions.checkArgument;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Writes supported Fluss values into driver-owned Trino blocks. */
+final class FlussRowDecoder {
+ private final List<FlussColumnHandle> columns;
+ private final List<Type> types;
+ private final List<DataType> dataTypes;
+
+ FlussRowDecoder(Schema schema, List<FlussColumnHandle> columns) {
+ checkNotNull(schema, "schema is null");
+ this.columns = ImmutableList.copyOf(checkNotNull(columns, "columns is null"));
+ ImmutableList.Builder<Type> types = ImmutableList.builder();
+ ImmutableList.Builder<DataType> dataTypes = ImmutableList.builder();
+ for (FlussColumnHandle column : columns) {
+ int ordinal = column.getOrdinalPosition();
+ checkArgument(ordinal < schema.getColumns().size(), "Column ordinal exceeds schema");
+ Schema.Column field = schema.getColumns().get(ordinal);
+ checkArgument(
+ field.getName().equals(column.getName()),
+ "Column does not match current table schema");
+ DataType dataType = field.getDataType();
+ dataTypes.add(dataType);
+ types.add(FlussTypeConverter.toTrinoType(dataType));
+ }
+ this.types = types.build();
+ this.dataTypes = dataTypes.build();
+ }
+
+ List<Type> getTypes() {
+ return types;
+ }
+
+ void append(InternalRow row, PageBuilder builder) {
+ for (int channel = 0; channel < columns.size(); channel++) {
+ writeValue(
+ row,
+ columns.get(channel).getOrdinalPosition(),
+ dataTypes.get(channel),
+ types.get(channel),
+ builder.getBlockBuilder(channel));
+ }
+ builder.declarePosition();
+ }
+
+ private static void writeValue(
+ DataGetters values, int position, DataType dataType, Type type, BlockBuilder block) {
+ if (values.isNullAt(position)) {
+ block.appendNull();
+ return;
+ }
+ switch (dataType.getTypeRoot()) {
+ case BOOLEAN:
+ type.writeBoolean(block, values.getBoolean(position));
+ break;
+ case TINYINT:
+ type.writeLong(block, values.getByte(position));
+ break;
+ case SMALLINT:
+ type.writeLong(block, values.getShort(position));
+ break;
+ case INTEGER:
+ case DATE:
+ type.writeLong(block, values.getInt(position));
+ break;
+ case BIGINT:
+ type.writeLong(block, values.getLong(position));
+ break;
+ case FLOAT:
+ type.writeLong(block, Float.floatToRawIntBits(values.getFloat(position)));
+ break;
+ case DOUBLE:
+ type.writeDouble(block, values.getDouble(position));
+ break;
+ case CHAR:
+ // Trino CHAR stores unpadded UTF-8; oversized Fluss CHAR maps to VARCHAR.
+ Slice chars =
+ wrappedBuffer(
+ values.getChar(position, ((CharType) dataType).getLength())
+ .toBytes());
+ type.writeSlice(
+ block,
+ type instanceof io.trino.spi.type.CharType
+ ? Chars.trimTrailingSpaces(chars)
+ : chars);
+ break;
+ case STRING:
+ type.writeSlice(block, wrappedBuffer(values.getString(position).toBytes()));
+ break;
+ case BINARY:
+ type.writeSlice(
+ block,
+ wrappedBuffer(
+ values.getBinary(position, ((BinaryType) dataType).getLength())));
+ break;
+ case BYTES:
+ type.writeSlice(block, wrappedBuffer(values.getBytes(position)));
+ break;
+ case DECIMAL:
+ DecimalType decimalType = (DecimalType) dataType;
+ Decimal decimal =
+ values.getDecimal(
+ position, decimalType.getPrecision(), decimalType.getScale());
+ if (((io.trino.spi.type.DecimalType) type).isShort()) {
+ type.writeLong(block, decimal.toUnscaledLong());
+ } else {
+ type.writeObject(block, Int128.valueOf(decimal.toBigDecimal().unscaledValue()));
+ }
+ break;
+ case TIME_WITHOUT_TIME_ZONE:
+ // Fluss InternalRow stores time as milliseconds of the day.
+ type.writeLong(block, values.getInt(position) * 1_000_000_000L);
+ break;
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ TimestampNtz timestamp =
+ values.getTimestampNtz(position, ((TimestampType) dataType).getPrecision());
+ long epochMicros =
+ Math.addExact(
+ Math.multiplyExact(timestamp.getMillisecond(), 1000),
+ timestamp.getNanoOfMillisecond() / 1000);
+ if (((io.trino.spi.type.TimestampType) type).isShort()) {
+ type.writeLong(block, epochMicros);
+ } else {
+ type.writeObject(
+ block,
+ new LongTimestamp(
+ epochMicros, (timestamp.getNanoOfMillisecond() % 1000) * 1000));
+ }
+ break;
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ TimestampLtz instant =
+ values.getTimestampLtz(
+ position, ((LocalZonedTimestampType) dataType).getPrecision());
+ if (((io.trino.spi.type.TimestampWithTimeZoneType) type).isShort()) {
+ type.writeLong(
+ block, packDateTimeWithZone(instant.getEpochMillisecond(), UTC_KEY));
+ } else {
+ type.writeObject(
+ block,
+ LongTimestampWithTimeZone.fromEpochMillisAndFraction(
+ instant.getEpochMillisecond(),
+ instant.getNanoOfMillisecond() * 1000,
+ UTC_KEY));
+ }
+ break;
+ case ARRAY:
+ InternalArray array = values.getArray(position);
+ DataType elementDataType = ((ArrayType) dataType).getElementType();
+ Type elementType = ((io.trino.spi.type.ArrayType) type).getElementType();
+ ((ArrayBlockBuilder) block)
+ .buildEntry(
+ elements -> {
+ for (int i = 0; i < array.size(); i++) {
+ writeValue(
+ array, i, elementDataType, elementType, elements);
+ }
+ });
+ break;
+ case MAP:
+ InternalMap map = values.getMap(position);
+ InternalArray keys = map.keyArray();
+ InternalArray mapValues = map.valueArray();
+ MapType mapDataType = (MapType) dataType;
+ io.trino.spi.type.MapType mapType = (io.trino.spi.type.MapType) type;
+ for (int i = 0; i < map.size(); i++) {
+ if (keys.isNullAt(i)) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR, "Fluss value contains a null map key");
+ }
+ }
+ ((MapBlockBuilder) block)
+ .strictNotDistinctFrom()
+ .buildEntry(
+ (keyBlock, valueBlock) -> {
+ for (int i = 0; i < map.size(); i++) {
+ writeValue(
+ keys,
+ i,
+ mapDataType.getKeyType(),
+ mapType.getKeyType(),
+ keyBlock);
+ writeValue(
+ mapValues,
+ i,
+ mapDataType.getValueType(),
+ mapType.getValueType(),
+ valueBlock);
+ }
+ });
+ break;
+ case ROW:
+ RowType rowDataType = (RowType) dataType;
+ InternalRow row = values.getRow(position, rowDataType.getFieldCount());
+ List<Type> fieldTypes = type.getTypeParameters();
+ ((RowBlockBuilder) block)
+ .buildEntry(
+ fields -> {
+ for (int i = 0; i < rowDataType.getFieldCount(); i++) {
+ writeValue(
+ row,
+ i,
+ rowDataType.getFields().get(i).getType(),
+ fieldTypes.get(i),
+ fields.get(i));
+ }
+ });
+ break;
+ default:
+ throw new TrinoException(
+ NOT_SUPPORTED,
+ "Unsupported Fluss read type: " + dataType.asSummaryString());
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussScanType.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussScanType.java
new file mode 100644
index 0000000000..b3e89e1fa5
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussScanType.java
@@ -0,0 +1,25 @@
+/*
+ * 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.fluss.trino;
+
+/** Identifies the storage scan performed for a Fluss bucket split. */
+public enum FlussScanType {
+ LOG,
+ KV
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplit.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplit.java
new file mode 100644
index 0000000000..78b6ecd687
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplit.java
@@ -0,0 +1,110 @@
+/*
+ * 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.fluss.trino;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.trino.spi.connector.ConnectorSplit;
+
+import java.util.Optional;
+
+import static io.airlift.slice.SizeOf.instanceSize;
+import static io.airlift.slice.SizeOf.sizeOf;
+import static org.apache.fluss.utils.Preconditions.checkArgument;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** A storage scan for one Fluss bucket, with an exclusive-end range for log scans. */
+public final class FlussSplit implements ConnectorSplit {
+ private static final int INSTANCE_SIZE = instanceSize(FlussSplit.class);
+
+ private final FlussScanType scanType;
+ private final FlussBucketHandle bucket;
+ private final Optional<FlussLogRange> logRange;
+
+ @JsonCreator
+ public FlussSplit(
+ @JsonProperty("scanType") FlussScanType scanType,
+ @JsonProperty("bucket") FlussBucketHandle bucket,
+ @JsonProperty("logRange") Optional<FlussLogRange> logRange) {
+ this.scanType = checkNotNull(scanType, "scanType is null");
+ this.bucket = checkNotNull(bucket, "bucket is null");
+ this.logRange = checkNotNull(logRange, "logRange is null");
+
+ switch (scanType) {
+ case LOG:
+ checkArgument(logRange.isPresent(), "LOG split requires a log range");
+ break;
+ case KV:
+ checkArgument(!logRange.isPresent(), "KV split cannot have a log range");
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported scanType: " + scanType);
+ }
+ }
+
+ static FlussSplit forLog(FlussBucketHandle bucket, long startOffset, long stoppingOffset) {
+ return new FlussSplit(
+ FlussScanType.LOG,
+ bucket,
+ Optional.of(new FlussLogRange(startOffset, stoppingOffset)));
+ }
+
+ static FlussSplit forKv(FlussBucketHandle bucket) {
+ return new FlussSplit(FlussScanType.KV, bucket, Optional.empty());
+ }
+
+ @JsonProperty
+ public FlussScanType getScanType() {
+ return scanType;
+ }
+
+ @JsonProperty
+ public FlussBucketHandle getBucket() {
+ return bucket;
+ }
+
+ @JsonProperty
+ public Optional<FlussLogRange> getLogRange() {
+ return logRange;
+ }
+
+ FlussLogRange getRequiredLogRange() {
+ return logRange.orElseThrow(
+ () -> new IllegalStateException("Split does not contain a log range"));
+ }
+
+ @Override
+ public long getRetainedSizeInBytes() {
+ return INSTANCE_SIZE
+ + bucket.getRetainedSizeInBytes()
+ + sizeOf(logRange, FlussLogRange::getRetainedSizeInBytes);
+ }
+
+ @Override
+ public String toString() {
+ switch (scanType) {
+ case LOG:
+ return "LOG " + bucket + ":" + getRequiredLogRange();
+ case KV:
+ return "KV " + bucket;
+ default:
+ throw new IllegalStateException("Unknown scan type: " + scanType);
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitManager.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitManager.java
new file mode 100644
index 0000000000..d28f333faf
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitManager.java
@@ -0,0 +1,62 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.metadata.TableInfo;
+
+import com.google.inject.Inject;
+import io.trino.spi.connector.ColumnHandle;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.ConnectorSplitManager;
+import io.trino.spi.connector.ConnectorSplitSource;
+import io.trino.spi.connector.ConnectorTableHandle;
+import io.trino.spi.connector.ConnectorTransactionHandle;
+import io.trino.spi.connector.Constraint;
+import io.trino.spi.connector.FixedSplitSource;
+
+import java.util.Set;
+
+import static org.apache.fluss.trino.FlussTableScanValidator.validateTable;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Plans bounded physical-bucket scans for native Fluss tables. */
+public final class FlussSplitManager implements ConnectorSplitManager {
+
+ private final FlussMetadataAccess metadataAccess;
+ private final FlussSplitPlanner splitPlanner;
+
+ @Inject
+ FlussSplitManager(FlussMetadataAccess metadataAccess, FlussSplitPlanner splitPlanner) {
+ this.metadataAccess = checkNotNull(metadataAccess, "metadataAccess is null");
+ this.splitPlanner = checkNotNull(splitPlanner, "splitPlanner is null");
+ }
+
+ @Override
+ public ConnectorSplitSource getSplits(
+ ConnectorTransactionHandle transaction,
+ ConnectorSession session,
+ ConnectorTableHandle table,
+ Set<ColumnHandle> dynamicFilterColumns,
+ Constraint constraint) {
+ FlussTableHandle handle = (FlussTableHandle) table;
+ TableInfo tableInfo = metadataAccess.getTableInfo(handle);
+ validateTable(handle, tableInfo);
+ return new FixedSplitSource(splitPlanner.plan(handle, tableInfo));
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitPlanner.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitPlanner.java
new file mode 100644
index 0000000000..0eda220a1a
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitPlanner.java
@@ -0,0 +1,129 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.admin.OffsetSpec;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList;
+
+import com.google.inject.Inject;
+import io.trino.spi.TrinoException;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_SPLIT_ERROR;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+final class FlussSplitPlanner {
+ private final FlussMetadataAccess metadataAccess;
+
+ @Inject
+ FlussSplitPlanner(FlussMetadataAccess metadataAccess) {
+ this.metadataAccess = checkNotNull(metadataAccess, "metadataAccess is null");
+ }
+
+ List<FlussSplit> plan(FlussTableHandle table, TableInfo tableInfo) {
+ List<FlussPhysicalBucket> buckets = metadataAccess.listScanBuckets(table);
+
+ validateBucketShape(buckets, tableInfo);
+
+ if (buckets.isEmpty()) {
+ return ImmutableList.of();
+ }
+
+ if (tableInfo.hasPrimaryKey()) {
+ return planKvSplits(buckets);
+ }
+
+ return planLogSplits(table, buckets);
+ }
+
+ private static void validateBucketShape(
+ List<FlussPhysicalBucket> buckets, TableInfo tableInfo) {
+ Set<FlussBucketHandle> seen = new HashSet<>();
+
+ for (FlussPhysicalBucket physicalBucket : buckets) {
+ FlussBucketHandle bucket = physicalBucket.getBucket();
+
+ if (bucket.isPartitioned() != tableInfo.isPartitioned()) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Fluss bucket partition layout does not match table metadata: "
+ + bucket
+ + ", tablePartitioned="
+ + tableInfo.isPartitioned());
+ }
+
+ if (!seen.add(bucket)) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Duplicate Fluss bucket in scan planning: " + bucket);
+ }
+ }
+ }
+
+ private static List<FlussSplit> planKvSplits(List<FlussPhysicalBucket> buckets) {
+ return buckets.stream()
+ .map(FlussPhysicalBucket::getBucket)
+ .map(FlussSplit::forKv)
+ .collect(ImmutableList.toImmutableList());
+ }
+
+ private List<FlussSplit> planLogSplits(
+ FlussTableHandle table, List<FlussPhysicalBucket> buckets) {
+ Map<FlussBucketHandle, Long> starts =
+ metadataAccess.resolveOffsets(table, buckets, new OffsetSpec.EarliestSpec());
+
+ Map<FlussBucketHandle, Long> stops =
+ metadataAccess.resolveOffsets(table, buckets, new OffsetSpec.LatestSpec());
+
+ List<FlussPhysicalBucket> remainingBuckets =
+ metadataAccess.retainCurrentBuckets(table, buckets);
+
+ ImmutableList.Builder<FlussSplit> splits = ImmutableList.builder();
+
+ for (FlussPhysicalBucket physicalBucket : remainingBuckets) {
+ FlussBucketHandle bucket = physicalBucket.getBucket();
+
+ Long start = starts.get(bucket);
+ Long stop = stops.get(bucket);
+
+ if (start == null || stop == null) {
+ throw new TrinoException(
+ FLUSS_SPLIT_ERROR, "Missing Fluss log offsets for " + bucket);
+ }
+
+ if (start > stop) {
+ throw new TrinoException(
+ FLUSS_SPLIT_ERROR,
+ "Invalid Fluss log range for " + bucket + ": [" + start + "," + stop + ")");
+ }
+
+ if (start < stop) {
+ splits.add(FlussSplit.forLog(bucket, start, stop));
+ }
+ }
+
+ return splits.build();
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitReader.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitReader.java
new file mode 100644
index 0000000000..05dc5cb890
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitReader.java
@@ -0,0 +1,82 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.row.InternalRow;
+
+import java.time.Duration;
+
+/**
+ * Reads rows for one physical Fluss split.
+ *
+ * <p>A reader owns the Fluss scanner and any buffered input belonging to the current scanner batch.
+ * Polling has three outcomes:
+ *
+ * <ul>
+ * <li>{@link PollResult#AVAILABLE}: at least one row can be consumed;
+ * <li>{@link PollResult#YIELD}: no row is currently available, but the split is not finished;
+ * <li>{@link PollResult#FINISHED}: the bounded split has been fully consumed.
+ * </ul>
+ *
+ * <p>The caller consumes the complete buffered batch before polling again.
+ */
+interface FlussSplitReader extends AutoCloseable {
+
+ enum PollResult {
+ AVAILABLE,
+ YIELD,
+ FINISHED
+ }
+
+ /**
+ * Polls the underlying Fluss scanner at most once.
+ *
+ * <p>This method must only be called when {@link #hasNext()} is false.
+ */
+ PollResult poll(Duration timeout);
+
+ /** Returns whether a buffered row can be consumed without another scanner poll. */
+ boolean hasNext();
+
+ /** Returns the next buffered row. */
+ InternalRow next();
+
+ /**
+ * Returns whether the bounded split is fully consumed.
+ *
+ * <p>A finished reader must not have buffered rows.
+ */
+ boolean isFinished();
+
+ /**
+ * Returns the currently retained input memory known to the reader.
+ *
+ * <p>This excludes memory whose retained size is not exposed by the Fluss client.
+ */
+ long getRetainedSizeInBytes();
+
+ /**
+ * Returns encoded input bytes consumed so far, or zero when the underlying Fluss API does not
+ * expose a useful byte count.
+ */
+ long getCompletedBytes();
+
+ @Override
+ void close() throws Exception;
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitReaderFactory.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitReaderFactory.java
new file mode 100644
index 0000000000..f81a2da449
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussSplitReaderFactory.java
@@ -0,0 +1,44 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.table.Table;
+
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+final class FlussSplitReaderFactory {
+
+ private FlussSplitReaderFactory() {}
+
+ static FlussSplitReader create(Table table, FlussSplit split) {
+ checkNotNull(table, "table is null");
+ checkNotNull(split, "split is null");
+
+ switch (split.getScanType()) {
+ case LOG:
+ return new FlussLogSplitReader(
+ table, split.getBucket(), split.getRequiredLogRange());
+ case KV:
+ return new FlussKvSplitReader(table, split.getBucket());
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported Fluss scan type: " + split.getScanType());
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTableHandle.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTableHandle.java
new file mode 100644
index 0000000000..6b20b1f201
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTableHandle.java
@@ -0,0 +1,132 @@
+/*
+ * 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.fluss.trino;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.trino.spi.connector.ConnectorTableHandle;
+
+import java.util.Objects;
+
+import static org.apache.fluss.utils.Preconditions.checkArgument;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Immutable Fluss table handle. */
+public final class FlussTableHandle implements ConnectorTableHandle {
+
+ // Trino-visible logical identity.
+ private final String schemaName;
+ private final String tableName;
+
+ // Physical Fluss identity.
+ private final String flussDatabaseName;
+ private final String flussTableName;
+ private final long tableId;
+ private final int schemaId;
+
+ @JsonCreator
+ public FlussTableHandle(
+ @JsonProperty("schemaName") String schemaName,
+ @JsonProperty("tableName") String tableName,
+ @JsonProperty("flussDatabaseName") String flussDatabaseName,
+ @JsonProperty("flussTableName") String flussTableName,
+ @JsonProperty("tableId") long tableId,
+ @JsonProperty("schemaId") int schemaId) {
+ this.schemaName = checkNotNull(schemaName, "schemaName is null");
+ this.tableName = checkNotNull(tableName, "tableName is null");
+ this.flussDatabaseName = checkNotNull(flussDatabaseName, "flussDatabaseName is null");
+ this.flussTableName = checkNotNull(flussTableName, "flussTableName is null");
+ checkArgument(tableId >= 0, "tableId must be non-negative");
+ checkArgument(schemaId >= 0, "schemaId must be non-negative");
+ this.tableId = tableId;
+ this.schemaId = schemaId;
+ }
+
+ @JsonProperty
+ public String getSchemaName() {
+ return schemaName;
+ }
+
+ @JsonProperty
+ public String getTableName() {
+ return tableName;
+ }
+
+ @JsonProperty
+ public String getFlussDatabaseName() {
+ return flussDatabaseName;
+ }
+
+ @JsonProperty
+ public String getFlussTableName() {
+ return flussTableName;
+ }
+
+ @JsonProperty
+ public long getTableId() {
+ return tableId;
+ }
+
+ @JsonProperty
+ public int getSchemaId() {
+ return schemaId;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ FlussTableHandle that = (FlussTableHandle) o;
+ return tableId == that.tableId
+ && schemaId == that.schemaId
+ && Objects.equals(schemaName, that.schemaName)
+ && Objects.equals(tableName, that.tableName)
+ && Objects.equals(flussDatabaseName, that.flussDatabaseName)
+ && Objects.equals(flussTableName, that.flussTableName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(
+ schemaName, tableName, flussDatabaseName, flussTableName, tableId, schemaId);
+ }
+
+ @Override
+ public String toString() {
+ return "FlussTableHandle{"
+ + "schemaName='"
+ + schemaName
+ + '\''
+ + ", tableName='"
+ + tableName
+ + '\''
+ + ", flussDatabaseName='"
+ + flussDatabaseName
+ + '\''
+ + ", flussTableName='"
+ + flussTableName
+ + '\''
+ + ", tableId="
+ + tableId
+ + ", schemaId="
+ + schemaId
+ + '}';
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTableProperties.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTableProperties.java
new file mode 100644
index 0000000000..35df424847
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTableProperties.java
@@ -0,0 +1,123 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableList;
+
+import io.trino.spi.session.PropertyMetadata;
+import io.trino.spi.type.ArrayType;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static io.trino.spi.session.PropertyMetadata.integerProperty;
+import static io.trino.spi.type.VarcharType.VARCHAR;
+import static org.apache.fluss.config.ConfigOptions.TABLE_KV_FORMAT_VERSION;
+import static org.apache.fluss.config.ConfigOptions.TABLE_KV_VALUE_LAYOUT_VERSION;
+import static org.apache.fluss.config.ConfigOptions.TABLE_REPLICATION_FACTOR;
+
+/** Fluss table attributes exposed by Trino SHOW CREATE TABLE. */
+final class FlussTableProperties {
+
+ private static final String PRIMARY_KEY = "primary_key";
+ private static final String PARTITIONED_BY = "partitioned_by";
+ private static final String BUCKET_KEY = "bucket_key";
+ private static final String BUCKET_COUNT = "bucket_count";
+ private static final String REPLICATION_FACTOR = "replication_factor";
+ private static final String KV_FORMAT_VERSION = "kv_format_version";
+ private static final String KV_VALUE_LAYOUT_VERSION = "kv_value_layout_version";
+
+ private static final List<PropertyMetadata<?>> TABLE_PROPERTIES =
+ ImmutableList.of(
+ columnListProperty(PRIMARY_KEY, "Ordered Fluss primary key columns"),
+ columnListProperty(PARTITIONED_BY, "Ordered Fluss partition key columns"),
+ columnListProperty(BUCKET_KEY, "Ordered Fluss bucket key columns"),
+ integerProperty(
+ BUCKET_COUNT,
+ "Configured Fluss bucket count; used as the default for new partitions",
+ null,
+ false),
+ integerProperty(REPLICATION_FACTOR, "Fluss replication factor", null, false),
+ integerProperty(KV_FORMAT_VERSION, "Fluss KV format version", null, false),
+ integerProperty(
+ KV_VALUE_LAYOUT_VERSION, "Fluss KV value layout version", null, false));
+
+ private FlussTableProperties() {}
+
+ static List<PropertyMetadata<?>> getTableProperties() {
+ return TABLE_PROPERTIES;
+ }
+
+ static Map<String, Object> fromTableInfo(TableInfo info) {
+ Map<String, Object> properties = new LinkedHashMap<>();
+
+ if (info.hasPrimaryKey()) {
+ properties.put(PRIMARY_KEY, toTrinoColumnNames(info.getPrimaryKeys()));
+
+ info.getProperties()
+ .getOptional(TABLE_KV_FORMAT_VERSION)
+ .ifPresent(value -> properties.put(KV_FORMAT_VERSION, value));
+
+ info.getProperties()
+ .getOptional(TABLE_KV_VALUE_LAYOUT_VERSION)
+ .ifPresent(value -> properties.put(KV_VALUE_LAYOUT_VERSION, value));
+ }
+
+ if (info.isPartitioned()) {
+ properties.put(PARTITIONED_BY, toTrinoColumnNames(info.getPartitionKeys()));
+ }
+
+ if (info.hasBucketKey()) {
+ properties.put(BUCKET_KEY, toTrinoColumnNames(info.getBucketKeys()));
+ }
+
+ properties.put(BUCKET_COUNT, info.getNumBuckets());
+
+ info.getProperties()
+ .getOptional(TABLE_REPLICATION_FACTOR)
+ .ifPresent(value -> properties.put(REPLICATION_FACTOR, value));
+
+ return Collections.unmodifiableMap(properties);
+ }
+
+ private static PropertyMetadata<?> columnListProperty(String name, String description) {
+ return new PropertyMetadata<>(
+ name,
+ description,
+ new ArrayType(VARCHAR),
+ List.class,
+ null,
+ false,
+ value ->
+ ((List<?>) value)
+ .stream().map(String.class::cast).collect(Collectors.toList()),
+ value -> value);
+ }
+
+ private static List<String> toTrinoColumnNames(List<String> columnNames) {
+ return columnNames.stream()
+ .map(name -> name.toLowerCase(Locale.ROOT))
+ .collect(ImmutableList.toImmutableList());
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTableScanValidator.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTableScanValidator.java
new file mode 100644
index 0000000000..8b82676625
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTableScanValidator.java
@@ -0,0 +1,79 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.metadata.TableInfo;
+
+import io.trino.spi.TrinoException;
+
+import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
+import static io.trino.spi.StandardErrorCode.UNSUPPORTED_TABLE_TYPE;
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_METADATA_CHANGED;
+
+final class FlussTableScanValidator {
+
+ private FlussTableScanValidator() {}
+
+ static void validateIdentity(FlussTableHandle handle, TableInfo info) {
+ if (handle.getTableId() != info.getTableId()) {
+ throw new TrinoException(
+ FLUSS_METADATA_CHANGED, "Fluss table changed; retry the query");
+ }
+
+ if (handle.getSchemaId() != info.getSchemaId()) {
+ throw new TrinoException(
+ FLUSS_METADATA_CHANGED, "Fluss table schema changed; retry the query");
+ }
+ }
+
+ static void validateTable(FlussTableHandle handle, TableInfo info) {
+ validateIdentity(handle, info);
+
+ if (info.getTableConfig().isDataLakeEnabled()) {
+ throw new TrinoException(
+ UNSUPPORTED_TABLE_TYPE, "Reading Fluss Lakehouse tables is not supported");
+ }
+ }
+
+ static void validateSplit(FlussSplit split, TableInfo info) {
+ FlussBucketHandle bucket = split.getBucket();
+
+ if (bucket.getTableId() != info.getTableId()) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR, "Fluss split table ID does not match the opened table");
+ }
+
+ if (bucket.isPartitioned() != info.isPartitioned()) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Fluss split partition layout does not match the opened table");
+ }
+
+ FlussScanType expected = info.hasPrimaryKey() ? FlussScanType.KV : FlussScanType.LOG;
+
+ if (split.getScanType() != expected) {
+ throw new TrinoException(
+ GENERIC_INTERNAL_ERROR,
+ "Fluss split scan type "
+ + split.getScanType()
+ + " does not match table scan type "
+ + expected);
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTransactionHandle.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTransactionHandle.java
new file mode 100644
index 0000000000..6c16c4ef67
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTransactionHandle.java
@@ -0,0 +1,26 @@
+/*
+ * 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.fluss.trino;
+
+import io.trino.spi.connector.ConnectorTransactionHandle;
+
+/** Transaction handle for the Fluss connector. */
+public enum FlussTransactionHandle implements ConnectorTransactionHandle {
+ INSTANCE
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTypeConverter.java b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTypeConverter.java
new file mode 100644
index 0000000000..ae40d238c9
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/FlussTypeConverter.java
@@ -0,0 +1,154 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.types.ArrayType;
+import org.apache.fluss.types.CharType;
+import org.apache.fluss.types.DataType;
+import org.apache.fluss.types.DecimalType;
+import org.apache.fluss.types.LocalZonedTimestampType;
+import org.apache.fluss.types.MapType;
+import org.apache.fluss.types.RowType;
+import org.apache.fluss.types.TimeType;
+import org.apache.fluss.types.TimestampType;
+
+import io.trino.spi.TrinoException;
+import io.trino.spi.type.Type;
+import io.trino.spi.type.TypeOperators;
+import io.trino.spi.type.VarcharType;
+
+import java.util.stream.Collectors;
+
+import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
+import static io.trino.spi.type.BigintType.BIGINT;
+import static io.trino.spi.type.BooleanType.BOOLEAN;
+import static io.trino.spi.type.DateType.DATE;
+import static io.trino.spi.type.DoubleType.DOUBLE;
+import static io.trino.spi.type.IntegerType.INTEGER;
+import static io.trino.spi.type.RealType.REAL;
+import static io.trino.spi.type.SmallintType.SMALLINT;
+import static io.trino.spi.type.TinyintType.TINYINT;
+import static io.trino.spi.type.VarbinaryType.VARBINARY;
+import static io.trino.spi.type.VarcharType.VARCHAR;
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Converts Fluss logical types to Trino types. */
+final class FlussTypeConverter {
+
+ private static final TypeOperators TYPE_OPERATORS = new TypeOperators();
+
+ private FlussTypeConverter() {}
+
+ static Type toTrinoType(DataType dataType) {
+ checkNotNull(dataType, "dataType is null");
+
+ switch (dataType.getTypeRoot()) {
+ case BOOLEAN:
+ return BOOLEAN;
+ case TINYINT:
+ return TINYINT;
+ case SMALLINT:
+ return SMALLINT;
+ case INTEGER:
+ return INTEGER;
+ case BIGINT:
+ return BIGINT;
+ case FLOAT:
+ return REAL;
+ case DOUBLE:
+ return DOUBLE;
+ case CHAR:
+ {
+ CharType charType = (CharType) dataType;
+ int length = charType.getLength();
+ if (length <= io.trino.spi.type.CharType.MAX_LENGTH) {
+ return io.trino.spi.type.CharType.createCharType(length);
+ }
+ if (length <= VarcharType.MAX_LENGTH) {
+ return VarcharType.createVarcharType(length);
+ }
+ return VARCHAR;
+ }
+
+ case STRING:
+ return VARCHAR;
+ case BINARY:
+ case BYTES:
+ return VARBINARY;
+ case DECIMAL:
+ {
+ DecimalType decimalType = (DecimalType) dataType;
+ return io.trino.spi.type.DecimalType.createDecimalType(
+ decimalType.getPrecision(), decimalType.getScale());
+ }
+ case DATE:
+ return DATE;
+ case TIME_WITHOUT_TIME_ZONE:
+ {
+ TimeType timeType = (TimeType) dataType;
+ return io.trino.spi.type.TimeType.createTimeType(timeType.getPrecision());
+ }
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ {
+ TimestampType timestampType = (TimestampType) dataType;
+ return io.trino.spi.type.TimestampType.createTimestampType(
+ timestampType.getPrecision());
+ }
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ {
+ LocalZonedTimestampType timestampType = (LocalZonedTimestampType) dataType;
+ return io.trino.spi.type.TimestampWithTimeZoneType
+ .createTimestampWithTimeZoneType(timestampType.getPrecision());
+ }
+ case ARRAY:
+ {
+ ArrayType arrayType = (ArrayType) dataType;
+ return new io.trino.spi.type.ArrayType(toTrinoType(arrayType.getElementType()));
+ }
+ case MAP:
+ {
+ MapType mapType = (MapType) dataType;
+ Type keyType = toTrinoType(mapType.getKeyType());
+ Type valueType = toTrinoType(mapType.getValueType());
+ if (!keyType.isComparable()) {
+ throw new TrinoException(
+ NOT_SUPPORTED,
+ "Unsupported Fluss map key type: "
+ + mapType.getKeyType().asSummaryString());
+ }
+ return new io.trino.spi.type.MapType(keyType, valueType, TYPE_OPERATORS);
+ }
+ case ROW:
+ {
+ RowType rowType = (RowType) dataType;
+ return io.trino.spi.type.RowType.from(
+ rowType.getFields().stream()
+ .map(
+ field ->
+ io.trino.spi.type.RowType.field(
+ field.getName(),
+ toTrinoType(field.getType())))
+ .collect(Collectors.toList()));
+ }
+ default:
+ throw new TrinoException(
+ NOT_SUPPORTED, "Unsupported Fluss type: " + dataType.asSummaryString());
+ }
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/ResolvedSchemaName.java b/fluss-trino/src/main/java/org/apache/fluss/trino/ResolvedSchemaName.java
new file mode 100644
index 0000000000..9b1b1b59af
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/ResolvedSchemaName.java
@@ -0,0 +1,48 @@
+/*
+ * 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.fluss.trino;
+
+import io.trino.spi.connector.SchemaTableName;
+
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Resolved mapping between a Trino schema name and the physical Fluss database name. */
+final class ResolvedSchemaName {
+
+ private final String trinoName;
+ private final String flussName;
+
+ ResolvedSchemaName(String trinoName, String flussName) {
+ this.trinoName = checkNotNull(trinoName, "trinoName is null");
+ this.flussName = checkNotNull(flussName, "flussName is null");
+ }
+
+ String getTrinoName() {
+ return trinoName;
+ }
+
+ String getFlussName() {
+ return flussName;
+ }
+
+ ResolvedTableName table(String trinoTableName, String flussTableName) {
+ return new ResolvedTableName(
+ new SchemaTableName(trinoName, trinoTableName), flussName, flussTableName);
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/ResolvedTableName.java b/fluss-trino/src/main/java/org/apache/fluss/trino/ResolvedTableName.java
new file mode 100644
index 0000000000..783c811d20
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/ResolvedTableName.java
@@ -0,0 +1,49 @@
+/*
+ * 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.fluss.trino;
+
+import io.trino.spi.connector.SchemaTableName;
+
+import static org.apache.fluss.utils.Preconditions.checkNotNull;
+
+/** Resolved mapping between a Trino table name and its physical Fluss table identity. */
+final class ResolvedTableName {
+
+ private final SchemaTableName trinoName;
+ private final String flussDatabaseName;
+ private final String flussTableName;
+
+ ResolvedTableName(SchemaTableName trinoName, String flussDatabaseName, String flussTableName) {
+ this.trinoName = checkNotNull(trinoName, "trinoName is null");
+ this.flussDatabaseName = checkNotNull(flussDatabaseName, "flussDatabaseName is null");
+ this.flussTableName = checkNotNull(flussTableName, "flussTableName is null");
+ }
+
+ SchemaTableName getTrinoName() {
+ return trinoName;
+ }
+
+ String getFlussDatabaseName() {
+ return flussDatabaseName;
+ }
+
+ String getFlussTableName() {
+ return flussTableName;
+ }
+}
diff --git a/fluss-trino/src/main/java/org/apache/fluss/trino/TrinoVersionCompatibility.java b/fluss-trino/src/main/java/org/apache/fluss/trino/TrinoVersionCompatibility.java
new file mode 100644
index 0000000000..f9a7463fd6
--- /dev/null
+++ b/fluss-trino/src/main/java/org/apache/fluss/trino/TrinoVersionCompatibility.java
@@ -0,0 +1,103 @@
+/*
+ * 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.fluss.trino;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+final class TrinoVersionCompatibility {
+
+ private static final int MIN_SUPPORTED_VERSION = 483;
+ private static final int MAX_SUPPORTED_VERSION = 483;
+
+ private static final int MIN_SUPPORTED_SNAPSHOT_VERSION = 483;
+ private static final int MAX_SUPPORTED_SNAPSHOT_VERSION = 483;
+
+ private static final Pattern VERSION_PATTERN =
+ Pattern.compile("^(\\d+)(-SNAPSHOT)?$", Pattern.CASE_INSENSITIVE);
+
+ private TrinoVersionCompatibility() {}
+
+ static void verifyCompatibleVersion(String spiVersion) {
+ ParsedVersion version = parseVersion(spiVersion);
+
+ if (version.isSnapshot()) {
+ verifySnapshotVersion(spiVersion, version.getVersion());
+ return;
+ }
+
+ verifyReleaseVersion(spiVersion, version.getVersion());
+ }
+
+ private static void verifyReleaseVersion(String spiVersion, int version) {
+ if (version < MIN_SUPPORTED_VERSION || version > MAX_SUPPORTED_VERSION) {
+ throw new IllegalStateException(
+ String.format(
+ "Unsupported Trino SPI version %s; supported release versions are %s through %s",
+ spiVersion, MIN_SUPPORTED_VERSION, MAX_SUPPORTED_VERSION));
+ }
+ }
+
+ private static void verifySnapshotVersion(String spiVersion, int version) {
+ if (version < MIN_SUPPORTED_SNAPSHOT_VERSION || version > MAX_SUPPORTED_SNAPSHOT_VERSION) {
+ throw new IllegalStateException(
+ String.format(
+ "Unsupported Trino SPI version %s; supported snapshot versions are %s-SNAPSHOT through %s-SNAPSHOT",
+ spiVersion,
+ MIN_SUPPORTED_SNAPSHOT_VERSION,
+ MAX_SUPPORTED_SNAPSHOT_VERSION));
+ }
+ }
+
+ private static ParsedVersion parseVersion(String spiVersion) {
+ if (spiVersion == null) {
+ throw new IllegalStateException("Unsupported Trino SPI version format: null");
+ }
+
+ Matcher matcher = VERSION_PATTERN.matcher(spiVersion);
+ if (!matcher.matches()) {
+ throw new IllegalStateException("Unsupported Trino SPI version format: " + spiVersion);
+ }
+
+ try {
+ return new ParsedVersion(Integer.parseInt(matcher.group(1)), matcher.group(2) != null);
+ } catch (NumberFormatException e) {
+ throw new IllegalStateException("Unsupported Trino SPI version format: " + spiVersion);
+ }
+ }
+
+ private static final class ParsedVersion {
+
+ private final int version;
+ private final boolean snapshot;
+
+ private ParsedVersion(int version, boolean snapshot) {
+ this.version = version;
+ this.snapshot = snapshot;
+ }
+
+ private int getVersion() {
+ return version;
+ }
+
+ private boolean isSnapshot() {
+ return snapshot;
+ }
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussBucketHandleTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussBucketHandleTest.java
new file mode 100644
index 0000000000..7f970b4b68
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussBucketHandleTest.java
@@ -0,0 +1,77 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.metadata.TableBucket;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Optional;
+
+import static io.airlift.json.JsonCodec.jsonCodec;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests physical bucket identity independently of a table's schema identity. */
+final class FlussBucketHandleTest {
+ @Test
+ void testPartitionIdentityRoundTripAndConversion() {
+ FlussBucketHandle bucket = new FlussBucketHandle(42, Optional.of(7L), 2);
+ FlussBucketHandle copy =
+ jsonCodec(FlussBucketHandle.class)
+ .fromJson(jsonCodec(FlussBucketHandle.class).toJson(bucket));
+ assertThat(copy).isEqualTo(bucket).hasSameHashCodeAs(bucket);
+ assertThat(copy.toTableBucket()).isEqualTo(new TableBucket(42, 7L, 2));
+ assertThat(copy.getRequiredPartitionId()).isEqualTo(7);
+ assertThat(copy).isNotEqualTo(new FlussBucketHandle(42, Optional.of(8L), 2));
+ assertThat(copy).isNotEqualTo(new FlussBucketHandle(43, Optional.of(7L), 2));
+ assertThat(copy).isNotEqualTo(new FlussBucketHandle(42, Optional.of(7L), 3));
+ FlussBucketHandle unpartitioned = new FlussBucketHandle(42, Optional.empty(), 2);
+ assertThat(unpartitioned.toTableBucket()).isEqualTo(new TableBucket(42, 2));
+ assertThat(unpartitioned).isNotEqualTo(copy);
+ assertThatThrownBy(unpartitioned::getRequiredPartitionId)
+ .isInstanceOf(IllegalStateException.class);
+ }
+
+ @Test
+ void testInvalidIdentifiers() {
+ assertThatThrownBy(() -> new FlussBucketHandle(-1, Optional.empty(), 0))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> new FlussBucketHandle(1, Optional.of(-1L), 0))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> new FlussBucketHandle(1, Optional.empty(), -1))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void testPartitionNameAndIdMustAgree() {
+ FlussBucketHandle bucket = new FlussBucketHandle(42, Optional.of(7L), 0);
+ assertThat(
+ new FlussPhysicalBucket(bucket, Optional.of("region=us"))
+ .getRequiredPartitionName())
+ .isEqualTo("region=us");
+ assertThatThrownBy(() -> new FlussPhysicalBucket(bucket, Optional.empty()))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ new FlussPhysicalBucket(
+ new FlussBucketHandle(42, Optional.empty(), 0),
+ Optional.of("region=us")))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussClientManagerTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussClientManagerTest.java
new file mode 100644
index 0000000000..be21a39e63
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussClientManagerTest.java
@@ -0,0 +1,308 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.Connection;
+import org.apache.fluss.client.ConnectionFactory;
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.exception.AuthenticationException;
+import org.apache.fluss.metadata.TablePath;
+
+import org.junit.jupiter.api.Test;
+import org.mockito.InOrder;
+import org.mockito.MockedStatic;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** Tests client ownership without creating network connections. */
+final class FlussClientManagerTest {
+ @Test
+ void testPlaintextConfigurationAndCloseOrder() throws Exception {
+ Connection connection = mock(Connection.class);
+ Admin admin = mock(Admin.class);
+ when(connection.getAdmin()).thenReturn(admin);
+
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ factory.when(() -> ConnectionFactory.createConnection(any(Configuration.class)))
+ .thenAnswer(
+ invocation -> {
+ Configuration config = invocation.getArgument(0);
+ assertThat(config.toMap())
+ .containsEntry("bootstrap.servers", "localhost:9123")
+ .containsEntry("client.security.protocol", "PLAINTEXT")
+ .doesNotContainKeys(
+ "client.security.sasl.mechanism",
+ "client.security.sasl.username",
+ "client.security.sasl.password");
+ return connection;
+ });
+
+ FlussClientManager manager =
+ new FlussClientManager(
+ new FlussConfig()
+ .setBootstrapServers("localhost:9123")
+ .setSecurityProtocol("PLAINTEXT"));
+
+ // Construction must not connect to Fluss.
+ factory.verifyNoInteractions();
+
+ assertThat(manager.getAdmin()).isSameAs(admin);
+ assertThat(manager.getAdmin()).isSameAs(admin);
+
+ manager.close();
+ manager.close();
+
+ assertThatThrownBy(manager::getAdmin)
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("closed");
+
+ InOrder order = inOrder(admin, connection);
+ order.verify(admin).close();
+ order.verify(connection).close();
+
+ verify(connection).getAdmin();
+ factory.verify(() -> ConnectionFactory.createConnection(any(Configuration.class)));
+ }
+ }
+
+ @Test
+ void testInitializationFailurePreservesAuthenticationCause() {
+ RuntimeException failure =
+ new RuntimeException(
+ "Failed to initialize Fluss client",
+ new AuthenticationException("Failed to create SASL client"));
+
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ factory.when(() -> ConnectionFactory.createConnection(any(Configuration.class)))
+ .thenThrow(failure);
+
+ assertThatThrownBy(
+ () ->
+ new FlussClientManager(
+ new FlussConfig()
+ .setBootstrapServers("localhost:9123"))
+ .getAdmin())
+ .isSameAs(failure);
+ }
+ }
+
+ @Test
+ void testSlowTableOpenDoesNotBlockOtherCallers() throws Exception {
+ Connection connection = mock(Connection.class);
+ Admin admin = mock(Admin.class);
+ Table table = mock(Table.class);
+ when(connection.getAdmin()).thenReturn(admin);
+
+ CountDownLatch openStarted = new CountDownLatch(1);
+ CountDownLatch releaseOpen = new CountDownLatch(1);
+ when(connection.getTable(any(TablePath.class)))
+ .thenAnswer(
+ invocation -> {
+ openStarted.countDown();
+ releaseOpen.await();
+ return table;
+ });
+
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ factory.when(() -> ConnectionFactory.createConnection(any(Configuration.class)))
+ .thenReturn(connection);
+
+ FlussClientManager manager =
+ new FlussClientManager(new FlussConfig().setBootstrapServers("localhost:9123"));
+ // Static mocks are thread-local, so initialize on the test thread.
+ assertThat(manager.getAdmin()).isSameAs(admin);
+
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<Table> opening =
+ executor.submit(() -> manager.openTable(TablePath.of("sales", "users")));
+ assertThat(openStarted.await(30, TimeUnit.SECONDS)).isTrue();
+
+ // Table opens issue blocking RPCs and must not serialize other callers.
+ assertThat(executor.submit(manager::getAdmin))
+ .succeedsWithin(Duration.ofSeconds(30))
+ .isSameAs(admin);
+
+ releaseOpen.countDown();
+ assertThat(opening).succeedsWithin(Duration.ofSeconds(30)).isSameAs(table);
+ } finally {
+ releaseOpen.countDown();
+ executor.shutdownNow();
+ manager.close();
+ }
+ }
+ }
+
+ @Test
+ void testPlaintextConfigurationDoesNotInitializeConnection() throws Exception {
+ for (FlussConfig config :
+ Arrays.asList(
+ new FlussConfig(), new FlussConfig().setSecurityProtocol("PLAINTEXT"))) {
+ config.setBootstrapServers("localhost:9123");
+
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ FlussClientManager manager = new FlussClientManager(config);
+ try {
+ factory.verifyNoInteractions();
+ } finally {
+ manager.close();
+ }
+ factory.verifyNoInteractions();
+ }
+ }
+ }
+
+ @Test
+ void testCloseBeforeInitializationPreventsLaterUse() throws Exception {
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ FlussClientManager manager =
+ new FlussClientManager(new FlussConfig().setBootstrapServers("localhost:9123"));
+
+ manager.close();
+ manager.close();
+
+ assertThatThrownBy(manager::getAdmin)
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("closed");
+ assertThatThrownBy(() -> manager.openTable(TablePath.of("sales", "users")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("closed");
+ factory.verifyNoInteractions();
+ }
+ }
+
+ @Test
+ void testRetryAfterAdminInitializationFailure() throws Exception {
+ Connection failedConnection = mock(Connection.class);
+ Connection connection = mock(Connection.class);
+ Admin admin = mock(Admin.class);
+ RuntimeException failure = new RuntimeException("cannot create admin");
+ when(failedConnection.getAdmin()).thenThrow(failure);
+ when(connection.getAdmin()).thenReturn(admin);
+
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ factory.when(() -> ConnectionFactory.createConnection(any(Configuration.class)))
+ .thenReturn(failedConnection, connection);
+
+ FlussClientManager manager =
+ new FlussClientManager(new FlussConfig().setBootstrapServers("localhost:9123"));
+ try {
+ assertThatThrownBy(manager::getAdmin).isSameAs(failure);
+ verify(failedConnection).close();
+ assertThat(manager.getAdmin()).isSameAs(admin);
+ assertThat(manager.getAdmin()).isSameAs(admin);
+ } finally {
+ manager.close();
+ }
+
+ factory.verify(
+ () -> ConnectionFactory.createConnection(any(Configuration.class)), times(2));
+ verify(failedConnection).close();
+ verify(admin).close();
+ verify(connection).close();
+ }
+ }
+
+ @Test
+ void testCloseConnectionWhenAdminCreationFails() throws Exception {
+ Connection connection = mock(Connection.class);
+ RuntimeException failure = new RuntimeException("cannot create admin");
+ when(connection.getAdmin()).thenThrow(failure);
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ factory.when(() -> ConnectionFactory.createConnection(any(Configuration.class)))
+ .thenReturn(connection);
+ assertThatThrownBy(
+ () ->
+ new FlussClientManager(
+ new FlussConfig()
+ .setBootstrapServers("localhost:9123"))
+ .getAdmin())
+ .isSameAs(failure);
+ verify(connection).close();
+ }
+ }
+
+ @Test
+ void testInitializationFailureRetainsCleanupFailure() throws Exception {
+ Connection connection = mock(Connection.class);
+ RuntimeException failure = new RuntimeException("cannot create admin");
+ IOException cleanupFailure = new IOException("cannot close connection");
+ when(connection.getAdmin()).thenThrow(failure);
+ doThrow(cleanupFailure).when(connection).close();
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ factory.when(() -> ConnectionFactory.createConnection(any(Configuration.class)))
+ .thenReturn(connection);
+ assertThatThrownBy(
+ () ->
+ new FlussClientManager(
+ new FlussConfig()
+ .setBootstrapServers("localhost:9123"))
+ .getAdmin())
+ .isSameAs(failure);
+ assertThat(failure.getSuppressed()).containsExactly(cleanupFailure);
+ }
+ }
+
+ @Test
+ void testCloseAttemptsBothResources() throws Exception {
+ Connection connection = mock(Connection.class);
+ Admin admin = mock(Admin.class);
+ when(connection.getAdmin()).thenReturn(admin);
+
+ IOException adminFailure = new IOException("cannot close admin");
+ IOException connectionFailure = new IOException("cannot close connection");
+ doThrow(adminFailure).when(admin).close();
+ doThrow(connectionFailure).when(connection).close();
+
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ factory.when(() -> ConnectionFactory.createConnection(any(Configuration.class)))
+ .thenReturn(connection);
+
+ FlussClientManager manager =
+ new FlussClientManager(new FlussConfig().setBootstrapServers("localhost:9123"));
+
+ assertThat(manager.getAdmin()).isSameAs(admin);
+
+ assertThatThrownBy(manager::close).isSameAs(adminFailure);
+ assertThat(adminFailure.getSuppressed()).containsExactly(connectionFailure);
+
+ verify(admin).close();
+ verify(connection).close();
+ }
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussColumnHandleTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussColumnHandleTest.java
new file mode 100644
index 0000000000..683d1a2f10
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussColumnHandleTest.java
@@ -0,0 +1,54 @@
+/*
+ * 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.fluss.trino;
+
+import io.airlift.json.JsonCodec;
+import org.junit.jupiter.api.Test;
+
+import static io.airlift.json.JsonCodec.jsonCodec;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests physical column identity and ordinal validation. */
+final class FlussColumnHandleTest {
+ @Test
+ void testJsonRoundTrip() {
+ FlussColumnHandle handle = new FlussColumnHandle("MixedCase", 2);
+ JsonCodec<FlussColumnHandle> codec = jsonCodec(FlussColumnHandle.class);
+ assertThat(codec.fromJson(codec.toJson(handle))).isEqualTo(handle);
+ }
+
+ @Test
+ void testEqualityIncludesCaseSensitiveNameAndOrdinal() {
+ FlussColumnHandle handle = new FlussColumnHandle("ID", 0);
+ FlussColumnHandle same = new FlussColumnHandle("ID", 0);
+ assertThat(handle).isEqualTo(same).hasSameHashCodeAs(same);
+ assertThat(handle).isNotEqualTo(new FlussColumnHandle("id", 0));
+ assertThat(handle).isNotEqualTo(new FlussColumnHandle("ID", 1));
+ }
+
+ @Test
+ void testRejectInvalidColumnIdentity() {
+ assertThatThrownBy(() -> new FlussColumnHandle(null, 0))
+ .isInstanceOf(NullPointerException.class)
+ .hasMessageContaining("name");
+ assertThatThrownBy(() -> new FlussColumnHandle("ID", -1))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("ordinalPosition");
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussColumnsSystemTableTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussColumnsSystemTableTest.java
new file mode 100644
index 0000000000..5f31e9b135
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussColumnsSystemTableTest.java
@@ -0,0 +1,129 @@
+/*
+ * 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.fluss.trino;
+
+import io.trino.spi.connector.ColumnMetadata;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.RecordCursor;
+import io.trino.spi.connector.SchemaTableName;
+import io.trino.spi.connector.SystemTable;
+import io.trino.spi.predicate.TupleDomain;
+import org.junit.jupiter.api.Test;
+
+import static io.trino.spi.type.BigintType.BIGINT;
+import static io.trino.spi.type.BooleanType.BOOLEAN;
+import static io.trino.spi.type.VarcharType.VARCHAR;
+import static org.apache.fluss.trino.TestingFlussMetadata.usersTable;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+
+/** Tests the public system-table schema and rows returned through the Trino cursor. */
+final class FlussColumnsSystemTableTest {
+ private final FlussColumnsSystemTable table =
+ new FlussColumnsSystemTable(
+ new SchemaTableName("sales", "users$columns"), usersTable());
+ private final ConnectorSession session = mock(ConnectorSession.class);
+
+ @Test
+ void testSystemTableMetadata() {
+ assertThat(table.getDistribution()).isEqualTo(SystemTable.Distribution.SINGLE_COORDINATOR);
+ assertThat(table.getTableMetadata().getTable())
+ .isEqualTo(new SchemaTableName("sales", "users$columns"));
+ assertThat(table.getTableMetadata().getColumns())
+ .extracting(ColumnMetadata::getName)
+ .containsExactly(
+ "column_name",
+ "ordinal_position",
+ "fluss_type",
+ "trino_type",
+ "is_nullable",
+ "primary_key_position",
+ "partition_key_position",
+ "bucket_key_position",
+ "comment");
+ assertThat(table.getTableMetadata().getColumns())
+ .extracting(ColumnMetadata::getType)
+ .containsExactly(
+ VARCHAR, BIGINT, VARCHAR, VARCHAR, BOOLEAN, BIGINT, BIGINT, BIGINT,
+ VARCHAR);
+ assertThat(table.getTableMetadata().getColumns())
+ .extracting(ColumnMetadata::isNullable)
+ .containsExactly(false, false, false, false, false, true, true, true, true);
+ }
+
+ @Test
+ void testColumnRowsPreserveNamesAndKeyOrder() {
+ try (RecordCursor cursor =
+ table.cursor(FlussTransactionHandle.INSTANCE, session, TupleDomain.all())) {
+ assertThat(cursor.advanceNextPosition()).isTrue();
+ assertThat(cursor.getSlice(0).toStringUtf8()).isEqualTo("Region");
+ assertThat(cursor.getLong(1)).isEqualTo(1);
+ assertThat(cursor.getSlice(2).toStringUtf8()).isEqualTo("STRING NOT NULL");
+ assertThat(cursor.getSlice(3).toStringUtf8()).isEqualTo("varchar");
+ assertThat(cursor.getBoolean(4)).isFalse();
+ assertThat(cursor.getLong(5)).isEqualTo(2);
+ assertThat(cursor.getLong(6)).isEqualTo(1);
+ assertThat(cursor.isNull(7)).isTrue();
+ assertThat(cursor.isNull(8)).isTrue();
+
+ assertThat(cursor.advanceNextPosition()).isTrue();
+ assertThat(cursor.getSlice(0).toStringUtf8()).isEqualTo("ID");
+ assertThat(cursor.getLong(1)).isEqualTo(2);
+ assertThat(cursor.getSlice(2).toStringUtf8()).isEqualTo("BIGINT NOT NULL");
+ assertThat(cursor.getSlice(3).toStringUtf8()).isEqualTo("bigint");
+ assertThat(cursor.getBoolean(4)).isFalse();
+ assertThat(cursor.getLong(5)).isEqualTo(1);
+ assertThat(cursor.isNull(6)).isTrue();
+ assertThat(cursor.getLong(7)).isEqualTo(1);
+ assertThat(cursor.getSlice(8).toStringUtf8()).isEqualTo("User identifier");
+
+ assertThat(cursor.advanceNextPosition()).isTrue();
+ assertThat(cursor.getSlice(0).toStringUtf8()).isEqualTo("Name");
+ assertThat(cursor.getLong(1)).isEqualTo(3);
+ assertThat(cursor.getSlice(2).toStringUtf8()).isEqualTo("STRING");
+ assertThat(cursor.getSlice(3).toStringUtf8()).isEqualTo("varchar");
+ assertThat(cursor.getBoolean(4)).isTrue();
+ assertThat(cursor.isNull(5)).isTrue();
+ assertThat(cursor.isNull(6)).isTrue();
+ assertThat(cursor.isNull(7)).isTrue();
+ assertThat(cursor.isNull(8)).isTrue();
+ assertThat(cursor.advanceNextPosition()).isFalse();
+ }
+ }
+
+ @Test
+ void testEmptyConstraintReturnsNoRows() {
+ try (RecordCursor cursor =
+ table.cursor(FlussTransactionHandle.INSTANCE, session, TupleDomain.none())) {
+ assertThat(cursor.advanceNextPosition()).isFalse();
+ }
+ }
+
+ @Test
+ void testCursorsAreIndependent() {
+ try (RecordCursor first =
+ table.cursor(FlussTransactionHandle.INSTANCE, session, TupleDomain.all());
+ RecordCursor second =
+ table.cursor(FlussTransactionHandle.INSTANCE, session, TupleDomain.all())) {
+ assertThat(first.advanceNextPosition()).isTrue();
+ assertThat(first.advanceNextPosition()).isTrue();
+ assertThat(second.advanceNextPosition()).isTrue();
+ assertThat(second.getSlice(0).toStringUtf8()).isEqualTo("Region");
+ }
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussConfigTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussConfigTest.java
new file mode 100644
index 0000000000..57d3d3ad18
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussConfigTest.java
@@ -0,0 +1,126 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableMap;
+
+import io.airlift.configuration.ConfigurationFactory;
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.Map;
+
+import static io.airlift.configuration.testing.ConfigAssertions.assertFullMapping;
+import static io.airlift.configuration.testing.ConfigAssertions.assertRecordedDefaults;
+import static io.airlift.configuration.testing.ConfigAssertions.recordDefaults;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests connector configuration through Airlift's configuration binding. */
+final class FlussConfigTest {
+ private static final Map<String, String> SASL_PROPERTIES =
+ ImmutableMap.of(
+ "client.security.sasl.mechanism", "PLAIN",
+ "client.security.sasl.username", "test-user",
+ "client.security.sasl.password", "test-password");
+
+ @Test
+ void testDefaults() {
+ assertRecordedDefaults(
+ recordDefaults(FlussConfig.class)
+ .setBootstrapServers(null)
+ .setSecurityProtocol(null)
+ .setSaslMechanism(null)
+ .setSaslUsername(null)
+ .setSaslPassword(null));
+ }
+
+ @Test
+ void testExplicitPropertyMappings() {
+ Map<String, String> properties =
+ ImmutableMap.of(
+ "bootstrap.servers", "localhost:9123,localhost:9124",
+ "client.security.protocol", "plaintext");
+ FlussConfig expected =
+ new FlussConfig()
+ .setBootstrapServers("localhost:9123,localhost:9124")
+ .setSecurityProtocol("plaintext");
+ // SASL properties cannot pass validation yet; their mapping is covered below.
+ assertFullMapping(properties, expected, SASL_PROPERTIES.keySet());
+ }
+
+ @Test
+ void testAuthenticationPropertiesAreRejected() {
+ Map<String, String> unsupported =
+ ImmutableMap.<String, String>builder()
+ .put("client.security.protocol", "SASL")
+ .putAll(SASL_PROPERTIES)
+ .build();
+ for (Map.Entry<String, String> property : unsupported.entrySet()) {
+ assertThatThrownBy(
+ () ->
+ new ConfigurationFactory(
+ ImmutableMap.of(
+ "bootstrap.servers",
+ "localhost:9123",
+ property.getKey(),
+ property.getValue()))
+ .build(FlussConfig.class))
+ .hasMessageContaining("only PLAINTEXT connections are currently supported");
+ }
+ }
+
+ @Test
+ void testPlaintextOnly() {
+ assertThat(new FlussConfig().isPlaintextOnly()).isTrue();
+ assertThat(new FlussConfig().setSecurityProtocol("PLAINTEXT").isPlaintextOnly()).isTrue();
+ assertThat(new FlussConfig().setSecurityProtocol("plaintext").isPlaintextOnly()).isTrue();
+ assertThat(new FlussConfig().setSecurityProtocol("SASL").isPlaintextOnly()).isFalse();
+ assertThat(
+ new FlussConfig()
+ .setSecurityProtocol("PLAINTEXT")
+ .setSaslUsername("test-user")
+ .isPlaintextOnly())
+ .isFalse();
+ }
+
+ @Test
+ void testBootstrapServersRequired() {
+ assertThatThrownBy(
+ () ->
+ new ConfigurationFactory(Collections.emptyMap())
+ .build(FlussConfig.class))
+ .hasMessageContaining("bootstrap.servers");
+ assertThatThrownBy(
+ () ->
+ new ConfigurationFactory(ImmutableMap.of("bootstrap.servers", ""))
+ .build(FlussConfig.class))
+ .hasMessageContaining("bootstrap.servers");
+ }
+
+ @Test
+ void testSecurityConfigurationIsOptional() {
+ FlussConfig config =
+ new ConfigurationFactory(ImmutableMap.of("bootstrap.servers", "localhost:9123"))
+ .build(FlussConfig.class);
+ assertThat(config.getSecurityProtocol()).isEmpty();
+ assertThat(config.getSaslMechanism()).isEmpty();
+ assertThat(config.getSaslUsername()).isEmpty();
+ assertThat(config.getSaslPassword()).isEmpty();
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussConnectorFactoryTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussConnectorFactoryTest.java
new file mode 100644
index 0000000000..4866ca1741
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussConnectorFactoryTest.java
@@ -0,0 +1,155 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.Connection;
+import org.apache.fluss.client.ConnectionFactory;
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.shaded.guava32.com.google.common.collect.ImmutableMap;
+
+import io.trino.plugin.base.classloader.ClassLoaderSafeConnectorMetadata;
+import io.trino.plugin.base.classloader.ClassLoaderSafeConnectorPageSourceProvider;
+import io.trino.plugin.base.classloader.ClassLoaderSafeConnectorSplitManager;
+import io.trino.spi.connector.Connector;
+import io.trino.spi.connector.ConnectorContext;
+import io.trino.spi.connector.ConnectorMetadata;
+import io.trino.spi.connector.ConnectorSession;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import java.util.Collections;
+import java.util.Map;
+
+import static io.trino.spi.transaction.IsolationLevel.READ_COMMITTED;
+import static java.util.concurrent.CompletableFuture.completedFuture;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.RETURNS_MOCKS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** Tests the real connector bootstrap and lifecycle with a mocked external connection. */
+final class FlussConnectorFactoryTest {
+ @Test
+ void testBootstrapMetadataAndShutdown() throws Exception {
+ ConnectorContext context = mock(ConnectorContext.class, RETURNS_MOCKS);
+ when(context.getSpiVersion()).thenReturn(new ConnectorContext() {}.getSpiVersion());
+ Connection connection = mock(Connection.class);
+ Admin admin = mock(Admin.class);
+ when(connection.getAdmin()).thenReturn(admin);
+ when(admin.listDatabases()).thenReturn(completedFuture(Collections.singletonList("Sales")));
+
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ factory.when(() -> ConnectionFactory.createConnection(any(Configuration.class)))
+ .thenReturn(connection);
+ Connector connector =
+ new FlussConnectorFactory()
+ .create(
+ "fluss",
+ Collections.singletonMap("bootstrap.servers", "localhost:9123"),
+ context);
+ try {
+ ConnectorMetadata metadata =
+ connector.getMetadata(
+ mock(ConnectorSession.class),
+ connector.beginTransaction(READ_COMMITTED, true, true));
+ assertThat(metadata).isInstanceOf(ClassLoaderSafeConnectorMetadata.class);
+ factory.verifyNoInteractions();
+ assertThat(metadata.listSchemaNames(mock(ConnectorSession.class)))
+ .containsExactly("sales");
+ assertThat(connector.getTableProperties()).isNotEmpty();
+ assertThat(connector.getPageSourceProvider())
+ .isInstanceOf(ClassLoaderSafeConnectorPageSourceProvider.class);
+ assertThat(connector.getSplitManager())
+ .isInstanceOf(ClassLoaderSafeConnectorSplitManager.class);
+ } finally {
+ connector.shutdown();
+ }
+ verify(admin).close();
+ verify(connection).close();
+ }
+ }
+
+ @Test
+ void testBootstrapAndShutdownWithoutFlussConnection() {
+ ConnectorContext context = mock(ConnectorContext.class, RETURNS_MOCKS);
+ when(context.getSpiVersion()).thenReturn(new ConnectorContext() {}.getSpiVersion());
+
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ factory.when(() -> ConnectionFactory.createConnection(any(Configuration.class)))
+ .thenThrow(new IllegalStateException("Fluss is unavailable"));
+
+ Connector connector =
+ new FlussConnectorFactory()
+ .create(
+ "fluss",
+ Collections.singletonMap("bootstrap.servers", "localhost:9123"),
+ context);
+ try {
+ factory.verifyNoInteractions();
+ } finally {
+ connector.shutdown();
+ }
+ factory.verifyNoInteractions();
+ }
+ }
+
+ @Test
+ void testRejectAuthenticationAtCatalogCreation() {
+ ConnectorContext context = mock(ConnectorContext.class, RETURNS_MOCKS);
+ when(context.getSpiVersion()).thenReturn(new ConnectorContext() {}.getSpiVersion());
+
+ for (Map.Entry<String, String> property :
+ ImmutableMap.of(
+ "client.security.protocol", "SASL",
+ "client.security.sasl.mechanism", "PLAIN",
+ "client.security.sasl.username", "test-user",
+ "client.security.sasl.password", "test-password")
+ .entrySet()) {
+ Map<String, String> config =
+ ImmutableMap.of(
+ "bootstrap.servers",
+ "localhost:9123",
+ property.getKey(),
+ property.getValue());
+
+ try (MockedStatic<ConnectionFactory> factory = mockStatic(ConnectionFactory.class)) {
+ assertThatThrownBy(
+ () -> new FlussConnectorFactory().create("fluss", config, context))
+ .hasMessageContaining("only PLAINTEXT connections are currently supported");
+ factory.verifyNoInteractions();
+ }
+ }
+ }
+
+ @Test
+ void testRejectMismatchedSpiVersion() {
+ ConnectorContext context = mock(ConnectorContext.class);
+ when(context.getSpiVersion()).thenReturn("incompatible-version");
+ assertThatThrownBy(
+ () ->
+ new FlussConnectorFactory()
+ .create("fluss", Collections.emptyMap(), context))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("Unsupported Trino SPI version");
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussConnectorTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussConnectorTest.java
new file mode 100644
index 0000000000..ec784f7714
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussConnectorTest.java
@@ -0,0 +1,82 @@
+/*
+ * 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.fluss.trino;
+
+import io.airlift.bootstrap.LifeCycleManager;
+import io.trino.spi.TrinoException;
+import io.trino.spi.connector.ConnectorMetadata;
+import io.trino.spi.connector.ConnectorPageSourceProvider;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.ConnectorSplitManager;
+import org.junit.jupiter.api.Test;
+
+import static io.trino.spi.StandardErrorCode.UNSUPPORTED_ISOLATION_LEVEL;
+import static io.trino.spi.transaction.IsolationLevel.READ_COMMITTED;
+import static io.trino.spi.transaction.IsolationLevel.SERIALIZABLE;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+/** Tests connector transaction and lifecycle contracts. */
+final class FlussConnectorTest {
+ @Test
+ void testMetadataForReadCommittedTransaction() {
+ ConnectorMetadata metadata = mock(ConnectorMetadata.class);
+ FlussConnector connector =
+ new FlussConnector(
+ mock(LifeCycleManager.class),
+ metadata,
+ mock(ConnectorSplitManager.class),
+ mock(ConnectorPageSourceProvider.class));
+ assertThat(connector.beginTransaction(READ_COMMITTED, true, true))
+ .isSameAs(FlussTransactionHandle.INSTANCE);
+ assertThat(
+ connector.getMetadata(
+ mock(ConnectorSession.class), FlussTransactionHandle.INSTANCE))
+ .isSameAs(metadata);
+ }
+
+ @Test
+ void testRejectUnsupportedIsolation() {
+ FlussConnector connector =
+ new FlussConnector(
+ mock(LifeCycleManager.class),
+ mock(ConnectorMetadata.class),
+ mock(ConnectorSplitManager.class),
+ mock(ConnectorPageSourceProvider.class));
+ assertThatThrownBy(() -> connector.beginTransaction(SERIALIZABLE, true, true))
+ .isInstanceOfSatisfying(
+ TrinoException.class,
+ failure ->
+ assertThat(failure.getErrorCode())
+ .isEqualTo(UNSUPPORTED_ISOLATION_LEVEL.toErrorCode()));
+ }
+
+ @Test
+ void testShutdownStopsLifecycle() {
+ LifeCycleManager lifecycle = mock(LifeCycleManager.class);
+ new FlussConnector(
+ lifecycle,
+ mock(ConnectorMetadata.class),
+ mock(ConnectorSplitManager.class),
+ mock(ConnectorPageSourceProvider.class))
+ .shutdown();
+ verify(lifecycle).stop();
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussKvScannerLifecycleITCase.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussKvScannerLifecycleITCase.java
new file mode 100644
index 0000000000..7e8c89ae65
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussKvScannerLifecycleITCase.java
@@ -0,0 +1,380 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.Connection;
+import org.apache.fluss.client.ConnectionFactory;
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.client.metadata.MetadataUpdater;
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.client.table.scanner.batch.KvBatchScanner;
+import org.apache.fluss.client.table.writer.UpsertWriter;
+import org.apache.fluss.cluster.Cluster;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.config.MemorySize;
+import org.apache.fluss.exception.ScannerExpiredException;
+import org.apache.fluss.exception.UnknownScannerIdException;
+import org.apache.fluss.metadata.Schema;
+import org.apache.fluss.metadata.SchemaGetter;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableDescriptor;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metadata.TablePath;
+import org.apache.fluss.row.BinaryString;
+import org.apache.fluss.row.GenericRow;
+import org.apache.fluss.row.InternalRow;
+import org.apache.fluss.rpc.gateway.TabletServerGateway;
+import org.apache.fluss.rpc.messages.ScanKvRequest;
+import org.apache.fluss.rpc.messages.ScanKvResponse;
+import org.apache.fluss.server.testutils.FlussClusterExtension;
+import org.apache.fluss.types.DataTypes;
+import org.apache.fluss.utils.CloseableIterator;
+import org.apache.fluss.utils.IOUtils;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Proxy;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.apache.fluss.testutils.common.CommonTestUtils.waitUntil;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/** Real-client checks for the difference between local close and remote snapshot reclamation. */
+class FlussKvScannerLifecycleITCase {
+
+ private static final Duration POLL_TIMEOUT = Duration.ofSeconds(30);
+ private static final int ROW_COUNT = 200;
+ private static final String PAYLOAD = new String(new char[512]).replace('\0', 'x');
+
+ @RegisterExtension
+ static final FlussClusterExtension CLUSTER =
+ FlussClusterExtension.builder()
+ .setNumOfTabletServers(1)
+ .setClusterConf(clusterConfig())
+ .build();
+
+ private Connection connection;
+ private Admin admin;
+ private TestingKvScanControl control;
+
+ @BeforeEach
+ void setUp() {
+ connection = ConnectionFactory.createConnection(CLUSTER.getClientConfig());
+ admin = connection.getAdmin();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ try {
+ if (control != null) {
+ control.removeAll();
+ }
+ } finally {
+ IOUtils.closeAll(admin, connection);
+ }
+ }
+
+ @Test
+ void testLostOpenResponseRequiresRemoteExpiration() throws Exception {
+ TableInfo info = createTable("lost_open");
+ FaultGateway gateway = new FaultGateway(info, Failure.LOST_OPEN);
+ try (KvBatchScanner scanner = newScanner(info, gateway)) {
+ assertThatThrownBy(() -> scanner.pollBatch(POLL_TIMEOUT))
+ .isInstanceOf(IOException.class)
+ .hasStackTraceContaining("lost open response");
+ scanner.close();
+ assertThat(scanner.pollBatch(POLL_TIMEOUT)).isNull();
+ assertThat(gateway.opens.get()).isEqualTo(1);
+ assertThat(gateway.closes.get()).isZero();
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ control.expireAll();
+ assertThat(control.activeScannerCount()).isZero();
+ }
+ }
+
+ @Test
+ void testFailedCloseCompletesLocallyBeforeRemoteExpiration() throws Exception {
+ TableInfo info = createTable("failed_close");
+ FaultGateway gateway = new FaultGateway(info, Failure.CLOSE);
+ try (KvBatchScanner scanner = newScanner(info, gateway)) {
+ assertFirstBatch(scanner);
+ waitForPrefetch(gateway);
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ scanner.close();
+ scanner.close();
+ assertThat(scanner.pollBatch(POLL_TIMEOUT)).isNull();
+ assertThat(gateway.opens.get()).isEqualTo(1);
+ assertThat(gateway.closes.get()).isEqualTo(1);
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ control.expireAll();
+ assertThat(control.activeScannerCount()).isZero();
+ }
+ }
+
+ @Test
+ void testLostContinuationFailsWithoutReopeningSnapshot() throws Exception {
+ TableInfo info = createTable("lost_continuation");
+ FaultGateway gateway = new FaultGateway(info, Failure.CONTINUATION);
+ try (KvBatchScanner scanner = newScanner(info, gateway)) {
+ assertFirstBatch(scanner);
+ waitForPrefetch(gateway);
+ assertThatThrownBy(() -> scanner.pollBatch(POLL_TIMEOUT))
+ .isInstanceOf(IOException.class)
+ .hasStackTraceContaining("lost continuation response");
+ assertThat(scanner.pollBatch(POLL_TIMEOUT)).isNull();
+ assertThat(gateway.opens.get()).isEqualTo(1);
+ assertThat(gateway.closes.get()).isEqualTo(1);
+ waitUntil(
+ () -> control.activeScannerCount() == 0,
+ POLL_TIMEOUT,
+ "Best-effort close did not release the server scanner");
+ }
+ }
+
+ @Test
+ void testExpiredSessionFailsWithoutReopeningSnapshot() throws Exception {
+ assertInvalidatedSessionFails("expired_session", true);
+ }
+
+ @Test
+ void testUnknownSessionFailsWithoutReopeningSnapshot() throws Exception {
+ assertInvalidatedSessionFails("unknown_session", false);
+ }
+
+ private void assertInvalidatedSessionFails(String tableName, boolean expire) throws Exception {
+ TableInfo info = createTable(tableName);
+ FaultGateway gateway = new FaultGateway(info, Failure.NONE);
+ try (KvBatchScanner scanner = newScanner(info, gateway)) {
+ assertFirstBatch(scanner);
+ waitForPrefetch(gateway);
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ if (expire) {
+ control.expireAll();
+ } else {
+ control.removeAll();
+ }
+ assertThat(control.activeScannerCount()).isZero();
+
+ // The already fetched second batch remains valid; its next prefetch sees the loss.
+ assertFirstBatch(scanner);
+ assertThatThrownBy(() -> scanner.pollBatch(POLL_TIMEOUT))
+ .isInstanceOf(IOException.class)
+ .hasCauseInstanceOf(
+ expire
+ ? ScannerExpiredException.class
+ : UnknownScannerIdException.class);
+ assertThat(scanner.pollBatch(POLL_TIMEOUT)).isNull();
+ scanner.close();
+ assertThat(gateway.opens.get()).isEqualTo(1);
+ assertThat(gateway.closes.get()).isZero();
+ assertThat(control.activeScannerCount()).isZero();
+ }
+ }
+
+ private TableInfo createTable(String name) throws Exception {
+ TablePath path = TablePath.of("fluss", name);
+ Schema schema =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("payload", DataTypes.STRING())
+ .primaryKey("id")
+ .build();
+ admin.createTable(
+ path,
+ TableDescriptor.builder().schema(schema).distributedBy(1).build(),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ TableInfo info = admin.getTableInfo(path).get(30, TimeUnit.SECONDS);
+ CLUSTER.waitUntilTableReady(info.getTableId());
+ try (Table table = connection.getTable(path)) {
+ UpsertWriter writer = table.newUpsert().createWriter();
+ List<CompletableFuture<?>> writes = new ArrayList<>();
+ for (int i = 0; i < ROW_COUNT; i++) {
+ writes.add(writer.upsert(GenericRow.of(i, BinaryString.fromString(PAYLOAD))));
+ }
+ CompletableFuture.allOf(writes.toArray(new CompletableFuture[0]))
+ .get(30, TimeUnit.SECONDS);
+ }
+ control = TestingKvScanControl.forBucket(CLUSTER, new TableBucket(info.getTableId(), 0));
+ return info;
+ }
+
+ private KvBatchScanner newScanner(TableInfo info, FaultGateway gateway) {
+ SchemaGetter schemaGetter = mock(SchemaGetter.class);
+ when(schemaGetter.getSchema(info.getSchemaId())).thenReturn(info.getSchema());
+ return new KvBatchScanner(
+ info,
+ new TableBucket(info.getTableId(), 0),
+ schemaGetter,
+ new ForwardingMetadataUpdater(gateway.proxy),
+ 4096,
+ null);
+ }
+
+ private static void assertFirstBatch(KvBatchScanner scanner) throws Exception {
+ try (CloseableIterator<InternalRow> rows = scanner.pollBatch(POLL_TIMEOUT)) {
+ assertThat(rows).isNotNull();
+ int count = 0;
+ while (rows.hasNext()) {
+ InternalRow row = rows.next();
+ assertThat(row.getInt(0)).isBetween(0, ROW_COUNT - 1);
+ assertThat(row.getString(1).toString()).isEqualTo(PAYLOAD);
+ count++;
+ }
+ assertThat(count).isBetween(1, ROW_COUNT / 3);
+ }
+ }
+
+ private static void waitForPrefetch(FaultGateway gateway) throws Exception {
+ waitUntil(
+ () -> gateway.responses.get() >= 2,
+ POLL_TIMEOUT,
+ "The server did not complete the prefetched continuation");
+ }
+
+ private static Configuration clusterConfig() {
+ Configuration configuration = new Configuration();
+ configuration.set(ConfigOptions.KV_SCANNER_MAX_BATCH_SIZE, new MemorySize(4096));
+ configuration.set(ConfigOptions.KV_SCANNER_TTL, Duration.ofMinutes(10));
+ configuration.set(ConfigOptions.KV_SCANNER_EXPIRATION_INTERVAL, Duration.ofDays(1));
+ return configuration;
+ }
+
+ private enum Failure {
+ NONE,
+ LOST_OPEN,
+ CLOSE,
+ CONTINUATION
+ }
+
+ private static final class FaultGateway {
+ private final AtomicInteger opens = new AtomicInteger();
+ private final AtomicInteger closes = new AtomicInteger();
+ private final AtomicInteger responses = new AtomicInteger();
+ private final TabletServerGateway proxy;
+
+ private FaultGateway(TableInfo info, Failure failure) {
+ TabletServerGateway delegate =
+ CLUSTER.newTabletServerClientForNode(
+ CLUSTER.waitAndGetLeader(new TableBucket(info.getTableId(), 0)));
+ proxy =
+ (TabletServerGateway)
+ Proxy.newProxyInstance(
+ TabletServerGateway.class.getClassLoader(),
+ new Class<?>[] {TabletServerGateway.class},
+ (ignored, method, args) -> {
+ if (!method.getName().equals("scanKv")) {
+ try {
+ return method.invoke(delegate, args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ }
+ }
+ ScanKvRequest request = (ScanKvRequest) args[0];
+ boolean close =
+ request.hasCloseScanner()
+ && request.isCloseScanner();
+ boolean open = request.hasBucketScanReq();
+ if (close) {
+ closes.incrementAndGet();
+ if (failure == Failure.CLOSE) {
+ CompletableFuture<ScanKvResponse> failed =
+ new CompletableFuture<>();
+ failed.completeExceptionally(
+ new IOException("close RPC unavailable"));
+ return failed;
+ }
+ } else if (open) {
+ opens.incrementAndGet();
+ }
+ return delegate.scanKv(request)
+ .thenApply(
+ response -> {
+ if (response.hasErrorCode()
+ && response.getErrorCode()
+ != 0) {
+ return response;
+ }
+ if (!close) {
+ assertThat(response.hasRecords())
+ .isTrue();
+ assertThat(
+ response
+ .isHasMoreResults())
+ .isTrue();
+ responses.incrementAndGet();
+ if (open
+ && failure
+ == Failure
+ .LOST_OPEN) {
+ throw new CompletionException(
+ new IOException(
+ "lost open response"));
+ }
+ if (!open
+ && failure
+ == Failure
+ .CONTINUATION) {
+ throw new CompletionException(
+ new IOException(
+ "lost continuation response"));
+ }
+ }
+ return response;
+ });
+ });
+ }
+ }
+
+ private static final class ForwardingMetadataUpdater extends MetadataUpdater {
+ private final TabletServerGateway gateway;
+
+ private ForwardingMetadataUpdater(TabletServerGateway gateway) {
+ super(null, new Configuration(), Cluster.empty());
+ this.gateway = gateway;
+ }
+
+ @Override
+ public void checkAndUpdateMetadata(TablePath tablePath, TableBucket tableBucket) {}
+
+ @Override
+ public int leaderFor(TablePath tablePath, TableBucket tableBucket) {
+ return 0;
+ }
+
+ @Override
+ public TabletServerGateway newTabletServerClientForNode(int serverId) {
+ return gateway;
+ }
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussKvSplitReaderTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussKvSplitReaderTest.java
new file mode 100644
index 0000000000..7624c14c33
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussKvSplitReaderTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.client.table.scanner.Scan;
+import org.apache.fluss.client.table.scanner.batch.BatchScanner;
+import org.apache.fluss.row.GenericRow;
+import org.apache.fluss.row.InternalRow;
+import org.apache.fluss.utils.CloseableIterator;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.fluss.trino.FlussSplitReader.PollResult.AVAILABLE;
+import static org.apache.fluss.trino.FlussSplitReader.PollResult.FINISHED;
+import static org.apache.fluss.trino.FlussSplitReader.PollResult.YIELD;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+/** Verifies the KV batch iterator protocol independently of Trino page assembly. */
+final class FlussKvSplitReaderTest {
+ @Test
+ void testEmptyBatchYieldsAndOnlyNullFinishes() throws Exception {
+ FlussBucketHandle bucket = new FlussBucketHandle(42, Optional.of(7L), 2);
+ Table table = mock(Table.class);
+ Scan scan = mock(Scan.class);
+ BatchScanner scanner = mock(BatchScanner.class);
+ when(table.newScan()).thenReturn(scan);
+ when(scan.createBatchScanner(bucket.toTableBucket())).thenReturn(scanner);
+ CloseableIterator<InternalRow> empty = spy(CloseableIterator.emptyIterator());
+ CloseableIterator<InternalRow> rows =
+ spy(
+ CloseableIterator.wrap(
+ Collections.<InternalRow>singletonList(GenericRow.of(1L))
+ .iterator()));
+ Duration timeout = Duration.ofMillis(100);
+ when(scanner.pollBatch(timeout)).thenReturn(empty, rows, null);
+ try (FlussKvSplitReader reader = new FlussKvSplitReader(table, bucket)) {
+ assertThat(reader.poll(timeout)).isEqualTo(YIELD);
+ verify(empty).close();
+ assertThat(reader.isFinished()).isFalse();
+ assertThat(reader.poll(timeout)).isEqualTo(AVAILABLE);
+ assertThatThrownBy(() -> reader.poll(timeout))
+ .isInstanceOf(IllegalStateException.class);
+ assertThat(reader.next().getLong(0)).isEqualTo(1);
+ verify(rows).close();
+ assertThat(reader.hasNext()).isFalse();
+ assertThat(reader.isFinished()).isFalse();
+ assertThat(reader.getCompletedBytes()).isZero();
+ assertThat(reader.getRetainedSizeInBytes()).isZero();
+ assertThat(reader.poll(timeout)).isEqualTo(FINISHED);
+ }
+ verify(scan).createBatchScanner(bucket.toTableBucket());
+ verifyNoMoreInteractions(scan);
+ verify(scanner).close();
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussLogRangeTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussLogRangeTest.java
new file mode 100644
index 0000000000..b439654838
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussLogRangeTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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.fluss.trino;
+
+import org.junit.jupiter.api.Test;
+
+import static io.airlift.json.JsonCodec.jsonCodec;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests exclusive-end log boundaries. */
+final class FlussLogRangeTest {
+ @Test
+ void testRoundTripAndEmptyRange() {
+ FlussLogRange range = new FlussLogRange(11, Long.MAX_VALUE);
+ FlussLogRange copy =
+ jsonCodec(FlussLogRange.class)
+ .fromJson(jsonCodec(FlussLogRange.class).toJson(range));
+ assertThat(copy).isEqualTo(range).hasSameHashCodeAs(range);
+ assertThat(copy.getStartOffset()).isEqualTo(11);
+ assertThat(copy.getStoppingOffset()).isEqualTo(Long.MAX_VALUE);
+ assertThat(copy.isEmpty()).isFalse();
+ assertThat(new FlussLogRange(1000, 1000).isEmpty()).isTrue();
+ assertThat(range).isNotEqualTo(new FlussLogRange(12, Long.MAX_VALUE));
+ assertThat(range).isNotEqualTo(new FlussLogRange(11, 12));
+ }
+
+ @Test
+ void testInvalidRanges() {
+ assertThatThrownBy(() -> new FlussLogRange(-1, 0))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> new FlussLogRange(2, 1))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussLogReadITCase.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussLogReadITCase.java
new file mode 100644
index 0000000000..58cd7c6ce0
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussLogReadITCase.java
@@ -0,0 +1,713 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.Connection;
+import org.apache.fluss.client.ConnectionFactory;
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.client.table.writer.AppendWriter;
+import org.apache.fluss.client.table.writer.UpsertWriter;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.metadata.LogFormat;
+import org.apache.fluss.metadata.PartitionSpec;
+import org.apache.fluss.metadata.Schema;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableChange;
+import org.apache.fluss.metadata.TableDescriptor;
+import org.apache.fluss.metadata.TablePath;
+import org.apache.fluss.row.BinaryString;
+import org.apache.fluss.row.Decimal;
+import org.apache.fluss.row.GenericArray;
+import org.apache.fluss.row.GenericMap;
+import org.apache.fluss.row.GenericRow;
+import org.apache.fluss.row.InternalRow;
+import org.apache.fluss.row.TimestampLtz;
+import org.apache.fluss.row.TimestampNtz;
+import org.apache.fluss.server.log.LogTablet;
+import org.apache.fluss.server.testutils.FlussClusterExtension;
+import org.apache.fluss.types.DataTypes;
+import org.apache.fluss.utils.IOUtils;
+import org.apache.fluss.utils.clock.ManualClock;
+
+import io.trino.testing.DistributedQueryRunner;
+import io.trino.testing.MaterializedRow;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.math.BigDecimal;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.testutils.common.CommonTestUtils.waitUntil;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** End-to-end reads through a coordinator and a separate Trino worker. */
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class FlussLogReadITCase {
+ private static final ManualClock CLOCK = new ManualClock(System.currentTimeMillis());
+
+ @RegisterExtension
+ static final FlussClusterExtension CLUSTER =
+ FlussClusterExtension.builder()
+ .setNumOfTabletServers(1)
+ .setClock(CLOCK)
+ .setClusterConf(clusterConfig())
+ .build();
+
+ private final FlussQueryRunner.TestingHooks gate = new FlussQueryRunner.TestingHooks();
+ private DistributedQueryRunner runner;
+ private Connection connection;
+ private Admin admin;
+
+ @BeforeAll
+ void setUp() throws Exception {
+ runner = FlussQueryRunner.create(CLUSTER.getBootstrapServers(), gate);
+ }
+
+ @BeforeEach
+ void openFixtureClient() {
+ connection = ConnectionFactory.createConnection(CLUSTER.getClientConfig());
+ admin = connection.getAdmin();
+ }
+
+ @AfterAll
+ void tearDown() throws Exception {
+ IOUtils.closeAll(runner);
+ }
+
+ @AfterEach
+ void readersAreReleased() throws Exception {
+ try {
+ waitUntil(
+ () -> gate.activeSources() == 0,
+ Duration.ofSeconds(30),
+ "Trino did not release all page sources");
+ } finally {
+ IOUtils.closeAll(admin, connection);
+ }
+ }
+
+ @Test
+ void testUserCancellationClosesActiveReader() throws Exception {
+ createTable("cancel_events", Schema.newBuilder().column("id", DataTypes.INT()).build(), 1);
+ try (Table table = connection.getTable(TablePath.of("fluss", "cancel_events"))) {
+ AppendWriter writer = table.newAppend().createWriter();
+ List<CompletableFuture<?>> writes = new ArrayList<>();
+ for (int i = 0; i < 3000; i++) {
+ writes.add(writer.append(GenericRow.of(i)));
+ }
+ CompletableFuture.allOf(writes.toArray(new CompletableFuture[0]))
+ .get(30, TimeUnit.SECONDS);
+ }
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ String sql = "SELECT id FROM cancel_events";
+ try (FlussQueryRunner.Barrier barrier = gate.pauseAfterRead("cancel_events")) {
+ Future<?> query = executor.submit(() -> runner.execute(sql));
+ barrier.awaitReached();
+ assertThat(gate.activeSources()).isGreaterThan(0);
+ io.trino.spi.QueryId queryId =
+ runner.getCoordinator().getQueryManager().getQueries().stream()
+ .filter(
+ info ->
+ info.getQuery().equals(sql)
+ && !info.getState().isDone())
+ .findFirst()
+ .get()
+ .getQueryId();
+ runner.getCoordinator().getQueryManager().cancelQuery(queryId);
+ assertThatThrownBy(() -> query.get(30, TimeUnit.SECONDS))
+ .hasStackTraceContaining("canceled");
+ waitUntil(
+ () -> gate.activeSources() == 0,
+ Duration.ofSeconds(30),
+ "Canceled reader was not closed");
+ } finally {
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+
+ @Test
+ void testDistributedLogReads() throws Exception {
+ assertThat(runner.getNodeCount()).isEqualTo(2);
+ Schema schema =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("name", DataTypes.STRING())
+ .build();
+ createTable("events", schema, 3);
+ append(
+ "events",
+ GenericRow.of(1, BinaryString.fromString("one")),
+ GenericRow.of(2, BinaryString.fromString("二")),
+ GenericRow.of(3, null));
+ assertThat(rows("SELECT * FROM events"))
+ .containsExactlyInAnyOrder(
+ Arrays.asList(1, "one"), Arrays.asList(2, "二"), Arrays.asList(3, null));
+ assertThat(rows("SELECT name, id FROM events WHERE id >= 2 ORDER BY id DESC"))
+ .containsExactly(Arrays.asList(null, 3), Arrays.asList("二", 2));
+ assertThat(runner.execute("SELECT count(*) FROM events").getOnlyValue()).isEqualTo(3L);
+ assertThat(rows("SELECT id FROM events ORDER BY id LIMIT 1"))
+ .containsExactly(Arrays.asList(1));
+ assertThat(rows("SELECT * FROM events LIMIT 1")).hasSize(1);
+ assertThat(rows("DESCRIBE events")).hasSize(2);
+ assertThat(runner.execute("SHOW CREATE TABLE events").getOnlyValue().toString())
+ .contains("CREATE TABLE", "events");
+ assertThat(rows("SELECT * FROM \"events$columns\"")).hasSize(2);
+ }
+
+ @Test
+ void testEmptyTable() throws Exception {
+ createTable("empty_events", Schema.newBuilder().column("id", DataTypes.INT()).build(), 3);
+ assertThat(rows("SELECT * FROM empty_events")).isEmpty();
+ assertThat(runner.execute("SELECT count(*) FROM empty_events").getOnlyValue())
+ .isEqualTo(0L);
+ }
+
+ @Test
+ void testAppendsAfterPlanningAreExcluded() throws Exception {
+ createTable("bounded_events", Schema.newBuilder().column("id", DataTypes.INT()).build(), 3);
+ append("bounded_events", GenericRow.of(1), GenericRow.of(2));
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pause("bounded_events")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT id FROM bounded_events"));
+ barrier.awaitPlanned();
+ append("bounded_events", GenericRow.of(3), GenericRow.of(4));
+ barrier.close();
+ assertThat(query.get(30, TimeUnit.SECONDS))
+ .containsExactlyInAnyOrder(Arrays.asList(1), Arrays.asList(2));
+ assertThat(runner.execute("SELECT count(*) FROM bounded_events").getOnlyValue())
+ .isEqualTo(4L);
+ } finally {
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+
+ @Test
+ void testAllMappedTypesThroughSql() throws Exception {
+ Schema schema =
+ Schema.newBuilder()
+ .column("c", DataTypes.CHAR(4))
+ .column("short_decimal", DataTypes.DECIMAL(18, 2))
+ .column("long_decimal", DataTypes.DECIMAL(38, 9))
+ .column("d", DataTypes.DATE())
+ .column("t", DataTypes.TIME(3))
+ .column("ts", DataTypes.TIMESTAMP(6))
+ .column("ts_nanos", DataTypes.TIMESTAMP(9))
+ .column("ltz", DataTypes.TIMESTAMP_LTZ(3))
+ .column("ltz_nanos", DataTypes.TIMESTAMP_LTZ(9))
+ .column("items", DataTypes.ARRAY(DataTypes.INT()))
+ .column("mapping", DataTypes.MAP(DataTypes.STRING(), DataTypes.INT()))
+ .column(
+ "nested",
+ DataTypes.ROW(
+ DataTypes.FIELD("id", DataTypes.INT()),
+ DataTypes.FIELD("name", DataTypes.STRING())))
+ .column("binary_value", DataTypes.BINARY(2))
+ .column("bytes_value", DataTypes.BYTES())
+ .build();
+ admin.createTable(
+ TablePath.of("fluss", "all_types"),
+ TableDescriptor.builder()
+ .schema(schema)
+ .distributedBy(1)
+ .logFormat(LogFormat.INDEXED)
+ .build(),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ append(
+ "all_types",
+ GenericRow.of(
+ BinaryString.fromString("ä¸ "),
+ Decimal.fromBigDecimal(new BigDecimal("-9999999999999999.99"), 18, 2),
+ Decimal.fromBigDecimal(
+ new BigDecimal("12345678901234567890123456789.123456789"), 38, 9),
+ -1,
+ 86399999,
+ TimestampNtz.fromMillis(-1, 999000),
+ TimestampNtz.fromMillis(-1, 999999),
+ TimestampLtz.fromEpochMillis(-1),
+ TimestampLtz.fromEpochMillis(-1, 999999),
+ GenericArray.of(1, null, 3),
+ new GenericMap(
+ Collections.singletonMap(BinaryString.fromString("k"), null)),
+ GenericRow.of(7, BinaryString.fromString("世界")),
+ new byte[] {0, (byte) 255},
+ new byte[] {1, 2}));
+ String expected =
+ "VALUES (CAST('ä¸' AS CHAR(4)), DECIMAL '-9999999999999999.99', "
+ + "DECIMAL '12345678901234567890123456789.123456789', DATE '1969-12-31', TIME '23:59:59.999', "
+ + "TIMESTAMP '1969-12-31 23:59:59.999999', TIMESTAMP '1969-12-31 23:59:59.999999999', "
+ + "TIMESTAMP '1969-12-31 23:59:59.999 UTC', TIMESTAMP '1969-12-31 23:59:59.999999999 UTC', "
+ + "ARRAY[1, NULL, 3], MAP(ARRAY['k'], ARRAY[CAST(NULL AS INTEGER)]), ROW(7, '世界'), X'00FF', X'0102')";
+
+ assertThat(runner.execute("SELECT * FROM all_types").getMaterializedRows())
+ .containsExactlyElementsOf(runner.execute(expected).getMaterializedRows());
+ append("all_types", new GenericRow(schema.getColumns().size()));
+ assertThat(
+ runner.execute(
+ "SELECT count(*) FROM all_types WHERE c IS NULL AND items IS NULL AND nested IS NULL")
+ .getOnlyValue())
+ .isEqualTo(1L);
+ assertThat(
+ runner.execute(
+ io.trino.Session.builder(runner.getDefaultSession())
+ .setTimeZoneKey(
+ io.trino.spi.type.TimeZoneKey
+ .getTimeZoneKey("Asia/Shanghai"))
+ .build(),
+ "SELECT to_unixtime(ltz), CAST(ts AS VARCHAR) FROM all_types")
+ .getMaterializedRows())
+ .isEqualTo(
+ runner.execute(
+ "SELECT to_unixtime(ltz), CAST(ts AS VARCHAR) FROM all_types")
+ .getMaterializedRows());
+ }
+
+ @Test
+ void testUnsupportedTablesKeepMetadataAvailable() throws Exception {
+ Schema schema = Schema.newBuilder().column("id", DataTypes.INT()).build();
+ admin.createTable(
+ TablePath.of("fluss", "partitioned"),
+ TableDescriptor.builder()
+ .schema(schema)
+ .partitionedBy("id")
+ .distributedBy(1)
+ .build(),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ admin.createTable(
+ TablePath.of("fluss", "primary_key"),
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .primaryKey("id")
+ .build())
+ .distributedBy(1)
+ .build(),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ admin.createTable(
+ TablePath.of("fluss", "lakehouse"),
+ TableDescriptor.builder()
+ .schema(schema)
+ .property(ConfigOptions.TABLE_DATALAKE_ENABLED, true)
+ .distributedBy(1)
+ .build(),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ assertThat(rows("DESCRIBE primary_key")).hasSize(1);
+ assertThat(runner.execute("SHOW CREATE TABLE primary_key").getOnlyValue().toString())
+ .contains("primary_key =");
+ assertThat(
+ runner.execute(
+ "SELECT primary_key_position FROM \"primary_key$columns\" WHERE column_name = 'id'")
+ .getOnlyValue())
+ .isEqualTo(1L);
+ assertThat(rows("DESCRIBE partitioned")).hasSize(1);
+ assertThat(rows("SELECT * FROM partitioned")).isEmpty();
+ for (String name : Collections.singletonList("lakehouse")) {
+ assertThat(rows("DESCRIBE " + name)).hasSize(1);
+ assertThat(rows("SHOW CREATE TABLE " + name)).hasSize(1);
+ assertThat(rows("SELECT * FROM \"" + name + "$columns\"")).hasSize(1);
+ assertThatThrownBy(() -> runner.execute("SELECT * FROM " + name))
+ .hasMessageContaining("not supported");
+ }
+ }
+
+ @Test
+ void testPartitionedLogAndPrimaryKeyReads() throws Exception {
+ for (boolean primaryKey : new boolean[] {false, true}) {
+ String name = primaryKey ? "partitioned_users" : "partitioned_events";
+ TablePath path = TablePath.of("fluss", name);
+ Schema.Builder schema =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("region", DataTypes.STRING());
+ if (primaryKey) {
+ schema.primaryKey("id", "region");
+ }
+ admin.createTable(
+ path,
+ TableDescriptor.builder()
+ .schema(schema.build())
+ .partitionedBy("region")
+ .distributedBy(2, "id")
+ .build(),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ for (String region : Arrays.asList("east", "west", "empty")) {
+ admin.createPartition(
+ path,
+ new PartitionSpec(Collections.singletonMap("region", region)),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ }
+ try (Table table = connection.getTable(path)) {
+ GenericRow east = GenericRow.of(1, BinaryString.fromString("east"));
+ GenericRow west = GenericRow.of(1, BinaryString.fromString("west"));
+ if (primaryKey) {
+ UpsertWriter writer = table.newUpsert().createWriter();
+ writer.upsert(east).get(30, TimeUnit.SECONDS);
+ writer.upsert(west).get(30, TimeUnit.SECONDS);
+ } else {
+ AppendWriter writer = table.newAppend().createWriter();
+ writer.append(east).get(30, TimeUnit.SECONDS);
+ writer.append(west).get(30, TimeUnit.SECONDS);
+ }
+ }
+ assertThat(rows("SELECT * FROM " + name))
+ .containsExactlyInAnyOrder(Arrays.asList(1, "east"), Arrays.asList(1, "west"));
+ assertThat(runner.execute("SELECT count(*) FROM " + name).getOnlyValue()).isEqualTo(2L);
+ }
+ }
+
+ @Test
+ void testContinuousAppendsDoNotExtendQuery() throws Exception {
+ createTable(
+ "continuous_events", Schema.newBuilder().column("id", DataTypes.INT()).build(), 1);
+ append("continuous_events", GenericRow.of(1));
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ AtomicBoolean writing = new AtomicBoolean(true);
+ CountDownLatch appended = new CountDownLatch(1);
+ Future<?> writer = null;
+ try (FlussQueryRunner.Barrier barrier = gate.pause("continuous_events")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT id FROM continuous_events"));
+ barrier.awaitPlanned();
+ writer =
+ executor.submit(
+ () -> {
+ try (Table table =
+ connection.getTable(
+ TablePath.of("fluss", "continuous_events"))) {
+ AppendWriter appender = table.newAppend().createWriter();
+ while (writing.get()) {
+ appender.append(GenericRow.of(2)).get(30, TimeUnit.SECONDS);
+ appended.countDown();
+ }
+ }
+ return null;
+ });
+ assertThat(appended.await(30, TimeUnit.SECONDS)).isTrue();
+ barrier.close();
+ assertThat(query.get(30, TimeUnit.SECONDS)).containsExactly(Arrays.asList(1));
+ assertThat(writer.isDone()).isFalse();
+ } finally {
+ writing.set(false);
+ try {
+ if (writer != null) {
+ writer.get(30, TimeUnit.SECONDS);
+ }
+ } finally {
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+ }
+
+ @Test
+ void testExpiredPlannedStartFails() throws Exception {
+ TablePath path = TablePath.of("fluss", "retained_events");
+ admin.createTable(
+ path,
+ TableDescriptor.builder()
+ .schema(Schema.newBuilder().column("id", DataTypes.INT()).build())
+ .distributedBy(1)
+ .property(ConfigOptions.TABLE_LOG_TTL, Duration.ofSeconds(1))
+ .build(),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ append("retained_events", GenericRow.of(1));
+ LogTablet log =
+ CLUSTER.waitAndGetLeaderReplica(
+ new TableBucket(
+ admin.getTableInfo(path)
+ .get(30, TimeUnit.SECONDS)
+ .getTableId(),
+ 0))
+ .getLogTablet();
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pause("retained_events")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT * FROM retained_events"));
+ barrier.awaitPlanned();
+ log.roll(Optional.empty());
+ CLOCK.advanceTime(Duration.ofSeconds(2));
+ log.deleteExpiredSegments();
+ assertThat(log.logStartOffset()).isGreaterThan(0);
+ barrier.close();
+ assertThatThrownBy(() -> query.get(30, TimeUnit.SECONDS))
+ .hasStackTraceContaining("OffsetOutOfRange");
+ } finally {
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+
+ @Test
+ void testReplacementAfterPlanningFails() throws Exception {
+ Schema schema = Schema.newBuilder().column("id", DataTypes.INT()).build();
+ createTable("replaced_events", schema, 1);
+ append("replaced_events", GenericRow.of(1));
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pause("replaced_events")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT * FROM replaced_events"));
+ barrier.awaitPlanned();
+ admin.dropTable(TablePath.of("fluss", "replaced_events"), false)
+ .get(30, TimeUnit.SECONDS);
+ createTable("replaced_events", schema, 1);
+ append("replaced_events", GenericRow.of(2));
+ barrier.close();
+ assertThatThrownBy(() -> query.get(30, TimeUnit.SECONDS))
+ .hasStackTraceContaining("changed");
+ } finally {
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+
+ @Test
+ void testSchemaChangeAfterPlanningFails() throws Exception {
+ createTable(
+ "evolving_events", Schema.newBuilder().column("id", DataTypes.INT()).build(), 1);
+ append("evolving_events", GenericRow.of(1));
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pause("evolving_events")) {
+ Future<?> query =
+ executor.submit(() -> runner.execute("SELECT * FROM evolving_events"));
+ barrier.awaitPlanned();
+ admin.alterTable(
+ TablePath.of("fluss", "evolving_events"),
+ Collections.singletonList(
+ TableChange.addColumn(
+ "name",
+ DataTypes.STRING(),
+ null,
+ TableChange.ColumnPosition.last())),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ barrier.close();
+ assertThatThrownBy(() -> query.get(30, TimeUnit.SECONDS))
+ .hasStackTraceContaining("changed");
+ } finally {
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+
+ @Test
+ void testTabletRestartAfterPlanning() throws Exception {
+ createTable("restart_events", Schema.newBuilder().column("id", DataTypes.INT()).build(), 1);
+ append("restart_events", GenericRow.of(1), GenericRow.of(2));
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pause("restart_events")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT * FROM restart_events"));
+ barrier.awaitPlanned();
+ CLUSTER.restartTabletServer(0, new Configuration());
+ barrier.close();
+ assertThat(query.get(30, TimeUnit.SECONDS))
+ .containsExactlyInAnyOrder(Arrays.asList(1), Arrays.asList(2));
+ } finally {
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+
+ @Test
+ void testLimitReleasesPartiallyConsumedReader() throws Exception {
+ createTable("limit_events", Schema.newBuilder().column("id", DataTypes.INT()).build(), 1);
+ try (Table table = connection.getTable(TablePath.of("fluss", "limit_events"))) {
+ AppendWriter writer = table.newAppend().createWriter();
+ List<CompletableFuture<?>> writes = new ArrayList<>();
+ for (int i = 0; i < 3000; i++) {
+ writes.add(writer.append(GenericRow.of(i)));
+ }
+ CompletableFuture.allOf(writes.toArray(new CompletableFuture[0]))
+ .get(30, TimeUnit.SECONDS);
+ }
+ int created = gate.createdSources();
+ assertThat(rows("SELECT id FROM limit_events LIMIT 1")).hasSize(1);
+ assertThat(gate.createdSources()).isGreaterThan(created);
+ waitUntil(
+ () -> gate.activeSources() == 0,
+ Duration.ofSeconds(30),
+ "LIMIT did not release its reader");
+ }
+
+ @Test
+ void testPrimitiveValuesThroughSql() throws Exception {
+ Schema schema =
+ Schema.newBuilder()
+ .column("b", DataTypes.BOOLEAN())
+ .column("tiny", DataTypes.TINYINT())
+ .column("small", DataTypes.SMALLINT())
+ .column("big", DataTypes.BIGINT())
+ .column("f", DataTypes.FLOAT())
+ .column("d", DataTypes.DOUBLE())
+ .build();
+ createTable("primitives", schema, 1);
+ append(
+ "primitives",
+ GenericRow.of(
+ true,
+ Byte.MIN_VALUE,
+ Short.MAX_VALUE,
+ Long.MAX_VALUE,
+ Float.NaN,
+ Double.NEGATIVE_INFINITY));
+ assertThat(rows("SELECT * FROM primitives"))
+ .containsExactlyElementsOf(
+ rows(
+ "VALUES (true, TINYINT '-128', SMALLINT '32767', BIGINT '9223372036854775807', CAST(nan() AS REAL), -infinity())"));
+ }
+
+ @Test
+ void testMultipleNonemptyBucketsAndEmptyBuckets() throws Exception {
+ TablePath path = TablePath.of("fluss", "bucket_events");
+ admin.createTable(
+ path,
+ TableDescriptor.builder()
+ .schema(Schema.newBuilder().column("id", DataTypes.INT()).build())
+ .distributedBy(3, "id")
+ .build(),
+ false)
+ .get(30, TimeUnit.SECONDS);
+ append("bucket_events", GenericRow.of(0));
+ assertThat(rows("SELECT * FROM bucket_events")).containsExactly(Arrays.asList(0));
+ try (Table table = connection.getTable(path)) {
+ AppendWriter writer = table.newAppend().createWriter();
+ List<CompletableFuture<?>> writes = new ArrayList<>();
+ for (int i = 1; i < 300; i++) {
+ writes.add(writer.append(GenericRow.of(i)));
+ }
+ CompletableFuture.allOf(writes.toArray(new CompletableFuture[0]))
+ .get(30, TimeUnit.SECONDS);
+ }
+ assertThat(
+ admin.listOffsets(
+ path,
+ Arrays.asList(0, 1, 2),
+ new org.apache.fluss.client.admin.OffsetSpec.LatestSpec())
+ .all()
+ .get(30, TimeUnit.SECONDS)
+ .values())
+ .allSatisfy(offset -> assertThat(offset).isGreaterThan(0));
+ assertThat(rows("SELECT count(*), sum(id) FROM bucket_events"))
+ .containsExactly(Arrays.asList(300L, 44850L));
+ assertThat(rows("SELECT id FROM bucket_events")).hasSize(300);
+ }
+
+ @Test
+ void testNonpartitionedTopologyCannotChangeAfterPlanning() throws Exception {
+ createTable(
+ "topology_events", Schema.newBuilder().column("id", DataTypes.INT()).build(), 1);
+ append("topology_events", GenericRow.of(1));
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pause("topology_events")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT * FROM topology_events"));
+ barrier.awaitPlanned();
+ assertThatThrownBy(
+ () ->
+ admin.alterTable(
+ TablePath.of("fluss", "topology_events"),
+ Collections.singletonList(
+ TableChange.modifyBucketCount(2)),
+ false)
+ .get(30, TimeUnit.SECONDS))
+ .hasStackTraceContaining("Non-partitioned table rescale is not yet supported");
+ barrier.close();
+ assertThat(query.get(30, TimeUnit.SECONDS)).containsExactly(Arrays.asList(1));
+ } finally {
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+
+ private static Configuration clusterConfig() {
+ Configuration configuration = new Configuration();
+ configuration.set(ConfigOptions.REMOTE_LOG_TASK_INTERVAL_DURATION, Duration.ZERO);
+ configuration.set(
+ ConfigOptions.DATALAKE_FORMAT, org.apache.fluss.metadata.DataLakeFormat.PAIMON);
+ return configuration;
+ }
+
+ // private void createTable(String name, Schema schema, int buckets) throws Exception {
+ // admin.createTable(
+ // TablePath.of("fluss", name),
+ //
+ // TableDescriptor.builder().schema(schema).distributedBy(buckets).build(),
+ // false)
+ // .get(30, TimeUnit.SECONDS);
+ // }
+
+ private void createTable(String name, Schema schema, int buckets) throws Exception {
+ TablePath tablePath = TablePath.of("fluss", name);
+
+ admin.createTable(
+ tablePath,
+ TableDescriptor.builder().schema(schema).distributedBy(buckets).build(),
+ false)
+ .get(30, TimeUnit.SECONDS);
+
+ long tableId = admin.getTableInfo(tablePath).get(30, TimeUnit.SECONDS).getTableId();
+
+ CLUSTER.waitUntilTableReady(tableId);
+ }
+
+ private void append(String name, InternalRow... rows) throws Exception {
+ try (Table table = connection.getTable(TablePath.of("fluss", name))) {
+ AppendWriter writer = table.newAppend().createWriter();
+ for (InternalRow row : rows) {
+ writer.append(row).get(30, TimeUnit.SECONDS);
+ }
+ }
+ }
+
+ private List<List<Object>> rows(String sql) {
+ return runner.execute(sql).getMaterializedRows().stream()
+ .map(MaterializedRow::getFields)
+ .collect(Collectors.toList());
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussLogSplitReaderTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussLogSplitReaderTest.java
new file mode 100644
index 0000000000..99a1e97f58
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussLogSplitReaderTest.java
@@ -0,0 +1,192 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.client.table.scanner.Scan;
+import org.apache.fluss.client.table.scanner.ScanRecord;
+import org.apache.fluss.client.table.scanner.log.LogScanner;
+import org.apache.fluss.client.table.scanner.log.ScanRecords;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.record.ChangeType;
+import org.apache.fluss.row.GenericRow;
+
+import io.trino.spi.TrinoException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.fluss.trino.FlussSplitReader.PollResult.AVAILABLE;
+import static org.apache.fluss.trino.FlussSplitReader.PollResult.FINISHED;
+import static org.apache.fluss.trino.FlussSplitReader.PollResult.YIELD;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/** Verifies log boundaries, scanner progress and physical bucket subscription. */
+final class FlussLogSplitReaderTest {
+ private static final Duration TIMEOUT = Duration.ofMillis(100);
+ private static final FlussBucketHandle BUCKET = new FlussBucketHandle(42, Optional.empty(), 0);
+ private final Table table = mock(Table.class);
+ private final Scan scan = mock(Scan.class);
+ private final LogScanner scanner = mock(LogScanner.class);
+
+ @BeforeEach
+ void setUp() {
+ when(table.newScan()).thenReturn(scan);
+ when(scan.createLogScanner()).thenReturn(scanner);
+ }
+
+ @Test
+ void testEmptyRangeDoesNotCreateScanner() throws Exception {
+ try (FlussLogSplitReader reader = create(1000, 1000)) {
+ assertThat(reader.isFinished()).isTrue();
+ assertThat(reader.poll(TIMEOUT)).isEqualTo(FINISHED);
+ assertThat(reader.hasNext()).isFalse();
+ }
+ verifyNoInteractions(table, scan, scanner);
+ }
+
+ @Test
+ void testStopsAtExclusiveBoundaryAndCountsOnlyConsumedBytes() throws Exception {
+ when(scanner.poll(TIMEOUT)).thenReturn(records(5, 9, 10, 11));
+ try (FlussLogSplitReader reader = create(5, 10)) {
+ assertThat(reader.poll(TIMEOUT)).isEqualTo(AVAILABLE);
+ assertThat(reader.getRetainedSizeInBytes()).isGreaterThan(0);
+ assertThatThrownBy(() -> reader.poll(TIMEOUT))
+ .isInstanceOf(IllegalStateException.class);
+ assertThat(reader.next().getLong(0)).isEqualTo(5);
+ assertThat(reader.next().getLong(0)).isEqualTo(9);
+ assertThat(reader.hasNext()).isFalse();
+ assertThat(reader.isFinished()).isTrue();
+ assertThat(reader.getCompletedBytes()).isEqualTo(16);
+ assertThat(reader.getRetainedSizeInBytes()).isZero();
+ assertThat(reader.poll(TIMEOUT)).isEqualTo(FINISHED);
+ }
+ verify(scanner).subscribe(0, 5);
+ verify(scanner).poll(TIMEOUT);
+ verify(scanner).close();
+ }
+
+ @Test
+ void testSmallBatchYieldsUntilProgressReachesStop() throws Exception {
+ when(scanner.poll(TIMEOUT))
+ .thenReturn(
+ records(5),
+ ScanRecords.EMPTY,
+ new ScanRecords(
+ Collections.emptyMap(),
+ Collections.singletonMap(BUCKET.toTableBucket(), 10L)));
+ try (FlussLogSplitReader reader = create(5, 10)) {
+ assertThat(reader.poll(TIMEOUT)).isEqualTo(AVAILABLE);
+ reader.next();
+ assertThat(reader.isFinished()).isFalse();
+ assertThat(reader.poll(TIMEOUT)).isEqualTo(YIELD);
+ assertThat(reader.poll(TIMEOUT)).isEqualTo(FINISHED);
+ }
+ }
+
+ @Test
+ void testRecordBeforeStartFails() throws Exception {
+ when(scanner.poll(TIMEOUT)).thenReturn(records(4));
+ try (FlussLogSplitReader reader = create(5, 10)) {
+ assertThatThrownBy(() -> reader.poll(TIMEOUT))
+ .isInstanceOf(TrinoException.class)
+ .hasMessageContaining("precedes");
+ }
+ }
+
+ @Test
+ void testPartitionedSubscription() throws Exception {
+ FlussBucketHandle partition = new FlussBucketHandle(42, Optional.of(7L), 2);
+ when(scanner.poll(TIMEOUT))
+ .thenReturn(
+ new ScanRecords(
+ Collections.singletonMap(
+ new TableBucket(42, 7L, 2),
+ Collections.singletonList(record(5)))));
+ try (FlussLogSplitReader reader =
+ new FlussLogSplitReader(table, partition, new FlussLogRange(5, 6))) {
+ assertThat(reader.poll(TIMEOUT)).isEqualTo(AVAILABLE);
+ assertThat(reader.next().getLong(0)).isEqualTo(5);
+ assertThat(reader.isFinished()).isTrue();
+ }
+ verify(scanner).subscribe(7L, 2, 5L);
+ }
+
+ @Test
+ void testSubscribeFailurePreservesCleanupFailure() throws Exception {
+ RuntimeException failure = new IllegalStateException("subscribe failed");
+ IOException cleanup = new IOException("close failed");
+ doThrow(failure).when(scanner).subscribe(0, 5);
+ doThrow(cleanup).when(scanner).close();
+ assertThatThrownBy(() -> create(5, 10)).isSameAs(failure);
+ assertThat(failure.getSuppressed()).containsExactly(cleanup);
+ }
+
+ @Test
+ void testPollFailureHasReadErrorContext() throws Exception {
+ RuntimeException failure = new IllegalStateException("poll failed");
+ when(scanner.poll(TIMEOUT)).thenThrow(failure);
+ try (FlussLogSplitReader reader = create(5, 10)) {
+ assertThatThrownBy(() -> reader.poll(TIMEOUT))
+ .isInstanceOf(TrinoException.class)
+ .hasCause(failure)
+ .hasMessageContaining("bucketId=0");
+ }
+ }
+
+ @Test
+ void testEarlyCloseClearsBufferAndIsIdempotent() throws Exception {
+ when(scanner.poll(TIMEOUT)).thenReturn(records(5, 6));
+ FlussLogSplitReader reader = create(5, 10);
+ reader.poll(TIMEOUT);
+ reader.close();
+ reader.close();
+ assertThat(reader.hasNext()).isFalse();
+ assertThat(reader.isFinished()).isTrue();
+ assertThat(reader.getRetainedSizeInBytes()).isZero();
+ verify(scanner).close();
+ }
+
+ private FlussLogSplitReader create(long start, long stop) {
+ return new FlussLogSplitReader(table, BUCKET, new FlussLogRange(start, stop));
+ }
+
+ private static ScanRecords records(long... offsets) {
+ return new ScanRecords(
+ Collections.singletonMap(
+ BUCKET.toTableBucket(),
+ Arrays.stream(offsets)
+ .mapToObj(FlussLogSplitReaderTest::record)
+ .collect(java.util.stream.Collectors.toList())));
+ }
+
+ private static ScanRecord record(long offset) {
+ return new ScanRecord(42, 1, offset, 0, ChangeType.INSERT, GenericRow.of(offset), 8);
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussMetadataAccessTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussMetadataAccessTest.java
new file mode 100644
index 0000000000..2422b6c005
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussMetadataAccessTest.java
@@ -0,0 +1,312 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.exception.DatabaseNotExistException;
+import org.apache.fluss.exception.TableNotExistException;
+import org.apache.fluss.metadata.BucketInfo;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metadata.TablePath;
+import org.apache.fluss.utils.concurrent.FutureUtils;
+
+import io.trino.spi.TrinoException;
+import io.trino.spi.connector.SchemaTableName;
+import io.trino.spi.connector.TableNotFoundException;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Optional;
+
+import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
+import static java.util.concurrent.CompletableFuture.completedFuture;
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_METADATA_CHANGED;
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_METADATA_ERROR;
+import static org.apache.fluss.trino.FlussErrorCode.FLUSS_SPLIT_ERROR;
+import static org.apache.fluss.trino.TestingFlussMetadata.metadataAccess;
+import static org.apache.fluss.trino.TestingFlussMetadata.usersTable;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** Tests physical name resolution and catalog failure translation at the Admin boundary. */
+final class FlussMetadataAccessTest {
+ private final Admin admin = mock(Admin.class);
+ private final FlussMetadataAccess access = metadataAccess(admin);
+
+ @Test
+ void testSchemaNamesAreCanonicalAndDistinct() {
+ when(admin.listDatabases())
+ .thenReturn(completedFuture(Arrays.asList("Sales", "sales", "Inventory")));
+ assertThat(access.listSchemaNames()).containsExactlyInAnyOrder("sales", "inventory");
+ assertThat(access.resolveSchema("INVENTORY"))
+ .hasValueSatisfying(
+ schema -> {
+ assertThat(schema.getTrinoName()).isEqualTo("inventory");
+ assertThat(schema.getFlussName()).isEqualTo("Inventory");
+ });
+ }
+
+ @Test
+ void testAmbiguousSchema() {
+ when(admin.listDatabases()).thenReturn(completedFuture(Arrays.asList("sales", "Sales")));
+ assertThatThrownBy(() -> access.resolveSchema("sales"))
+ .isInstanceOfSatisfying(
+ TrinoException.class,
+ failure ->
+ assertThat(failure.getErrorCode())
+ .isEqualTo(NOT_SUPPORTED.toErrorCode()))
+ .hasMessage("Ambiguous Fluss database 'sales': Sales, sales");
+ assertThatThrownBy(() -> access.listTableNameMappings(Optional.empty()))
+ .isInstanceOf(TrinoException.class)
+ .hasMessageContaining("Ambiguous Fluss database");
+ }
+
+ @Test
+ void testResolvePhysicalTableName() {
+ when(admin.listDatabases()).thenReturn(completedFuture(Collections.singletonList("Sales")));
+ when(admin.listTables("Sales"))
+ .thenReturn(completedFuture(Collections.singletonList("Users")));
+ assertThat(access.resolveTable(new SchemaTableName("sales", "users")))
+ .hasValueSatisfying(
+ table -> {
+ assertThat(table.getTrinoName())
+ .isEqualTo(new SchemaTableName("sales", "users"));
+ assertThat(table.getFlussDatabaseName()).isEqualTo("Sales");
+ assertThat(table.getFlussTableName()).isEqualTo("Users");
+ });
+ verify(admin).listTables("Sales");
+ }
+
+ @Test
+ void testCatalogWideListingResolvesEachPhysicalDatabase() {
+ when(admin.listDatabases())
+ .thenReturn(completedFuture(Arrays.asList("Sales", "Inventory")));
+ when(admin.listTables("Sales"))
+ .thenReturn(completedFuture(Collections.singletonList("Users")));
+ when(admin.listTables("Inventory"))
+ .thenReturn(completedFuture(Collections.singletonList("Products")));
+ assertThat(access.listTableNameMappings(Optional.empty()))
+ .flatExtracting(FlussMetadataAccess.TableNameMapping::listTableNames)
+ .containsExactly(
+ new SchemaTableName("sales", "users"),
+ new SchemaTableName("inventory", "products"));
+ }
+
+ @Test
+ void testTargetedListingIgnoresUnrelatedSchemaAmbiguity() {
+ when(admin.listDatabases())
+ .thenReturn(completedFuture(Arrays.asList("Sales", "sales", "Inventory")));
+ when(admin.listTables("Inventory"))
+ .thenReturn(completedFuture(Collections.singletonList("Products")));
+ assertThat(access.listTableNameMappings(Optional.of("inventory")))
+ .flatExtracting(FlussMetadataAccess.TableNameMapping::listTableNames)
+ .containsExactly(new SchemaTableName("inventory", "products"));
+ }
+
+ @Test
+ void testMissingSchema() {
+ when(admin.listDatabases()).thenReturn(completedFuture(Collections.emptyList()));
+ assertThat(access.resolveSchema("missing")).isEmpty();
+ assertThat(access.resolveTable(new SchemaTableName("missing", "users"))).isEmpty();
+ assertThat(access.listTableNameMappings(Optional.of("missing"))).isEmpty();
+ }
+
+ @Test
+ void testTableIndexResolvesOnlyRequestedNames() {
+ when(admin.listTables("Sales"))
+ .thenReturn(completedFuture(Arrays.asList("Users", "Order", "oRder")));
+ FlussMetadataAccess.TableNameMapping index =
+ access.loadTableNameMapping(new ResolvedSchemaName("sales", "Sales"));
+ assertThat(index.listTableNames())
+ .containsExactly(
+ new SchemaTableName("sales", "users"),
+ new SchemaTableName("sales", "order"));
+ assertThat(index.resolveTable("USERS"))
+ .hasValueSatisfying(
+ table -> assertThat(table.getFlussTableName()).isEqualTo("Users"));
+ assertThat(index.resolveTable("missing")).isEmpty();
+ assertThatThrownBy(() -> index.resolveTable("order"))
+ .isInstanceOf(TrinoException.class)
+ .hasMessage("Ambiguous Fluss table 'order': Order, oRder");
+ verify(admin, times(1)).listTables("Sales");
+ }
+
+ @Test
+ void testDatabaseDroppedBeforeListingTables() {
+ when(admin.listTables("Sales"))
+ .thenReturn(
+ FutureUtils.completedExceptionally(
+ new DatabaseNotExistException("dropped")));
+ assertThat(
+ access.loadTableNameMapping(new ResolvedSchemaName("sales", "Sales"))
+ .listTableNames())
+ .isEmpty();
+ }
+
+ @Test
+ void testDiscoverySkipsDroppedTableOrDatabase() {
+ TablePath path = TablePath.of("Sales", "Users");
+ when(admin.getTableInfo(path))
+ .thenReturn(
+ FutureUtils.completedExceptionally(new TableNotExistException("dropped")),
+ FutureUtils.completedExceptionally(
+ new DatabaseNotExistException("dropped")));
+ ResolvedTableName table =
+ new ResolvedTableName(new SchemaTableName("sales", "users"), "Sales", "Users");
+ assertThat(access.findTableInfo(table)).isEmpty();
+ assertThat(access.findTableInfo(table)).isEmpty();
+ }
+
+ @Test
+ void testExistingHandleReportsDroppedTable() {
+ TableNotExistException failure = new TableNotExistException("dropped");
+ when(admin.getTableInfo(TablePath.of("Sales", "Users")))
+ .thenReturn(FutureUtils.completedExceptionally(failure));
+ assertThatThrownBy(
+ () ->
+ access.getTableInfo(
+ new FlussTableHandle(
+ "sales", "users", "Sales", "Users", 42, 3)))
+ .isInstanceOf(TableNotFoundException.class)
+ .hasCause(failure)
+ .hasMessageContaining("sales.users");
+ }
+
+ @Test
+ void testValidateTableAndSchemaIdentity() {
+ TableInfo info = usersTable();
+ when(admin.getTableInfo(TablePath.of("Sales", "Users"))).thenReturn(completedFuture(info));
+ assertThat(
+ access.getTableInfo(
+ new FlussTableHandle("sales", "users", "Sales", "Users", 42, 3)))
+ .isSameAs(info);
+ assertThatThrownBy(
+ () ->
+ access.getTableInfo(
+ new FlussTableHandle(
+ "sales", "users", "Sales", "Users", 41, 3)))
+ .isInstanceOfSatisfying(
+ TrinoException.class,
+ failure ->
+ assertThat(failure.getErrorCode())
+ .isEqualTo(FLUSS_METADATA_CHANGED.toErrorCode()))
+ .hasMessageContaining("changed");
+ assertThatThrownBy(
+ () ->
+ access.getTableInfo(
+ new FlussTableHandle(
+ "sales", "users", "Sales", "Users", 42, 2)))
+ .isInstanceOf(TrinoException.class)
+ .hasMessageContaining("changed");
+ }
+
+ @Test
+ void testDescribeBucketsPreservesPhysicalPartitionIdentity() {
+ TablePath path = TablePath.of("Sales", "Users");
+ when(admin.describeBuckets(path))
+ .thenReturn(
+ completedFuture(
+ Collections.singletonList(
+ new BucketInfo(
+ path,
+ 42,
+ 17L,
+ "region=west",
+ 2,
+ null,
+ null,
+ null,
+ Collections.emptyList(),
+ Collections.emptyList()))));
+ assertThat(
+ access.listScanBuckets(
+ new FlussTableHandle("sales", "users", "Sales", "Users", 42, 3)))
+ .singleElement()
+ .satisfies(
+ bucket -> {
+ assertThat(bucket.getBucket())
+ .isEqualTo(new FlussBucketHandle(42, Optional.of(17L), 2));
+ assertThat(bucket.getRequiredPartitionName()).isEqualTo("region=west");
+ });
+ }
+
+ @Test
+ void testDescribeBucketsRejectsRecreatedTable() {
+ TablePath path = TablePath.of("Sales", "Users");
+ when(admin.describeBuckets(path))
+ .thenReturn(
+ completedFuture(
+ Collections.singletonList(
+ new BucketInfo(
+ path,
+ 43,
+ null,
+ null,
+ 0,
+ null,
+ null,
+ null,
+ Collections.emptyList(),
+ Collections.emptyList()))));
+ assertThatThrownBy(
+ () ->
+ access.listScanBuckets(
+ new FlussTableHandle(
+ "sales", "users", "Sales", "Users", 42, 3)))
+ .isInstanceOfSatisfying(
+ TrinoException.class,
+ failure ->
+ assertThat(failure.getErrorCode())
+ .isEqualTo(FLUSS_SPLIT_ERROR.toErrorCode()))
+ .hasMessageContaining("unexpected table ID");
+ }
+
+ @Test
+ void testUnexpectedFailurePreservesCause() {
+ RuntimeException failure = new RuntimeException("RPC failed");
+ when(admin.listDatabases()).thenReturn(FutureUtils.completedExceptionally(failure));
+ assertThatThrownBy(access::listSchemaNames)
+ .isInstanceOfSatisfying(
+ TrinoException.class,
+ exception ->
+ assertThat(exception.getErrorCode())
+ .isEqualTo(FLUSS_METADATA_ERROR.toErrorCode()))
+ .hasCause(failure);
+ }
+
+ @Test
+ void testDiscoveryDoesNotHideUnexpectedFailure() {
+ RuntimeException failure = new RuntimeException("permission denied");
+ when(admin.getTableInfo(TablePath.of("Sales", "Users")))
+ .thenReturn(FutureUtils.completedExceptionally(failure));
+ assertThatThrownBy(
+ () ->
+ access.findTableInfo(
+ new ResolvedTableName(
+ new SchemaTableName("sales", "users"),
+ "Sales",
+ "Users")))
+ .isInstanceOf(TrinoException.class)
+ .hasCause(failure);
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussMetadataTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussMetadataTest.java
new file mode 100644
index 0000000000..43661ac1a9
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussMetadataTest.java
@@ -0,0 +1,358 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.exception.TableNotExistException;
+import org.apache.fluss.metadata.Schema;
+import org.apache.fluss.metadata.TableDescriptor;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metadata.TablePath;
+import org.apache.fluss.types.DataTypes;
+import org.apache.fluss.utils.concurrent.FutureUtils;
+
+import io.trino.spi.TrinoException;
+import io.trino.spi.connector.ColumnHandle;
+import io.trino.spi.connector.ColumnMetadata;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.ConnectorTableHandle;
+import io.trino.spi.connector.ConnectorTableMetadata;
+import io.trino.spi.connector.ConnectorTableVersion;
+import io.trino.spi.connector.RelationColumnsMetadata;
+import io.trino.spi.connector.RelationCommentMetadata;
+import io.trino.spi.connector.SchemaTableName;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+
+import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
+import static io.trino.spi.type.BigintType.BIGINT;
+import static io.trino.spi.type.VarcharType.VARCHAR;
+import static java.util.concurrent.CompletableFuture.completedFuture;
+import static org.apache.fluss.trino.TestingFlussMetadata.metadataAccess;
+import static org.apache.fluss.trino.TestingFlussMetadata.tableInfo;
+import static org.apache.fluss.trino.TestingFlussMetadata.usersTable;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** Tests Trino metadata contracts using real metadata access and a mocked Fluss Admin. */
+final class FlussMetadataTest {
+ private static final SchemaTableName USERS = new SchemaTableName("sales", "users");
+ private static final TablePath PHYSICAL_USERS = TablePath.of("Sales", "Users");
+
+ private final Admin admin = mock(Admin.class);
+ private final FlussMetadata metadata = new FlussMetadata(metadataAccess(admin));
+ private final ConnectorSession session = mock(ConnectorSession.class);
+
+ @Test
+ void testTableHandlePreservesPhysicalIdentity() {
+ givenTables("Users");
+ when(admin.getTableInfo(PHYSICAL_USERS)).thenReturn(completedFuture(usersTable()));
+ ConnectorTableHandle handle =
+ metadata.getTableHandle(session, USERS, Optional.empty(), Optional.empty());
+ assertThat(handle)
+ .isEqualTo(new FlussTableHandle("sales", "users", "Sales", "Users", 42, 3));
+ assertThat(metadata.getTableName(session, handle)).isEqualTo(USERS);
+ }
+
+ @Test
+ void testMissingTableHasNoHandle() {
+ givenTables("Users");
+ assertThat(
+ metadata.getTableHandle(
+ session,
+ new SchemaTableName("sales", "missing"),
+ Optional.empty(),
+ Optional.empty()))
+ .isNull();
+ when(admin.getTableInfo(PHYSICAL_USERS))
+ .thenReturn(
+ FutureUtils.completedExceptionally(new TableNotExistException("dropped")));
+ assertThat(metadata.getTableHandle(session, USERS, Optional.empty(), Optional.empty()))
+ .isNull();
+ }
+
+ @Test
+ void testRejectTableVersioning() {
+ ConnectorTableVersion version = mock(ConnectorTableVersion.class);
+ assertThatThrownBy(
+ () ->
+ metadata.getTableHandle(
+ session, USERS, Optional.of(version), Optional.empty()))
+ .isInstanceOfSatisfying(
+ TrinoException.class,
+ failure ->
+ assertThat(failure.getErrorCode())
+ .isEqualTo(NOT_SUPPORTED.toErrorCode()))
+ .hasMessageContaining("does not support table versioning");
+ assertThatThrownBy(
+ () ->
+ metadata.getTableHandle(
+ session, USERS, Optional.empty(), Optional.of(version)))
+ .isInstanceOf(TrinoException.class)
+ .hasMessageContaining("does not support table versioning");
+ }
+
+ @Test
+ void testTableHandleRejectsAmbiguousPhysicalNames() {
+ givenTables("Users", "users");
+ assertThatThrownBy(
+ () ->
+ metadata.getTableHandle(
+ session, USERS, Optional.empty(), Optional.empty()))
+ .isInstanceOfSatisfying(
+ TrinoException.class,
+ failure ->
+ assertThat(failure.getErrorCode())
+ .isEqualTo(NOT_SUPPORTED.toErrorCode()))
+ .hasMessageContaining("Ambiguous Fluss table");
+ verify(admin, never()).getTableInfo(PHYSICAL_USERS);
+ }
+
+ @Test
+ void testTableMetadataAndColumnHandles() {
+ when(admin.getTableInfo(PHYSICAL_USERS)).thenReturn(completedFuture(usersTable()));
+ FlussTableHandle handle = new FlussTableHandle("sales", "users", "Sales", "Users", 42, 3);
+ ConnectorTableMetadata table = metadata.getTableMetadata(session, handle);
+ assertThat(table.getTable()).isEqualTo(USERS);
+ assertThat(table.getComment()).contains("Registered users");
+ assertThat(table.getColumns())
+ .extracting(ColumnMetadata::getName)
+ .containsExactly("region", "id", "name");
+ assertThat(table.getColumns())
+ .extracting(ColumnMetadata::getType)
+ .containsExactly(VARCHAR, BIGINT, VARCHAR);
+ assertThat(table.getColumns())
+ .extracting(ColumnMetadata::isNullable)
+ .containsExactly(false, false, true);
+ assertThat(table.getColumns().get(1).getComment()).contains("User identifier");
+ assertThat(table.getProperties())
+ .containsEntry("primary_key", Arrays.asList("id", "region"));
+
+ Map<String, ColumnHandle> columns = metadata.getColumnHandles(session, handle);
+ assertThat(columns).containsOnlyKeys("region", "id", "name");
+ assertThat(columns.get("id")).isEqualTo(new FlussColumnHandle("ID", 1));
+ assertThat(metadata.getColumnMetadata(session, handle, columns.get("id")))
+ .isEqualTo(table.getColumns().get(1));
+ }
+
+ @Test
+ void testRejectInvalidColumnHandle() {
+ when(admin.getTableInfo(PHYSICAL_USERS)).thenReturn(completedFuture(usersTable()));
+ FlussTableHandle table = new FlussTableHandle("sales", "users", "Sales", "Users", 42, 3);
+ assertThatThrownBy(
+ () ->
+ metadata.getColumnMetadata(
+ session, table, new FlussColumnHandle("missing", 3)))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Invalid column ordinal");
+ assertThatThrownBy(
+ () ->
+ metadata.getColumnMetadata(
+ session, table, new FlussColumnHandle("id", 1)))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("does not match current table schema");
+ }
+
+ @Test
+ void testRejectAmbiguousColumnNames() {
+ TableInfo info =
+ tableInfo(
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("ID", DataTypes.INT())
+ .column("id", DataTypes.INT())
+ .build())
+ .distributedBy(1)
+ .build());
+ when(admin.getTableInfo(PHYSICAL_USERS)).thenReturn(completedFuture(info));
+ FlussTableHandle table = new FlussTableHandle("sales", "users", "Sales", "Users", 42, 3);
+ assertThatThrownBy(() -> metadata.getTableMetadata(session, table))
+ .isInstanceOf(TrinoException.class)
+ .hasMessageContaining("Ambiguous Fluss columns");
+ assertThatThrownBy(() -> metadata.getColumnHandles(session, table))
+ .isInstanceOf(TrinoException.class)
+ .hasMessageContaining("Ambiguous Fluss columns");
+ }
+
+ @Test
+ void testListTablesIncludesAmbiguousLogicalNamesOnce() {
+ givenTables("Users", "Order", "oRder");
+ assertThat(metadata.listTables(session, Optional.of("sales")))
+ .containsExactly(USERS, new SchemaTableName("sales", "order"));
+ }
+
+ @Test
+ void testRelationFilterRunsBeforeResolvingAmbiguousNames() {
+ givenTables("Users", "Order", "oRder");
+ when(admin.getTableInfo(PHYSICAL_USERS)).thenReturn(completedFuture(usersTable()));
+ Iterator<RelationColumnsMetadata> columns =
+ metadata.streamRelationColumns(
+ session,
+ Optional.of("sales"),
+ names -> {
+ assertThat(names)
+ .containsExactlyInAnyOrder(
+ USERS, new SchemaTableName("sales", "order"));
+ return Collections.singleton(USERS);
+ });
+ assertThat(columns)
+ .toIterable()
+ .singleElement()
+ .satisfies(
+ relation -> {
+ assertThat(relation.name()).isEqualTo(USERS);
+ assertThat(relation.tableColumns())
+ .hasValueSatisfying(
+ fields ->
+ assertThat(fields)
+ .extracting(ColumnMetadata::getName)
+ .containsExactly(
+ "region", "id", "name"));
+ assertThat(relation.redirected()).isFalse();
+ });
+ verify(admin, never()).getTableInfo(TablePath.of("Sales", "Order"));
+ }
+
+ @Test
+ void testSelectedAmbiguousRelationFails() {
+ givenTables("Order", "oRder");
+ assertThatThrownBy(
+ () ->
+ metadata.streamRelationColumns(
+ session, Optional.of("sales"), names -> names))
+ .isInstanceOf(TrinoException.class)
+ .hasMessageContaining("Ambiguous Fluss table");
+ }
+
+ @Test
+ void testEmptyRelationFilterDoesNotLoadTableMetadata() {
+ givenTables("Users");
+ assertThat(
+ metadata.streamRelationColumns(
+ session, Optional.of("sales"), names -> Collections.emptySet()))
+ .isExhausted();
+ assertThat(
+ metadata.streamRelationComments(
+ session, Optional.of("sales"), names -> Collections.emptySet()))
+ .isExhausted();
+ verify(admin, never()).getTableInfo(PHYSICAL_USERS);
+ }
+
+ @Test
+ void testRelationDiscoverySkipsDroppedTables() {
+ givenTables("Dropped", "Users");
+ when(admin.getTableInfo(TablePath.of("Sales", "Dropped")))
+ .thenReturn(
+ FutureUtils.completedExceptionally(new TableNotExistException("dropped")));
+ when(admin.getTableInfo(PHYSICAL_USERS)).thenReturn(completedFuture(usersTable()));
+ assertThat(metadata.streamRelationColumns(session, Optional.of("sales"), names -> names))
+ .toIterable()
+ .extracting(RelationColumnsMetadata::name)
+ .containsExactly(USERS);
+ assertThat(metadata.streamRelationComments(session, Optional.of("sales"), names -> names))
+ .toIterable()
+ .extracting(RelationCommentMetadata::name)
+ .containsExactly(USERS);
+ }
+
+ @Test
+ void testRelationCommentsApplyFilter() {
+ givenTables("Users", "Order", "oRder");
+ when(admin.getTableInfo(PHYSICAL_USERS)).thenReturn(completedFuture(usersTable()));
+ assertThat(
+ metadata.streamRelationComments(
+ session,
+ Optional.of("sales"),
+ names -> Collections.singleton(USERS)))
+ .toIterable()
+ .containsExactly(
+ RelationCommentMetadata.forRelation(
+ USERS, Optional.of("Registered users")));
+ }
+
+ @Test
+ void testEmptyCommentsAreAbsent() {
+ givenTables("Users");
+ when(admin.getTableInfo(PHYSICAL_USERS))
+ .thenReturn(
+ completedFuture(
+ tableInfo(
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .build())
+ .distributedBy(1)
+ .comment("")
+ .build())));
+ assertThat(metadata.streamRelationComments(session, Optional.of("sales"), names -> names))
+ .toIterable()
+ .containsExactly(RelationCommentMetadata.forRelation(USERS, Optional.empty()));
+ }
+
+ @Test
+ void testColumnsSystemTableDiscovery() {
+ givenTables("Users");
+ when(admin.getTableInfo(PHYSICAL_USERS)).thenReturn(completedFuture(usersTable()));
+ SchemaTableName name = new SchemaTableName("sales", "users$columns");
+ assertThat(metadata.getSystemTable(session, name))
+ .hasValueSatisfying(
+ table -> assertThat(table.getTableMetadata().getTable()).isEqualTo(name));
+ assertThat(metadata.getSystemTable(session, USERS)).isEmpty();
+ assertThat(metadata.getSystemTable(session, new SchemaTableName("sales", "$columns")))
+ .isEmpty();
+ assertThat(
+ metadata.getSystemTable(
+ session, new SchemaTableName("sales", "missing$columns")))
+ .isEmpty();
+ }
+
+ @Test
+ void testSystemTableAbsentWhenBaseTableDropped() {
+ givenTables("Users");
+ when(admin.getTableInfo(PHYSICAL_USERS))
+ .thenReturn(
+ FutureUtils.completedExceptionally(new TableNotExistException("dropped")));
+ assertThat(metadata.getSystemTable(session, new SchemaTableName("sales", "users$columns")))
+ .isEmpty();
+ }
+
+ @Test
+ void testMissingSchemaHasNoSystemTable() {
+ when(admin.listDatabases()).thenReturn(completedFuture(Collections.emptyList()));
+ assertThat(
+ metadata.getSystemTable(
+ session, new SchemaTableName("missing", "users$columns")))
+ .isEmpty();
+ }
+
+ private void givenTables(String... names) {
+ when(admin.listDatabases()).thenReturn(completedFuture(Collections.singletonList("Sales")));
+ when(admin.listTables("Sales")).thenReturn(completedFuture(Arrays.asList(names)));
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPageSourceProviderTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPageSourceProviderTest.java
new file mode 100644
index 0000000000..d5380702ca
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPageSourceProviderTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.fluss.trino;
+
+import io.trino.spi.connector.ConnectorPageSource;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.DynamicFilter;
+import io.trino.spi.connector.MemoryContext;
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+/** Verifies that provider creation leaves reading and validation to the lazy page source. */
+final class FlussPageSourceProviderTest {
+ @Test
+ void testCreatesLazyPageSourceForBothScanTypes() throws Exception {
+ FlussClientManager clients = mock(FlussClientManager.class);
+ FlussTableHandle table = new FlussTableHandle("sales", "users", "Sales", "Users", 42, 1);
+ FlussBucketHandle bucket = new FlussBucketHandle(42, Optional.empty(), 0);
+ FlussPageSourceProvider provider = new FlussPageSourceProvider(clients);
+ for (FlussSplit split :
+ new FlussSplit[] {FlussSplit.forLog(bucket, 0, 0), FlussSplit.forKv(bucket)}) {
+ try (ConnectorPageSource source =
+ provider.createPageSource(
+ FlussTransactionHandle.INSTANCE,
+ mock(ConnectorSession.class),
+ split,
+ table,
+ Optional.empty(),
+ Collections.emptyList(),
+ DynamicFilter.EMPTY,
+ MemoryContext.NO_LIMIT)) {
+ assertThat(source).isInstanceOf(FlussPageSource.class);
+ assertThat(source.isFinished()).isFalse();
+ assertThat(source.isBlocked().isDone()).isTrue();
+ }
+ }
+ verifyNoInteractions(clients);
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPageSourceTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPageSourceTest.java
new file mode 100644
index 0000000000..0a04c680f5
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPageSourceTest.java
@@ -0,0 +1,616 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.client.table.scanner.Scan;
+import org.apache.fluss.client.table.scanner.ScanRecord;
+import org.apache.fluss.client.table.scanner.batch.BatchScanner;
+import org.apache.fluss.client.table.scanner.log.LogScanner;
+import org.apache.fluss.client.table.scanner.log.ScanRecords;
+import org.apache.fluss.metadata.Schema;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableDescriptor;
+import org.apache.fluss.metadata.TableInfo;
+import org.apache.fluss.metadata.TablePath;
+import org.apache.fluss.record.ChangeType;
+import org.apache.fluss.row.GenericRow;
+import org.apache.fluss.row.InternalRow;
+import org.apache.fluss.types.DataTypes;
+import org.apache.fluss.utils.CloseableIterator;
+
+import io.trino.spi.TrinoException;
+import io.trino.spi.connector.MemoryContext;
+import io.trino.spi.connector.SourcePage;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InOrder;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+import static io.trino.spi.type.BigintType.BIGINT;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+/** Verifies shared page assembly, worker validation and resource ownership using a KV reader. */
+final class FlussPageSourceTest {
+ private static final FlussTableHandle HANDLE =
+ new FlussTableHandle("sales", "users", "Sales", "Users", 42, 1);
+ private static final TablePath PATH = TablePath.of("Sales", "Users");
+ private static final TableBucket BUCKET = new TableBucket(42, 0);
+ private static final Duration POLL_TIMEOUT = Duration.ofMillis(100);
+ private final FlussClientManager clients = mock(FlussClientManager.class);
+ private final Table table = mock(Table.class);
+ private final Scan scan = mock(Scan.class);
+ private final BatchScanner scanner = mock(BatchScanner.class);
+ private FlussPageSource source;
+
+ @BeforeEach
+ void setUp() {
+ when(clients.openTable(PATH)).thenReturn(table);
+ when(table.getTableInfo()).thenReturn(tableInfo(42, 1, 1, 0, true));
+ when(table.newScan()).thenReturn(scan);
+ when(scan.createBatchScanner(BUCKET)).thenReturn(scanner);
+ }
+
+ @AfterEach
+ void tearDown() {
+ if (source != null) {
+ source.close();
+ }
+ }
+
+ @Test
+ void testLazyInitializationAndEarlyClose() {
+ source = create();
+ assertThat(source.isBlocked().isDone()).isTrue();
+ assertThat(source.isFinished()).isFalse();
+ source.close();
+ source.close();
+ assertThat(source.getNextSourcePage()).isNull();
+ assertThat(source.isFinished()).isTrue();
+ verifyNoInteractions(clients, table, scan, scanner);
+ }
+
+ @Test
+ void testEmptyBatchYieldsButNullFinishes() throws Exception {
+ CloseableIterator<InternalRow> empty = rows(0);
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenReturn(empty).thenReturn(null);
+ source = create();
+ assertThat(source.getNextSourcePage()).isNull();
+ assertThat(source.isFinished()).isFalse();
+ verify(scanner).pollBatch(POLL_TIMEOUT);
+ verify(empty).close();
+ assertThat(source.getNextSourcePage()).isNull();
+ assertThat(source.isFinished()).isTrue();
+ verify(scanner, times(2)).pollBatch(POLL_TIMEOUT);
+ verify(scanner).close();
+ verify(table).close();
+ }
+
+ @Test
+ void testBatchSpansPagesWithoutAdditionalPoll() throws Exception {
+ CloseableIterator<InternalRow> batch = rows(2050);
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenReturn(batch).thenReturn(null);
+ source = create();
+ List<Long> values = new ArrayList<>();
+ for (int size : new int[] {1024, 1024, 2}) {
+ SourcePage page = source.getNextSourcePage();
+ assertThat(page.getPositionCount()).isEqualTo(size);
+ for (int i = 0; i < size; i++) {
+ values.add(BIGINT.getLong(page.getBlock(0), i));
+ }
+ verify(scanner).pollBatch(POLL_TIMEOUT);
+ assertThat(source.isFinished()).isFalse();
+ }
+ assertThat(values).hasSize(2050);
+ for (int i = 0; i < values.size(); i++) {
+ assertThat(values.get(i)).isEqualTo((long) i);
+ }
+ verify(batch).close();
+ assertThat(source.getCompletedPositions()).hasValue(2050);
+ assertThat(source.getCompletedBytes()).isZero();
+ assertThat(source.getNextSourcePage()).isNull();
+ assertThat(source.isFinished()).isTrue();
+ verify(scan).createBatchScanner(BUCKET);
+ verifyNoMoreInteractions(scan);
+ }
+
+ @Test
+ void testLogBatchSpansPagesAndCompletesAtStop() throws Exception {
+ LogScanner logScanner = mock(LogScanner.class);
+ when(table.getTableInfo()).thenReturn(tableInfo(42, 1, 1, 0, false));
+ when(scan.createLogScanner()).thenReturn(logScanner);
+ List<ScanRecord> records = new ArrayList<>();
+ for (int i = 0; i < 2052; i++) {
+ records.add(new ScanRecord(42, 1, i, 0, ChangeType.INSERT, GenericRow.of((long) i), 8));
+ }
+ when(logScanner.poll(POLL_TIMEOUT))
+ .thenReturn(new ScanRecords(Collections.singletonMap(BUCKET, records)));
+ source =
+ create(
+ FlussSplit.forLog(new FlussBucketHandle(42, Optional.empty(), 0), 0, 2050),
+ Collections.singletonList(new FlussColumnHandle("id", 0)),
+ MemoryContext.NO_LIMIT);
+ int position = 0;
+ for (int size : new int[] {1024, 1024, 2}) {
+ SourcePage page = source.getNextSourcePage();
+ assertThat(page.getPositionCount()).isEqualTo(size);
+ for (int i = 0; i < size; i++) {
+ assertThat(BIGINT.getLong(page.getBlock(0), i)).isEqualTo(position++);
+ }
+ }
+ assertThat(source.isFinished()).isTrue();
+ assertThat(source.getCompletedPositions()).hasValue(2050);
+ assertThat(source.getCompletedBytes()).isEqualTo(2050L * 8);
+ verify(logScanner).poll(POLL_TIMEOUT);
+ verify(logScanner).close();
+ verify(table).close();
+ }
+
+ @Test
+ void testZeroColumnsRetainRealRowCount() throws Exception {
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenReturn(rows(3)).thenReturn(null);
+ source =
+ create(
+ FlussSplit.forKv(new FlussBucketHandle(42, Optional.empty(), 0)),
+ Collections.emptyList(),
+ MemoryContext.NO_LIMIT);
+ SourcePage page = source.getNextSourcePage();
+ assertThat(page.getChannelCount()).isZero();
+ assertThat(page.getPositionCount()).isEqualTo(3);
+ assertThat(source.isFinished()).isFalse();
+ }
+
+ @Test
+ void testReorderedAndNullColumns() throws Exception {
+ when(scanner.pollBatch(POLL_TIMEOUT))
+ .thenReturn(
+ spy(
+ CloseableIterator.wrap(
+ Arrays.<InternalRow>asList(
+ GenericRow.of(1L, null),
+ GenericRow.of(2L, 7L))
+ .iterator())));
+ source =
+ create(
+ FlussSplit.forKv(new FlussBucketHandle(42, Optional.empty(), 0)),
+ Arrays.asList(
+ new FlussColumnHandle("value", 1), new FlussColumnHandle("id", 0)),
+ MemoryContext.NO_LIMIT);
+ SourcePage page = source.getNextSourcePage();
+ assertThat(page.getBlock(0).isNull(0)).isTrue();
+ assertThat(BIGINT.getLong(page.getBlock(0), 1)).isEqualTo(7);
+ assertThat(BIGINT.getLong(page.getBlock(1), 0)).isEqualTo(1);
+ }
+
+ @Test
+ void testIdentityAndScanTypeCheckedBeforeScannerCreation() throws Exception {
+ for (TableInfo info :
+ Arrays.asList(
+ tableInfo(43, 1, 1, 0, true),
+ tableInfo(42, 2, 1, 0, true),
+ tableInfo(42, 1, 1, 0, false))) {
+ when(table.getTableInfo()).thenReturn(info);
+ source = create();
+ assertThatThrownBy(source::getNextSourcePage).isInstanceOf(TrinoException.class);
+ assertThat(source.isFinished()).isTrue();
+ }
+ verify(table, times(3)).close();
+ verifyNoInteractions(scan, scanner);
+ }
+
+ @Test
+ void testInvalidColumnFailsBeforeScannerCreation() throws Exception {
+ source =
+ create(
+ FlussSplit.forKv(new FlussBucketHandle(42, Optional.empty(), 0)),
+ Collections.singletonList(new FlussColumnHandle("wrong", 0)),
+ MemoryContext.NO_LIMIT);
+ assertThatThrownBy(source::getNextSourcePage).hasMessageContaining("schema");
+ verify(table).close();
+ verifyNoInteractions(scan, scanner);
+ }
+
+ @Test
+ void testMetadataFailureClosesTable() throws Exception {
+ RuntimeException failure = new IllegalStateException("metadata failed");
+ when(table.getTableInfo()).thenThrow(failure);
+ source = create();
+ assertThatThrownBy(source::getNextSourcePage).isSameAs(failure);
+ verify(table).close();
+ verifyNoInteractions(scan, scanner);
+ }
+
+ @Test
+ void testWorkerRejectsUnsupportedCapabilitiesBeforeScannerCreation() throws Exception {
+ for (boolean partitioned : new boolean[] {true, false}) {
+ TableDescriptor.Builder descriptor =
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("id", DataTypes.BIGINT())
+ .column("value", DataTypes.BIGINT())
+ .primaryKey("id", "value")
+ .build())
+ .distributedBy(1);
+ if (partitioned) {
+ descriptor.partitionedBy("value");
+ } else {
+ descriptor.property("table.datalake.enabled", "true");
+ }
+ when(table.getTableInfo())
+ .thenReturn(TableInfo.of(PATH, 42, 1, descriptor.build(), null, 0, 0));
+ source = create();
+ assertThatThrownBy(source::getNextSourcePage).isInstanceOf(TrinoException.class);
+ }
+ verify(table, times(2)).close();
+ verifyNoInteractions(scan, scanner);
+ }
+
+ @Test
+ void testInitializationFailureClosesAcquiredTable() throws Exception {
+ RuntimeException failure = new IllegalStateException("create failed");
+ when(scan.createBatchScanner(BUCKET)).thenThrow(failure);
+ source = create();
+ assertThatThrownBy(source::getNextSourcePage).isSameAs(failure);
+ verify(table).close();
+ verifyNoInteractions(scanner);
+ }
+
+ @Test
+ void testOpenFailureDoesNotRetry() {
+ RuntimeException failure = new IllegalStateException("open failed");
+ when(clients.openTable(PATH)).thenThrow(failure);
+ source = create();
+ assertThatThrownBy(source::getNextSourcePage).isSameAs(failure);
+ assertThat(source.getNextSourcePage()).isNull();
+ verify(clients).openTable(PATH);
+ verifyNoInteractions(table, scanner);
+ }
+
+ @Test
+ void testPollIOExceptionIncludesBucketAndPreservesCleanup() throws Exception {
+ IOException failure = new IOException("snapshot expired");
+ IOException cleanup = new IOException("close failed");
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenThrow(failure);
+ doThrow(cleanup).when(scanner).close();
+ source = create();
+ assertThatThrownBy(source::getNextSourcePage)
+ .isInstanceOf(TrinoException.class)
+ .hasMessageContaining("bucketId=0")
+ .hasCause(failure)
+ .satisfies(error -> assertThat(error.getSuppressed()).hasSize(1));
+ assertThat(source.getReadTimeNanos()).isGreaterThan(0);
+ assertThat(source.getNextSourcePage()).isNull();
+ verify(table).close();
+ verify(scanner).pollBatch(POLL_TIMEOUT);
+ }
+
+ @Test
+ void testIteratorFailuresCloseAllResources() throws Exception {
+ for (boolean failHasNext : new boolean[] {true, false}) {
+ CloseableIterator<InternalRow> batch = rows(1);
+ RuntimeException failure = new IllegalStateException("iterator failed");
+ if (failHasNext) {
+ when(batch.hasNext()).thenThrow(failure);
+ } else {
+ doThrow(failure).when(batch).next();
+ }
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenReturn(batch);
+ source = create();
+ assertThatThrownBy(source::getNextSourcePage).isSameAs(failure);
+ verify(batch).close();
+ }
+ verify(scanner, times(2)).close();
+ verify(table, times(2)).close();
+ }
+
+ @Test
+ void testDecodeFailurePreservesIteratorCloseFailure() throws Exception {
+ InternalRow row = mock(InternalRow.class);
+ RuntimeException failure = new IllegalStateException("decode failed");
+ RuntimeException cleanup = new IllegalStateException("iterator close failed");
+ when(row.isNullAt(0)).thenThrow(failure);
+ CloseableIterator<InternalRow> batch =
+ spy(CloseableIterator.wrap(Arrays.asList(row, row).iterator()));
+ doThrow(cleanup).when(batch).close();
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenReturn(batch);
+ source = create();
+ assertThatThrownBy(source::getNextSourcePage).isSameAs(failure);
+ assertThat(failure.getSuppressed()).hasSize(1);
+ assertThat(failure.getSuppressed()[0]).hasCause(cleanup);
+ verify(scanner).close();
+ verify(table).close();
+ }
+
+ @Test
+ void testExhaustedIteratorCloseFailureIsNotRetried() throws Exception {
+ CloseableIterator<InternalRow> batch = rows(1);
+ RuntimeException failure = new IllegalStateException("iterator close failed");
+ doThrow(failure).when(batch).close();
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenReturn(batch);
+ source = create();
+ assertThatThrownBy(source::getNextSourcePage).isSameAs(failure);
+ source.close();
+ verify(batch).close();
+ verify(scanner).close();
+ verify(table).close();
+ assertThat(source.getCompletedPositions()).hasValue(0);
+ }
+
+ @Test
+ void testEarlyCloseOrderAndSuppressedFailures() throws Exception {
+ CloseableIterator<InternalRow> batch = rows(2050);
+ MemoryContext memory = mock(MemoryContext.class);
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenReturn(batch);
+ source =
+ create(
+ FlussSplit.forKv(new FlussBucketHandle(42, Optional.empty(), 0)),
+ Collections.emptyList(),
+ memory);
+ source.getNextSourcePage();
+ RuntimeException iteratorFailure = new IllegalStateException("iterator close failed");
+ IOException scannerFailure = new IOException("scanner close failed");
+ IOException tableFailure = new IOException("table close failed");
+ RuntimeException memoryFailure = new IllegalStateException("memory release failed");
+ doThrow(iteratorFailure).when(batch).close();
+ doThrow(scannerFailure).when(scanner).close();
+ doThrow(tableFailure).when(table).close();
+ doThrow(memoryFailure).when(memory).setBytes(0);
+ assertThatThrownBy(source::close).hasCause(iteratorFailure);
+ assertThat(iteratorFailure.getSuppressed())
+ .containsExactly(scannerFailure, tableFailure, memoryFailure);
+ source.close();
+ InOrder order = inOrder(batch, scanner, table, memory);
+ order.verify(batch).close();
+ order.verify(scanner).close();
+ order.verify(table).close();
+ order.verify(memory, atLeastOnce()).setBytes(0);
+ assertThat(source.getNextSourcePage()).isNull();
+ }
+
+ @Test
+ void testCloseErrorStillReleasesOtherResources() throws Exception {
+ CloseableIterator<InternalRow> batch = rows(2050);
+ MemoryContext memory = mock(MemoryContext.class);
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenReturn(batch);
+ source =
+ create(
+ FlussSplit.forKv(new FlussBucketHandle(42, Optional.empty(), 0)),
+ Collections.emptyList(),
+ memory);
+ source.getNextSourcePage();
+ AssertionError failure = new AssertionError("iterator close error");
+ doThrow(failure).when(batch).close();
+ assertThatThrownBy(source::close).isSameAs(failure);
+ verify(scanner).close();
+ verify(table).close();
+ verify(memory, atLeastOnce()).setBytes(0);
+ source.close();
+ verify(batch).close();
+ }
+
+ @Test
+ void testMemoryFailureClosesRemainingIterator() throws Exception {
+ CloseableIterator<InternalRow> batch = rows(2050);
+ MemoryContext memory = mock(MemoryContext.class);
+ RuntimeException failure = new IllegalStateException("reservation denied");
+ doAnswer(
+ invocation -> {
+ if ((long) invocation.getArgument(0) > 0) {
+ throw failure;
+ }
+ return null;
+ })
+ .when(memory)
+ .setBytes(anyLong());
+ when(scanner.pollBatch(POLL_TIMEOUT)).thenReturn(batch);
+ source =
+ create(
+ FlussSplit.forKv(new FlussBucketHandle(42, Optional.empty(), 0)),
+ Collections.singletonList(new FlussColumnHandle("id", 0)),
+ memory);
+ assertThatThrownBy(source::getNextSourcePage).isSameAs(failure);
+ verify(batch).close();
+ verify(scanner).close();
+ verify(table).close();
+ verify(memory, atLeastOnce()).setBytes(0);
+ assertThat(source.getCompletedPositions()).hasValue(0);
+ }
+
+ @Test
+ void testPollingAndMemoryStayOnCallingThread() throws Exception {
+ Thread caller = Thread.currentThread();
+ MemoryContext memory = mock(MemoryContext.class);
+ List<Long> reservations = new ArrayList<>();
+ doAnswer(
+ invocation -> {
+ assertThat(Thread.currentThread()).isSameAs(caller);
+ reservations.add(invocation.getArgument(0));
+ return null;
+ })
+ .when(memory)
+ .setBytes(anyLong());
+ when(scanner.pollBatch(POLL_TIMEOUT))
+ .thenAnswer(
+ invocation -> {
+ assertThat(Thread.currentThread()).isSameAs(caller);
+ return rows(1);
+ });
+ source =
+ create(
+ FlussSplit.forKv(new FlussBucketHandle(42, Optional.empty(), 0)),
+ Collections.singletonList(new FlussColumnHandle("id", 0)),
+ memory);
+ source.getNextSourcePage();
+ assertThat(reservations).anyMatch(value -> value > 0);
+ assertThat(reservations.get(reservations.size() - 1)).isZero();
+ assertThat(source.getCompletedBytes()).isZero();
+ }
+
+ @Test
+ void testReadAndCloseUsePluginClassLoader() throws Exception {
+ ClassLoader pluginClassLoader = FlussPageSource.class.getClassLoader();
+
+ when(clients.openTable(PATH))
+ .thenAnswer(
+ invocation -> {
+ assertThat(Thread.currentThread().getContextClassLoader())
+ .isSameAs(pluginClassLoader);
+ return table;
+ });
+
+ when(scan.createBatchScanner(BUCKET))
+ .thenAnswer(
+ invocation -> {
+ assertThat(Thread.currentThread().getContextClassLoader())
+ .isSameAs(pluginClassLoader);
+ return scanner;
+ });
+
+ when(scanner.pollBatch(POLL_TIMEOUT))
+ .thenAnswer(
+ invocation -> {
+ assertThat(Thread.currentThread().getContextClassLoader())
+ .isSameAs(pluginClassLoader);
+ return rows(1);
+ });
+
+ doAnswer(
+ invocation -> {
+ assertThat(Thread.currentThread().getContextClassLoader())
+ .isSameAs(pluginClassLoader);
+ return null;
+ })
+ .when(scanner)
+ .close();
+
+ doAnswer(
+ invocation -> {
+ assertThat(Thread.currentThread().getContextClassLoader())
+ .isSameAs(pluginClassLoader);
+ return null;
+ })
+ .when(table)
+ .close();
+
+ source = create();
+
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ ClassLoader other = new ClassLoader(null) {};
+
+ try {
+ Thread.currentThread().setContextClassLoader(other);
+
+ assertThat(source.getNextSourcePage()).isNotNull();
+ assertThat(Thread.currentThread().getContextClassLoader()).isSameAs(other);
+
+ source.close();
+
+ assertThat(source.isFinished()).isTrue();
+ assertThat(Thread.currentThread().getContextClassLoader()).isSameAs(other);
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+
+ verify(scanner).close();
+ verify(table).close();
+ }
+
+ @Test
+ void testClassLoaderRestoredAfterInitializationFailure() {
+ RuntimeException failure = new IllegalStateException("open failed");
+ when(clients.openTable(PATH)).thenThrow(failure);
+
+ source = create();
+
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ ClassLoader other = new ClassLoader(null) {};
+
+ try {
+ Thread.currentThread().setContextClassLoader(other);
+
+ assertThatThrownBy(source::getNextSourcePage).isSameAs(failure);
+
+ assertThat(Thread.currentThread().getContextClassLoader()).isSameAs(other);
+ assertThat(source.isFinished()).isTrue();
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+ }
+
+ private FlussPageSource create() {
+ return create(
+ FlussSplit.forKv(new FlussBucketHandle(42, Optional.empty(), 0)),
+ Collections.singletonList(new FlussColumnHandle("id", 0)),
+ MemoryContext.NO_LIMIT);
+ }
+
+ private FlussPageSource create(
+ FlussSplit split, List<FlussColumnHandle> columns, MemoryContext memory) {
+ return new FlussPageSource(clients, HANDLE, split, columns, memory);
+ }
+
+ private static TableInfo tableInfo(
+ long id, int schemaId, int bucketCount, int bucketEpoch, boolean primaryKey) {
+ Schema.Builder schema =
+ Schema.newBuilder()
+ .column("id", DataTypes.BIGINT())
+ .column("value", DataTypes.BIGINT());
+ if (primaryKey) {
+ schema.primaryKey("id");
+ }
+ return TableInfo.of(
+ PATH,
+ id,
+ schemaId,
+ TableDescriptor.builder().schema(schema.build()).distributedBy(bucketCount).build(),
+ null,
+ 0,
+ 0,
+ bucketEpoch);
+ }
+
+ private static CloseableIterator<InternalRow> rows(int count) {
+ List<InternalRow> values = new ArrayList<>();
+ for (long i = 0; i < count; i++) {
+ values.add(GenericRow.of(i, i));
+ }
+ return spy(CloseableIterator.wrap(values.iterator()));
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPluginTest.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPluginTest.java
new file mode 100644
index 0000000000..b90c10f5c9
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPluginTest.java
@@ -0,0 +1,35 @@
+/*
+ * 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.fluss.trino;
+
+import io.trino.spi.connector.ConnectorFactory;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Tests plugin registration. */
+final class FlussPluginTest {
+
+ @Test
+ void testConnectorFactory() {
+ assertThat(new FlussPlugin().getConnectorFactories())
+ .singleElement()
+ .extracting(ConnectorFactory::getName)
+ .isEqualTo("fluss");
+ }
+}
diff --git a/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPrimaryKeyReadITCase.java b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPrimaryKeyReadITCase.java
new file mode 100644
index 0000000000..934c7afc19
--- /dev/null
+++ b/fluss-trino/src/test/java/org/apache/fluss/trino/FlussPrimaryKeyReadITCase.java
@@ -0,0 +1,699 @@
+/*
+ * 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.fluss.trino;
+
+import org.apache.fluss.client.Connection;
+import org.apache.fluss.client.ConnectionFactory;
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.client.table.writer.UpsertWriter;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.config.MemorySize;
+import org.apache.fluss.metadata.Schema;
+import org.apache.fluss.metadata.TableBucket;
+import org.apache.fluss.metadata.TableChange;
+import org.apache.fluss.metadata.TableDescriptor;
+import org.apache.fluss.metadata.TablePath;
+import org.apache.fluss.row.BinaryString;
+import org.apache.fluss.row.Decimal;
+import org.apache.fluss.row.GenericArray;
+import org.apache.fluss.row.GenericMap;
+import org.apache.fluss.row.GenericRow;
+import org.apache.fluss.row.InternalRow;
+import org.apache.fluss.row.TimestampLtz;
+import org.apache.fluss.row.TimestampNtz;
+import org.apache.fluss.server.testutils.FlussClusterExtension;
+import org.apache.fluss.types.DataTypes;
+import org.apache.fluss.utils.IOUtils;
+
+import io.trino.testing.DistributedQueryRunner;
+import io.trino.testing.MaterializedRow;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.math.BigDecimal;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+
+import static org.apache.fluss.testutils.common.CommonTestUtils.waitUntil;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Current-state SQL reads using the production connector on a separate Trino worker. */
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class FlussPrimaryKeyReadITCase {
+ private static final int SNAPSHOT_ROWS = 3000;
+ private static final Schema SCHEMA =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("name", DataTypes.STRING())
+ .primaryKey("id")
+ .build();
+
+ @RegisterExtension
+ static final FlussClusterExtension CLUSTER =
+ FlussClusterExtension.builder()
+ .setNumOfTabletServers(1)
+ .setClusterConf(clusterConfig())
+ .build();
+
+ private final FlussQueryRunner.TestingHooks gate = new FlussQueryRunner.TestingHooks();
+ private final List<TestingKvScanControl> scanners = new ArrayList<>();
+ private DistributedQueryRunner runner;
+ private Connection connection;
+ private Admin admin;
+
+ @BeforeAll
+ void setUp() throws Exception {
+ runner = FlussQueryRunner.create(CLUSTER.getBootstrapServers(), gate);
+ }
+
+ @BeforeEach
+ void openClient() {
+ connection = ConnectionFactory.createConnection(CLUSTER.getClientConfig());
+ admin = connection.getAdmin();
+ }
+
+ @AfterEach
+ void readersAreReleased() throws Exception {
+ try {
+ waitUntil(
+ () -> gate.activeSources() == 0,
+ Duration.ofSeconds(30),
+ "Trino did not release its KV sources");
+ for (TestingKvScanControl control : scanners) {
+ waitUntil(
+ () -> control.activeScannerCount() == 0,
+ Duration.ofSeconds(30),
+ "Fluss did not release its KV sessions");
+ }
+ } finally {
+ scanners.clear();
+ IOUtils.closeAll(admin, connection);
+ }
+ }
+
+ @AfterAll
+ void tearDown() throws Exception {
+ IOUtils.closeAll(runner);
+ }
+
+ @Test
+ void testCurrentStateAndSqlOperations() throws Exception {
+ assertThat(runner.getNodeCount()).isEqualTo(2);
+ createTable("current_state", SCHEMA, 3);
+ upsert("current_state", row(1, "one"), row(2, "two"), row(3, "three"));
+ assertThat(rows("SELECT * FROM current_state"))
+ .containsExactlyInAnyOrder(
+ Arrays.asList(1, "one"),
+ Arrays.asList(2, "two"),
+ Arrays.asList(3, "three"));
+ upsert("current_state", row(1, "updated"), row(4, null));
+ delete("current_state", row(2, null));
+ assertThat(rows("SELECT * FROM current_state"))
+ .containsExactlyInAnyOrder(
+ Arrays.asList(1, "updated"),
+ Arrays.asList(3, "three"),
+ Arrays.asList(4, null));
+ assertThat(rows("SELECT name, id FROM current_state WHERE id >= 3 ORDER BY id DESC"))
+ .containsExactly(Arrays.asList(null, 4), Arrays.asList("three", 3));
+ assertThat(runner.execute("SELECT count(*) FROM current_state").getOnlyValue())
+ .isEqualTo(3L);
+ assertThat(rows("SELECT id FROM current_state ORDER BY id LIMIT 1"))
+ .containsExactly(Arrays.asList(1));
+ assertThat(rows("DESCRIBE current_state")).hasSize(2);
+ assertThat(runner.execute("SHOW CREATE TABLE current_state").getOnlyValue().toString())
+ .contains("primary_key =");
+ assertThat(
+ runner.execute(
+ "SELECT primary_key_position FROM \"current_state$columns\" WHERE column_name = 'id'")
+ .getOnlyValue())
+ .isEqualTo(1L);
+ }
+
+ @Test
+ void testCompositeKeysAndEmptyBuckets() throws Exception {
+ Schema schema =
+ Schema.newBuilder()
+ .column("tenant", DataTypes.INT())
+ .column("id", DataTypes.INT())
+ .column("name", DataTypes.STRING())
+ .primaryKey("tenant", "id")
+ .build();
+ createTable("composite_state", schema, 3);
+ assertThat(rows("SELECT * FROM composite_state")).isEmpty();
+ assertThat(runner.execute("SELECT count(*) FROM composite_state").getOnlyValue())
+ .isEqualTo(0L);
+ upsert("composite_state", GenericRow.of(1, 1, BinaryString.fromString("first")));
+ assertThat(rows("SELECT * FROM composite_state"))
+ .containsExactly(Arrays.asList(1, 1, "first"));
+ try (Table table = connection.getTable(path("composite_state"))) {
+ UpsertWriter writer = table.newUpsert().createWriter();
+ List<CompletableFuture<?>> writes = new ArrayList<>();
+ for (int i = 0; i < 300; i++) {
+ writes.add(
+ writer.upsert(GenericRow.of(i % 2, i, BinaryString.fromString("value"))));
+ }
+ CompletableFuture.allOf(writes.toArray(new CompletableFuture[0]))
+ .get(30, TimeUnit.SECONDS);
+ }
+ assertThat(
+ admin.listOffsets(
+ path("composite_state"),
+ Arrays.asList(0, 1, 2),
+ new org.apache.fluss.client.admin.OffsetSpec.LatestSpec())
+ .all()
+ .get(30, TimeUnit.SECONDS)
+ .values())
+ .allSatisfy(offset -> assertThat(offset).isGreaterThan(0));
+ upsert("composite_state", GenericRow.of(0, 1, BinaryString.fromString("other tenant")));
+ delete("composite_state", GenericRow.of(1, 1, null));
+ assertThat(rows("SELECT tenant, id, name FROM composite_state WHERE id = 1"))
+ .containsExactly(Arrays.asList(0, 1, "other tenant"));
+ assertThat(rows("SELECT count(*), sum(id) FROM composite_state"))
+ .containsExactly(Arrays.asList(300L, 44850L));
+ }
+
+ @Test
+ void testSnapshotOpensAfterPlanning() throws Exception {
+ createTable("open_boundary", SCHEMA, 1);
+ upsert("open_boundary", row(1, "old"), row(2, "delete"));
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pause("open_boundary")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT * FROM open_boundary"));
+ barrier.awaitPlanned();
+ upsert("open_boundary", row(1, "new"), row(3, "insert"));
+ delete("open_boundary", row(2, null));
+ barrier.close();
+ assertThat(query.get(30, TimeUnit.SECONDS))
+ .containsExactlyInAnyOrder(Arrays.asList(1, "new"), Arrays.asList(3, "insert"));
+ } finally {
+ shutdown(executor);
+ }
+ }
+
+ @Test
+ void testOpenedSnapshotSurvivesInsertsUpdatesAndDeletes() throws Exception {
+ TestingKvScanControl control = createLargeTable("snapshot_state");
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pauseAfterRead("snapshot_state")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT * FROM snapshot_state"));
+ barrier.awaitReached();
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ upsert("snapshot_state", row(0, "new"), row(SNAPSHOT_ROWS, "inserted"));
+ delete("snapshot_state", row(SNAPSHOT_ROWS - 1, null));
+ barrier.close();
+ assertThat(query.get(30, TimeUnit.SECONDS))
+ .containsExactlyInAnyOrderElementsOf(expectedSnapshot());
+ assertThat(rows("SELECT * FROM snapshot_state WHERE id IN (0, 2999, 3000)"))
+ .containsExactlyInAnyOrder(
+ Arrays.asList(0, "new"), Arrays.asList(SNAPSHOT_ROWS, "inserted"));
+ } finally {
+ shutdown(executor);
+ }
+ }
+
+ @Test
+ void testContinuingWritesDoNotExtendSnapshot() throws Exception {
+ TestingKvScanControl control = createLargeTable("continuous_state");
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ AtomicBoolean writing = new AtomicBoolean(true);
+ CountDownLatch written = new CountDownLatch(1);
+ Future<?> writerTask = null;
+ try (FlussQueryRunner.Barrier barrier = gate.pauseAfterRead("continuous_state")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT * FROM continuous_state"));
+ barrier.awaitReached();
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ writerTask =
+ executor.submit(
+ () -> {
+ try (Table table = connection.getTable(path("continuous_state"))) {
+ UpsertWriter writer = table.newUpsert().createWriter();
+ int id = SNAPSHOT_ROWS;
+ while (writing.get()) {
+ writer.upsert(row(id++, "new")).get(30, TimeUnit.SECONDS);
+ written.countDown();
+ }
+ }
+ return null;
+ });
+ assertThat(written.await(30, TimeUnit.SECONDS)).isTrue();
+ barrier.close();
+ assertThat(query.get(30, TimeUnit.SECONDS))
+ .containsExactlyInAnyOrderElementsOf(expectedSnapshot());
+ assertThat(writerTask.isDone()).isFalse();
+ } finally {
+ writing.set(false);
+ try {
+ if (writerTask != null) {
+ writerTask.get(30, TimeUnit.SECONDS);
+ }
+ } finally {
+ shutdown(executor);
+ }
+ }
+ }
+
+ @Test
+ void testLimitClosesRemoteSession() throws Exception {
+ TestingKvScanControl control = createLargeTable("limit_state");
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pauseAfterRead("limit_state")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT * FROM limit_state LIMIT 1"));
+ barrier.awaitReached();
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ assertThat(gate.activeSources()).isGreaterThan(0);
+ barrier.close();
+ assertThat(query.get(30, TimeUnit.SECONDS)).hasSize(1);
+ awaitClosed(control);
+ } finally {
+ shutdown(executor);
+ }
+ }
+
+ @Test
+ void testCancellationClosesRemoteSession() throws Exception {
+ TestingKvScanControl control = createLargeTable("cancel_state");
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ String sql = "SELECT * FROM cancel_state";
+ try (FlussQueryRunner.Barrier barrier = gate.pauseAfterRead("cancel_state")) {
+ Future<?> query = executor.submit(() -> runner.execute(sql));
+ barrier.awaitReached();
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ io.trino.spi.QueryId queryId =
+ runner.getCoordinator().getQueryManager().getQueries().stream()
+ .filter(
+ info ->
+ info.getQuery().equals(sql)
+ && !info.getState().isDone())
+ .findFirst()
+ .get()
+ .getQueryId();
+ runner.getCoordinator().getQueryManager().cancelQuery(queryId);
+ assertThatThrownBy(() -> query.get(30, TimeUnit.SECONDS))
+ .hasStackTraceContaining("canceled");
+ barrier.close();
+ awaitClosed(control);
+ } finally {
+ shutdown(executor);
+ }
+ }
+
+ @Test
+ void testExpiredSessionFailsWithoutReopeningSnapshot() throws Exception {
+ assertInvalidSessionFails("expired_state", true);
+ }
+
+ @Test
+ void testUnknownSessionFailsWithoutReopeningSnapshot() throws Exception {
+ assertInvalidSessionFails("unknown_state", false);
+ }
+
+ private void assertInvalidSessionFails(String name, boolean expire) throws Exception {
+ TestingKvScanControl control = createLargeTable(name);
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pauseAfterRead(name)) {
+ Future<?> query = executor.submit(() -> runner.execute("SELECT * FROM " + name));
+ barrier.awaitReached();
+ assertThat(control.scannerIds()).hasSize(1);
+ control.awaitCallSequence(1);
+ if (expire) {
+ control.expireAll();
+ } else {
+ control.removeAll();
+ }
+ assertThat(control.activeScannerCount()).isZero();
+ barrier.close();
+ assertThatThrownBy(() -> query.get(30, TimeUnit.SECONDS))
+ .hasStackTraceContaining("scanner");
+ awaitClosed(control);
+ } finally {
+ shutdown(executor);
+ }
+ }
+
+ @Test
+ void testHistoricalSchemaValuesAreMapped() throws Exception {
+ createTable("schema_history", SCHEMA, 1);
+ upsert("schema_history", row(1, "old"));
+ addColumn("schema_history");
+ upsert("schema_history", GenericRow.of(2, BinaryString.fromString("new"), 20));
+ assertThat(rows("SELECT * FROM schema_history"))
+ .containsExactlyInAnyOrder(
+ Arrays.asList(1, "old", null), Arrays.asList(2, "new", 20));
+ }
+
+ @Test
+ void testSchemaChangeAfterPlanningFails() throws Exception {
+ createTable("schema_planned", SCHEMA, 1);
+ upsert("schema_planned", row(1, "old"));
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pause("schema_planned")) {
+ Future<?> query = executor.submit(() -> runner.execute("SELECT * FROM schema_planned"));
+ barrier.awaitPlanned();
+ addColumn("schema_planned");
+ barrier.close();
+ assertThatThrownBy(() -> query.get(30, TimeUnit.SECONDS))
+ .hasStackTraceContaining("changed");
+ } finally {
+ shutdown(executor);
+ }
+ }
+
+ @Test
+ void testSchemaChangeAfterOpeningPreservesTargetSchema() throws Exception {
+ TestingKvScanControl control = createLargeTable("schema_opened");
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pauseAfterRead("schema_opened")) {
+ Future<List<List<Object>>> query =
+ executor.submit(() -> rows("SELECT * FROM schema_opened"));
+ barrier.awaitReached();
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ addColumn("schema_opened");
+ upsert(
+ "schema_opened",
+ GenericRow.of(SNAPSHOT_ROWS, BinaryString.fromString("new"), 20));
+ barrier.close();
+ assertThat(query.get(30, TimeUnit.SECONDS))
+ .containsExactlyInAnyOrderElementsOf(expectedSnapshot());
+ assertThat(rows("SELECT * FROM schema_opened WHERE id = 3000"))
+ .containsExactly(Arrays.asList(SNAPSHOT_ROWS, "new", 20));
+ } finally {
+ shutdown(executor);
+ }
+ }
+
+ @Test
+ void testReplacementAfterPlanningFails() throws Exception {
+ createTable("replacement_planned", SCHEMA, 1);
+ upsert("replacement_planned", row(1, "old"));
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pause("replacement_planned")) {
+ Future<?> query =
+ executor.submit(() -> runner.execute("SELECT * FROM replacement_planned"));
+ barrier.awaitPlanned();
+ admin.dropTable(path("replacement_planned"), false).get(30, TimeUnit.SECONDS);
+ createTable("replacement_planned", SCHEMA, 1);
+ upsert("replacement_planned", row(2, "replacement"));
+ barrier.close();
+ assertThatThrownBy(() -> query.get(30, TimeUnit.SECONDS))
+ .hasStackTraceContaining("changed");
+ } finally {
+ shutdown(executor);
+ }
+ }
+
+ @Test
+ void testReplacementAfterOpeningFailsWithoutReadingReplacement() throws Exception {
+ TestingKvScanControl control = createLargeTable("replacement_opened");
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (FlussQueryRunner.Barrier barrier = gate.pauseAfterRead("replacement_opened")) {
+ Future<?> query =
+ executor.submit(() -> runner.execute("SELECT * FROM replacement_opened"));
+ barrier.awaitReached();
+ assertThat(control.activeScannerCount()).isEqualTo(1);
+ admin.dropTable(path("replacement_opened"), false).get(30, TimeUnit.SECONDS);
... 2358 lines suppressed ...