hello-stephen commented on code in PR #71174:
URL: https://github.com/apache/doris/pull/71174#discussion_r4795784843


##########
fe/fe-core/src/main/java/org/apache/doris/qe/runtime/PipelineExecutionTask.java:
##########
@@ -134,7 +150,7 @@ private void sendAndWaitPhaseOneRpc() throws UserException, 
RpcException {
             rpcs.add(new RpcInfo(
                     fragmentsTask,
                     DateTime.now().getMillis(),
-                    
fragmentsTask.sendPhaseOneRpc(coordinatorContext.twoPhaseExecution()))
+                    
fragmentsTask.sendPhaseOneRpc(coordinatorContext.twoPhaseExecution(), 
queryDeadline()))

Review Comment:
   [P2] Cancel pending fragment admission when KILL QUERY arrives
   
   `execute()` holds the `CoordinatorContext` monitor while waiting for the 
phase-one and phase-two futures. A concurrent `KILL QUERY` reaches 
`Coordinator.cancel()` and blocks in `updateStatusIfOk()` on that same monitor. 
If a fragment is still waiting in FE admission, the admission callback can send 
it before the cancel thread reaches `cancelPendingRpcs()`. The existing 
sibling-failure test cancels from inside the dispatch thread and misses this 
ordering. Let external cancellation detach pending dispatch before it waits for 
the coordinator monitor, and cover the concurrent cancel path.



##########
fe/fe-core/src/main/java/org/apache/doris/planner/GroupCommitPlanner.java:
##########
@@ -167,7 +167,12 @@ public PGroupCommitInsertResponse 
executeGroupCommitInsert(ConnectContext ctx,
                 rows.size(), DebugUtil.printId(loadId));
         Future<PGroupCommitInsertResponse> future = 
BackendServiceProxy.getInstance()
                 .groupCommitInsert(new TNetworkAddress(backend.getHost(), 
backend.getBrpcPort()), request);
-        return future.get();
+        try {
+            return future.get();
+        } finally {
+            // Interruption can precede admission; do not dispatch the 
abandoned insert later.
+            future.cancel(true);

Review Comment:
   [P2] Bind prepared Group Commit admission to KILL QUERY
   
   `ExecuteCommand` takes the prepared Group Commit path before starting a 
coordinator or running `InsertIntoTableCommand`. `KILL QUERY` sets the 
command’s cancel flag, and its wait returns because that command never entered 
its running state. The change here cancels the future only after `get()` exits, 
and SQL cancellation does not interrupt that wait. If the insert is still 
queued in FE admission, it can reach the BE after `KILL QUERY` returns. Tie 
this future to statement cancellation and cover a kill while admission is 
pending.



##########
fe/fe-core/src/main/java/org/apache/doris/rpc/BackendServiceClient.java:
##########
@@ -46,20 +69,288 @@ public static boolean supportsPrivateFileKeys() {
     private final PBackendServiceGrpc.PBackendServiceBlockingStub blockingStub;
     private final ManagedChannel channel;
     private final long execPlanTimeout;
+    private final boolean internalRpc;
+    private final AuthorityPublisher authorityPublisher;
+
+    @FunctionalInterface
+    interface AuthorityPublisher {
+        void publish(long backendId) throws Exception;
+    }
+
+    private volatile long authBackendId;
+
+    private record Target(long backendId, int clusterId, long epoch) {
+    }
+
+    private static final ListeningExecutorService REGISTRATION_EXECUTOR = 
MoreExecutors.listeningDecorator(
+            
ThreadPoolManager.newDaemonFixedThreadPool(Config.heartbeat_mgr_threads_num,
+                    Config.heartbeat_mgr_blocking_queue_size, 
"rpc-authority-registration", true,
+                    new 
java.util.concurrent.ThreadPoolExecutor.AbortPolicy()));
+    private static final ScheduledExecutorService ADMISSION_TIMER = 
admissionTimer();
+
+    private static ScheduledExecutorService admissionTimer() {
+        java.util.concurrent.ScheduledThreadPoolExecutor timer =
+                ThreadPoolManager.newDaemonScheduledThreadPool(1, 
"rpc-authority-deadline", true);
+        // Successful RPCs must not retain a timer node until their original 
deadline.
+        timer.setRemoveOnCancelPolicy(true);
+        return timer;
+    }
+
+    private Target admittedTarget;
+    private Admission admission;
+
+    // One owner can be blocked in a non-interruptible journal write. Keep 
only live,
+    // bounded waiters: nonCancellationPropagating would retain every 
cancelled wrapper
+    // on that owner's listener stack until the journal eventually completes.
+    private static final class Admission {
+        private final SettableFuture<Void> completed = SettableFuture.create();
+        private final Set<SettableFuture<Void>> waiters = new HashSet<>();
+
+        private Admission() {
+            completed.addListener(() -> {
+                List<SettableFuture<Void>> pending;
+                synchronized (this) {
+                    pending = new ArrayList<>(waiters);
+                    waiters.clear();
+                }
+                for (SettableFuture<Void> waiter : pending) {
+                    waiter.setFuture(completed);
+                }
+            }, MoreExecutors.directExecutor());
+        }
+
+        private synchronized ListenableFuture<Void> newWaiter() {
+            if (completed.isDone()) {
+                return completed;
+            }
+            if (waiters.size() >= Math.max(1, 
Config.grpc_threadmgr_threads_nums)) {
+                return Futures.immediateFailedFuture(new 
RejectedExecutionException("Too many authority waiters"));
+            }
+            SettableFuture<Void> waiter = SettableFuture.create();
+            waiters.add(waiter);
+            waiter.addListener(() -> {
+                synchronized (this) {
+                    waiters.remove(waiter);
+                }
+            }, MoreExecutors.directExecutor());
+            return waiter;
+        }
+    }
 
     public BackendServiceClient(TNetworkAddress address, String resolvedIp, 
Executor executor) {
         this(address, resolvedIp, executor, true);
     }
 
     public BackendServiceClient(TNetworkAddress address, String resolvedIp, 
Executor executor, boolean internalRpc) {
+        this(address, resolvedIp, executor, internalRpc, 
FrontendRpcAuthority::registerSelf);
+    }
+
+    BackendServiceClient(TNetworkAddress address, String resolvedIp, Executor 
executor, boolean internalRpc,
+            AuthorityPublisher authorityPublisher) {
+        this.authorityPublisher = authorityPublisher;
         this.address = address;
+        this.internalRpc = internalRpc;
         channel = CHANNEL_PROVIDER.createChannel(address, resolvedIp, 
executor, internalRpc);
         stub = PBackendServiceGrpc.newFutureStub(channel);
         blockingStub = PBackendServiceGrpc.newBlockingStub(channel);
         // execPlanTimeout should be greater than future.get timeout, 
otherwise future will throw ExecutionException
         execPlanTimeout = Config.remote_fragment_exec_timeout_ms + 5000;
     }
 
+    private Target localTarget() {
+        return localTarget(authBackendId);
+    }
+
+    private Target localTarget(long backendId) {
+        SystemInfoService system = Env.getCurrentSystemInfo();
+        Backend target = system.getBackend(backendId > 0 ? backendId : 
authBackendId);
+        // Resolve through live metadata so endpoint reuse cannot retain a 
dropped backend's identity.
+        if (target == null || target.getBrpcPort() != address.port || 
!target.getHost().equals(address.hostname)) {
+            target = 
system.getAllClusterBackendsNoException().values().stream()
+                    .filter(backend -> backend.getBrpcPort() == address.port
+                            && backend.getHost().equals(address.hostname))
+                    .findFirst().orElseThrow(() -> new 
IllegalStateException("Unknown internal RPC backend"));
+        }
+        authBackendId = target.getId();
+        return new Target(target.getId(), Env.getCurrentEnv().getClusterId(), 
target.getProcessEpoch());
+    }
+
+    private synchronized Admission admit(Target target, boolean repair) {
+        if (target.equals(admittedTarget) && admission != null
+                && (!repair || !admission.completed.isDone())) {
+            return admission;
+        }
+        Admission shared = new Admission();

Review Comment:
   [P3] Coalesce authority repair across channel shards
   
   `BackendServiceProxy` round-robins across 48 shards by default, and each 
shard can create a separate `BackendServiceClient` for the same BE. If 
concurrent requests see a missing key before publication, each shard starts its 
own repair. Those redundant jobs compete for the shared registration queue and 
still contact the master when dequeued after another shard has published the 
key. Share in-flight repair by BE identity and process epoch while preserving 
each caller’s deadline and cancellation.



##########
fe/fe-core/src/main/java/org/apache/doris/system/HeartbeatMgr.java:
##########
@@ -143,13 +155,80 @@ public static boolean refreshChangelogTtlReferenceTso() {
         }
     }
 
-    /**
-     * At each round:
-     * 1. send heartbeat to all nodes
-     * 2. collect the heartbeat response from all nodes, and handle them
-     */
+    private record RpcAuthority(TMasterInfo master, List<TFrontendInfo> 
frontends) {
+        TMasterInfo envelope() {
+            // Deep-copy only the small target envelope. Generated Thrift copy 
constructors
+            // would otherwise allocate the entire membership list once per 
backend.
+            return new TMasterInfo(master).setFrontendInfos(frontends);
+        }
+    }
+
+    public long getMasterEpoch() {
+        TMasterInfo current = masterInfo.get();
+        if (current == null) {
+            throw new IllegalStateException("Master authority is not 
initialized");
+        }
+        return current.getEpoch();
+    }
+
+    // Capture the epoch and complete authority together. The sequence orders 
even concurrent
+    // on-demand publications, so a slow old heartbeat cannot roll back a 
newer registration.
+    private RpcAuthority captureRpcAuthority() {
+        return Env.getCurrentEnv().withFrontendRpcAuthorityLock(() -> {
+            TMasterInfo current = masterInfo.get();
+            if (current == null || !Env.getCurrentEnv().isMaster()) {
+                throw new IllegalStateException("Frontend is not master");
+            }
+            TMasterInfo snapshot = new TMasterInfo(current);
+            snapshot.setRpcAuthorityVersion(++authorityVersion);
+            if (Config.isCloudMode()) {
+                snapshot.setMetaServiceEndpoint(Config.meta_service_endpoint);
+            }
+            return new RpcAuthority(snapshot, 
List.copyOf(Env.getCurrentEnv().getFrontendInfos()));
+        });
+    }
+
+    public HeartbeatResponse publishRpcAuthority(Backend backend) {
+        return new BackendHeartbeatHandler(backend, 
captureRpcAuthority()).call();
+    }
+
+    public void applyFrontendHeartbeat(FrontendHbResponse response) {
+        applyFrontendHeartbeats(List.of(response));
+    }
+
+    private void applyFrontendHeartbeats(List<FrontendHbResponse> responses) {
+        Env env = Env.getCurrentEnv();
+        env.withFrontendRpcAuthorityLock(() -> {
+            HbPackage changes = new HbPackage();
+            for (FrontendHbResponse response : responses) {
+                Frontend member = env.getFeByName(response.getName());
+                if (member == null || !response.matchesIdentity(member, 
member.getRpcIdentityVersion())) {
+                    continue;
+                }
+                if (response.getStatus() == HbStatus.BAD && !member.isAlive() 
&& member.getProcessUUID() == 0) {
+                    // A repeated failure changes only transient diagnostics, 
not persisted authority.
+                    handleHbResponse(response, false);
+                    continue;
+                }
+                changes.addHbResponse(response);
+            }
+            if (!changes.getHbResults().isEmpty()) {
+                // Preserve writer order and durable-before-live publication 
with one commit for
+                // the entire FE round, rather than N serial synchronous 
journal transactions.
+                env.getEditLog().logHeartbeat(changes);

Review Comment:
   [P2] Keep routine heartbeat journal waits out of the catalog lock
   
   A successful FE round reaches this synchronous commit even when every 
signing identity is unchanged. `withFrontendRpcAuthorityLock()` holds the 
global `Env` lock across the journal wait. A slow flush can now make catalog 
operations time out acquiring that lock and can delay the authority capture 
required before the next BE heartbeat dispatch. Preserve durable ordering for 
identity changes while moving routine heartbeat I/O out of the catalog critical 
section.



##########
fe/fe-core/src/main/java/org/apache/doris/system/HeartbeatMgr.java:
##########
@@ -143,13 +155,80 @@ public static boolean refreshChangelogTtlReferenceTso() {
         }
     }
 
-    /**
-     * At each round:
-     * 1. send heartbeat to all nodes
-     * 2. collect the heartbeat response from all nodes, and handle them
-     */
+    private record RpcAuthority(TMasterInfo master, List<TFrontendInfo> 
frontends) {
+        TMasterInfo envelope() {
+            // Deep-copy only the small target envelope. Generated Thrift copy 
constructors
+            // would otherwise allocate the entire membership list once per 
backend.
+            return new TMasterInfo(master).setFrontendInfos(frontends);
+        }
+    }
+
+    public long getMasterEpoch() {
+        TMasterInfo current = masterInfo.get();
+        if (current == null) {
+            throw new IllegalStateException("Master authority is not 
initialized");
+        }
+        return current.getEpoch();
+    }
+
+    // Capture the epoch and complete authority together. The sequence orders 
even concurrent
+    // on-demand publications, so a slow old heartbeat cannot roll back a 
newer registration.
+    private RpcAuthority captureRpcAuthority() {
+        return Env.getCurrentEnv().withFrontendRpcAuthorityLock(() -> {
+            TMasterInfo current = masterInfo.get();
+            if (current == null || !Env.getCurrentEnv().isMaster()) {
+                throw new IllegalStateException("Frontend is not master");
+            }
+            TMasterInfo snapshot = new TMasterInfo(current);
+            snapshot.setRpcAuthorityVersion(++authorityVersion);
+            if (Config.isCloudMode()) {
+                snapshot.setMetaServiceEndpoint(Config.meta_service_endpoint);
+            }
+            return new RpcAuthority(snapshot, 
List.copyOf(Env.getCurrentEnv().getFrontendInfos()));
+        });
+    }
+
+    public HeartbeatResponse publishRpcAuthority(Backend backend) {
+        return new BackendHeartbeatHandler(backend, 
captureRpcAuthority()).call();

Review Comment:
   [P2] Capture the current backend identity with its authority sequence
   
   An on-demand registration can look up a backend and pause before this 
capture. If an operator drops and re-adds the backend at the same heartbeat 
endpoint, a periodic heartbeat can install the replacement ID before the old 
request resumes. The old request then gets a higher sequence and the BE 
installs the removed ID. The replacement remains schedulable in FE metadata, 
but the BE rejects requests signed for its new ID without the 
registration-required marker. Bind both heartbeat publishers’ sequence 
allocation to the same live backend identity.



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