github-actions[bot] commented on code in PR #71005:
URL: https://github.com/apache/doris/pull/71005#discussion_r4690660500


##########
fe/fe-core/src/main/java/org/apache/doris/common/util/FetchRemoteTabletSchemaUtil.java:
##########
@@ -62,12 +68,73 @@
 public class FetchRemoteTabletSchemaUtil {
     private static final Logger LOG = 
LogManager.getLogger(FetchRemoteTabletSchemaUtil.class);
 
-    private final List<Tablet> remoteTablets;
-    private final List<Column> tableColumns;
+    private final int tabletCount;
+    private final Map<Long, List<Replica>> tabletReplicas = 
Maps.newLinkedHashMap();
 
+    /** Capture the candidate replica lists under the table lock and resolve 
Cloud routes during fetch. */
     public FetchRemoteTabletSchemaUtil(List<Tablet> tablets) {
-        this.remoteTablets = tablets;
-        this.tableColumns = Lists.newArrayList();
+        tabletCount = tablets.size();
+        for (Tablet tablet : tablets) {
+            tabletReplicas.put(tablet.getId(), 
Lists.newArrayList(tablet.getReplicas()));
+        }
+    }
+
+    public record PartitionTablets(Partition partition, List<Tablet> tablets) {
+    }
+
+    /** Capture tablet lists under the table lock. Cloud visibility can 
require a separate RPC. */
+    public static List<PartitionTablets> 
snapshotPartitions(Collection<Partition> partitions) {
+        boolean cloudMode = Config.isCloudMode();
+        List<PartitionTablets> snapshot = Lists.newArrayList();
+        for (Partition partition : partitions) {
+            if (cloudMode || partition.getVisibleVersion() > 
Partition.PARTITION_INIT_VERSION) {
+                snapshot.add(new PartitionTablets(partition, 
partition.getBaseIndex().getTablets()));
+            }
+        }
+        return snapshot;
+    }
+
+    public static List<Tablet> collectTablets(List<PartitionTablets> 
partitions) throws AnalysisException {
+        if (partitions.isEmpty()) {
+            return Collections.emptyList();
+        }
+        boolean cloudMode = Config.isCloudMode();
+        List<Long> cloudVersions = cloudMode ? 
getCloudVisibleVersions(partitions) : List.of();
+        int maxTablets = 
ConnectContext.get().getSessionVariable().maxFetchRemoteTabletCount;
+        List<Tablet> tablets = Lists.newArrayList();
+        long tabletCount = 0;
+        for (int i = 0; i < partitions.size(); ++i) {
+            if (cloudMode && cloudVersions.get(i) <= 
Partition.PARTITION_INIT_VERSION) {
+                continue;
+            }
+            PartitionTablets partition = partitions.get(i);
+            tabletCount += partition.tablets().size();

Review Comment:
   [P2] Deduplicate partitions before enforcing the tablet limit
   
   Partition lists can contain the same name more than once: 
`PartitionNamesInfo.validate()` accepts this, and `getNamedPartitions()` adds 
the same partition for each occurrence. This loop therefore counts its tablets 
repeatedly. For a nonempty one-tablet `p1` with 
`max_fetch_remote_schema_tablet_count=1`, `DESC t PARTITION(p1)` succeeds but 
`DESC t PARTITION(p1,p1)` now fails as needing two tablets, even though the 
later tablet-ID map and worker assignment sets read only one. The previous 
sampling path handled this input. Please deduplicate resolved partition IDs or 
unique tablet IDs before applying both hard-limit checks.



##########
fe/fe-core/src/main/java/org/apache/doris/common/util/FetchRemoteTabletSchemaUtil.java:
##########
@@ -121,112 +188,144 @@ private static Type getTypeFromTypeName(String 
typeName, int precision, int scal
         return res;
     }
 
-    public List<Column> fetch() {
-        // 1. Find which Backend (BE) servers the tablets are on
-        Preconditions.checkNotNull(remoteTablets);
+    public List<Column> fetch() throws AnalysisException {
+        if (tabletReplicas.isEmpty()) {
+            return Collections.emptyList();
+        }
+        int maxTablets = 
ConnectContext.get().getSessionVariable().maxFetchRemoteTabletCount;
+        checkTabletCount(tabletCount, maxTablets);
+        // Resolve a Cloud compute group at most once, after the table lock 
has been released.
+        String clusterId = null;
         Map<Long, Set<Long>> beIdToTabletId = Maps.newHashMap();
-        for (Tablet tablet : remoteTablets) {
-            for (Replica replica : tablet.getReplicas()) {
-                // only need alive replica
-                if (replica.isAlive()) {
-                    Set<Long> tabletIds = beIdToTabletId.computeIfAbsent(
-                                    replica.getBackendIdWithoutException(), k 
-> Sets.newHashSet());
-                    tabletIds.add(tablet.getId());
+        Map<Long, Backend> liveBackends = Maps.newHashMap();
+        for (Map.Entry<Long, List<Replica>> tablet : 
tabletReplicas.entrySet()) {
+            boolean hasLiveBackend = false;
+            for (Replica replica : tablet.getValue()) {
+                if (!replica.isAlive()) {
+                    continue;
+                }
+                long backendId;
+                if (replica instanceof CloudReplica) {
+                    if (clusterId == null) {
+                        clusterId = resolveComputeGroup();
+                    }
+                    try {
+                        backendId = ((CloudReplica) 
replica).getBackendIdWithClusterId(clusterId);
+                    } catch (ComputeGroupException e) {
+                        LOG.debug("Could not route tablet {} for remote 
schema", tablet.getKey(), e);
+                        continue;
+                    }
+                } else {
+                    backendId = replica.getBackendIdWithoutException();
                 }
+                Backend backend = liveBackends.get(backendId);
+                if (backend == null) {
+                    backend = Env.getCurrentSystemInfo().getBackend(backendId);
+                    if (backend == null || !backend.isAlive()) {
+                        continue;
+                    }
+                    liveBackends.put(backendId, backend);
+                }
+                beIdToTabletId.computeIfAbsent(backendId, k -> 
Sets.newHashSet()).add(tablet.getKey());
+                hasLiveBackend = true;
+            }
+            if (!hasLiveBackend) {
+                throw new AnalysisException("Extended DESCRIBE could not find 
a live replica for tablet "
+                        + tablet.getKey());
             }
         }
 
         // 2. Randomly select 2 Backend (BE) servers to act as coordinators.
         // Coordinator BE is responsible for collecting all table columns and 
returning to the FE.
         // Two BE provide a retry opportunity with the second one in case the 
first attempt fails.
         List<PTabletsLocation> locations = Lists.newArrayList();
-        List<Backend> coordinatorBackend = Lists.newArrayList();
+        List<Backend> coordinatorBackend = 
Lists.newArrayList(liveBackends.values());
         for (Map.Entry<Long, Set<Long>> entry : beIdToTabletId.entrySet()) {
-            Long backendId = entry.getKey();
-            Set<Long> tabletIds = entry.getValue();
-            Backend backend = 
Env.getCurrentEnv().getCurrentSystemInfo().getBackend(backendId);
-            LOG.debug("fetch schema from coord backend {}, sample tablets 
count {}",
-                            backend.getId(), tabletIds.size());
-            // only need alive be
-            if (!backend.isAlive()) {
-                continue;
-            }
-            coordinatorBackend.add(backend);
-            PTabletsLocation.Builder locationBuilder = 
PTabletsLocation.newBuilder()
-                                                        
.setHost(backend.getHost())
-                                                        
.setBrpcPort(backend.getBrpcPort());
-            PTabletsLocation location = 
locationBuilder.addAllTabletId(tabletIds).build();
-            locations.add(location);
+            Backend backend = liveBackends.get(entry.getKey());
+            locations.add(PTabletsLocation.newBuilder()
+                    .setHost(backend.getHost())
+                    .setBrpcPort(backend.getBrpcPort())
+                    .addAllTabletId(entry.getValue())
+                    .build());
         }
-        // pick 2 random coordinator
         Collections.shuffle(coordinatorBackend);
-        if (!coordinatorBackend.isEmpty()) {
-            coordinatorBackend = coordinatorBackend.subList(0, Math.min(2, 
coordinatorBackend.size()));
-            LOG.debug("pick coordinator backend {}", 
coordinatorBackend.get(0));
-        }
-        PFetchRemoteSchemaRequest.Builder requestBuilder = 
PFetchRemoteSchemaRequest.newBuilder()
-                                                                    
.addAllTabletLocation(locations)
-                                                                    
.setIsCoordinator(true);
-        // 3. Send rpc to coordinatorBackend util succeed or retry
-        for (Backend be : coordinatorBackend) {
+        PFetchRemoteSchemaRequest request = 
PFetchRemoteSchemaRequest.newBuilder()
+                .addAllTabletLocation(locations)
+                .setIsCoordinator(true)
+                .build();
+        long timeoutSeconds = Math.max(0L, 
ConnectContext.get().getSessionVariable().fetchRemoteSchemaTimeoutSeconds);
+        long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSeconds);
+        long startNanos = System.nanoTime();
+        Exception lastFailure = null;
+        for (Backend be : coordinatorBackend.subList(0, Math.min(2, 
coordinatorBackend.size()))) {
+            // A second coordinator only gets the time left by the first 
attempt.
+            if (lastFailure != null && System.nanoTime() - startNanos >= 
timeoutNanos) {
+                break;
+            }
+            PFetchRemoteSchemaResponse response;
             try {
-                PFetchRemoteSchemaRequest request = requestBuilder.build();
                 Future<PFetchRemoteSchemaResponse> future = 
BackendServiceProxy.getInstance()
-                                            
.fetchRemoteTabletSchemaAsync(be.getBrpcAddress(), request);
-                PFetchRemoteSchemaResponse response = null;
+                        .fetchRemoteTabletSchemaAsync(be.getBrpcAddress(), 
request);
                 try {
-                    response = future.get(
-                        
ConnectContext.get().getSessionVariable().fetchRemoteSchemaTimeoutSeconds, 
TimeUnit.SECONDS);
-                    TStatusCode code = 
TStatusCode.findByValue(response.getStatus().getStatusCode());
-                    String errMsg;
-                    if (code != TStatusCode.OK) {
-                        if 
(!response.getStatus().getErrorMsgsList().isEmpty()) {
-                            errMsg = 
response.getStatus().getErrorMsgsList().get(0);
-                        } else {
-                            errMsg = "fetchRemoteTabletSchemaAsync failed. 
backend address: "
-                                    + be.getHost() + " : " + be.getBrpcPort();
-                        }
-                        throw new RpcException(be.getHost(), errMsg);
+                    while 
(DebugPointUtil.isEnable("FetchRemoteTabletSchemaUtil.fetch.waitForResponse")) {
+                        Thread.sleep(100);
                     }
-                    fillColumns(response);
-                    return tableColumns;
-                } catch (AnalysisException e) {
-                    // continue to get result
-                    LOG.warn(e);
-                } catch (InterruptedException e) {
-                    // continue to get result
-                    LOG.warn("fetch remote schema future get interrupted 
Exception");
+                    long remainingNanos = Math.max(0L, timeoutNanos - 
(System.nanoTime() - startNanos));
+                    response = future.get(remainingNanos, 
TimeUnit.NANOSECONDS);
                 } catch (TimeoutException e) {
                     future.cancel(true);
-                    // continue to get result
-                    LOG.warn("fetch remote schema result timeout, addr {}", 
be.getBrpcAddress());
+                    throw new AnalysisException("Remote schema RPC timed out 
on " + be.getBrpcAddress(), e);
+                } catch (InterruptedException e) {
+                    future.cancel(true);
+                    throw e;
+                }
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                throw new AnalysisException("Extended DESCRIBE interrupted 
while fetching remote schema", e);
+            } catch (AnalysisException | RpcException | ExecutionException e) {
+                lastFailure = e;
+                LOG.warn("Failed to fetch remote schema from {}", 
be.getBrpcAddress(), e);
+                continue;
+            }
+            if (!response.hasStatus() || response.getStatus().getStatusCode() 
!= TStatusCode.OK.getValue()) {
+                AnalysisException failure = new AnalysisException("Remote 
schema RPC failed on "
+                        + be.getBrpcAddress() + " " + 
response.getStatus().getErrorMsgsList());
+                // Worker RPCs already retry transport failures within their 
own deadline.
+                // Moving an accepted request to another coordinator repeats 
the worker fan-out.
+                if (response.hasStatus() && response.getCoordinatorAccepted()) 
{
+                    throw failure;
+                }
+                lastFailure = failure;
+            } else if (!response.hasMergedSchema()) {
+                lastFailure = new AnalysisException("Missing merged schema 
from " + be.getBrpcAddress());
+            } else {
+                try {
+                    return decodeColumns(response.getMergedSchema());
+                } catch (AnalysisException e) {
+                    lastFailure = e;
                 }
-            }    catch (RpcException e) {
-                LOG.warn("fetch remote schema result rpc exception {}, e {}", 
be.getBrpcAddress(), e);
-            } catch (ExecutionException e) {
-                LOG.warn("fetch remote schema ExecutionException, addr {}, e 
{}", be.getBrpcAddress(), e);
             }
+            LOG.warn("Failed to fetch remote schema from {}", 
be.getBrpcAddress(), lastFailure);
         }
-        return tableColumns;
+        throw new AnalysisException("Extended DESCRIBE failed to fetch a 
complete remote schema"

Review Comment:
   [P2] Reuse the fetched PROC result when deriving its headers
   
   With extended Variant schemas enabled, `ShowProcCommand.handleShowProc()` 
calls this fetch once for the rows and again from `getMetaData(procNode)`. If 
the first fan-out succeeds but the second hits a worker I/O error or exhausted 
RPC retries, this new exception reaches `getMetaData()`, which catches it and 
returns zero columns. The command then emits the six-value rows from the first 
fetch with a zero-column header, producing a malformed MySQL result instead of 
a valid schema or an error. Please derive both headers and rows from the same 
`ProcResult` (and cover first-success/second-failure), so enabling error 
propagation is safe for the SHOW PROC callers too.



-- 
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