924060929 commented on code in PR #69886:
URL: https://github.com/apache/doris/pull/69886#discussion_r4794312518


##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonWritePlanProvider.java:
##########
@@ -159,11 +165,24 @@ public ConnectorSinkPlan planWrite(ConnectorSession 
session, ConnectorWriteHandl
         transaction.bind(binding);
 
         TPaimonTableSink sink = new TPaimonTableSink();
-        sink.setSerializedTable(binding.getSerializedTable());
+        List<String> columns = outputColumnNames(handle);
+        Map<String, String> storageOptions = new 
LinkedHashMap<>(binding.getHadoopConfig());
+        for (StorageProperties storage : 
context.getStorageContext().getStorageProperties()) {
+            storage.toBackendProperties().ifPresent(properties -> 
storageOptions.putAll(properties.toMap()));
+        }
+        storageOptions.putAll(table.options());
+        TPaimonWriteMode mode = writeMode(handle);
+        Optional<String> fallbackReason = rustWriterFallbackReason(session, 
table, columns, storageOptions, mode);
+        boolean rust = fallbackReason.isEmpty();
+        sink.setSerializedTable(LEGACY_BE_REJECTION_MARKER);

Review Comment:
   [P1] Rolling upgrade breaks already-released Paimon writes.
   
   Paimon JNI writes already exist on branch-4.1 / branch-4.2 
(`TPaimonTableSink` fields 1-7, `PaimonJniWriter`), so this protocol change 
must stay upgrade-compatible. Upgrade order is BE first, then FE. During that 
window, an old FE sends only `serialized_table`, but the new BE 
(`jni_paimon_write_backend.cpp`) now returns `NotSupported("Paimon writes 
require a table descriptor; upgrade the FE")`. So every Paimon INSERT fails 
until all FEs are upgraded, even with the Rust writer disabled.
   
   The marker string here is also a workaround: an old BE will try to 
base64/Java-deserialize `"Paimon table descriptor required: upgrade the BE"` 
and report an unreadable error.
   
   Suggestion:
   - BE: keep the legacy `serialized_table` (JNI) path for at least one 
release, used when `table_desc` is unset.
   - FE: bump be_exec_version / `MIN_BE_EXEC_VERSION` and reject old BEs 
clearly in `requireBeExecVersion`, instead of writing a marker into field 1.



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonWritePlanProvider.java:
##########
@@ -159,11 +165,24 @@ public ConnectorSinkPlan planWrite(ConnectorSession 
session, ConnectorWriteHandl
         transaction.bind(binding);
 
         TPaimonTableSink sink = new TPaimonTableSink();
-        sink.setSerializedTable(binding.getSerializedTable());
+        List<String> columns = outputColumnNames(handle);
+        Map<String, String> storageOptions = new 
LinkedHashMap<>(binding.getHadoopConfig());
+        for (StorageProperties storage : 
context.getStorageContext().getStorageProperties()) {
+            storage.toBackendProperties().ifPresent(properties -> 
storageOptions.putAll(properties.toMap()));
+        }
+        storageOptions.putAll(table.options());
+        TPaimonWriteMode mode = writeMode(handle);
+        Optional<String> fallbackReason = rustWriterFallbackReason(session, 
table, columns, storageOptions, mode);
+        boolean rust = fallbackReason.isEmpty();
+        sink.setSerializedTable(LEGACY_BE_REJECTION_MARKER);
+        sink.setTableDesc(binding.getTableDescriptor(storageOptions, rust));
+        sink.setCommitMessageVersion(rust ? RUST_COMMIT_VERSION : new 
CommitMessageSerializer().getVersion());
+        sink.setBackendSelectionReason(fallbackReason.orElse(
+                mode == TPaimonWriteMode.OVERWRITE ? "supported_overwrite" : 
"supported_append"));
         sink.setHadoopConfig(binding.getHadoopConfig());
-        sink.setColumnNames(outputColumnNames(handle));
-        sink.setBackendType(TPaimonWriteBackendType.JNI);
-        sink.setWriteMode(writeMode(handle));
+        sink.setColumnNames(columns);
+        sink.setBackendType(rust ? TPaimonWriteBackendType.FFI : 
TPaimonWriteBackendType.JNI);

Review Comment:
   [P2] The writer has no BE capability gate, unlike the reader.
   
   The Rust reader is gated by 
`request.allBackendsSupport("paimon-rust-reader")`, which comes from the 
heartbeat field `supports_paimon_rust_reader`. The writer selects FFI whenever 
the table is eligible, without checking whether the BEs can run it. Please 
reuse the same mechanism (a writer capability bit) and fall back to JNI when 
any BE lacks it, rather than failing the statement.



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonRustWriteSupport.java:
##########
@@ -0,0 +1,146 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.connector.paimon;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.table.AppendOnlyFileStoreTable;
+import org.apache.paimon.table.BucketMode;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.PrimaryKeyFileStoreTable;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.TimestampType;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/** Selects the table features supported by the Rust writer and its Java 
commit protocol. */
+public final class PaimonRustWriteSupport {
+    private PaimonRustWriteSupport() {
+    }
+
+    public static boolean isSupported(FileStoreTable table, List<String> 
columns,
+            Map<String, String> storageOptions) {
+        return unsupportedReason(table, columns, storageOptions).isEmpty();
+    }
+
+    public static Optional<String> unsupportedReason(FileStoreTable table, 
List<String> columns,
+            Map<String, String> storageOptions) {
+        Map<String, String> options = table.options();
+        CoreOptions coreOptions = new CoreOptions(options);
+        if (!(table instanceof AppendOnlyFileStoreTable) && !(table instanceof 
PrimaryKeyFileStoreTable)) {
+            return Optional.of("table_implementation");
+        }
+        if (PaimonTableDescriptor.usesRestDataToken(table)) {
+            // A captured STS token can expire during an INSERT; only JNI 
preserves REST refresh.
+            return Optional.of("rest_vended_credentials");
+        }
+        // Fixed and dynamic buckets reuse the existing Doris bucket routing or
+        // single-writer distribution. Keep postpone bucket layout on JNI.
+        if (coreOptions.bucket() != -1 && coreOptions.bucket() < 1) {
+            return Optional.of("bucket_mode");
+        }
+        if (!"main".equals(CoreOptions.branch(options))) {
+            return Optional.of("non_main_branch");
+        }
+        // Rust's cross-partition assigner rejects TTL-based index state.
+        if (table.bucketMode() == BucketMode.KEY_DYNAMIC
+                && options.containsKey("cross-partition-upsert.index-ttl")) {
+            return Optional.of("cross_partition_index_ttl");
+        }
+        // The C writer emits level-0 files without compaction. First-row batch
+        // scans skip those files, so a successful INSERT would remain 
invisible.
+        if (coreOptions.mergeEngine() == CoreOptions.MergeEngine.FIRST_ROW) {
+            return Optional.of("first_row_requires_compaction");
+        }
+        if (!"parquet".equalsIgnoreCase(coreOptions.formatType())) {
+            return Optional.of("file_format");
+        }
+        if 
(!columns.equals(table.schema().fields().stream().map(DataField::name).collect(Collectors.toList())))
 {
+            return Optional.of("column_mapping");
+        }
+        for (Map.Entry<String, String> option : options.entrySet()) {

Review Comment:
   [P1, please confirm] Eligibility is a denylist of options, while the feature 
is on by default.
   
   Any Paimon option that is not listed here and not implemented by paimon-rust 
v0.5.0 silently goes to Rust and can produce results that differ from Java. 
Examples in Paimon 2.1 that this list does not reject: `bucket-function.type`, 
`sequence.field`, `record-level.expire-time`, `clustering.*`, 
`file.format.per.level`, `file.compression.per.level`, 
`full-compaction.delta-commits`.
   
   The most concrete risk is `bucket-function.type=mod/hive`. 
`fixedBucketDistribution()` already treats a non-DEFAULT bucket function 
specially (it falls back to a single writer). If the Rust writer computes 
buckets with the default hash, the same primary key lands in different buckets 
for Rust and JNI/Flink writes, and you get duplicate keys.
   
   Could you confirm Rust support for these options? Either way, I'd prefer an 
allowlist of verified options, or at least an explicit `bucketFunctionType() != 
DEFAULT -> JNI` check.



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonConnectorTransaction.java:
##########
@@ -104,11 +105,16 @@ public void addCommitData(byte[] commitFragment) {
         Preconditions.checkState(message.isSetPayload(), "Paimon commit 
message payload is missing");
         byte[] payload = message.getPayload();
         Preconditions.checkState(payload.length > 0, "Paimon commit message 
payload is empty");
+        List<byte[]> aborted = Collections.emptyList();
         synchronized (this) {
             if (commitPayloadSet.add(new CommitPayloadKey(payload))) {
                 commitPayloads.add(payload);
             }
+            if (state == CommitState.ABORTED) {

Review Comment:
   [P2] This ABORTED branch is unreachable through the engine.
   
   `PluginDrivenTransactionManager.rollback(id)` removes the txn from 
`transactions` and from `GlobalExternalTransactionInfoMgr` before delegating, 
and `PluginDrivenTransaction.addCommitData` starts with `requireActive()`. So a 
BE report that arrives after rollback either fails in `getTxnById` ("Can't find 
txn") or throws IllegalStateException. It never reaches this method, so late 
files stay orphaned and only unit tests cover this branch. Please remove it, or 
handle late commit data in the engine layer if cleanup is really needed.



##########
fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java:
##########
@@ -3172,6 +3173,10 @@ public void checkFetchSplitsMaxWaitTime(String value) 
throws Exception {
             description = "Prefer paimon-rust for eligible Paimon reads")
     private boolean enablePaimonRustReader = false;
 
+    @VarAttrDef.VarAttr(name = ENABLE_PAIMON_RUST_WRITER, needForward = true,
+            description = "Prefer the Paimon Rust writer; unsupported writes 
use JNI")
+    private boolean enablePaimonRustWriter = true;

Review Comment:
   [P2] Defaulting to true makes a new native write path, with no compaction 
(see the PK comment) and memory accounting that is only estimated, the default 
for every eligible INSERT. I'd suggest defaulting to false for the first 
release, or at least limiting the default to append tables.



##########
gensrc/thrift/Descriptors.thrift:
##########
@@ -581,3 +581,25 @@ struct TDescriptorTable {
   // all table descriptors referenced by tupleDescriptors
   3: optional list<TTableDescriptor> tableDescriptors;
 }
+
+// Portable catalog services used when rebuilding a Java Paimon table. No 
serialized SDK objects.
+struct TPaimonCatalogContext {
+    1: optional map<string, string> options
+    2: optional map<string, string> hadoop_config
+    3: optional string table_uuid
+    4: optional bool catalog_loader_enabled
+    5: optional bool supports_version_management
+    6: optional bool supports_partition_modification
+}
+
+// Resolved, statement-pinned metadata shared by Paimon SDK backends.
+struct TPaimonTableDesc {
+    1: optional string table_path
+    2: optional string schema_json
+    3: optional string database_name
+    4: optional string table_name
+    5: optional string branch
+    6: optional map<string, string> storage_options
+    // Field 7 was commit_message_version; commit protocol belongs to the sink.

Review Comment:
   [P3] Field 7 was never merged on any branch, so this comment is misleading. 
Please drop it.



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonWriteBinding.java:
##########
@@ -291,8 +286,33 @@ FileStoreTable getTable() {
         return table;
     }
 
-    String getSerializedTable() {
-        return serializedTable;
+    TPaimonTableDesc getTableDescriptor(Map<String, String> storageOptions,
+            boolean rust) {
+        Map<String, String> options = new 
HashMap<>(backendTable.schema().options());
+        if (rust) {
+            options.put("write.parquet-buffer-size", "8 mb");
+            if (!backendTable.primaryKeys().isEmpty()) {
+                // The SDK's default 256 MiB key-value buffer cannot reach its 
flush
+                // threshold under the default 64 MiB writer budget. Retain 
smaller
+                // table settings and flush larger buffers before exhausting 
that budget.
+                long writeBufferSize = 
Math.min(CoreOptions.fromMap(options).writeBufferSize(), 8L * 1024 * 1024);

Review Comment:
   [P1] Primary-key tables written by Rust never compact, and this 8 MiB cap 
makes sorted runs grow quickly.
   
   The PR's own comment says the C writer emits level-0 files without 
compaction. With `write-buffer-size` capped at 8 MiB, every 8 MiB of input 
flushes a new level-0 sorted run. Example: a 2 GB insert into one bucket leaves 
hundreds of sorted runs, every later read has to merge all of them, and each 
new INSERT adds more with no upper bound. The Java writer (non write-only) 
compacts at `num-sorted-run.compaction-trigger` and applies backpressure at 
`num-sorted-run.stop-trigger`. `requiresSingleWriter()` in this connector also 
assumes the writer owns compaction for non write-only tables.
   
   Since `enable_paimon_rust_writer` defaults to true, existing PK tables will 
degrade after upgrade. Suggest: only select Rust for PK tables with 
`write-only=true` (an external compaction job exists), or until Rust supports 
compaction; or default the switch to false for the first release. Append tables 
have the same small-file issue to a lesser degree.



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonTableDescriptor.java:
##########
@@ -0,0 +1,149 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.connector.paimon;
+
+import org.apache.doris.connector.spi.DorisConnectorException;
+import org.apache.doris.thrift.TPaimonCatalogContext;
+import org.apache.doris.thrift.TPaimonTableDesc;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.catalog.CatalogContext;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.rest.RESTTokenFileIO;
+import org.apache.paimon.schema.TableSchema;
+import org.apache.paimon.table.CatalogEnvironment;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.utils.JsonSerdeUtil;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+/** Portable table metadata pinned by FE for Paimon readers and writers. */
+public final class PaimonTableDescriptor {
+    private PaimonTableDescriptor() {
+    }
+
+    static boolean usesRestDataToken(FileStoreTable table) {
+        CatalogContext context = table.catalogEnvironment().catalogContext();
+        // RESTCatalog can wrap RESTTokenFileIO in a cache, so retain its 
effective option too.
+        return table.fileIO() instanceof RESTTokenFileIO
+                || (context != null && 
context.options().get(RESTTokenFileIO.DATA_TOKEN_ENABLED));
+    }
+
+    public static TPaimonTableDesc describeForScan(FileStoreTable table, 
String database, String name,
+            Map<String, String> storageOptions) {
+        return describe(table.location().toString(), 
PaimonScanParams.withoutTimeTravelSelectors(table.schema()),
+                database, name, storageOptions);
+    }
+
+    public static TPaimonTableDesc describe(String location, TableSchema 
schema, String database, String name,
+            Map<String, String> storageOptions) {
+        TPaimonTableDesc result = new TPaimonTableDesc();
+        result.setTablePath(location);
+        try {
+            result.setSchemaJson(JsonSerdeUtil.toJson(schema));
+        } catch (Exception e) {
+            throw new DorisConnectorException("Failed to serialize Paimon 
table schema", e);
+        }
+        result.setDatabaseName(database);
+        result.setTableName(name);
+        result.setBranch(CoreOptions.branch(schema.options()));
+        result.setStorageOptions(normalizeStorage(location, storageOptions));
+        return result;
+    }
+
+    public static TPaimonTableDesc describe(FileStoreTable table, TableSchema 
schema, String database, String name,
+            Map<String, String> storageOptions, boolean 
supportsPartitionModification) {
+        CatalogEnvironment environment = table.catalogEnvironment();
+        Identifier identifier = environment.identifier();
+        // Doris names may be aliases or case mappings; catalog services need 
the pinned remote identity.
+        TPaimonTableDesc result = describe(table.location().toString(), schema,
+                identifier == null ? database : identifier.getDatabaseName(),
+                identifier == null ? name : identifier.getTableName(), 
storageOptions);
+        TPaimonCatalogContext context = new TPaimonCatalogContext();
+        context.setCatalogLoaderEnabled(environment.catalogLoader() != null);
+        
context.setSupportsVersionManagement(environment.supportsVersionManagement());
+        
context.setSupportsPartitionModification(supportsPartitionModification);
+        if (environment.uuid() != null) {
+            context.setTableUuid(environment.uuid());
+        }
+        if (environment.catalogContext() != null) {
+            context.setOptions(environment.catalogContext().options().toMap());
+            Map<String, String> hadoopConfig = new HashMap<>();
+            environment.catalogContext().hadoopConf().forEach(entry -> {
+                String[] sources = 
environment.catalogContext().hadoopConf().getPropertySources(entry.getKey());
+                // Both sides ship the same Hadoop defaults. Carry site files 
and explicit overrides,
+                // rather than copying thousands of built-in settings into 
each descriptor.
+                if (sources == null || sources.length == 0
+                        || Arrays.stream(sources).anyMatch(source -> 
!source.endsWith("-default.xml"))) {
+                    hadoopConfig.put(entry.getKey(), entry.getValue());
+                }
+            });
+            context.setHadoopConfig(hadoopConfig);
+        } else {
+            context.setOptions(Collections.emptyMap());
+            context.setHadoopConfig(Collections.emptyMap());
+        }
+        result.setCatalogContext(context);
+        return result;
+    }
+
+    static Map<String, String> normalizeStorage(String location, Map<String, 
String> original) {

Review Comment:
   [P2] Storage normalization is in the wrong layer.
   
   This is a hand-written alias table (`AWS_*`, `fs.s3a.*`, and even `fs.oss.*` 
mapped to `s3.*` under the s3 scheme), moved here from the BE reader. 
Converting catalog storage properties into backend keys is the job of 
fe-filesystem (`StorageProperties` typed conversions). A second copy here will 
drift from fe-filesystem. Also, `storageOptions.putAll(table.options())` in 
`planWrite` mixes all table options into `storage_options` and lets them 
override catalog credentials, which is unclear semantics. Suggest a typed 
conversion in fe-filesystem for the Rust/opendal key set.



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonScanPlanProvider.java:
##########
@@ -1371,6 +1367,25 @@ rowType, filterReadsTimestamp(rowType, filter.get())
             }
         }
 
+        // Offline metadata callers have no session and cannot select a Rust 
split.
+        if (table instanceof FileStoreTable && session != null && 
Boolean.parseBoolean(
+                
session.getSessionProperties().get("enable_paimon_rust_reader"))) {

Review Comment:
   [P3] This hard-codes the `enable_paimon_rust_reader` check, duplicating 
`PaimonRustReaderSelector`, and serializes the schema whenever the switch is 
on, even when no Rust split is produced. Consider reusing the selector 
constant/decision and building the descriptor only when Rust splits exist.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to