You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kudu.apache.org by mg...@apache.org on 2026/03/20 11:48:30 UTC

(kudu) branch master updated: KUDU-3692 Export entity attributes as Prometheus labels

This is an automated email from the ASF dual-hosted git repository.

mgreber pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/kudu.git


The following commit(s) were added to refs/heads/master by this push:
     new 2991ce972 KUDU-3692 Export entity attributes as Prometheus labels
2991ce972 is described below

commit 2991ce9722f692a4d964b0d92e9e200309fee2ad
Author: Yan-Daojiang <ya...@163.com>
AuthorDate: Tue Mar 10 15:31:08 2026 +0800

    KUDU-3692 Export entity attributes as Prometheus labels
    
    Add a runtime flag, --prometheus_use_entity_labels (default false), to control
    the Prometheus exposition format.
    
    When enabled, entity identity and part of attributes are exported as labels
    instead of being embedded in metric names, improving Prometheus naming compliance
    and enabling aggregation by entity attributes.
    
    This change also:
    - Deduplicates HELP/TYPE lines for metrics shared across many entities.
    - Escapes Prometheus label values (\, ", and newlines).
    - Ensures histogram _sum/_count lines carry labels and unit_type.
    - Keeps the legacy, prefix-based format when the flag is disabled.
    
    Update Prometheus-related unit/integration tests and the output checker to
    validate the new format and preserve legacy coverage.
    
    Change-Id: I690918d06f19c393369b8fc43c3ec90dd2231d3d
    Reviewed-on: http://gerrit.cloudera.org:8080/24096
    Reviewed-by: Alexey Serbin <al...@apache.org>
    Reviewed-by: Marton Greber <gr...@gmail.com>
    Tested-by: Marton Greber <gr...@gmail.com>
---
 src/kudu/master/master.cc          |   3 +-
 src/kudu/tserver/tablet_server.cc  |   3 +-
 src/kudu/util/metrics-test.cc      | 235 +++++++++++++++++++++++++++++++------
 src/kudu/util/metrics.cc           | 203 +++++++++++++++++++++++++-------
 src/kudu/util/metrics.h            |  41 +++++--
 src/kudu/util/prometheus_writer.cc |  95 ++++++++++++++-
 src/kudu/util/prometheus_writer.h  |  52 ++++++++
 src/kudu/util/test_util.cc         |  69 ++++++-----
 8 files changed, 579 insertions(+), 122 deletions(-)

diff --git a/src/kudu/master/master.cc b/src/kudu/master/master.cc
index c0fa3bf1c..9ab7158a0 100644
--- a/src/kudu/master/master.cc
+++ b/src/kudu/master/master.cc
@@ -69,6 +69,7 @@
 #include "kudu/util/net/net_util.h"
 #include "kudu/util/net/sockaddr.h"
 #include "kudu/util/openssl_util.h"
+#include "kudu/util/prometheus_writer.h"
 #include "kudu/util/status.h"
 #include "kudu/util/thread.h"
 #include "kudu/util/threadpool.h"
@@ -263,7 +264,7 @@ Status GetMasterEntryForHost(const shared_ptr<rpc::Messenger>& messenger,
 }  // anonymous namespace
 
 Master::Master(const MasterOptions& opts)
-    : KuduServer("Master", opts, "kudu.master"),
+    : KuduServer("Master", opts, kMetricEntityIdMaster),
       state_(kStopped),
       catalog_manager_(new CatalogManager(this)),
       txn_manager_(FLAGS_txn_manager_enabled ? new TxnManager(this) : nullptr),
diff --git a/src/kudu/tserver/tablet_server.cc b/src/kudu/tserver/tablet_server.cc
index 37bf958da..12e77dccb 100644
--- a/src/kudu/tserver/tablet_server.cc
+++ b/src/kudu/tserver/tablet_server.cc
@@ -44,6 +44,7 @@
 #include "kudu/util/maintenance_manager.h"
 #include "kudu/util/net/dns_resolver.h"
 #include "kudu/util/net/net_util.h"
+#include "kudu/util/prometheus_writer.h"
 #include "kudu/util/status.h"
 
 namespace kudu {
@@ -61,7 +62,7 @@ namespace kudu {
 namespace tserver {
 
 TabletServer::TabletServer(const TabletServerOptions& opts)
-    : KuduServer("TabletServer", opts, "kudu.tabletserver"),
+    : KuduServer("TabletServer", opts, kMetricEntityIdTabletServer),
       state_(kStopped),
       quiescing_(false),
       fail_heartbeats_for_tests_(false),
diff --git a/src/kudu/util/metrics-test.cc b/src/kudu/util/metrics-test.cc
index c56f4a237..acb9a7184 100644
--- a/src/kudu/util/metrics-test.cc
+++ b/src/kudu/util/metrics-test.cc
@@ -28,7 +28,7 @@
 #include <utility>
 #include <vector>
 
-#include <gflags/gflags_declare.h>
+#include <gflags/gflags.h>
 #include <glog/logging.h>
 #include <gtest/gtest.h>
 #include <rapidjson/document.h>
@@ -37,6 +37,7 @@
 #include "kudu/gutil/map-util.h"
 #include "kudu/gutil/ref_counted.h"
 #include "kudu/gutil/strings/split.h"
+#include "kudu/gutil/strings/util.h"
 #include "kudu/util/hdr_histogram.h"
 #include "kudu/util/jsonreader.h"
 #include "kudu/util/jsonwriter.h"
@@ -55,6 +56,7 @@ using std::unordered_set;
 using std::vector;
 
 DECLARE_int32(metrics_retirement_age_ms);
+DECLARE_bool(metrics_prometheus_use_entity_labels);
 
 namespace kudu {
 
@@ -148,75 +150,122 @@ TEST_F(MetricsTest, ResetCounter) {
 }
 
 TEST_F(MetricsTest, TableAndTabletPrometheusTest) {
+  google::FlagSaver saver;
+  FLAGS_metrics_prometheus_use_entity_labels = true;
+
+  // Use a dedicated registry so only tablet/table entities are present.
+  MetricRegistry registry;
+
   // Simulate two tablets in the metric registry. Write out their metric data.
-  auto tablet_metric_entity = METRIC_ENTITY_tablet.Instantiate(&registry_, "000000");
+  auto tablet_metric_entity = METRIC_ENTITY_tablet.Instantiate(&registry, "000000");
   auto tablet_counter = METRIC_tablet_test_counter.Instantiate(tablet_metric_entity);
   tablet_counter->IncrementBy(11);
 
-  auto tablet_metric_entity2 = METRIC_ENTITY_tablet.Instantiate(&registry_, "1111111111");
+  auto tablet_metric_entity2 = METRIC_ENTITY_tablet.Instantiate(&registry, "1111111111");
   auto tablet_counter2 = METRIC_tablet_test_counter.Instantiate(tablet_metric_entity2);
   tablet_counter2->IncrementBy(2);
 
-  auto table_metric_entity = METRIC_ENTITY_table.Instantiate(&registry_, "table1");
+  auto table_metric_entity = METRIC_ENTITY_table.Instantiate(&registry, "table1");
   auto table1_counter = METRIC_table_test_counter.Instantiate(table_metric_entity);
   table1_counter->IncrementBy(888);
 
-  auto table_metric_entity2 = METRIC_ENTITY_table.Instantiate(&registry_, "table2");
+  auto table_metric_entity2 = METRIC_ENTITY_table.Instantiate(&registry, "table2");
   auto table2_counter = METRIC_table_test_counter.Instantiate(table_metric_entity2);
   table2_counter->Increment();
 
   auto table_metric_entity3 = METRIC_ENTITY_table.Instantiate(
-      &registry_, "55555555555555555555555555555555");
+      &registry, "55555555555555555555555555555555");
   auto table3_counter = METRIC_table_test_counter.Instantiate(table_metric_entity3);
   table3_counter->IncrementBy(5);
 
   ostringstream output;
   PrometheusWriter writer(&output);
-  ASSERT_OK(registry_.WriteAsPrometheus(&writer, {}));
+  ASSERT_OK(registry.WriteAsPrometheus(&writer, {}));
 
   // The order of elements in the output depends on the ordering in hash-map
   // of metric entities and might be different in different STL implementations.
   const auto& out = output.str();
+  // With labels, the metric name no longer includes the entity ID.
+  // HELP/TYPE is emitted once per metric name (deduped).
   ASSERT_STR_CONTAINS(out,
-      "# HELP kudu_tablet_000000_tablet_test_counter Tablet-wise test counter description.\n"
-      "# TYPE kudu_tablet_000000_tablet_test_counter counter\n"
-       "kudu_tablet_000000_tablet_test_counter{unit_type=\"bytes\"} 11\n"
+      "# HELP kudu_tablet_test_counter Tablet-wise test counter description.\n"
+      "# TYPE kudu_tablet_test_counter counter\n"
   );
   ASSERT_STR_CONTAINS(out,
-      "# HELP kudu_tablet_1111111111_tablet_test_counter Tablet-wise test counter description.\n"
-      "# TYPE kudu_tablet_1111111111_tablet_test_counter counter\n"
-      "kudu_tablet_1111111111_tablet_test_counter{unit_type=\"bytes\"} 2\n"
+      "kudu_tablet_test_counter{type=\"tablet\",id=\"000000\",unit_type=\"bytes\"} 11\n"
   );
   ASSERT_STR_CONTAINS(out,
-      "# HELP kudu_table_table1_table_test_counter Table-wise test counter description.\n"
-      "# TYPE kudu_table_table1_table_test_counter counter\n"
-      "kudu_table_table1_table_test_counter{unit_type=\"bytes\"} 888\n"
+      "kudu_tablet_test_counter{type=\"tablet\",id=\"1111111111\",unit_type=\"bytes\"} 2\n"
+  );
+  ASSERT_STR_CONTAINS(out,
+      "# HELP kudu_table_test_counter Table-wise test counter description.\n"
+      "# TYPE kudu_table_test_counter counter\n"
   );
   ASSERT_STR_CONTAINS(out,
-      "# HELP kudu_table_table2_table_test_counter Table-wise test counter description.\n"
-      "# TYPE kudu_table_table2_table_test_counter counter\n"
-      "kudu_table_table2_table_test_counter{unit_type=\"bytes\"} 1\n"
+      "kudu_table_test_counter{type=\"table\",id=\"table1\",unit_type=\"bytes\"} 888\n"
   );
   ASSERT_STR_CONTAINS(out,
-      "# HELP kudu_table_55555555555555555555555555555555_table_test_counter "
-          "Table-wise test counter description.\n"
-      "# TYPE kudu_table_55555555555555555555555555555555_table_test_counter "
-          "counter\n"
-      "kudu_table_55555555555555555555555555555555_table_test_counter{unit_type=\"bytes\"} 5\n"
+      "kudu_table_test_counter{type=\"table\",id=\"table2\",unit_type=\"bytes\"} 1\n"
   );
+  ASSERT_STR_CONTAINS(out,
+      "kudu_table_test_counter{type=\"table\","
+          "id=\"55555555555555555555555555555555\",unit_type=\"bytes\"} 5\n"
+  );
+
+  // Verify that HELP/TYPE lines are emitted exactly once per metric name.
+  ASSERT_EQ(1, CountSubstring(out, "# HELP kudu_tablet_test_counter "));
+  ASSERT_EQ(1, CountSubstring(out, "# TYPE kudu_tablet_test_counter "));
+  ASSERT_EQ(1, CountSubstring(out, "# HELP kudu_table_test_counter "));
+  ASSERT_EQ(1, CountSubstring(out, "# TYPE kudu_table_test_counter "));
 
-  // The lines above and one trailing empty line is the only output expected.
+  // 2 HELP/TYPE blocks (tablet + table) + 2 tablet values + 3 table values + trailing empty line.
   const vector<string> lines = strings::Split(out, "\n");
-  ASSERT_EQ(3 + 3 + 3 + 3 + 3 + 1, lines.size());
+  ASSERT_EQ(2 + 2 + 2 + 3 + 1, lines.size());
   ASSERT_TRUE(lines.back().empty());
 }
 
+TEST_F(MetricsTest, TableAndTabletLegacyPrometheusTest) {
+  google::FlagSaver saver;
+  // Verify the legacy format (flag off): entity IDs embedded in metric names.
+  FLAGS_metrics_prometheus_use_entity_labels = false;
+
+  // Use a dedicated registry so only tablet/table entities are present.
+  MetricRegistry registry;
+
+  auto tablet_entity = METRIC_ENTITY_tablet.Instantiate(&registry, "000000");
+  auto tablet_counter = METRIC_tablet_test_counter.Instantiate(tablet_entity);
+  tablet_counter->IncrementBy(11);
+
+  auto table_entity = METRIC_ENTITY_table.Instantiate(&registry, "table1");
+  auto table_counter = METRIC_table_test_counter.Instantiate(table_entity);
+  table_counter->IncrementBy(888);
+
+  ostringstream output;
+  PrometheusWriter writer(&output);
+  ASSERT_OK(registry.WriteAsPrometheus(&writer, {}));
+
+  const auto& out = output.str();
+  // Legacy format: entity ID is embedded in the metric name prefix.
+  ASSERT_STR_CONTAINS(out,
+      "# HELP kudu_tablet_000000_tablet_test_counter "
+      "Tablet-wise test counter description.\n"
+      "# TYPE kudu_tablet_000000_tablet_test_counter counter\n"
+      "kudu_tablet_000000_tablet_test_counter{unit_type=\"bytes\"} 11\n"
+  );
+  ASSERT_STR_CONTAINS(out,
+      "# HELP kudu_table_table1_table_test_counter "
+      "Table-wise test counter description.\n"
+      "# TYPE kudu_table_table1_table_test_counter counter\n"
+      "kudu_table_table1_table_test_counter{unit_type=\"bytes\"} 888\n"
+  );
+}
+
 TEST_F(MetricsTest, CounterPrometheusTest) {
   scoped_refptr<Counter> requests(new Counter(&METRIC_test_counter));
 
   ostringstream output;
   PrometheusWriter writer(&output);
-  ASSERT_OK(requests->WriteAsPrometheus(&writer, {}));
+  ASSERT_OK(requests->WriteAsPrometheus(&writer, "", ""));
 
   const string expected_output = "# HELP test_counter Description of test counter\n"
                                  "# TYPE test_counter counter\n"
@@ -286,7 +335,7 @@ TEST_F(MetricsTest, StringGaugeForPrometheus) {
 
   ostringstream output;
   PrometheusWriter writer(&output);
-  ASSERT_OK(state->WriteAsPrometheus(&writer, {}));
+  ASSERT_OK(state->WriteAsPrometheus(&writer, "", ""));
   // String-based gauges are not consumable by Prometheus.
   ASSERT_EQ("", output.str());
 
@@ -295,14 +344,14 @@ TEST_F(MetricsTest, StringGaugeForPrometheus) {
     const Metric* g = state.get();
     ostringstream output;
     PrometheusWriter writer(&output);
-    ASSERT_OK(g->WriteAsPrometheus(&writer, {}));
+    ASSERT_OK(g->WriteAsPrometheus(&writer, "", ""));
     ASSERT_EQ("", output.str());
   }
   {
     const Metric* m = state.get();
     ostringstream output;
     PrometheusWriter writer(&output);
-    ASSERT_OK(m->WriteAsPrometheus(&writer, {}));
+    ASSERT_OK(m->WriteAsPrometheus(&writer, "", ""));
     ASSERT_EQ("", output.str());
   }
 }
@@ -323,7 +372,7 @@ TEST_F(MetricsTest, StringFunctionGaugeForPrometheus) {
 
   ostringstream output;
   PrometheusWriter writer(&output);
-  ASSERT_OK(gauge->WriteAsPrometheus(&writer, {}));
+  ASSERT_OK(gauge->WriteAsPrometheus(&writer, "", ""));
   // String-based gauges are not consumable by Prometheus.
   ASSERT_EQ("", output.str());
 }
@@ -409,17 +458,49 @@ TEST_F(MetricsTest, MeanGaugePrometheusTest) {
 
   ostringstream output;
   PrometheusWriter writer(&output);
-  ASSERT_OK(average_usage->WriteAsPrometheus(&writer, {}));
+  ASSERT_OK(average_usage->WriteAsPrometheus(&writer, "", ""));
 
   const string expected_output = "# HELP test_mean_gauge Description of mean Gauge\n"
                                  "# TYPE test_mean_gauge gauge\n"
                                  "test_mean_gauge{unit_type=\"units\"} 0\n"
+                                 "# HELP test_mean_gauge_count Test mean Gauge (count)\n"
+                                 "# TYPE test_mean_gauge_count gauge\n"
                                  "test_mean_gauge_count{unit_type=\"units\"} 0\n"
+                                 "# HELP test_mean_gauge_sum Description of mean Gauge (sum)\n"
+                                 "# TYPE test_mean_gauge_sum gauge\n"
                                  "test_mean_gauge_sum{unit_type=\"units\"} 0\n";
 
   ASSERT_EQ(expected_output, output.str());
 }
 
+// Define a MeanGauge with a non-"units" unit to verify that _count always
+// reports unit_type="units" while _sum keeps the original unit.
+METRIC_DEFINE_gauge_double(test_entity, test_mean_gauge_bytes, "Test mean Gauge bytes",
+                           MetricUnit::kBytes, "Description of mean Gauge in bytes",
+                           kudu::MetricLevel::kInfo);
+
+TEST_F(MetricsTest, MeanGaugePrometheusCountUnitTest) {
+  scoped_refptr<MeanGauge> gauge =
+    METRIC_test_mean_gauge_bytes.InstantiateMeanGauge(entity_);
+  gauge->set_value(1024.0, 4.0);
+
+  ostringstream output;
+  PrometheusWriter writer(&output);
+  ASSERT_OK(gauge->WriteAsPrometheus(&writer, "", ""));
+
+  const string& result = output.str();
+  // The main metric and _sum should carry the original unit ("bytes").
+  ASSERT_STR_CONTAINS(result, "test_mean_gauge_bytes{unit_type=\"bytes\"} 256");
+  ASSERT_STR_CONTAINS(result, "test_mean_gauge_bytes_sum{unit_type=\"bytes\"} 1024");
+  // _count must carry "units", not "bytes".
+  ASSERT_STR_CONTAINS(result, "test_mean_gauge_bytes_count{unit_type=\"units\"} 4");
+  ASSERT_STR_NOT_CONTAINS(result, "test_mean_gauge_bytes_count{unit_type=\"bytes\"}");
+  // The HELP line of _count should use the metric label, not the description
+  // which may mention the unit (e.g. "...in bytes").
+  ASSERT_STR_CONTAINS(result, "# HELP test_mean_gauge_bytes_count Test mean Gauge bytes (count)");
+  ASSERT_STR_NOT_CONTAINS(result, "# HELP test_mean_gauge_bytes_count Description of mean Gauge in bytes");
+}
+
 METRIC_DEFINE_gauge_uint64(test_entity, test_gauge, "Test uint64 Gauge",
                            MetricUnit::kBytes, "Description of Test Gauge",
                            kudu::MetricLevel::kInfo);
@@ -493,7 +574,7 @@ TEST_F(MetricsTest, AtomicGaugePrometheusTest) {
 
   ostringstream output;
   PrometheusWriter writer(&output);
-  ASSERT_OK(mem_usage->WriteAsPrometheus(&writer, {}));
+  ASSERT_OK(mem_usage->WriteAsPrometheus(&writer, "", ""));
 
   const string expected_output = "# HELP test_gauge Description of Test Gauge\n"
                                  "# TYPE test_gauge gauge\n"
@@ -508,7 +589,7 @@ TEST_F(MetricsTest, AtomicGaugeBooleanPrometheusTest) {
 
   ostringstream output;
   PrometheusWriter writer(&output);
-  ASSERT_OK(clock_extrapolating->WriteAsPrometheus(&writer, {}));
+  ASSERT_OK(clock_extrapolating->WriteAsPrometheus(&writer, "", ""));
 
   const string expected_output = "# HELP test_gauge_bool Description of Test boolean Gauge\n"
                                  "# TYPE test_gauge_bool gauge\n"
@@ -664,7 +745,7 @@ TEST_F(MetricsTest, FunctionGaugePrometheusTest) {
 
   ostringstream output;
   PrometheusWriter writer(&output);
-  ASSERT_OK(gauge->WriteAsPrometheus(&writer, {}));
+  ASSERT_OK(gauge->WriteAsPrometheus(&writer, "", ""));
 
   const string expected_output = "# HELP test_func_gauge Test Gauge 2\n"
                                  "# TYPE test_func_gauge gauge\n"
@@ -729,6 +810,84 @@ TEST_F(MetricsTest, SimpleHistogramMergeTest) {
 }
 
 TEST_F(MetricsTest, HistogramPrometheusTest) {
+  google::FlagSaver saver;
+  FLAGS_metrics_prometheus_use_entity_labels = true;
+
+  constexpr const char* const kExpectedOutput =
+      "# HELP test_hist foo\n"
+      "# TYPE test_hist summary\n"
+      "test_hist{unit_type=\"milliseconds\",quantile=\"0\"} 1\n"
+      "test_hist{unit_type=\"milliseconds\",quantile=\"0.75\"} 2\n"
+      "test_hist{unit_type=\"milliseconds\",quantile=\"0.95\"} 3\n"
+      "test_hist{unit_type=\"milliseconds\",quantile=\"0.99\"} 4\n"
+      "test_hist{unit_type=\"milliseconds\",quantile=\"0.999\"} 5\n"
+      "test_hist{unit_type=\"milliseconds\",quantile=\"0.9999\"} 5\n"
+      "test_hist{unit_type=\"milliseconds\",quantile=\"1\"} 5\n"
+  "# HELP test_hist_sum foo (sum)\n"
+  "# TYPE test_hist_sum counter\n"
+      "test_hist_sum{unit_type=\"milliseconds\"} 1460\n"
+  "# HELP test_hist_count Test Histogram (count)\n"
+  "# TYPE test_hist_count counter\n"
+      "test_hist_count{unit_type=\"units\"} 1000\n";
+
+  scoped_refptr<Histogram> hist = METRIC_test_hist.Instantiate(entity_);
+  hist->IncrementBy(1, 700);
+  hist->IncrementBy(2, 200);
+  hist->IncrementBy(3, 50);
+  hist->IncrementBy(4, 40);
+  hist->IncrementBy(5, 10);
+
+  ostringstream output;
+  PrometheusWriter writer(&output);
+  ASSERT_OK(hist->WriteAsPrometheus(&writer, "", ""));
+  ASSERT_EQ(kExpectedOutput, output.str());
+}
+
+// Verify that when the histogram uses a non-trivial unit (e.g. milliseconds),
+// the _count metric reports unit_type="units" (dimensionless) while _sum
+// keeps the original unit. Uses non-empty entity labels to match the real-world
+// scenario (e.g. tablet entities) reported in code review.
+TEST_F(MetricsTest, HistogramPrometheusCountUnitTest) {
+  google::FlagSaver saver;
+  FLAGS_metrics_prometheus_use_entity_labels = true;
+
+  scoped_refptr<Histogram> hist = METRIC_test_hist.Instantiate(entity_);
+  hist->IncrementBy(10, 5);
+
+  ostringstream output;
+  PrometheusWriter writer(&output);
+  // Pass entity labels to simulate a real tablet entity context, e.g.:
+  //   kudu_test_hist_count{type="tablet",id="abc123",...,unit_type="units"} 5
+  ASSERT_OK(hist->WriteAsPrometheus(
+      &writer, "kudu_", "type=\"tablet\",id=\"abc123\""));
+
+  const string& result = output.str();
+  // The quantile lines should carry the original unit.
+  ASSERT_STR_CONTAINS(result,
+      "type=\"tablet\",id=\"abc123\",unit_type=\"milliseconds\",quantile=");
+  // _sum should carry the original unit.
+  ASSERT_STR_CONTAINS(result,
+      "kudu_test_hist_sum{type=\"tablet\",id=\"abc123\","
+      "unit_type=\"milliseconds\"}");
+  // _count must carry "units", not the histogram's native unit.
+  ASSERT_STR_CONTAINS(result,
+      "kudu_test_hist_count{type=\"tablet\",id=\"abc123\","
+      "unit_type=\"units\"}");
+  // Make sure _count does NOT carry the histogram's native unit.
+  ASSERT_STR_NOT_CONTAINS(result,
+      "test_hist_count{type=\"tablet\",id=\"abc123\","
+      "unit_type=\"milliseconds\"}");
+  // The HELP line of _count should use the metric label, not the description
+  // which may include unit-specific wording (e.g. "Microseconds spent on...").
+  ASSERT_STR_CONTAINS(result, "# HELP kudu_test_hist_count Test Histogram (count)");
+  ASSERT_STR_NOT_CONTAINS(result, "# HELP kudu_test_hist_count foo");
+}
+
+TEST_F(MetricsTest, HistogramLegacyPrometheusTest) {
+  google::FlagSaver saver;
+  // Verify legacy histogram format: space after comma, _sum/_count have no labels.
+  FLAGS_metrics_prometheus_use_entity_labels = false;
+
   constexpr const char* const kExpectedOutput =
       "# HELP test_hist foo\n"
       "# TYPE test_hist summary\n"
@@ -739,7 +898,11 @@ TEST_F(MetricsTest, HistogramPrometheusTest) {
       "test_hist{unit_type=\"milliseconds\", quantile=\"0.999\"} 5\n"
       "test_hist{unit_type=\"milliseconds\", quantile=\"0.9999\"} 5\n"
       "test_hist{unit_type=\"milliseconds\", quantile=\"1\"} 5\n"
+      "# HELP test_hist_sum foo (sum)\n"
+      "# TYPE test_hist_sum counter\n"
       "test_hist_sum 1460\n"
+      "# HELP test_hist_count Test Histogram (count)\n"
+      "# TYPE test_hist_count counter\n"
       "test_hist_count 1000\n";
 
   scoped_refptr<Histogram> hist = METRIC_test_hist.Instantiate(entity_);
@@ -751,7 +914,7 @@ TEST_F(MetricsTest, HistogramPrometheusTest) {
 
   ostringstream output;
   PrometheusWriter writer(&output);
-  ASSERT_OK(hist->WriteAsPrometheus(&writer, {}));
+  ASSERT_OK(hist->WriteAsPrometheus(&writer, "", ""));
   ASSERT_EQ(kExpectedOutput, output.str());
 }
 
diff --git a/src/kudu/util/metrics.cc b/src/kudu/util/metrics.cc
index 91f1fc5da..30fa0316a 100644
--- a/src/kudu/util/metrics.cc
+++ b/src/kudu/util/metrics.cc
@@ -39,6 +39,12 @@ DEFINE_int32(metrics_retirement_age_ms, 120 * 1000,
 TAG_FLAG(metrics_retirement_age_ms, runtime);
 TAG_FLAG(metrics_retirement_age_ms, advanced);
 
+DEFINE_bool(metrics_prometheus_use_entity_labels, false,
+            "If true, entity attributes (type, id, table_id, table_name) "
+            "are exported as Prometheus labels and metric names have no entity prefix. "
+            "If false, entity IDs are embedded in metric names (legacy format).");
+TAG_FLAG(metrics_prometheus_use_entity_labels, runtime);
+
 // Process/server-wide metrics should go into the 'server' entity.
 // More complex applications will define other entities.
 METRIC_DEFINE_entity(server);
@@ -72,9 +78,10 @@ void WriteMetricsToJson(JsonWriter* writer,
 
 void WriteMetricsPrometheus(PrometheusWriter* writer,
                             const MetricEntity::MetricMap& metrics,
-                            const string& prefix) {
-  for (const auto& [_, val] : metrics) {
-    WARN_NOT_OK(val->WriteAsPrometheus(writer, prefix),
+                            const string& prefix,
+                            const string& labels) {
+  for (const auto& [name, val] : metrics) {
+    WARN_NOT_OK(val->WriteAsPrometheus(writer, prefix, labels),
                 Substitute("unable to write '$0' ($1) in Prometheus format",
                            val->prototype()->name(), val->prototype()->description()));
   }
@@ -406,9 +413,6 @@ Status MetricEntity::WriteAsJson(JsonWriter* writer, const MetricJsonOptions& op
 
 Status MetricEntity::WriteAsPrometheus(
     PrometheusWriter* writer, const MetricPrometheusOptions& opts) const {
-  static const string kIdMaster = "kudu.master";
-  static const string kIdTabletServer = "kudu.tabletserver";
-
   MetricMap metrics;
   AttributeMap attrs;
   const auto s = GetMetricsAndAttrs(opts.filters, &metrics, &attrs);
@@ -418,23 +422,28 @@ Status MetricEntity::WriteAsPrometheus(
     return Status::OK();
   }
   RETURN_NOT_OK(s);
+  if (FLAGS_metrics_prometheus_use_entity_labels) {
+    const string labels = BuildPrometheusLabels(prototype_->name(), id_, attrs);
+    WriteMetricsPrometheus(writer, metrics, "kudu_", labels);
+    return Status::OK();
+  }
+
+  // Legacy format: embed entity type/id in the metric name prefix.
   if (strcmp(prototype_->name(), "server") == 0) {
-    if (id_ == kIdMaster) {
-      // Prefix all master metrics with 'kudu_master_'.
-      static const string kMasterPrefix = "kudu_master_";
-      WriteMetricsPrometheus(writer, metrics, kMasterPrefix);
-      return Status::OK();
-    }
-    if (id_ == kIdTabletServer) {
-      // Prefix all tablet server metrics with 'kudu_tserver_'.
-      static const string kTabletServerPrefix = "kudu_tserver_";
-      WriteMetricsPrometheus(writer, metrics, kTabletServerPrefix);
-      return Status::OK();
+    string prefix;
+    if (id_ == kMetricEntityIdMaster) {
+      prefix = "kudu_master_";
+    } else if (id_ == kMetricEntityIdTabletServer) {
+      prefix = "kudu_tserver_";
+    } else {
+      return Status::NotSupported(
+          Substitute("$0: unexpected server-level metric entity", id_));
     }
-    return Status::NotSupported(Substitute("$0: unexpected server-level metric entity", id_));
+    WriteMetricsPrometheus(writer, metrics, prefix, "");
+    return Status::OK();
   }
   const string prefix = Substitute("kudu_$0_$1_", prototype_->name(), id_);
-  WriteMetricsPrometheus(writer, metrics, prefix);
+  WriteMetricsPrometheus(writer, metrics, prefix, "");
   return Status::OK();
 }
 
@@ -739,6 +748,15 @@ void MetricPrototype::WriteFields(JsonWriter* writer,
 
 void MetricPrototype::WriteHelpAndType(PrometheusWriter* writer,
                                        const string& prefix) const {
+  // Deduplicate HELP/TYPE output: once metric names are shared across entities,
+  // we must only emit HELP/TYPE once per metric name. When using the legacy
+  // format (metrics_prometheus_use_entity_labels=false), each entity has a unique
+  // prefix so dedup never triggers, which is the correct behavior.
+  const string full_name = Substitute("$0$1", prefix, name());
+  if (!writer->ShouldWriteHelpAndType(full_name)) {
+    return;
+  }
+
   static constexpr const char* const kSummary = "summary";
 
   // The way how HdrHistogram-backed stats are presented in Kudu metrics
@@ -830,9 +848,11 @@ Status Gauge::WriteAsJson(JsonWriter* writer,
   return Status::OK();
 }
 
-Status Gauge::WriteAsPrometheus(PrometheusWriter* writer, const string& prefix) const {
+Status Gauge::WriteAsPrometheus(PrometheusWriter* writer,
+                                const string& prefix,
+                                const string& labels) const {
   prototype_->WriteHelpAndType(writer, prefix);
-  WriteValue(writer, prefix);
+  WriteValue(writer, prefix, labels);
 
   return Status::OK();
 }
@@ -916,12 +936,14 @@ void StringGauge::WriteValue(JsonWriter* writer) const {
 // An alternative could be defining an empty implementation for Gauge::WriteValue()
 // virtual method and not adding this empty override here.
 void StringGauge::WriteValue(PrometheusWriter* /*writer*/,
-                             const string& /*prefix*/) const {
+                             const string& /*prefix*/,
+                             const string& /*labels*/) const {
   DCHECK(false);
 }
 
 Status StringGauge::WriteAsPrometheus(PrometheusWriter* /*writer*/,
-                                      const string& /*prefix*/) const {
+                                      const string& /*prefix*/,
+                                      const string& /*labels*/) const {
   // Prometheus doesn't support string gauges.
   // This function ensures that output written to Prometheus is empty.
   return Status::OK();
@@ -988,18 +1010,43 @@ void MeanGauge::WriteValue(JsonWriter* writer) const {
   writer->Double(total_count());
 }
 
-void MeanGauge::WriteValue(PrometheusWriter* writer, const string& prefix) const {
-  static constexpr const char* const kFmt = "$0$1$2{unit_type=\"$3\"} $4\n";
+void MeanGauge::WriteValue(PrometheusWriter* writer,
+                           const string& prefix,
+                           const string& labels) const {
+  static constexpr const char* const kFmt = "$0$1$2{$3unit_type=\"$4\"} $5\n";
+  static constexpr const char* const kHelpTypeFmt =
+      "# HELP $0$1$2 $3\n# TYPE $4$5$6 $7\n";
+
+  const string label_prefix = PrometheusLabelPrefixForInjection(labels);
 
   const char* const name = prototype_->name();
   DCHECK(name);
   const char* const unit = MetricUnit::Name(prototype_->unit());
   DCHECK(unit);
+  const char* const description = prototype_->description();
+  DCHECK(description);
 
   string out;
-  SubstituteAndAppend(&out, kFmt, prefix, name, "", unit, value());
-  SubstituteAndAppend(&out, kFmt, prefix, name, "_count", unit, total_count());
-  SubstituteAndAppend(&out, kFmt, prefix, name, "_sum", unit, total_sum());
+  SubstituteAndAppend(&out, kFmt, prefix, name, "", label_prefix, unit, value());
+
+  const string full_count_name = Substitute("$0$1_count", prefix, name);
+  if (writer->ShouldWriteHelpAndType(full_count_name)) {
+    const string count_help = Substitute("$0 (count)", prototype_->label());
+    SubstituteAndAppend(&out, kHelpTypeFmt,
+                        prefix, name, "_count", count_help,
+                        prefix, name, "_count", MetricType::Name(MetricType::kGauge));
+  }
+  SubstituteAndAppend(&out, kFmt, prefix, name, "_count", label_prefix,
+                      MetricUnit::Name(MetricUnit::kUnits), total_count());
+
+  const string full_sum_name = Substitute("$0$1_sum", prefix, name);
+  if (writer->ShouldWriteHelpAndType(full_sum_name)) {
+    const string sum_help = Substitute("$0 (sum)", description);
+    SubstituteAndAppend(&out, kHelpTypeFmt,
+                        prefix, name, "_sum", sum_help,
+                        prefix, name, "_sum", MetricType::Name(MetricType::kGauge));
+  }
+  SubstituteAndAppend(&out, kFmt, prefix, name, "_sum", label_prefix, unit, total_sum());
 
   writer->WriteEntry(out);
 }
@@ -1042,10 +1089,18 @@ Status Counter::WriteAsJson(JsonWriter* writer,
   return Status::OK();
 }
 
-Status Counter::WriteAsPrometheus(PrometheusWriter* writer, const string& prefix) const {
+Status Counter::WriteAsPrometheus(PrometheusWriter* writer,
+                                  const string& prefix,
+                                  const string& labels) const {
   prototype_->WriteHelpAndType(writer, prefix);
-  writer->WriteEntry(Substitute("$0$1{unit_type=\"$2\"} $3\n", prefix, prototype_->name(),
-                                MetricUnit::Name(prototype_->unit()), value()));
+  const string label_prefix = PrometheusLabelPrefixForInjection(labels);
+  writer->WriteEntry(Substitute(
+      "$0$1{$2unit_type=\"$3\"} $4\n",
+      prefix,
+      prototype_->name(),
+      label_prefix,
+      MetricUnit::Name(prototype_->unit()),
+      value()));
   return Status::OK();
 }
 
@@ -1106,7 +1161,8 @@ Status Histogram::WriteAsJson(JsonWriter* writer,
 }
 
 Status Histogram::WriteAsPrometheus(PrometheusWriter* writer,
-                                    const string& prefix) const {
+                                    const string& prefix,
+                                    const string& labels) const {
   static constexpr struct QuantileInfo {
     const char* const tag;
     const double quantile;
@@ -1117,8 +1173,8 @@ Status Histogram::WriteAsPrometheus(PrometheusWriter* writer,
     { "0.999",  99.9  },
     { "0.9999", 99.99 },
   };
-  static constexpr const char* const kFmt =
-      "$0$1{unit_type=\"$2\", quantile=\"$3\"} $4\n";
+  static constexpr const char* const kHelpTypeFmt =
+      "# HELP $0$1 $2\n# TYPE $3$4 $5\n";
 
   const char* const name = prototype_->name();
   DCHECK(name);
@@ -1129,14 +1185,79 @@ Status Histogram::WriteAsPrometheus(PrometheusWriter* writer,
   // the output.
   const HdrHistogram h(*histogram_);
   string out;
-  SubstituteAndAppend(&out, kFmt, prefix, name, unit, "0", h.MinValue());
-  for (const auto& [tag, q] : kQuantiles) {
-    SubstituteAndAppend(&out, kFmt, prefix, name, unit, tag, h.ValueAtPercentile(q));
+  if (FLAGS_metrics_prometheus_use_entity_labels) {
+    // New format: labels injected, no space after comma, _sum/_count carry unit_type.
+    static constexpr const char* const kFmt =
+        "$0$1{$2unit_type=\"$3\",quantile=\"$4\"} $5\n";
+    static constexpr const char* const kSumCountFmt =
+        "$0$1{$2unit_type=\"$3\"} $4\n";
+
+    const string label_prefix = PrometheusLabelPrefixForInjection(labels);
+
+    SubstituteAndAppend(&out, kFmt, prefix, name, label_prefix, unit, "0", h.MinValue());
+    for (const auto& [tag, q] : kQuantiles) {
+      SubstituteAndAppend(&out, kFmt, prefix, name, label_prefix, unit,
+                         tag, h.ValueAtPercentile(q));
+    }
+    SubstituteAndAppend(&out, kFmt, prefix, name, label_prefix, unit, "1", h.MaxValue());
+
+    const string sum_name = Substitute("$0_sum", name);
+    const string count_name = Substitute("$0_count", name);
+    const string full_sum_name = Substitute("$0$1", prefix, sum_name);
+    if (writer->ShouldWriteHelpAndType(full_sum_name)) {
+      const string sum_help = Substitute("$0 (sum)", prototype_->description());
+      SubstituteAndAppend(&out, kHelpTypeFmt,
+                          prefix, sum_name, sum_help,
+                          prefix, sum_name, MetricType::Name(MetricType::kCounter));
+    }
+    SubstituteAndAppend(&out, kSumCountFmt,
+                        prefix, sum_name, label_prefix, unit, h.TotalSum());
+
+    const string full_count_name = Substitute("$0$1", prefix, count_name);
+    if (writer->ShouldWriteHelpAndType(full_count_name)) {
+      const string count_help = Substitute("$0 (count)", prototype_->label());
+      SubstituteAndAppend(&out, kHelpTypeFmt,
+                          prefix, count_name, count_help,
+                          prefix, count_name, MetricType::Name(MetricType::kCounter));
+    }
+    SubstituteAndAppend(&out, kSumCountFmt,
+                        prefix, count_name, label_prefix,
+                        MetricUnit::Name(MetricUnit::kUnits), h.TotalCount());
+  } else {
+    // Legacy format: no labels, space after comma, _sum/_count have no labels.
+    static constexpr const char* const kLegacyFmt =
+        "$0$1{unit_type=\"$2\", quantile=\"$3\"} $4\n";
+    static constexpr const char* const kLegacySumCountFmt =
+        "$0$1 $2\n";
+
+    SubstituteAndAppend(&out, kLegacyFmt, prefix, name, unit, "0", h.MinValue());
+    for (const auto& [tag, q] : kQuantiles) {
+      SubstituteAndAppend(&out, kLegacyFmt, prefix, name, unit, tag, h.ValueAtPercentile(q));
+    }
+    SubstituteAndAppend(&out, kLegacyFmt, prefix, name, unit, "1", h.MaxValue());
+
+    const string sum_name = Substitute("$0_sum", name);
+    const string count_name = Substitute("$0_count", name);
+    const string full_sum_name = Substitute("$0$1", prefix, sum_name);
+    if (writer->ShouldWriteHelpAndType(full_sum_name)) {
+      const string sum_help = Substitute("$0 (sum)", prototype_->description());
+      SubstituteAndAppend(&out, kHelpTypeFmt,
+                          prefix, sum_name, sum_help,
+                          prefix, sum_name, MetricType::Name(MetricType::kCounter));
+    }
+    SubstituteAndAppend(&out, kLegacySumCountFmt,
+                        prefix, sum_name, h.TotalSum());
+
+    const string full_count_name = Substitute("$0$1", prefix, count_name);
+    if (writer->ShouldWriteHelpAndType(full_count_name)) {
+      const string count_help = Substitute("$0 (count)", prototype_->label());
+      SubstituteAndAppend(&out, kHelpTypeFmt,
+                          prefix, count_name, count_help,
+                          prefix, count_name, MetricType::Name(MetricType::kCounter));
+    }
+    SubstituteAndAppend(&out, kLegacySumCountFmt,
+                        prefix, count_name, h.TotalCount());
   }
-  SubstituteAndAppend(&out, kFmt, prefix, name, unit, "1", h.MaxValue());
-
-  SubstituteAndAppend(&out, "$0$1_sum $2\n", prefix, name, h.TotalSum());
-  SubstituteAndAppend(&out, "$0$1_count $2\n", prefix, name, h.TotalCount());
 
   prototype_->WriteHelpAndType(writer, prefix);
   writer->WriteEntry(out);
diff --git a/src/kudu/util/metrics.h b/src/kudu/util/metrics.h
index adcfb23cf..8f8de248c 100644
--- a/src/kudu/util/metrics.h
+++ b/src/kudu/util/metrics.h
@@ -777,7 +777,8 @@ class Metric : public RefCountedThreadSafe<Metric> {
   virtual Status WriteAsJson(JsonWriter* writer,
                              const MetricJsonOptions& opts) const = 0;
   // All metrics must be able to render themselves as Prometheus.
-  virtual Status WriteAsPrometheus(PrometheusWriter* writer, const std::string& prefix) const = 0;
+  virtual Status WriteAsPrometheus(PrometheusWriter* writer, const std::string& prefix,
+                                   const std::string& labels) const = 0;
 
   const MetricPrototype* prototype() const { return prototype_; }
 
@@ -1050,10 +1051,12 @@ class Gauge : public Metric {
   ~Gauge() override {}
   Status WriteAsJson(JsonWriter* w, const MetricJsonOptions& opts) const override;
 
-  Status WriteAsPrometheus(PrometheusWriter* w, const std::string& prefix) const override;
+  Status WriteAsPrometheus(PrometheusWriter* w, const std::string& prefix,
+                           const std::string& labels) const override;
  protected:
   virtual void WriteValue(JsonWriter* writer) const = 0;
-  virtual void WriteValue(PrometheusWriter* writer, const std::string& prefix) const = 0;
+  virtual void WriteValue(PrometheusWriter* writer, const std::string& prefix,
+                          const std::string& labels) const = 0;
  private:
   DISALLOW_COPY_AND_ASSIGN(Gauge);
 };
@@ -1072,12 +1075,14 @@ class StringGauge : public Gauge {
     return false;
   }
   void MergeFrom(const scoped_refptr<Metric>& other) override;
-  Status WriteAsPrometheus(PrometheusWriter* w, const std::string& prefix) const override;
+  Status WriteAsPrometheus(PrometheusWriter* w, const std::string& prefix,
+                           const std::string& labels) const override;
  protected:
   FRIEND_TEST(MetricsTest, SimpleStringGaugeForMergeTest);
   FRIEND_TEST(MetricsTest, StringGaugeForPrometheus);
   void WriteValue(JsonWriter* writer) const override;
-  void WriteValue(PrometheusWriter* writer, const std::string& prefix) const override;
+  void WriteValue(PrometheusWriter* writer, const std::string& prefix,
+                  const std::string& labels) const override;
   void FillUniqueValuesUnlocked();
   std::unordered_set<std::string> unique_values();
  private:
@@ -1107,7 +1112,8 @@ class MeanGauge : public Gauge {
 
  protected:
   void WriteValue(JsonWriter* writer) const override;
-  void WriteValue(PrometheusWriter* writer, const std::string& prefix) const override;
+  void WriteValue(PrometheusWriter* writer, const std::string& prefix,
+                  const std::string& labels) const override;
  private:
   double total_sum_;
   double total_count_;
@@ -1119,23 +1125,26 @@ class MeanGauge : public Gauge {
 template<typename T>
 void WriteValuePrometheus(PrometheusWriter* writer,
                           const std::string& prefix,
+                          const std::string& labels,
                           const char* proto_name,
                           const char* unit_name,
                           const T& value) {
-  static constexpr const char* const kFmt = "$0$1{unit_type=\"$2\"} $3\n";
+  static constexpr const char* const kFmt = "$0$1{$2unit_type=\"$3\"} $4\n";
 
   if constexpr (!std::is_arithmetic_v<T>) {
     // Non-arithmetic gauges aren't supported by Prometheus.
     return;
   }
 
+  const std::string label_prefix = PrometheusLabelPrefixForInjection(labels);
+
   // For a boolean gauge, convert false/true to 0/1 for Prometheus.
   if constexpr (std::is_same_v<T, bool>) {
     return writer->WriteEntry(
-        strings::Substitute(kFmt, prefix, proto_name, unit_name, value ? 1 : 0));
+        strings::Substitute(kFmt, prefix, proto_name, label_prefix, unit_name, value ? 1 : 0));
   } else {
     return writer->WriteEntry(
-        strings::Substitute(kFmt, prefix, proto_name, unit_name, value));
+        strings::Substitute(kFmt, prefix, proto_name, label_prefix, unit_name, value));
   }
 }
 
@@ -1208,9 +1217,11 @@ class AtomicGauge : public Gauge {
     writer->Value(value());
   }
 
-  void WriteValue(PrometheusWriter* writer,const std::string& prefix) const override {
+  void WriteValue(PrometheusWriter* writer, const std::string& prefix,
+                  const std::string& labels) const override {
     return WriteValuePrometheus(writer,
                                 prefix,
+                                labels,
                                 prototype_->name(),
                                 MetricUnit::Name(prototype_->unit()),
                                 value());
@@ -1307,9 +1318,11 @@ class FunctionGauge : public Gauge {
     writer->Value(value());
   }
 
-  void WriteValue(PrometheusWriter* writer, const std::string& prefix) const override {
+  void WriteValue(PrometheusWriter* writer, const std::string& prefix,
+                  const std::string& labels) const override {
     return WriteValuePrometheus(writer,
                                 prefix,
+                                labels,
                                 prototype_->name(),
                                 MetricUnit::Name(prototype_->unit()),
                                 value());
@@ -1435,7 +1448,8 @@ class Counter : public Metric {
   void IncrementBy(int64_t amount);
   Status WriteAsJson(JsonWriter* w, const MetricJsonOptions& opts) const override;
 
-  Status WriteAsPrometheus(PrometheusWriter* w, const std::string& prefix) const override;
+  Status WriteAsPrometheus(PrometheusWriter* w, const std::string& prefix,
+                           const std::string& labels) const override;
 
   bool IsUntouched() const override {
     return value() == 0;
@@ -1511,7 +1525,8 @@ class Histogram : public Metric {
 
   Status WriteAsJson(JsonWriter* w, const MetricJsonOptions& opts) const override;
 
-  Status WriteAsPrometheus(PrometheusWriter* w, const std::string& prefix) const override;
+  Status WriteAsPrometheus(PrometheusWriter* w, const std::string& prefix,
+                           const std::string& labels) const override;
 
   // Returns a snapshot of this histogram including the bucketed values and counts.
   Status GetHistogramSnapshotPB(HistogramSnapshotPB* snapshot_pb,
diff --git a/src/kudu/util/prometheus_writer.cc b/src/kudu/util/prometheus_writer.cc
index d68f88b9e..fa1fb1378 100644
--- a/src/kudu/util/prometheus_writer.cc
+++ b/src/kudu/util/prometheus_writer.cc
@@ -18,7 +18,100 @@
 #include "kudu/util/prometheus_writer.h"
 
 #include <sstream>
+#include <string>
+#include <unordered_map>
+#include <utility>
 
-void PrometheusWriter::WriteEntry(const std::string& data) {
+#include <glog/logging.h>
+
+#include "kudu/gutil/map-util.h"
+
+using std::string;
+using std::unordered_map;
+
+const char kMetricEntityIdMaster[] = "kudu.master";
+const char kMetricEntityIdTabletServer[] = "kudu.tabletserver";
+
+void PrometheusWriter::WriteEntry(const string& data) {
   *output_ << data;
 }
+
+bool PrometheusWriter::ShouldWriteHelpAndType(const string& metric_name) {
+  return written_help_types_.emplace(metric_name).second;
+}
+
+string EscapePrometheusLabelValue(const string& value) {
+  string result;
+  result.reserve(value.size());
+  for (char c : value) {
+    switch (c) {
+      case '\\': result += "\\\\"; break;
+      case '"':  result += "\\\""; break;
+      case '\n': result += "\\n"; break;
+      default:   result += c; break;
+    }
+  }
+  return result;
+}
+
+string BuildPrometheusLabels(
+    const string& entity_type,
+    const string& entity_id,
+    const unordered_map<string, string>& attrs) {
+  DCHECK(entity_type == "server" ||
+         entity_type == "table" ||
+         entity_type == "tablet")
+      << "unexpected entity type: " << entity_type;
+  if (entity_type == "server") {
+    return BuildServerPrometheusLabels(entity_id, attrs);
+  }
+  return BuildTableTabletPrometheusLabels(entity_type, entity_id, attrs);
+}
+
+string BuildServerPrometheusLabels(
+    const string& entity_id,
+    const unordered_map<string, string>& attrs) {
+  string labels;
+  if (entity_id == kMetricEntityIdMaster) {
+    labels = "type=\"master\"";
+  } else if (entity_id == kMetricEntityIdTabletServer) {
+    labels = "type=\"tserver\"";
+  } else {
+    LOG(DFATAL) << "Unexpected server-level metric entity: " << entity_id;
+    labels = "type=\"" + EscapePrometheusLabelValue(entity_id) + "\"";
+  }
+
+  const auto* uuid = FindOrNull(attrs, string("uuid"));
+  if (uuid) {
+    DCHECK(uuid->find_first_of("\\\"\n") == string::npos)
+        << "uuid needs escaping: " << *uuid;
+    labels += ",id=\"" + *uuid + "\"";
+  }
+
+  return labels;
+}
+
+string BuildTableTabletPrometheusLabels(
+    const string& entity_type,
+    const string& entity_id,
+    const unordered_map<string, string>& attrs) {
+  DCHECK(entity_type == "table" || entity_type == "tablet")
+      << "unexpected entity type: " << entity_type;
+  DCHECK(entity_id.find_first_of("\\\"\n") == string::npos)
+      << "entity_id needs escaping: " << entity_id;
+
+  string labels;
+  labels += "type=\"" + entity_type + "\"";
+  labels += ",id=\"" + entity_id + "\"";
+  // Add well-known attributes in a stable order.
+  static const char* const kKnownAttrs[] = {
+    "table_id", "table_name"
+  };
+  for (const char* key : kKnownAttrs) {
+    const auto* val = FindOrNull(attrs, string(key));
+    if (val) {
+      labels += "," + string(key) + "=\"" + EscapePrometheusLabelValue(*val) + "\"";
+    }
+  }
+  return labels;
+}
diff --git a/src/kudu/util/prometheus_writer.h b/src/kudu/util/prometheus_writer.h
index 528438f6a..05c7a253b 100644
--- a/src/kudu/util/prometheus_writer.h
+++ b/src/kudu/util/prometheus_writer.h
@@ -18,6 +18,8 @@
 
 #include <iosfwd>
 #include <string>
+#include <unordered_map>
+#include <unordered_set>
 
 class PrometheusWriter {
 
@@ -26,6 +28,56 @@ class PrometheusWriter {
 
   void WriteEntry(const std::string& data);
 
+  // Returns true if HELP/TYPE for the given metric name has not been written yet,
+  // and marks it as written. Returns false if already written (i.e. skip duplicate).
+  bool ShouldWriteHelpAndType(const std::string& metric_name);
+
  private:
   std::ostringstream* output_;
+  std::unordered_set<std::string> written_help_types_;
 };
+
+// Metric entity IDs for server-level metric entities.
+extern const char kMetricEntityIdMaster[];      // "kudu.master"
+extern const char kMetricEntityIdTabletServer[]; // "kudu.tabletserver"
+
+// Escape a string value for use in a Prometheus label value.
+// Escapes backslash, double-quote, and newline characters.
+std::string EscapePrometheusLabelValue(const std::string& value);
+
+// Build a Prometheus labels string from entity type, id, and attributes.
+// The returned string has the form: type="tablet",tablet_id="xxx",table_id="yyy",...
+// without surrounding braces and without a trailing comma.
+std::string BuildPrometheusLabels(
+    const std::string& entity_type,
+    const std::string& entity_id,
+    const std::unordered_map<std::string, std::string>& attrs);
+
+// Normalize a Prometheus labels string for injection before additional labels.
+//
+// Many Prometheus output format strings append more labels after an existing labels
+// string (e.g. "{<labels>unit_type=\"bytes\"}"). To avoid relying on a silent
+// trailing-comma contract, call this helper to ensure the returned string is either
+// empty or ends with a comma.
+inline std::string PrometheusLabelPrefixForInjection(const std::string& labels) {
+    if (labels.empty()) {
+        return "";
+    }
+    if (labels.back() == ',') {
+        return labels;
+    }
+    return labels + ",";
+}
+
+// Build Prometheus label string for server-level entities (master/tserver).
+// Returns labels of the form: type="master",id="<uuid>"
+std::string BuildServerPrometheusLabels(
+    const std::string& entity_id,
+    const std::unordered_map<std::string, std::string>& attrs);
+
+// Build Prometheus label string for table/tablet entities.
+// Returns labels of the form: type="<entity_type>",id="<entity_id>"[,table_id=...,table_name=...]
+std::string BuildTableTabletPrometheusLabels(
+    const std::string& entity_type,
+    const std::string& entity_id,
+    const std::unordered_map<std::string, std::string>& attrs);
diff --git a/src/kudu/util/test_util.cc b/src/kudu/util/test_util.cc
index ab160ab9e..81c1e9b30 100644
--- a/src/kudu/util/test_util.cc
+++ b/src/kudu/util/test_util.cc
@@ -28,7 +28,7 @@
 #include <memory>
 #include <ostream>
 #include <string>
-#include <unordered_set>
+#include <tuple>
 #include <utility>
 #include <vector>
 
@@ -61,7 +61,6 @@
 #include "kudu/util/status.h"
 #include "kudu/util/string_case.h"
 #include "kudu/util/subprocess.h"
-#include "kudu/util/test_macros.h"
 
 DEFINE_string(test_leave_files, "on_failure",
               "Whether to leave test files around after the test run. "
@@ -725,37 +724,49 @@ const unordered_map<string, string>& GetMasterWebserverEndpoints(const string& t
 
 void CheckPrometheusOutput(const string& prometheus_output) {
   vector<string> lines = strings::Split(prometheus_output, "\n", strings::SkipEmpty());
-  vector<vector<string>> metric_groups;
-  // Split the lines into groups. Every group contains a help line, a type line and
-  // then lines with the actual metric values in this order.
+
+  // Single-pass validation: collect HELP/TYPE declarations and verify that
+  // they appear before any corresponding value lines (Prometheus exposition
+  // format requires HELP/TYPE to precede metric values).
+  std::unordered_map<string, string> help_lines;
+  std::unordered_map<string, string> type_lines;
   for (const auto& line : lines) {
-    if (HasPrefixString(line, "# HELP")) {
-      metric_groups.push_back({line});
-    } else if (HasPrefixString(line, "# TYPE")) {
-      metric_groups.back().push_back(line);
-    } else {
-      metric_groups.back().push_back(line);
+    if (HasPrefixString(line, "# HELP ")) {
+      vector<string> parts(strings::Split(line, " "));
+      ASSERT_GE(parts.size(), 3);
+      const string& name = parts[2];
+      ASSERT_TRUE(help_lines.emplace(name, line).second)
+          << "Duplicate HELP for metric: " << name;
+    } else if (HasPrefixString(line, "# TYPE ")) {
+      vector<string> parts(strings::Split(line, " "));
+      ASSERT_GE(parts.size(), 4);
+      const string& name = parts[2];
+      ASSERT_TRUE(type_lines.emplace(name, line).second)
+          << "Duplicate TYPE for metric: " << name;
+    } else if (!HasPrefixString(line, "#")) {
+      // This is a value line. Verify that HELP and TYPE have already been seen.
+      auto brace_pos = line.find('{');
+      auto space_pos = line.find(' ');
+      auto end_pos = std::min(brace_pos, space_pos);
+      ASSERT_NE(end_pos, string::npos) << "Malformed value line: " << line;
+      string metric_name = line.substr(0, end_pos);
+      ASSERT_TRUE(help_lines.count(metric_name) > 0)
+          << "Value line before or without HELP for metric: " << metric_name
+          << "\n  line: " << line;
+      ASSERT_TRUE(type_lines.count(metric_name) > 0)
+          << "Value line before or without TYPE for metric: " << metric_name
+          << "\n  line: " << line;
     }
   }
 
-  std::unordered_set<string> metric_names;
-  for (const auto& group : metric_groups) {
-    ASSERT_GE(group.size(), 3);
-    ASSERT_STR_MATCHES(group[0], "^# HELP ");
-    ASSERT_STR_MATCHES(group[1], "^# TYPE ");
-    vector<string> help_line_split(strings::Split(group[0], " "));
-    vector<string> type_line_split(strings::Split(group[1], " "));
-    ASSERT_GE(help_line_split.size(), 3);
-    ASSERT_GE(type_line_split.size(), 3);
-    string name_from_help_line = help_line_split[2];
-    string name_from_type_line = type_line_split[2];
-    ASSERT_EQ(name_from_type_line, name_from_help_line);
-    ASSERT_TRUE(metric_names.emplace(name_from_help_line).second)
-        << "Duplicate metric: " << name_from_help_line;
-    for (int i = 2; i < group.size(); i++) {
-      ASSERT_TRUE(HasPrefixString(group[i], name_from_help_line))
-          << "Every line should start with the expected metric name: " << name_from_help_line;
-    }
+  // Every HELP should have a corresponding TYPE and vice versa.
+  for (const auto& [name, _] : help_lines) {
+    ASSERT_TRUE(type_lines.count(name) > 0)
+        << "HELP without TYPE for: " << name;
+  }
+  for (const auto& [name, _] : type_lines) {
+    ASSERT_TRUE(help_lines.count(name) > 0)
+        << "TYPE without HELP for: " << name;
   }
 }