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


##########
fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/TableQueryPlanAction.java:
##########
@@ -160,15 +162,42 @@ public Object query_plan(
                     ConnectContext.get().getCloudCluster();
                 }
                 // parse/analysis/plan the sql and acquire tablet distributions
-                handleQuery(ConnectContext.get(), dbName, tblName, sql, 
resultMap);
+                handleQuery(ConnectContext.get(), dbName, tblName, sql, 
resultMap, executionTargets);
             } finally {
                 table.readUnlock();
             }
+            // Registration performs network I/O. Release metadata locks 
first, then admit
+            // every replica advertised to an external scanner, not just the 
chosen scan node.
+            List<java.util.concurrent.Future<Void>> admissions = new 
ArrayList<>();
+            try {
+                for (TNetworkAddress target : 
executionTargets.stream().distinct().toList()) {
+                    Backend backend = 
Env.getCurrentSystemInfo().getAllClusterBackendsNoException().values().stream()
+                            .filter(be -> be.getHost().equals(target.hostname) 
&& be.getBePort() == target.port)
+                            .findFirst().orElseThrow(() -> new 
IllegalStateException("Unknown scanner backend"));
+                    
admissions.add(BackendServiceProxy.getInstance().awaitExecutionAuthority(
+                            new TNetworkAddress(backend.getHost(), 
backend.getBrpcPort())));
+                }
+                for (java.util.concurrent.Future<Void> admission : admissions) 
{
+                    admission.get();

Review Comment:
   [P2] Keep usable scanner routes when one replica fails admission
   
   `OlapScanNode` advertises every query-available replica based on heartbeat 
state. A replica can keep reporting healthy heartbeats while its BRPC endpoint 
is unreachable. If each tablet also has another admitted replica, this `get()` 
still fails the entire export and discards every usable Thrift route. Keep the 
admitted routes per tablet and fail the export only if some tablet has none. 
Please cover a replicated table with one unavailable BRPC endpoint.



##########
regression-test/suites/rpc_p0/test_internal_rpc_request_auth_lifecycle.groovy:
##########
@@ -0,0 +1,280 @@
+// 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.
+
+import groovy.json.JsonOutput
+import groovy.json.JsonSlurper
+import 
org.apache.arrow.driver.jdbc.shaded.org.apache.arrow.memory.RootAllocator
+import 
org.apache.arrow.driver.jdbc.shaded.org.apache.arrow.vector.ipc.ArrowStreamReader
+import org.apache.doris.regression.suite.ConnectionInfo
+import org.apache.doris.regression.util.Http
+import org.apache.doris.thrift.BackendService
+import org.apache.doris.thrift.FrontendService
+import org.apache.doris.thrift.TScanCloseParams
+import org.apache.doris.thrift.TScanNextBatchParams
+import org.apache.doris.thrift.TScanOpenParams
+import org.apache.doris.thrift.TStatusCode
+import org.apache.thrift.protocol.TBinaryProtocol
+import org.apache.thrift.server.TThreadPoolServer
+import org.apache.thrift.transport.TServerSocket
+import org.apache.thrift.transport.TSocket
+
+import java.lang.reflect.InvocationTargetException
+import java.nio.file.Files
+import java.sql.DriverManager
+import java.sql.SQLException
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicBoolean
+import java.util.concurrent.atomic.AtomicInteger
+import java.util.concurrent.atomic.AtomicLong
+
+suite("test_internal_rpc_request_auth_lifecycle", "p0,nonConcurrent") {
+    // Owned PID checks require procfs; return before launching helpers on 
unsupported hosts.
+    if 
(!System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("linux")) {
+        logger.info("RPC authentication lifecycle fixture requires Linux; 
skipping on this host")
+        return
+    }
+    def logRoot = new File(System.getProperty("DORIS_HOME"), 
"regression-test/log").toPath()
+    Files.createDirectories(logRoot)
+    def logs = Files.createTempDirectory(logRoot, "request-auth-").toFile()
+    def helper = new File(context.file.parentFile, "request_auth_fixture.py")
+    def fixtureTestLog = new File(logs, "fixture-tests.log")
+    def fixtureTests = new ProcessBuilder("python3", "-m", "unittest", 
"discover", "-s", helper.parent,
+            "-p", "test_request_auth_fixture.py", 
"-v").redirectErrorStream(true)
+            .redirectOutput(fixtureTestLog).start()
+    try {
+        assertTrue(fixtureTests.waitFor(30, TimeUnit.SECONDS), "Fixture unit 
tests timed out; see ${logs}")
+        assertEquals(0, fixtureTests.exitValue(),
+                "Fixture unit tests failed; see 
${logs}\n${fixtureTestLog.getText('UTF-8')}")
+    } finally { fixtureTests.destroyForcibly() }
+    def process = new ProcessBuilder("python3", helper.absolutePath, 
"--package-home",
+            getConf("requestAuthPackageHome", 
System.getProperty("DORIS_HOME")), "--log-dir", logs.absolutePath)
+            .redirectError(new File(logs, "fixture.log")).start()
+    def reader = process.inputStream.newReader("UTF-8")
+    def writer = process.outputStream.newWriter("UTF-8")
+    def receive = { long seconds ->
+        long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds)
+        while (!reader.ready() && process.isAlive() && System.nanoTime() < 
deadline) { Thread.sleep(100) }
+        assertTrue(reader.ready(), "Authentication fixture did not respond; 
see ${logs}")
+        new JsonSlurper().parseText(reader.readLine())
+    }
+    TThreadPoolServer metadataProxy = null
+    TServerSocket metadataTransport = null
+    def metadataExecutor = Executors.newSingleThreadExecutor()
+    def legacyMetadata = new AtomicBoolean(true)
+    def legacyResponses = new AtomicInteger()
+    def lastLegacyReplyNanos = new AtomicLong()
+    def legacyReplyGapNanos = new AtomicLong()
+    def upgradedResponses = new AtomicInteger()
+    try {
+        def endpoints = receive(450)
+        // Keep the origin FE/catalog and backend IDs unchanged while the 
remote metadata gains its identity.
+        def handler = 
java.lang.reflect.Proxy.newProxyInstance(FrontendService.Iface.classLoader,
+                [FrontendService.Iface] as Class[], { proxy, method, arguments 
->
+                    def socket = new TSocket("127.0.0.1", 
endpoints.remote.ports.fe.rpc_port as int, 10000)
+                    socket.open()
+                    try {
+                        def result = method.invoke(new 
FrontendService.Client(new TBinaryProtocol(socket)), arguments)
+                        if (method.name == "getBackendMeta") {
+                            if (legacyMetadata.get()) {
+                                result.unsetClusterId()
+                                long now = System.nanoTime()
+                                legacyReplyGapNanos.set(now - 
lastLegacyReplyNanos.getAndSet(now))
+                                legacyResponses.incrementAndGet()
+                            } else {
+                                upgradedResponses.incrementAndGet()
+                            }
+                        }
+                        return result
+                    } catch (InvocationTargetException failure) {
+                        throw failure.cause
+                    } finally { socket.close() }
+                } as java.lang.reflect.InvocationHandler)
+        metadataTransport = new TServerSocket(new ServerSocket(0, 50, 
InetAddress.loopbackAddress))
+        int metadataPort = metadataTransport.serverSocket.localPort
+        metadataProxy = new TThreadPoolServer(new 
TThreadPoolServer.Args(metadataTransport)
+                .processor(new 
FrontendService.Processor(handler)).minWorkerThreads(1).maxWorkerThreads(4))
+        def servingProxy = metadataProxy
+        metadataExecutor.submit({ servingProxy.serve() } as Runnable)
+        def withCluster = { ports, Closure action ->
+            String url = 
"jdbc:mysql://127.0.0.1:${ports.query_port}/?useLocalSessionState=true&useSSL=false"
 +
+                    "&connectTimeout=2000&socketTimeout=60000"
+            def previous = context.threadLocalConn.get()
+            try {
+                DriverManager.getConnection(url, "root", "").withCloseable { 
connection ->
+                    context.threadLocalConn.set(new ConnectionInfo(conn: 
connection, username: "root", password: ""))
+                    action.call()
+                }
+            } finally {
+                if (previous == null) { context.threadLocalConn.remove() }
+                else { context.threadLocalConn.set(previous) }
+            }
+        }
+        def waitReady = { Closure condition ->
+            long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(120)
+            while (true) {
+                try { if (condition.call()) { return } } catch (SQLException 
pending) {
+                    if (System.nanoTime() >= deadline) { throw pending }
+                }
+                assertTrue(System.nanoTime() < deadline, "Fixture backends did 
not become ready; see ${logs}")
+                Thread.sleep(100)
+            }
+        }
+        [endpoints.local, endpoints.remote].each { endpoint ->
+            waitReady {
+                withCluster(endpoint.ports.fe) {
+                    sql_return_maparray("SHOW BACKENDS").count {
+                        it.Alive.toString().equalsIgnoreCase("true")
+                    } == endpoint.backends.size()
+                }
+            }
+            withCluster(endpoint.ports.fe) {
+                assertEquals("true", sql("ADMIN SHOW FRONTEND CONFIG LIKE 
'%enable_all_http_auth'")[0][1])
+                sql "CREATE DATABASE IF NOT EXISTS rpc_auth_fixture"
+                sql "DROP TABLE IF EXISTS rpc_auth_fixture.rpc_auth_source"
+                sql """CREATE TABLE rpc_auth_fixture.rpc_auth_source (id INT, 
value STRING)
+                       DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 8
+                       PROPERTIES ("replication_num"="1")"""
+            }
+        }
+        withCluster(endpoints.remote.ports.fe) {
+            sql "INSERT INTO rpc_auth_fixture.rpc_auth_source VALUES 
(10,'ten'),(20,'twenty')"
+            assertEquals(2, endpoints.remote.backends.size())
+            assertEquals(2, sql_return_maparray("SHOW TABLETS FROM 
rpc_auth_fixture.rpc_auth_source")
+                    .collect { it.BackendId }.toSet().size())
+        }
+        withCluster(endpoints.local.ports.fe) {
+            sql "INSERT INTO rpc_auth_fixture.rpc_auth_source VALUES 
(1,'one'),(2,'two')"
+            sql "DROP CATALOG IF EXISTS rpc_auth_remote"
+            sql """CREATE CATALOG rpc_auth_remote PROPERTIES (
+                   "type"="doris", 
"fe_http_hosts"="http://127.0.0.1:${endpoints.remote.ports.fe.http_port}";,
+                   "fe_thrift_hosts"="127.0.0.1:${metadataPort}",
+                   
"fe_arrow_hosts"="127.0.0.1:${endpoints.remote.ports.fe.arrow_flight_sql_port}",
+                   "user"="root", "password"="", "use_arrow_flight"="false")"""
+            // An enforcing upgraded worker rejects the legacy metadata's 
unknown destination namespace.
+            test {
+                sql "SELECT id,value FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source ORDER BY id"
+                exception "NOT_AUTHORIZED"
+            }
+            assertTrue(legacyResponses.get() > 0)
+            int warmMetadataRequests = legacyResponses.get()
+            test {
+                sql "SELECT id,value FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source ORDER BY id"
+                exception "NOT_AUTHORIZED"
+            }
+            // Recent unknown identities are shared across queries; a slow 
query may span the cooldown.
+            int refreshed = legacyResponses.get() - warmMetadataRequests
+            assertTrue(refreshed <= 1, "Identity resolution must remain 
independent of worker count")
+            if (refreshed > 0) {
+                assertTrue(legacyReplyGapNanos.get() >= 
TimeUnit.SECONDS.toNanos(5),
+                        "Legacy metadata was polled before the 
unknown-identity cooldown expired")
+            }
+            legacyMetadata.set(false)
+            // Wait out the five-second negative cache; the first upgraded 
query must succeed without retries.
+            TimeUnit.SECONDS.sleep(6)
+            qt_remote_native "SELECT id,value FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source ORDER BY id"
+            qt_cross_cluster_join """SELECT l.id,r.value FROM 
rpc_auth_fixture.rpc_auth_source l
+                    JOIN rpc_auth_remote.rpc_auth_fixture.rpc_auth_source r ON 
r.id=l.id*10 ORDER BY l.id"""
+            sql "CREATE TABLE rpc_auth_fixture.rpc_auth_copy LIKE 
rpc_auth_fixture.rpc_auth_source"
+            sql """INSERT INTO rpc_auth_fixture.rpc_auth_copy
+                   SELECT id,value FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source"""
+            qt_cross_cluster_insert "SELECT id,value FROM 
rpc_auth_fixture.rpc_auth_copy ORDER BY id"
+        }
+        assertTrue(upgradedResponses.get() > 0, "The live origin must refresh 
legacy destination metadata")
+        def probe = { String key ->
+            def connection = new 
URL("http://127.0.0.1:${endpoints.remote.ports.be.brpc_port}/"; +
+                    
"doris.PBackendService/hand_shake").openConnection(Proxy.NO_PROXY)
+            connection.requestMethod = "POST"
+            connection.connectTimeout = 5000
+            connection.readTimeout = 5000
+            connection.doOutput = true
+            connection.setRequestProperty("Content-Type", "application/json")
+            try {
+                connection.outputStream.withCloseable {
+                    it.write(JsonOutput.toJson([frontend_public_key: 
key]).getBytes("UTF-8"))
+                }
+                assertEquals(200, connection.responseCode)
+                connection.inputStream.withCloseable { new 
JsonSlurper().parse(it).frontend_key_registered }
+            } finally { connection.disconnect() }
+        }
+        assertEquals(false, probe("unregistered authority"), "Remote BE must 
keep authentication enabled")
+        assertEquals(true, probe(endpoints.local.public_key))
+
+        def exported = 
Http.POST("http://127.0.0.1:${endpoints.local.ports.fe.http_port}/"; +
+                "api/rpc_auth_fixture/rpc_auth_source/_query_plan",
+                [sql: "SELECT id FROM rpc_auth_fixture.rpc_auth_source"], 
true, "root", "")
+        assertEquals(0, exported.code, exported.toString())
+        assertEquals(200, exported.data.status, exported.data.toString())
+        // Trust in an issuing FE must not make a plan valid in a different 
destination cluster.
+        def remoteSocket = new TSocket("127.0.0.1", 
endpoints.remote.ports.be.be_port as int, 10000)
+        remoteSocket.open()
+        try {
+            def remoteClient = new BackendService.Client(new 
TBinaryProtocol(remoteSocket))
+            def wrongCluster = new 
TScanOpenParams().setCluster("default_cluster").setDatabase("rpc_auth_fixture")
+                    
.setTable("rpc_auth_source").setTabletIds(exported.data.partitions.keySet().collect
 { it as long })
+                    
.setOpaquedQueryPlan(exported.data.opaqued_query_plan).setUser("root").setPasswd("")
+            assertEquals(TStatusCode.NOT_AUTHORIZED, 
remoteClient.openScanner(wrongCluster).status.statusCode)
+        } finally { remoteSocket.close() }
+        // Reopen exactly the same snapshot bytes after the issuer restarts 
and heartbeats again.
+        writer.write("restart-local\n"); writer.flush()
+        assertEquals(true, receive(180).ok)
+        withCluster(endpoints.local.ports.fe) {
+            qt_after_master_restart "SELECT count(*) FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source"
+        }
+        Thread.sleep(3000)
+        String route = 
exported.data.partitions.values().first().routings.first()
+        String host = route.substring(0, route.lastIndexOf(':')).replace('[', 
'').replace(']', '')
+        int port = route.substring(route.lastIndexOf(':') + 1) as int
+        def socket = new TSocket(host, port, 10000)
+        socket.open()
+        def allocator = new RootAllocator()
+        try {
+            def client = new BackendService.Client(new TBinaryProtocol(socket))
+            def params = new 
TScanOpenParams().setCluster("default_cluster").setDatabase("rpc_auth_fixture")
+                    
.setTable("rpc_auth_source").setTabletIds(exported.data.partitions.keySet().collect
 { it as long })
+                    
.setOpaquedQueryPlan(exported.data.opaqued_query_plan).setUser("root").setPasswd("")
+            def opened = client.openScanner(params)
+            assertEquals(TStatusCode.OK, opened.status.statusCode, 
opened.toString())
+            long rows = 0
+            try {
+                while (true) {
+                    def batch = client.getNext(new 
TScanNextBatchParams().setContextId(opened.contextId).setOffset(rows))
+                    assertEquals(TStatusCode.OK, batch.status.statusCode, 
batch.toString())
+                    if (batch.eos) { break }
+                    def arrow = new ArrowStreamReader(new 
ByteArrayInputStream(batch.rows), allocator)
+                    try { while (arrow.loadNextBatch()) { rows += 
arrow.vectorSchemaRoot.rowCount } }
+                    finally { arrow.close() }
+                }
+            } finally { client.closeScanner(new 
TScanCloseParams().setContextId(opened.contextId)) }
+            assertEquals(2L, rows)
+        } finally { allocator.close(); socket.close() }
+
+    } finally {
+        try {
+            // Stop the origin first so its pooled metadata sockets cannot 
keep the proxy workers blocked.
+            try { writer.close() } catch (IOException ignored) { }
+            try { assertTrue(process.waitFor(60, TimeUnit.SECONDS), "Fixture 
did not stop; see ${logs}") }
+            finally { process.destroyForcibly(); reader.close() }

Review Comment:
   [P3] Let the fixture clean up its daemons before force-killing it
   
   If startup times out while Python is still starting or registering nodes, 
closing stdin cannot stop it because it has yet to reach the command loop. 
Those waits can outlast the extra 60 seconds. `destroyForcibly()` then skips 
the Python `finally` that stops the already launched FE and BE processes and 
removes the fixture directory. Send SIGTERM on the timeout path and give the 
existing cleanup handler time to finish before escalating.



##########
fe/fe-core/src/main/java/org/apache/doris/rpc/BackendServiceClient.java:
##########
@@ -46,20 +67,238 @@ 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() {
+        SystemInfoService system = Env.getCurrentSystemInfo();
+        Backend target = system.getBackend(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();
+        admittedTarget = target;
+        admission = shared;
+        String key = InternalRpcRequestSigner.getInstance().getPublicKey();
+        ListenableFuture<Void> work = 
Futures.transformAsync(isFrontendKeyRegistered(key), registered -> {
+            if (Boolean.TRUE.equals(registered)) {
+                return Futures.immediateVoidFuture();
+            }
+            if (registered == null) {
+                return Futures.immediateFailedFuture(new 
IllegalStateException("Backend authority is unreachable"));
+            }
+            // Blocking control-plane calls use a separate bounded executor, 
never gRPC's callbacks.
+            return Futures.transformAsync(REGISTRATION_EXECUTOR.submit(() -> {
+                authorityPublisher.publish(target.backendId());
+                return null;
+            }), unused -> Futures.transform(isFrontendKeyRegistered(key), 
acknowledged -> {
+                if (!Boolean.TRUE.equals(acknowledged)) {
+                    throw new IllegalStateException("Backend has not 
acknowledged frontend authority");
+                }
+                return null;
+            }, MoreExecutors.directExecutor()), 
MoreExecutors.directExecutor());
+        }, MoreExecutors.directExecutor());
+        // A registration may own a durable journal write. Interrupting it can 
terminate
+        // the FE. Bound each caller's view instead, and retain this shared 
work until it
+        // really finishes so timed-out callers cannot enqueue duplicate 
journal owners.
+        shared.completed.setFuture(work);
+        shared.completed.addListener(() -> {
+            if (hasFailed(shared.completed)) {
+                synchronized (this) {
+                    if (admission == shared) {
+                        admission = null;
+                    }
+                }
+            }
+        }, MoreExecutors.directExecutor());
+        return shared;
+    }
+
+    private static boolean hasFailed(ListenableFuture<?> future) {
+        try {
+            Futures.getDone(future);
+            return false;
+        } catch (Exception e) {
+            return true;
+        }
+    }
+
+    public ListenableFuture<Void> awaitExecutionAuthority() {
+        return Futures.withTimeout(admit(localTarget(), true).newWaiter(),
+                execPlanTimeout, TimeUnit.MILLISECONDS, ADMISSION_TIMER);
+    }
+
+    private <T> ListenableFuture<T> execute(String method, MessageLite 
request, long backendId, int clusterId,
+            Function<PBackendServiceGrpc.PBackendServiceFutureStub, 
ListenableFuture<T>> dispatch,
+            Function<T, Types.PStatus> status) {
+        // Preserve existing execution budgets: only fragment RPCs own this 
deadline.
+        // Other callers retain their existing wait policy; their admission is 
still bounded.
+        Deadline deadline = method.startsWith("exec_plan_fragment")
+                ? Deadline.after(execPlanTimeout, TimeUnit.MILLISECONDS) : 
null;
+        if (!internalRpc) {
+            // Remote authorities are explicitly configured by the destination 
administrator.
+            PBackendServiceGrpc.PBackendServiceFutureStub remote = backendId 
<= 0 ? stub
+                    : signedStub(method, request, backendId, clusterId);
+            return dispatch.apply(deadline == null ? remote : 
remote.withDeadline(deadline));
+        }
+        Target target = localTarget();
+        return executeAdmitted(method, request, target, deadline, dispatch, 
status, false);
+    }
+
+    private <T> ListenableFuture<T> executeAdmitted(String method, MessageLite 
request, Target target,
+            Deadline deadline, 
Function<PBackendServiceGrpc.PBackendServiceFutureStub, ListenableFuture<T>> 
dispatch,
+            Function<T, Types.PStatus> status, boolean repair) {
+        long remaining = deadline == null ? 
TimeUnit.MILLISECONDS.toNanos(execPlanTimeout)
+                : deadline.timeRemaining(TimeUnit.NANOSECONDS);
+        if (remaining <= 0) {
+            return 
Futures.immediateFailedFuture(io.grpc.Status.DEADLINE_EXCEEDED.asRuntimeException());
+        }
+        // Each waiter owns its deadline and cancellation. Neither can poison 
shared admission.
+        Admission owner = admit(target, repair);
+        remaining = deadline == null ? remaining : 
deadline.timeRemaining(TimeUnit.NANOSECONDS);
+        if (remaining <= 0) {
+            return 
Futures.immediateFailedFuture(io.grpc.Status.DEADLINE_EXCEEDED.asRuntimeException());
+        }
+        ListenableFuture<Void> ready = Futures.withTimeout(owner.newWaiter(), 
remaining, TimeUnit.NANOSECONDS,
+                ADMISSION_TIMER);
+        return Futures.transformAsync(ready, unused -> {

Review Comment:
   [P2] Cancel pending fragment dispatch when the coordinator aborts
   
   If worker A fails while worker B is waiting for authority, 
`PipelineExecutionTask` cancels B through a separate BE RPC and leaves B's 
dispatch future live. B has no query context yet, so 
`FragmentMgr::cancel_query` returns and the RPC acknowledges success. When 
admission completes, this callback sends the canceled fragment anyway. That can 
start one-phase work or leave a two-phase fragment prepared until BE cleanup. 
Tie pending prepare and start futures to coordinator cancellation and the query 
deadline. The client test that explicitly cancels a future does not exercise 
this coordinator path.



##########
threat-model.md:
##########
@@ -436,6 +436,62 @@ Out-of-scope adversaries:
 
 ## 4.8 Security properties the project provides
 
+**Signed frontend execution requests (defense in depth).** With BE
+`enable_internal_rpc_request_auth=true` (default, restart required), the
+`exec_plan_fragment`, `exec_plan_fragment_prepare`, `exec_plan_fragment_start`,
+`test_jdbc_connection`, `group_commit_insert`, `tablet_fetch_data` and
+`fold_constant_expr` receivers require an FE Ed25519 signature before queueing
+or initializing executable content. It binds the complete request, method,
+destination cluster and backend IDs, and timestamp. Ordinary RPC 
authorizations expire after
+60 seconds with at most 30 seconds of future clock skew; retries within that
+window are allowed. The shared cluster token is not the signing key.
+
+Each FE persists its private signing identity in its metadata directory with
+owner-only permissions and atomic replacement. Keep this file in FE metadata
+backups. The separate `.pub` file contains only the public key. Public keys
+follow the existing master-heartbeat authority; the network-isolation and
+private-RPC transport requirements for that control plane still apply. An FE
+registers its full membership identity and actual RPC endpoint with the master.
+The master independently verifies the endpoint and journals the identity before
+acknowledging it. In-flight responses from replaced identities cannot overwrite
+new registrations. Master epoch and snapshot sequence fence delayed worker 
heartbeats.
+
+Management listeners do not wait for worker availability. Before each target's
+first local executable request, the sender obtains a positive authority 
acknowledgment;
+missing publication is repaired through the master. Shared admission has 
bounded
+resources and each caller retains its own cancellation and overall deadline. 
Only
+an explicit pre-execution registration-required response permits one repair 
retry.
+Optional handshake fields preserve older-worker compatibility. The receiver 
reads
+one immutable membership and destination snapshot per request, outside the 
writer lock.
+
+Exported `_query_plan` scanner capabilities authenticate the exact FE-issued
+legacy Thrift prefix with a bounded, versioned authorization trailer. The 
payload
+is stored once; older readers retain the original plan fields. The backend 
Thrift
+listener reserves 4 KiB above its configured message budget for the trailer's 
encoded
+overhead. Upgrade BEs first to obtain this reserve. Older BE transports need 
their
+`thrift_max_message_size` increased by 4 KiB and a restart before consuming 
newly
+issued capabilities at the previous size boundary. Issuance admits every 
advertised
+replica after releasing metadata locks.
+Capability lifetime follows the existing snapshot/split contract rather than a 
new
+wall-clock cutoff: connectors can persist a plan for delayed opens and 
checkpoint
+recovery. A normal FE restart retains its identity and those capabilities. 
Removing
+the issuer's trusted key revokes them; normal tablet snapshot retention still 
applies.
+Enforcing receivers also accept the preceding signed-envelope format during 
upgrades.
+
+For a BE-first upgrade, explicitly disable enforcement on upgraded BEs until
+all FEs can sign and publish their keys, then restart BEs with enforcement

Review Comment:
   [P2] Account for saved unsigned scanner plans before restoring enforcement
   
   The previous FE exported unsigned plans, and scanner clients can reuse the 
same plan across tablet opens or checkpoint recovery. Following this sequence 
rejects those existing plans as soon as BE enforcement resumes, even if all 
upgraded FEs can sign new ones. Document that operators must drain or 
deliberately re-export legacy plans before restoring enforcement, and explain 
that re-exporting can select a different snapshot.



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