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


##########
be/src/service/internal_service.cpp:
##########
@@ -1237,131 +1244,306 @@ void 
PInternalServiceImpl::_get_column_ids_by_tablet_ids(
     response->mutable_status()->set_status_code(TStatusCode::OK);
 }
 
-template <class RPCResponse>
-struct AsyncRPCContext {
-    RPCResponse response;
-    brpc::Controller cntl;
-    brpc::CallId cid;
+namespace {
+
+struct SchemaRpc {
+    PFetchRemoteSchemaRequest request;
+    PFetchRemoteSchemaResponse response;
+    brpc::Controller controller;
+    std::optional<brpc::CallId> call_id;
 };
 
-void 
PInternalService::fetch_remote_tablet_schema(google::protobuf::RpcController* 
controller,
-                                                  const 
PFetchRemoteSchemaRequest* request,
-                                                  PFetchRemoteSchemaResponse* 
response,
-                                                  google::protobuf::Closure* 
done) {
-    bool ret = _heavy_work_pool.try_offer([request, response, done]() {
-        brpc::ClosureGuard closure_guard(done);
-        Status st = Status::OK();
-        std::shared_ptr<MemTrackerLimiter> mem_tracker = 
MemTrackerLimiter::create_shared(
-                MemTrackerLimiter::Type::OTHER,
-                fmt::format("InternalService::fetch_remote_tablet_schema"));
-        SCOPED_ATTACH_TASK(mem_tracker);
-        if (request->is_coordinator()) {
-            // Spawn rpc request to none coordinator nodes, and finally merge 
them all
-            PFetchRemoteSchemaRequest remote_request(*request);
-            // set it none coordinator to get merged schema
-            remote_request.set_is_coordinator(false);
-            using PFetchRemoteTabletSchemaRpcContext = 
AsyncRPCContext<PFetchRemoteSchemaResponse>;
-            std::vector<PFetchRemoteTabletSchemaRpcContext> rpc_contexts(
-                    request->tablet_location_size());
-            for (int i = 0; i < request->tablet_location_size(); ++i) {
-                std::string host = request->tablet_location(i).host();
-                int32_t brpc_port = request->tablet_location(i).brpc_port();
-                std::shared_ptr<PBackendService_Stub> stub(
-                        
ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
-                                host, brpc_port));
-                if (stub == nullptr) {
-                    LOG(WARNING) << "Failed to init rpc to " << host << ":" << 
brpc_port;
-                    st = Status::InternalError("Failed to init rpc to {}:{}", 
host, brpc_port);
-                    continue;
-                }
-                rpc_contexts[i].cid = rpc_contexts[i].cntl.call_id();
-                
rpc_contexts[i].cntl.set_timeout_ms(config::fetch_remote_schema_rpc_timeout_ms);
-                stub->fetch_remote_tablet_schema(&rpc_contexts[i].cntl, 
&remote_request,
-                                                 &rpc_contexts[i].response, 
brpc::DoNothing());
+bool has_required_tablet_coverage(const SchemaRpc& rpc) {
+    const auto& location = rpc.request.tablet_location(0);
+    return location.tablet_visible_version_size() == 0 ||
+           (rpc.response.has_tablet_coverage() && 
rpc.response.tablet_versions_verified());
+}
+
+bool has_legacy_remote_schema(const SchemaRpc& rpc) {
+    const auto& location = rpc.request.tablet_location(0);
+    return location.tablet_visible_version_size() > 0 &&
+           !rpc.response.has_tablet_versions_verified() && 
rpc.response.has_merged_schema();
+}
+
+Status check_remote_tablet_coverage(const std::vector<SchemaRpc>& rpcs,
+                                    std::unordered_set<int64_t>& 
legacy_tablets) {
+    // Healthy requests do not need per-tablet sets.
+    if (std::ranges::none_of(rpcs, [](const auto& rpc) {
+            return !has_required_tablet_coverage(rpc) ||
+                   rpc.response.tablet_coverage().missing_tablet_id_size() > 0;
+        })) {
+        return Status::OK();
+    }
+    std::unordered_set<int64_t> uncovered;
+    std::unordered_set<int64_t> covered;
+    for (const auto& rpc : rpcs) {
+        const auto& assigned = rpc.request.tablet_location(0).tablet_id();
+        const bool legacy = has_legacy_remote_schema(rpc);
+        if (!has_required_tablet_coverage(rpc) && !legacy) {
+            uncovered.insert(assigned.begin(), assigned.end());
+            continue;
+        }
+        if (!rpc.response.has_tablet_coverage() && !legacy) {
+            continue;
+        }
+        const auto& reported_missing = 
rpc.response.tablet_coverage().missing_tablet_id();
+        std::unordered_map<int64_t, bool> missing;
+        for (int64_t tablet_id : reported_missing) {
+            missing.try_emplace(tablet_id, false);
+        }
+        for (int64_t tablet_id : assigned) {
+            if (auto it = missing.find(tablet_id); it != missing.end()) {
+                it->second = true;
+                uncovered.insert(tablet_id);
+            } else if (legacy) {
+                legacy_tablets.insert(tablet_id);
+            } else if (rpc.response.has_merged_schema()) {
+                covered.insert(tablet_id);
             }
-            std::vector<TabletSchemaSPtr> schemas;
-            for (auto& rpc_context : rpc_contexts) {
-                brpc::Join(rpc_context.cid);
-                if (!st.ok()) {
-                    // make sure all flying rpc request is joined
+        }
+        for (const auto& [tablet_id, assigned_here] : missing) {
+            if (!assigned_here) {
+                return Status::InternalError("Worker reported an unassigned 
tablet {}", tablet_id);
+            }
+        }
+    }
+    for (int64_t tablet_id : covered) {
+        uncovered.erase(tablet_id);
+        legacy_tablets.erase(tablet_id);
+    }
+    // A legacy reply can replace missing version support. Reported missing 
tablets or an
+    // explicit negative verification still require another worker to prove 
coverage.
+    if (!uncovered.empty()) {
+        return Status::Error<ErrorCode::TABLE_NOT_FOUND>(
+                "Extended DESCRIBE could not read tablet {} ({} uncovered 
tablets)",
+                *std::min_element(uncovered.begin(), uncovered.end()), 
uncovered.size());
+    }
+    return Status::OK();
+}
+
+void append_remote_variant_schema(const PFetchRemoteSchemaResponse& response,
+                                  std::vector<TabletSchemaSPtr>& schemas) {
+    auto schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(response.merged_schema());
+    schemas.push_back(std::move(schema));
+}
+
+Status collect_remote_variant_schemas(const PFetchRemoteSchemaRequest& request,
+                                      std::vector<TabletSchemaSPtr>& schemas,
+                                      bool& versions_verified) {
+    std::vector<SchemaRpc> rpcs(request.tablet_location_size());
+    auto join_rpcs = [&] {
+        for (auto& rpc : rpcs) {
+            if (rpc.call_id.has_value()) {
+                brpc::Join(*rpc.call_id);
+                rpc.call_id.reset();
+            }
+        }
+    };
+    // Controllers, responses and the request must survive all dispatched RPCs 
on error too.
+    Defer join_on_exit {join_rpcs};
+    for (int i = 0; i < request.tablet_location_size(); ++i) {
+        const auto& location = request.tablet_location(i);
+        auto stub = 
ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
+                location.host(), location.brpc_port());
+        if (stub == nullptr) {
+            return Status::NetworkError("Failed to initialize remote schema 
RPC to {}:{}",
+                                        location.host(), location.brpc_port());
+        }
+        auto& rpc = rpcs[i];
+        rpc.request.set_is_coordinator(false);
+        rpc.request.set_report_tablet_coverage(true);
+        *rpc.request.add_tablet_location() = location;
+        
rpc.controller.set_timeout_ms(config::fetch_remote_schema_rpc_timeout_ms);
+        stub->fetch_remote_tablet_schema(&rpc.controller, &rpc.request, 
&rpc.response,
+                                         brpc::DoNothing());
+        // Preparing the callback can throw before BRPC takes ownership of the 
call.
+        rpc.call_id = rpc.controller.call_id();
+    }
+    join_rpcs();
+    for (const auto& rpc : rpcs) {
+        if (rpc.controller.Failed()) {
+            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
+                    rpc.controller.remote_side());
+            return Status::NetworkError("Remote schema RPC failed: {}", 
rpc.controller.ErrorText());
+        }
+        if (!rpc.response.has_status()) {
+            return Status::InternalError("Remote schema RPC did not return a 
status");
+        }
+        if (rpc.response.status().status_code() != 0) {
+            return Status::create(rpc.response.status());
+        }
+        if (!has_required_tablet_coverage(rpc)) {
+            continue;
+        }
+        if (!rpc.response.has_merged_schema()) {
+            // A new worker with no local copies can still contribute a 
coverage report.
+            const int missing = 
rpc.response.tablet_coverage().missing_tablet_id_size();
+            if (missing > 0 && missing == 
rpc.request.tablet_location(0).tablet_id_size()) {
+                continue;
+            }
+            return Status::InternalError("Remote schema RPC did not return a 
merged schema");
+        }
+        append_remote_variant_schema(rpc.response, schemas);
+    }
+    std::unordered_set<int64_t> legacy_tablets;
+    RETURN_IF_ERROR(check_remote_tablet_coverage(rpcs, legacy_tablets));
+    if (!legacy_tablets.empty()) {
+        versions_verified = false;
+        for (const auto& rpc : rpcs) {
+            if (has_legacy_remote_schema(rpc) &&
+                std::ranges::any_of(rpc.request.tablet_location(0).tablet_id(),
+                                    [&](int64_t id) { return 
legacy_tablets.contains(id); })) {
+                append_remote_variant_schema(rpc.response, schemas);
+            }
+        }
+    }
+    return Status::OK();
+}
+
+Result<std::vector<RowsetSharedPtr>> capture_desc_rowsets(const 
BaseTabletSPtr& tablet,
+                                                          int64_t 
visible_version) {
+    if (visible_version < 0) {
+        return tablet->get_snapshot_rowset();
+    }
+    if (auto cloud_tablet = std::dynamic_pointer_cast<CloudTablet>(tablet)) {
+        // The cached tablet might have been loaded before the partition 
committed this version.
+        // sync_rowsets skips the MS RPC when the requested version is already 
available locally.
+        SyncOptions options;
+        options.query_version = visible_version;
+        RETURN_IF_ERROR_RESULT(cloud_tablet->sync_rowsets(options));
+    }
+    std::shared_lock lock(tablet->get_header_lock());
+    if (tablet->max_version_unlocked() < visible_version) {
+        return ResultError(Status::Error<ErrorCode::VERSION_NOT_EXIST>(
+                "Tablet {} is behind visible version {}", tablet->tablet_id(), 
visible_version));
+    }
+    auto captured = tablet->capture_consistent_rowsets_unlocked(Version(0, 
visible_version),
+                                                                
CaptureRowsetOps {});
+    if (!captured.has_value()) {
+        return ResultError(std::move(captured.error()));
+    }
+    return std::move(captured.value().rowsets);
+}
+
+Status collect_local_variant_schemas(const PFetchRemoteSchemaRequest& request,
+                                     PFetchRemoteSchemaResponse* response,
+                                     std::vector<TabletSchemaSPtr>& schemas) {
+    const auto backend = BackendOptions::get_local_backend();
+    for (const auto& location : request.tablet_location()) {
+        if (backend.host != location.host() || config::brpc_port != 
location.brpc_port()) {
+            continue;
+        }
+        auto* coverage =
+                request.report_tablet_coverage() ? 
response->mutable_tablet_coverage() : nullptr;
+        for (int i = 0; i < location.tablet_id_size(); ++i) {
+            int64_t tablet_id = location.tablet_id(i);
+            auto tablet = ExecEnv::get_tablet(tablet_id);
+            if (!tablet.has_value()) {
+                // Local placement can be stale while another replica still 
covers this tablet.
+                // A Cloud lookup or file-read failure does not establish that 
a replica is absent.
+                if (coverage != nullptr && !config::is_cloud_mode() &&
+                    tablet.error().is<ErrorCode::TABLE_NOT_FOUND>()) {
+                    coverage->add_missing_tablet_id(tablet_id);
                     continue;
                 }
-                if (rpc_context.cntl.Failed()) {
-                    LOG(WARNING) << "fetch_remote_tablet_schema rpc err:"
-                                 << rpc_context.cntl.ErrorText();
-                    
ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
-                            rpc_context.cntl.remote_side());
-                    st = Status::InternalError("fetch_remote_tablet_schema rpc 
err: {}",
-                                               rpc_context.cntl.ErrorText());
-                }
-                if (rpc_context.response.status().status_code() != 0) {
-                    st = Status::create(rpc_context.response.status());
-                }
-                if (rpc_context.response.has_merged_schema()) {
-                    TabletSchemaSPtr schema = std::make_shared<TabletSchema>();
-                    schema->init_from_pb(rpc_context.response.merged_schema());
-                    schemas.push_back(schema);
-                }
+                return tablet.error().prepend(
+                        fmt::format("Extended DESCRIBE could not get tablet 
{}. ", tablet_id));
             }
-            if (!schemas.empty() && st.ok()) {
-                // merge all
-                TabletSchemaSPtr merged_schema;
-                st = variant_util::get_least_common_schema(schemas, nullptr, 
merged_schema);
-                if (!st.ok()) {
-                    LOG(WARNING) << "Failed to get least common schema: " << 
st.to_string();
-                    st = Status::InternalError("Failed to get least common 
schema: {}",
-                                               st.to_string());
+            int64_t version = location.tablet_visible_version_size() == 0
+                                      ? -1
+                                      : location.tablet_visible_version(i);
+            auto rowsets = capture_desc_rowsets(tablet.value(), version);
+            if (!rowsets.has_value()) {
+                // A replica which has not caught up cannot prove coverage for 
this tablet.
+                if (coverage != nullptr && !config::is_cloud_mode() &&
+                    rowsets.error().is<ErrorCode::VERSION_NOT_EXIST>()) {

Review Comment:
   [P2] Let a healthy replica cover a hole in another replica’s versions
   
   A live duplicate-key replica can contain version 3 after missing version 2. 
The max-version check passes for a request through version 3, but rowset 
capture returns the version graph’s internal error for the gap. This branch 
only reports VERSION_NOT_EXIST as missing, so the coordinator aborts before it 
can use another replica that has the full version range. Report a proven 
missing local version range through tablet coverage and keep actual metadata 
and I/O errors fatal. The lagging-replica test currently exercises only the 
case where the local maximum is below the requested version.



##########
be/src/service/internal_service.cpp:
##########
@@ -1237,131 +1244,306 @@ void 
PInternalServiceImpl::_get_column_ids_by_tablet_ids(
     response->mutable_status()->set_status_code(TStatusCode::OK);
 }
 
-template <class RPCResponse>
-struct AsyncRPCContext {
-    RPCResponse response;
-    brpc::Controller cntl;
-    brpc::CallId cid;
+namespace {
+
+struct SchemaRpc {
+    PFetchRemoteSchemaRequest request;
+    PFetchRemoteSchemaResponse response;
+    brpc::Controller controller;
+    std::optional<brpc::CallId> call_id;
 };
 
-void 
PInternalService::fetch_remote_tablet_schema(google::protobuf::RpcController* 
controller,
-                                                  const 
PFetchRemoteSchemaRequest* request,
-                                                  PFetchRemoteSchemaResponse* 
response,
-                                                  google::protobuf::Closure* 
done) {
-    bool ret = _heavy_work_pool.try_offer([request, response, done]() {
-        brpc::ClosureGuard closure_guard(done);
-        Status st = Status::OK();
-        std::shared_ptr<MemTrackerLimiter> mem_tracker = 
MemTrackerLimiter::create_shared(
-                MemTrackerLimiter::Type::OTHER,
-                fmt::format("InternalService::fetch_remote_tablet_schema"));
-        SCOPED_ATTACH_TASK(mem_tracker);
-        if (request->is_coordinator()) {
-            // Spawn rpc request to none coordinator nodes, and finally merge 
them all
-            PFetchRemoteSchemaRequest remote_request(*request);
-            // set it none coordinator to get merged schema
-            remote_request.set_is_coordinator(false);
-            using PFetchRemoteTabletSchemaRpcContext = 
AsyncRPCContext<PFetchRemoteSchemaResponse>;
-            std::vector<PFetchRemoteTabletSchemaRpcContext> rpc_contexts(
-                    request->tablet_location_size());
-            for (int i = 0; i < request->tablet_location_size(); ++i) {
-                std::string host = request->tablet_location(i).host();
-                int32_t brpc_port = request->tablet_location(i).brpc_port();
-                std::shared_ptr<PBackendService_Stub> stub(
-                        
ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
-                                host, brpc_port));
-                if (stub == nullptr) {
-                    LOG(WARNING) << "Failed to init rpc to " << host << ":" << 
brpc_port;
-                    st = Status::InternalError("Failed to init rpc to {}:{}", 
host, brpc_port);
-                    continue;
-                }
-                rpc_contexts[i].cid = rpc_contexts[i].cntl.call_id();
-                
rpc_contexts[i].cntl.set_timeout_ms(config::fetch_remote_schema_rpc_timeout_ms);
-                stub->fetch_remote_tablet_schema(&rpc_contexts[i].cntl, 
&remote_request,
-                                                 &rpc_contexts[i].response, 
brpc::DoNothing());
+bool has_required_tablet_coverage(const SchemaRpc& rpc) {
+    const auto& location = rpc.request.tablet_location(0);
+    return location.tablet_visible_version_size() == 0 ||
+           (rpc.response.has_tablet_coverage() && 
rpc.response.tablet_versions_verified());
+}
+
+bool has_legacy_remote_schema(const SchemaRpc& rpc) {
+    const auto& location = rpc.request.tablet_location(0);
+    return location.tablet_visible_version_size() > 0 &&
+           !rpc.response.has_tablet_versions_verified() && 
rpc.response.has_merged_schema();
+}
+
+Status check_remote_tablet_coverage(const std::vector<SchemaRpc>& rpcs,
+                                    std::unordered_set<int64_t>& 
legacy_tablets) {
+    // Healthy requests do not need per-tablet sets.
+    if (std::ranges::none_of(rpcs, [](const auto& rpc) {
+            return !has_required_tablet_coverage(rpc) ||
+                   rpc.response.tablet_coverage().missing_tablet_id_size() > 0;
+        })) {
+        return Status::OK();
+    }
+    std::unordered_set<int64_t> uncovered;
+    std::unordered_set<int64_t> covered;
+    for (const auto& rpc : rpcs) {
+        const auto& assigned = rpc.request.tablet_location(0).tablet_id();
+        const bool legacy = has_legacy_remote_schema(rpc);
+        if (!has_required_tablet_coverage(rpc) && !legacy) {
+            uncovered.insert(assigned.begin(), assigned.end());
+            continue;
+        }
+        if (!rpc.response.has_tablet_coverage() && !legacy) {
+            continue;
+        }
+        const auto& reported_missing = 
rpc.response.tablet_coverage().missing_tablet_id();
+        std::unordered_map<int64_t, bool> missing;
+        for (int64_t tablet_id : reported_missing) {
+            missing.try_emplace(tablet_id, false);
+        }
+        for (int64_t tablet_id : assigned) {
+            if (auto it = missing.find(tablet_id); it != missing.end()) {
+                it->second = true;
+                uncovered.insert(tablet_id);
+            } else if (legacy) {
+                legacy_tablets.insert(tablet_id);
+            } else if (rpc.response.has_merged_schema()) {
+                covered.insert(tablet_id);
             }
-            std::vector<TabletSchemaSPtr> schemas;
-            for (auto& rpc_context : rpc_contexts) {
-                brpc::Join(rpc_context.cid);
-                if (!st.ok()) {
-                    // make sure all flying rpc request is joined
+        }
+        for (const auto& [tablet_id, assigned_here] : missing) {
+            if (!assigned_here) {
+                return Status::InternalError("Worker reported an unassigned 
tablet {}", tablet_id);
+            }
+        }
+    }
+    for (int64_t tablet_id : covered) {
+        uncovered.erase(tablet_id);
+        legacy_tablets.erase(tablet_id);
+    }
+    // A legacy reply can replace missing version support. Reported missing 
tablets or an
+    // explicit negative verification still require another worker to prove 
coverage.
+    if (!uncovered.empty()) {
+        return Status::Error<ErrorCode::TABLE_NOT_FOUND>(
+                "Extended DESCRIBE could not read tablet {} ({} uncovered 
tablets)",
+                *std::min_element(uncovered.begin(), uncovered.end()), 
uncovered.size());
+    }
+    return Status::OK();
+}
+
+void append_remote_variant_schema(const PFetchRemoteSchemaResponse& response,
+                                  std::vector<TabletSchemaSPtr>& schemas) {
+    auto schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(response.merged_schema());
+    schemas.push_back(std::move(schema));
+}
+
+Status collect_remote_variant_schemas(const PFetchRemoteSchemaRequest& request,
+                                      std::vector<TabletSchemaSPtr>& schemas,
+                                      bool& versions_verified) {
+    std::vector<SchemaRpc> rpcs(request.tablet_location_size());
+    auto join_rpcs = [&] {
+        for (auto& rpc : rpcs) {
+            if (rpc.call_id.has_value()) {
+                brpc::Join(*rpc.call_id);
+                rpc.call_id.reset();
+            }
+        }
+    };
+    // Controllers, responses and the request must survive all dispatched RPCs 
on error too.
+    Defer join_on_exit {join_rpcs};
+    for (int i = 0; i < request.tablet_location_size(); ++i) {
+        const auto& location = request.tablet_location(i);
+        auto stub = 
ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
+                location.host(), location.brpc_port());
+        if (stub == nullptr) {
+            return Status::NetworkError("Failed to initialize remote schema 
RPC to {}:{}",
+                                        location.host(), location.brpc_port());
+        }
+        auto& rpc = rpcs[i];
+        rpc.request.set_is_coordinator(false);
+        rpc.request.set_report_tablet_coverage(true);
+        *rpc.request.add_tablet_location() = location;
+        
rpc.controller.set_timeout_ms(config::fetch_remote_schema_rpc_timeout_ms);
+        stub->fetch_remote_tablet_schema(&rpc.controller, &rpc.request, 
&rpc.response,
+                                         brpc::DoNothing());
+        // Preparing the callback can throw before BRPC takes ownership of the 
call.
+        rpc.call_id = rpc.controller.call_id();
+    }
+    join_rpcs();
+    for (const auto& rpc : rpcs) {
+        if (rpc.controller.Failed()) {
+            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
+                    rpc.controller.remote_side());
+            return Status::NetworkError("Remote schema RPC failed: {}", 
rpc.controller.ErrorText());
+        }
+        if (!rpc.response.has_status()) {
+            return Status::InternalError("Remote schema RPC did not return a 
status");
+        }
+        if (rpc.response.status().status_code() != 0) {
+            return Status::create(rpc.response.status());
+        }
+        if (!has_required_tablet_coverage(rpc)) {
+            continue;
+        }
+        if (!rpc.response.has_merged_schema()) {
+            // A new worker with no local copies can still contribute a 
coverage report.
+            const int missing = 
rpc.response.tablet_coverage().missing_tablet_id_size();
+            if (missing > 0 && missing == 
rpc.request.tablet_location(0).tablet_id_size()) {
+                continue;
+            }
+            return Status::InternalError("Remote schema RPC did not return a 
merged schema");
+        }
+        append_remote_variant_schema(rpc.response, schemas);
+    }
+    std::unordered_set<int64_t> legacy_tablets;
+    RETURN_IF_ERROR(check_remote_tablet_coverage(rpcs, legacy_tablets));
+    if (!legacy_tablets.empty()) {
+        versions_verified = false;
+        for (const auto& rpc : rpcs) {
+            if (has_legacy_remote_schema(rpc) &&
+                std::ranges::any_of(rpc.request.tablet_location(0).tablet_id(),
+                                    [&](int64_t id) { return 
legacy_tablets.contains(id); })) {
+                append_remote_variant_schema(rpc.response, schemas);
+            }
+        }
+    }
+    return Status::OK();
+}
+
+Result<std::vector<RowsetSharedPtr>> capture_desc_rowsets(const 
BaseTabletSPtr& tablet,
+                                                          int64_t 
visible_version) {
+    if (visible_version < 0) {
+        return tablet->get_snapshot_rowset();
+    }
+    if (auto cloud_tablet = std::dynamic_pointer_cast<CloudTablet>(tablet)) {
+        // The cached tablet might have been loaded before the partition 
committed this version.
+        // sync_rowsets skips the MS RPC when the requested version is already 
available locally.
+        SyncOptions options;
+        options.query_version = visible_version;
+        RETURN_IF_ERROR_RESULT(cloud_tablet->sync_rowsets(options));
+    }
+    std::shared_lock lock(tablet->get_header_lock());
+    if (tablet->max_version_unlocked() < visible_version) {
+        return ResultError(Status::Error<ErrorCode::VERSION_NOT_EXIST>(
+                "Tablet {} is behind visible version {}", tablet->tablet_id(), 
visible_version));
+    }
+    auto captured = tablet->capture_consistent_rowsets_unlocked(Version(0, 
visible_version),
+                                                                
CaptureRowsetOps {});
+    if (!captured.has_value()) {
+        return ResultError(std::move(captured.error()));
+    }
+    return std::move(captured.value().rowsets);
+}
+
+Status collect_local_variant_schemas(const PFetchRemoteSchemaRequest& request,
+                                     PFetchRemoteSchemaResponse* response,
+                                     std::vector<TabletSchemaSPtr>& schemas) {
+    const auto backend = BackendOptions::get_local_backend();
+    for (const auto& location : request.tablet_location()) {
+        if (backend.host != location.host() || config::brpc_port != 
location.brpc_port()) {
+            continue;
+        }
+        auto* coverage =
+                request.report_tablet_coverage() ? 
response->mutable_tablet_coverage() : nullptr;
+        for (int i = 0; i < location.tablet_id_size(); ++i) {
+            int64_t tablet_id = location.tablet_id(i);
+            auto tablet = ExecEnv::get_tablet(tablet_id);
+            if (!tablet.has_value()) {
+                // Local placement can be stale while another replica still 
covers this tablet.
+                // A Cloud lookup or file-read failure does not establish that 
a replica is absent.
+                if (coverage != nullptr && !config::is_cloud_mode() &&

Review Comment:
   [P2] Preserve old coordinator recovery when a local replica is absent
   
   An old coordinator sends an unversioned request with no coverage flag. If a 
listed shared-nothing replica has disappeared, an upgraded worker now returns 
TABLE_NOT_FOUND because coverage is null. The old coordinator fails the entire 
fetch even when another worker returns the tablet’s schema. Before the upgrade 
the worker skipped the absent copy, allowing the coordinator to merge the 
healthy reply. Preserve that missing-copy behavior for the legacy request and 
keep strict coverage reporting for capable coordinators.



##########
be/src/service/internal_service.cpp:
##########
@@ -1237,131 +1244,306 @@ void 
PInternalServiceImpl::_get_column_ids_by_tablet_ids(
     response->mutable_status()->set_status_code(TStatusCode::OK);
 }
 
-template <class RPCResponse>
-struct AsyncRPCContext {
-    RPCResponse response;
-    brpc::Controller cntl;
-    brpc::CallId cid;
+namespace {
+
+struct SchemaRpc {
+    PFetchRemoteSchemaRequest request;
+    PFetchRemoteSchemaResponse response;
+    brpc::Controller controller;
+    std::optional<brpc::CallId> call_id;
 };
 
-void 
PInternalService::fetch_remote_tablet_schema(google::protobuf::RpcController* 
controller,
-                                                  const 
PFetchRemoteSchemaRequest* request,
-                                                  PFetchRemoteSchemaResponse* 
response,
-                                                  google::protobuf::Closure* 
done) {
-    bool ret = _heavy_work_pool.try_offer([request, response, done]() {
-        brpc::ClosureGuard closure_guard(done);
-        Status st = Status::OK();
-        std::shared_ptr<MemTrackerLimiter> mem_tracker = 
MemTrackerLimiter::create_shared(
-                MemTrackerLimiter::Type::OTHER,
-                fmt::format("InternalService::fetch_remote_tablet_schema"));
-        SCOPED_ATTACH_TASK(mem_tracker);
-        if (request->is_coordinator()) {
-            // Spawn rpc request to none coordinator nodes, and finally merge 
them all
-            PFetchRemoteSchemaRequest remote_request(*request);
-            // set it none coordinator to get merged schema
-            remote_request.set_is_coordinator(false);
-            using PFetchRemoteTabletSchemaRpcContext = 
AsyncRPCContext<PFetchRemoteSchemaResponse>;
-            std::vector<PFetchRemoteTabletSchemaRpcContext> rpc_contexts(
-                    request->tablet_location_size());
-            for (int i = 0; i < request->tablet_location_size(); ++i) {
-                std::string host = request->tablet_location(i).host();
-                int32_t brpc_port = request->tablet_location(i).brpc_port();
-                std::shared_ptr<PBackendService_Stub> stub(
-                        
ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
-                                host, brpc_port));
-                if (stub == nullptr) {
-                    LOG(WARNING) << "Failed to init rpc to " << host << ":" << 
brpc_port;
-                    st = Status::InternalError("Failed to init rpc to {}:{}", 
host, brpc_port);
-                    continue;
-                }
-                rpc_contexts[i].cid = rpc_contexts[i].cntl.call_id();
-                
rpc_contexts[i].cntl.set_timeout_ms(config::fetch_remote_schema_rpc_timeout_ms);
-                stub->fetch_remote_tablet_schema(&rpc_contexts[i].cntl, 
&remote_request,
-                                                 &rpc_contexts[i].response, 
brpc::DoNothing());
+bool has_required_tablet_coverage(const SchemaRpc& rpc) {
+    const auto& location = rpc.request.tablet_location(0);
+    return location.tablet_visible_version_size() == 0 ||
+           (rpc.response.has_tablet_coverage() && 
rpc.response.tablet_versions_verified());
+}
+
+bool has_legacy_remote_schema(const SchemaRpc& rpc) {
+    const auto& location = rpc.request.tablet_location(0);
+    return location.tablet_visible_version_size() > 0 &&
+           !rpc.response.has_tablet_versions_verified() && 
rpc.response.has_merged_schema();
+}
+
+Status check_remote_tablet_coverage(const std::vector<SchemaRpc>& rpcs,
+                                    std::unordered_set<int64_t>& 
legacy_tablets) {
+    // Healthy requests do not need per-tablet sets.
+    if (std::ranges::none_of(rpcs, [](const auto& rpc) {
+            return !has_required_tablet_coverage(rpc) ||
+                   rpc.response.tablet_coverage().missing_tablet_id_size() > 0;
+        })) {
+        return Status::OK();
+    }
+    std::unordered_set<int64_t> uncovered;
+    std::unordered_set<int64_t> covered;
+    for (const auto& rpc : rpcs) {
+        const auto& assigned = rpc.request.tablet_location(0).tablet_id();
+        const bool legacy = has_legacy_remote_schema(rpc);
+        if (!has_required_tablet_coverage(rpc) && !legacy) {
+            uncovered.insert(assigned.begin(), assigned.end());
+            continue;
+        }
+        if (!rpc.response.has_tablet_coverage() && !legacy) {
+            continue;
+        }
+        const auto& reported_missing = 
rpc.response.tablet_coverage().missing_tablet_id();
+        std::unordered_map<int64_t, bool> missing;
+        for (int64_t tablet_id : reported_missing) {
+            missing.try_emplace(tablet_id, false);
+        }
+        for (int64_t tablet_id : assigned) {
+            if (auto it = missing.find(tablet_id); it != missing.end()) {
+                it->second = true;
+                uncovered.insert(tablet_id);
+            } else if (legacy) {
+                legacy_tablets.insert(tablet_id);
+            } else if (rpc.response.has_merged_schema()) {
+                covered.insert(tablet_id);
             }
-            std::vector<TabletSchemaSPtr> schemas;
-            for (auto& rpc_context : rpc_contexts) {
-                brpc::Join(rpc_context.cid);
-                if (!st.ok()) {
-                    // make sure all flying rpc request is joined
+        }
+        for (const auto& [tablet_id, assigned_here] : missing) {
+            if (!assigned_here) {
+                return Status::InternalError("Worker reported an unassigned 
tablet {}", tablet_id);
+            }
+        }
+    }
+    for (int64_t tablet_id : covered) {
+        uncovered.erase(tablet_id);
+        legacy_tablets.erase(tablet_id);
+    }
+    // A legacy reply can replace missing version support. Reported missing 
tablets or an
+    // explicit negative verification still require another worker to prove 
coverage.
+    if (!uncovered.empty()) {
+        return Status::Error<ErrorCode::TABLE_NOT_FOUND>(
+                "Extended DESCRIBE could not read tablet {} ({} uncovered 
tablets)",
+                *std::min_element(uncovered.begin(), uncovered.end()), 
uncovered.size());
+    }
+    return Status::OK();
+}
+
+void append_remote_variant_schema(const PFetchRemoteSchemaResponse& response,
+                                  std::vector<TabletSchemaSPtr>& schemas) {
+    auto schema = std::make_shared<TabletSchema>();
+    schema->init_from_pb(response.merged_schema());
+    schemas.push_back(std::move(schema));
+}
+
+Status collect_remote_variant_schemas(const PFetchRemoteSchemaRequest& request,
+                                      std::vector<TabletSchemaSPtr>& schemas,
+                                      bool& versions_verified) {
+    std::vector<SchemaRpc> rpcs(request.tablet_location_size());
+    auto join_rpcs = [&] {
+        for (auto& rpc : rpcs) {
+            if (rpc.call_id.has_value()) {
+                brpc::Join(*rpc.call_id);
+                rpc.call_id.reset();
+            }
+        }
+    };
+    // Controllers, responses and the request must survive all dispatched RPCs 
on error too.
+    Defer join_on_exit {join_rpcs};
+    for (int i = 0; i < request.tablet_location_size(); ++i) {
+        const auto& location = request.tablet_location(i);
+        auto stub = 
ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
+                location.host(), location.brpc_port());
+        if (stub == nullptr) {
+            return Status::NetworkError("Failed to initialize remote schema 
RPC to {}:{}",
+                                        location.host(), location.brpc_port());
+        }
+        auto& rpc = rpcs[i];
+        rpc.request.set_is_coordinator(false);
+        rpc.request.set_report_tablet_coverage(true);
+        *rpc.request.add_tablet_location() = location;
+        
rpc.controller.set_timeout_ms(config::fetch_remote_schema_rpc_timeout_ms);
+        stub->fetch_remote_tablet_schema(&rpc.controller, &rpc.request, 
&rpc.response,
+                                         brpc::DoNothing());
+        // Preparing the callback can throw before BRPC takes ownership of the 
call.
+        rpc.call_id = rpc.controller.call_id();
+    }
+    join_rpcs();
+    for (const auto& rpc : rpcs) {
+        if (rpc.controller.Failed()) {
+            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
+                    rpc.controller.remote_side());
+            return Status::NetworkError("Remote schema RPC failed: {}", 
rpc.controller.ErrorText());
+        }
+        if (!rpc.response.has_status()) {
+            return Status::InternalError("Remote schema RPC did not return a 
status");
+        }
+        if (rpc.response.status().status_code() != 0) {
+            return Status::create(rpc.response.status());
+        }
+        if (!has_required_tablet_coverage(rpc)) {
+            continue;
+        }
+        if (!rpc.response.has_merged_schema()) {
+            // A new worker with no local copies can still contribute a 
coverage report.
+            const int missing = 
rpc.response.tablet_coverage().missing_tablet_id_size();
+            if (missing > 0 && missing == 
rpc.request.tablet_location(0).tablet_id_size()) {
+                continue;
+            }
+            return Status::InternalError("Remote schema RPC did not return a 
merged schema");
+        }
+        append_remote_variant_schema(rpc.response, schemas);
+    }
+    std::unordered_set<int64_t> legacy_tablets;
+    RETURN_IF_ERROR(check_remote_tablet_coverage(rpcs, legacy_tablets));
+    if (!legacy_tablets.empty()) {
+        versions_verified = false;
+        for (const auto& rpc : rpcs) {
+            if (has_legacy_remote_schema(rpc) &&
+                std::ranges::any_of(rpc.request.tablet_location(0).tablet_id(),
+                                    [&](int64_t id) { return 
legacy_tablets.contains(id); })) {
+                append_remote_variant_schema(rpc.response, schemas);

Review Comment:
   [P2] Limit legacy schema fallback to tablets without verified coverage
   
   If an old worker has tablets A and B and a new worker verifies A at version 
2, legacy fallback is needed only for B. This appends the old worker’s combined 
schema for A and B, so a path from A at version 3 can still appear despite the 
verified read of A. The FE can return the compatible result when no fully 
verified result is available. Fetch only the unresolved tablets from the old 
worker before merging, and assert the returned paths in the mixed-worker test.



##########
be/src/exec/common/variant_util.cpp:
##########
@@ -1643,83 +1613,78 @@ bool generate_sub_column_info(const TabletSchema& 
schema, int32_t col_unique_id,
     return false;
 }
 
-TabletSchemaSPtr VariantCompactionUtil::calculate_variant_extended_schema(
-        const std::vector<RowsetSharedPtr>& rowsets, const TabletSchemaSPtr& 
base_schema) {
-    if (rowsets.empty()) {
-        return nullptr;
+static Status collect_rowset_variant_schemas(const RowsetSharedPtr& rs,
+                                             std::vector<TabletSchemaSPtr>& 
schemas) {
+    const auto& tablet_schema = rs->tablet_schema();
+    SegmentCacheHandle segment_cache;
+    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
+            std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
+    for (const auto& segment : segment_cache.get_segments()) {
+        TabletSchemaSPtr schema = 
tablet_schema->copy_without_variant_extracted_columns();
+        for (const auto& column : tablet_schema->columns()) {
+            if (!column->is_variant_type()) {
+                continue;
+            }
+            std::shared_ptr<segment_v2::VariantColumnReader> 
variant_column_reader;
+            OlapReaderStatistics stats;
+            StorageReadOptions read_options(stats);
+            auto st =
+                    segment->get_variant_root_reader(*column, read_options, 
&variant_column_reader);
+            if (st.is<ErrorCode::NOT_FOUND>()) {

Review Comment:
   [P2] Propagate object-store NOT_FOUND while reading a Variant root
   
   This branch also swallows NOT_FOUND from the storage read. On a Cloud V3 
segment whose footer is cached but whose Variant root metadata is uncached, an 
S3 404 on the root metadata range is propagated through ExternalColMetaUtil and 
get_variant_root_reader. The worker then skips the root and can report the 
tablet as covered with its paths missing. Give the expected absent-column case 
a distinct result from errors reading a physically present root, and cover a V3 
root metadata read returning NOT_FOUND.



##########
fe/fe-core/src/main/java/org/apache/doris/common/proc/RemoteIndexSchemaProcDir.java:
##########
@@ -80,32 +68,92 @@ public boolean register(String name, ProcNodeInterface 
node) {
 
     @Override
     public ProcNodeInterface lookup(String partitionString) throws 
AnalysisException {
-        Preconditions.checkNotNull(table);
-
-        List<String> partitionNameList = new 
ArrayList<String>(Arrays.asList(partitionString.split(",")));
-        if (partitionNameList == null || partitionNameList.isEmpty()) {
+        List<String> partitionNames = 
Arrays.asList(partitionString.split(","));
+        if (partitionNames.isEmpty()) {
             throw new AnalysisException("Describe table[" + table.getName() + 
"] failed");
         }
-        List<Partition> partitions = Lists.newArrayList();
+        return snapshot(partitionNames);
+    }
+
+    public RemoteIndexSchemaProcNode snapshot() throws AnalysisException {
+        return snapshot(List.of());
+    }
+
+    private RemoteIndexSchemaProcNode snapshot(List<String> partitionNames) 
throws AnalysisException {
         table.readLock();
         try {
-            if (table.isManagedTable()) {
-                OlapTable olapTable = (OlapTable) table;
-                for (String partitionName : partitionNameList) {
-                    Partition partition = 
olapTable.getPartition(partitionName);
-                    if (partition == null) {
-                        throw new AnalysisException("Partition " + 
partitionName + " does not exist");
-                    }
-                    partitions.add(partition);
-                }
-            } else {
-                throw new AnalysisException(table.getName() + " is not a OLAP 
table, describe table failed");
+            SchemaGeneration generation = getSchemaGeneration();
+            boolean sampleByPartition = partitionNames.isEmpty();
+            Collection<Partition> partitions = sampleByPartition
+                    ? table.getPartitions() : 
getNamedPartitions(partitionNames);
+            List<Column> schema = table.getSchemaByIndexId(indexId);
+            Set<String> bfColumns = 
IndexInfoProcDir.getBloomFilterColumns(table);
+            ProcResult baseSchema = IndexSchemaProcNode.createResult(schema, 
bfColumns, List.of());
+            List<PartitionTablets> partitionTablets = 
FetchRemoteTabletSchemaUtil.snapshotPartitions(partitions);
+            return new RemoteIndexSchemaProcNode(
+                    baseSchema, bfColumns, () -> 
fetchRemoteSchema(partitionTablets, generation, sampleByPartition));
+        } finally {
+            table.readUnlock();
+        }
+    }
+
+    private List<Column> fetchRemoteSchema(List<PartitionTablets> partitions, 
SchemaGeneration generation,
+            boolean sampleByPartition) throws AnalysisException {
+        if (partitions.isEmpty()) {
+            return List.of();
+        }
+        // Cloud partition visibility may require a Meta Service RPC.
+        List<VersionedTablet> tablets = 
FetchRemoteTabletSchemaUtil.sampleTablets(partitions, sampleByPartition);
+        FetchRemoteTabletSchemaUtil fetcher;
+        table.readLock();
+        try {
+            checkSchemaGeneration(generation);

Review Comment:
   [P2] Revalidate the Cloud partition list after fetching versions
   
   Whole-table DESC captures the partition list before the unlocked Meta 
Service call, while this check only compares index generations. If p1 is the 
sole partition at capture time, then p2 is added and receives a new Variant 
path before another new path is inserted into p1, the lookup can see the later 
p1 version while the sampled tablet set still omits p2. With a budget that 
covers all tablets, the result matches neither point in time. Capture and 
recheck the table’s partition topology version across the lookup and retry or 
fail if it changed.



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