You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by mi...@apache.org on 2026/06/03 17:47:30 UTC

(impala) branch master updated: IMPALA-14332: Add X-Request-Id as HttpRequestId attribute on root OTel span

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

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git


The following commit(s) were added to refs/heads/master by this push:
     new 3ae0a559b IMPALA-14332: Add X-Request-Id as HttpRequestId attribute on root OTel span
3ae0a559b is described below

commit 3ae0a559be45e8d375ca54cc75953182d6d27ff0
Author: Arnab Karmakar <ar...@gmail.com>
AuthorDate: Thu Feb 19 21:56:04 2026 -0800

    IMPALA-14332: Add X-Request-Id as HttpRequestId attribute on root OTel span
    
    When using the hs2-http protocol, the X-Request-Id HTTP header value
    is now captured and added as an attribute named "HttpRequestId" on the
    root OpenTelemetry span. The iteration count suffix (e.g., "-8" in
    "uuid-8") that the Impala shell appends is automatically removed to
    provide a clean UUID for tracing.
    
    Implementation details:
    - Capture X-Request-Id header in THttpServer and store in ConnectionContext
    - Propagate value to SessionState during session creation
    - Add HttpRequestId attribute to root span in SpanManager constructor
    
    Testing:
    - Added C++ unit tests (otel-test.cc) for request ID processing
    - Added Python integration test using ImpalaHS2Client over hs2-http
    - Test verifies HttpRequestId attribute format and cross-checks with logs
    
    Change-Id: I9e14f5b503ff7379463332bae34c266afc395524
    Reviewed-on: http://gerrit.cloudera.org:8080/24008
    Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
    Tested-by: Michael Smith <mi...@cloudera.com>
---
 be/src/observe/otel-trace-manager-test.cc | 62 +++++++++++++++++++++++++++++++
 be/src/observe/otel-trace-manager.cc      | 55 +++++++++++++++++++++++++++
 be/src/observe/otel-trace-manager.h       |  6 +++
 be/src/rpc/authentication.cc              | 10 +++++
 be/src/rpc/thrift-server.h                |  3 ++
 be/src/service/impala-hs2-server.cc       |  1 +
 be/src/service/impala-server.h            |  4 ++
 be/src/transport/THttpServer.cpp          | 10 +++--
 be/src/transport/THttpServer.h            |  6 +++
 tests/custom_cluster/test_otel_trace.py   | 55 ++++++++++++++++++++++++++-
 tests/util/otel_trace.py                  | 56 +++++++++++++++++++++++-----
 11 files changed, 254 insertions(+), 14 deletions(-)

diff --git a/be/src/observe/otel-trace-manager-test.cc b/be/src/observe/otel-trace-manager-test.cc
index 9889067ae..a9690c55c 100644
--- a/be/src/observe/otel-trace-manager-test.cc
+++ b/be/src/observe/otel-trace-manager-test.cc
@@ -119,3 +119,65 @@ TEST(OtelTraceManagerTest, TraceQueryNotCalled) {
   EXPECT_FALSE(filesystem::exists(trace_file));
 } // test OtelTraceManagerTest.TraceQueryNotCalled
 
+// Test processing of X-Request-Id header values to remove iteration count.
+TEST(OtelTraceManagerTest, ProcessRequestIdForAttribute) {
+  // Test with a valid UUID without iteration count
+  string result = test::process_request_id_for_attribute_for_testing(
+      "18bb03c8-7de6-11f0-9112-8b736586fd91");
+  EXPECT_EQ("18bb03c8-7de6-11f0-9112-8b736586fd91", result);
+
+  // Test with a valid UUID with iteration count
+  result = test::process_request_id_for_attribute_for_testing(
+      "18bb03c8-7de6-11f0-9112-8b736586fd91-8");
+  EXPECT_EQ("18bb03c8-7de6-11f0-9112-8b736586fd91", result);
+
+  // Test with a valid UUID with multi-digit iteration count
+  result = test::process_request_id_for_attribute_for_testing(
+      "18bb03c8-7de6-11f0-9112-8b736586fd91-123");
+  EXPECT_EQ("18bb03c8-7de6-11f0-9112-8b736586fd91", result);
+
+  // Test with zero as iteration count
+  result = test::process_request_id_for_attribute_for_testing(
+      "18bb03c8-7de6-11f0-9112-8b736586fd91-0");
+  EXPECT_EQ("18bb03c8-7de6-11f0-9112-8b736586fd91", result);
+
+  // Test with uppercase UUID
+  result = test::process_request_id_for_attribute_for_testing(
+      "18BB03C8-7DE6-11F0-9112-8B736586FD91");
+  EXPECT_EQ("18BB03C8-7DE6-11F0-9112-8B736586FD91", result);
+
+  // Test with mixed case UUID
+  result = test::process_request_id_for_attribute_for_testing(
+      "18Bb03C8-7dE6-11f0-9112-8B736586fD91-5");
+  EXPECT_EQ("18Bb03C8-7dE6-11f0-9112-8B736586fD91", result);
+
+  // Test with empty string
+  result = test::process_request_id_for_attribute_for_testing("");
+  EXPECT_EQ("", result);
+
+  // Test with non-numeric suffix (should not be removed)
+  result = test::process_request_id_for_attribute_for_testing(
+      "18bb03c8-7de6-11f0-9112-8b736586fd91-abc");
+  EXPECT_EQ("18bb03c8-7de6-11f0-9112-8b736586fd91-abc", result);
+
+  // Test with UUID that has no hyphens
+  result = test::process_request_id_for_attribute_for_testing(
+      "18bb03c87de611f091128b736586fd91");
+  EXPECT_EQ("18bb03c87de611f091128b736586fd91", result);
+
+  // Test with UUID that has no hyphens but has iteration count appended with hyphen
+  result = test::process_request_id_for_attribute_for_testing(
+      "18bb03c87de611f091128b736586fd91-5");
+  EXPECT_EQ("18bb03c87de611f091128b736586fd91", result);
+
+  // Test with UUID where last segment is all decimal digits (should NOT be removed)
+  // Per RFC9562, UUID last segment is always 12 chars
+  result = test::process_request_id_for_attribute_for_testing(
+      "a6dd52ba-18d1-11f1-ba97-665407384305");
+  EXPECT_EQ("a6dd52ba-18d1-11f1-ba97-665407384305", result);
+
+  // Test with UUID where last segment is all decimal digits, plus iteration count
+  result = test::process_request_id_for_attribute_for_testing(
+      "a6dd52ba-18d1-11f1-ba97-665407384305-2");
+  EXPECT_EQ("a6dd52ba-18d1-11f1-ba97-665407384305", result);
+}
diff --git a/be/src/observe/otel-trace-manager.cc b/be/src/observe/otel-trace-manager.cc
index 1f5cc0247..f95667dda 100644
--- a/be/src/observe/otel-trace-manager.cc
+++ b/be/src/observe/otel-trace-manager.cc
@@ -54,6 +54,7 @@ DECLARE_bool(otel_trace_exhaustive_dchecks);
 
 // Names of attributes only on Root spans.
 static constexpr char const* ATTR_ERROR_MESSAGE = "ErrorMessage";
+static constexpr char const* ATTR_HTTP_REQUEST_ID = "HttpRequestId";
 static constexpr char const* ATTR_QUERY_START_TIME = "QueryStartTime";
 static constexpr char const* ATTR_RETRIED_QUERY_ID = "RetriedQueryId";
 static constexpr char const* ATTR_RUNTIME = "Runtime";
@@ -122,6 +123,37 @@ static void debug_log_span(const BufferedSpan* span, const string& span_name,
   }
 } // function debug_log_span
 
+// Helper function to process X-Request-Id header value by removing the iteration count.
+// The Impala shell appends an iteration count to the request ID (e.g., "-8" in
+// "18bb03c8-7de6-11f0-9112-8b736586fd91-8"). This function removes that suffix.
+// Per RFC9562, a UUID in hex-and-dash format has a 12-character final segment.
+// We distinguish iteration count from UUID last segment by length.
+static string process_request_id_for_attribute(const string& request_id) {
+  if (request_id.empty()) return "";
+
+  size_t last_hyphen = request_id.rfind('-');
+  if (last_hyphen == string::npos || last_hyphen >= request_id.length() - 1) {
+    return request_id;
+  }
+
+  string suffix = request_id.substr(last_hyphen + 1);
+
+  // UUID last segment is always 12 hex characters
+  if (suffix.length() == 12) {
+    return request_id;  // This is the UUID's last segment, not an iteration count
+  }
+
+  // Check if suffix is all decimal digits (iteration count)
+  for (char c : suffix) {
+    if (!isdigit(c)) {
+      return request_id;  // Not all digits, return original
+    }
+  }
+
+  // All digits and not 12 chars long - it's an iteration count
+  return request_id.substr(0, last_hyphen);
+} // function process_request_id_for_attribute
+
 OtelTraceManager::OtelTraceManager(nostd::shared_ptr<trace::Tracer> tracer,
     ClientRequestState* client_request_state) : tracer_(std::move(tracer)),
     client_request_state_(client_request_state),
@@ -158,6 +190,13 @@ OtelTraceManager::OtelTraceManager(nostd::shared_ptr<trace::Tracer> tracer,
               ExecEnv::GetInstance()->configured_backend_address())}},
         context::Context().SetValue(trace::kIsRootSpanKey, true),
         trace::SpanKind::kServer);
+
+    // Add HttpRequestId if X-Request-Id header was provided via hs2-http
+    if (client_request_state_->session() != nullptr &&
+        !client_request_state_->session()->http_request_id.empty()) {
+      span_root_->SetAttribute(ATTR_HTTP_REQUEST_ID, process_request_id_for_attribute(
+          client_request_state_->session()->http_request_id));
+    }
   }
 } // ctor
 
@@ -301,6 +340,16 @@ void OtelTraceManager::StartChildSpanInit() {
         PrintId(client_request_state_->session_id()));
     span->SetAttribute(ATTR_USER_NAME,
         client_request_state_->effective_user());
+
+    // Add HttpRequestId if X-Request-Id header was provided via hs2-http
+    if (client_request_state_->session() != nullptr &&
+        !client_request_state_->session()->http_request_id.empty()) {
+      string processed_request_id = process_request_id_for_attribute(
+          client_request_state_->session()->http_request_id);
+      if (!processed_request_id.empty()) {
+        span->SetAttribute(ATTR_HTTP_REQUEST_ID, processed_request_id);
+      }
+    }
   }
 } // function StartChildSpanInit
 
@@ -693,4 +742,10 @@ void OtelTraceManager::EndChildSpan(const ChildSpanType& span_type,
   }
 } // function EndChildSpan
 
+namespace test {
+string process_request_id_for_attribute_for_testing(const string& request_id) {
+  return process_request_id_for_attribute(request_id);
+}
+} // namespace test
+
 } // namespace impala
\ No newline at end of file
diff --git a/be/src/observe/otel-trace-manager.h b/be/src/observe/otel-trace-manager.h
index 8387f0d9d..e60675796 100644
--- a/be/src/observe/otel-trace-manager.h
+++ b/be/src/observe/otel-trace-manager.h
@@ -199,4 +199,10 @@ private:
   bool started_ = false;
 };  // class OtelTraceManager
 
+namespace test {
+// Testing helper function to process X-Request-Id header values.
+// Removes iteration count suffix while preserving the UUID portion.
+std::string process_request_id_for_attribute_for_testing(const std::string& request_id);
+} // namespace test
+
 } // namespace impala
diff --git a/be/src/rpc/authentication.cc b/be/src/rpc/authentication.cc
index df47e92dc..691a6cddd 100644
--- a/be/src/rpc/authentication.cc
+++ b/be/src/rpc/authentication.cc
@@ -722,6 +722,12 @@ bool SetOrigin(
   return false;
 }
 
+bool SetRequestId(ThriftServer::ConnectionContext* connection_context,
+    const std::string& request_id) {
+  connection_context->http_request_id = request_id;
+  return false;
+}
+
 static bool TrustedDomainCheck(ThriftServer::ConnectionContext* connection_context,
     const AuthenticationHash& hash, const std::string& origin,
     const string& auth_header) {
@@ -1619,6 +1625,8 @@ void SecureAuthProvider::SetupConnectionContext(
       }
       callbacks.set_http_origin_fn = std::bind(SetOrigin, connection_ptr.get(),
           std::placeholders::_1);
+      callbacks.set_http_request_id_fn = std::bind(SetRequestId, connection_ptr.get(),
+          std::placeholders::_1);
       http_input_transport->setCallbacks(callbacks);
       http_output_transport->setCallbacks(callbacks);
       socket = down_cast<TSocket*>(http_input_transport->getUnderlyingTransport().get());
@@ -1682,6 +1690,8 @@ void NoAuthProvider::SetupConnectionContext(
       callbacks.return_headers_fn = std::bind(ReturnHeaders, connection_ptr.get());
       callbacks.set_http_origin_fn = std::bind(SetOrigin, connection_ptr.get(),
           std::placeholders::_1);
+      callbacks.set_http_request_id_fn = std::bind(SetRequestId, connection_ptr.get(),
+          std::placeholders::_1);
       http_input_transport->setCallbacks(callbacks);
       http_output_transport->setCallbacks(callbacks);
       socket = down_cast<TSocket*>(http_input_transport->getUnderlyingTransport().get());
diff --git a/be/src/rpc/thrift-server.h b/be/src/rpc/thrift-server.h
index 2fe01138e..badf8ecb2 100644
--- a/be/src/rpc/thrift-server.h
+++ b/be/src/rpc/thrift-server.h
@@ -128,6 +128,9 @@ class ThriftServer {
     /// If using hs2-http protocol, this is the origin of the session
     /// as recorded in the X-Forwarded-For http message header.
     std::string http_origin;
+    /// If using hs2-http protocol, this is the request ID from the
+    /// X-Request-Id http message header.
+    std::string http_request_id;
     std::string server_name;
     /// Used to pass HTTP headers generated by the input transport to the output transport
     /// to be returned.
diff --git a/be/src/service/impala-hs2-server.cc b/be/src/service/impala-hs2-server.cc
index 20dfe1caa..e4a688d4c 100644
--- a/be/src/service/impala-hs2-server.cc
+++ b/be/src/service/impala-hs2-server.cc
@@ -344,6 +344,7 @@ void ImpalaServer::OpenSession(TOpenSessionResp& return_val,
   }
   state->network_address = ThriftServer::GetThreadConnectionContext()->network_address;
   state->http_origin = ThriftServer::GetThreadConnectionContext()->http_origin;
+  state->http_request_id = ThriftServer::GetThreadConnectionContext()->http_request_id;
   state->last_accessed_ms = UnixMillis();
   // request.client_protocol is not guaranteed to be a valid TProtocolVersion::type, so
   // loading it can cause undefined behavior. Instead, we copy it to a value of the
diff --git a/be/src/service/impala-server.h b/be/src/service/impala-server.h
index 7b26d7576..037765b26 100644
--- a/be/src/service/impala-server.h
+++ b/be/src/service/impala-server.h
@@ -631,6 +631,10 @@ class ImpalaServer : public ImpalaServiceIf,
     /// as recorded in the X-Forwarded-For http message header.
     std::string http_origin;
 
+    /// If using hs2-http protocol, this is the request ID from the
+    /// X-Request-Id http message header.
+    std::string http_request_id;
+
     /// Protects all fields below. See "Locking" in the class comment for lock
     /// acquisition order.
     std::mutex lock;
diff --git a/be/src/transport/THttpServer.cpp b/be/src/transport/THttpServer.cpp
index 43ea10d70..bd6650c4d 100644
--- a/be/src/transport/THttpServer.cpp
+++ b/be/src/transport/THttpServer.cpp
@@ -281,9 +281,8 @@ void THttpServer::headersDone() {
   }
 
   // Trim and truncate the value of the 'X-Forwarded-For' header.
-  string origin = origin_;
-  // After copying origin, reset the value so that it can be reused for the next message.
-  origin_ = "";
+  string origin;
+  std::swap(origin, origin_);
   StripWhiteSpace(&origin);
   if (origin.length() > MAX_X_FORWARDED_HEADER_LENGTH) {
     origin = origin.substr(0, MAX_X_FORWARDED_HEADER_LENGTH);
@@ -291,6 +290,11 @@ void THttpServer::headersDone() {
   // Store the truncated value of the 'X-Forwarded-For' header in the Connection Context.
   callbacks_.set_http_origin_fn(origin);
 
+  // Store the value of the 'X-Request-Id' header in the Connection Context.
+  string request_id;
+  std::swap(request_id, header_x_request_id_);
+  callbacks_.set_http_request_id_fn(request_id);
+
   if (!has_ldap_ && !has_kerberos_ && !has_saml_ && !has_jwt_ && !has_oauth_) {
     // We don't need to authenticate.
     resetAuthState();
diff --git a/be/src/transport/THttpServer.h b/be/src/transport/THttpServer.h
index 82708c849..0de87aeb7 100644
--- a/be/src/transport/THttpServer.h
+++ b/be/src/transport/THttpServer.h
@@ -115,6 +115,12 @@ public:
       return false;
     };
 
+    // Function that stores the connection's 'X-Request-Id' header in the Connection
+    // Context so that it can be tracked.
+    std::function<bool(std::string)> set_http_request_id_fn = [&](const std::string&) {
+      return false;
+    };
+
     // Function that takes the connection's 'Authorization' header and returns true if
     // the basic auth header contains a valid username.
     std::function<bool(const std::string&)> trusted_auth_header_handle_fn =
diff --git a/tests/custom_cluster/test_otel_trace.py b/tests/custom_cluster/test_otel_trace.py
index 996e066c7..4c346cb0b 100644
--- a/tests/custom_cluster/test_otel_trace.py
+++ b/tests/custom_cluster/test_otel_trace.py
@@ -28,6 +28,7 @@ from thrift.transport.TTransport import TBufferedTransport
 from impala_thrift_gen.ImpalaService import ImpalaHiveServer2Service
 from impala_thrift_gen.TCLIService import TCLIService
 from impala.error import HiveServer2Error
+from shell.impala_shell.impala_client import ImpalaHS2Client
 from tests.common.custom_cluster_test_suite import CustomClusterTestSuite
 from tests.common.file_utils import count_lines, wait_for_file_line_count
 from tests.common.impala_connection import \
@@ -57,13 +58,13 @@ class TestOtelTraceBase(CustomClusterTestSuite):
 
   def assert_trace(self, query_id, query_profile, cluster_id, trace_cnt=1, err_span="",
       missing_spans=[], async_close=False, exact_trace_cnt=False,
-      adm_result_missing=False):
+      adm_result_missing=False, http_request_id=None):
     """Helper method to assert a trace exists in the trace file with the required inputs
        for log file path, trace file path, and trace file line count (that was determined
        before the test ran)."""
     assert_trace(self.build_log_path("impalad", "INFO"), self.trace_file_path,
         self.trace_file_count, query_id, query_profile, cluster_id, trace_cnt, err_span,
-        missing_spans, async_close, exact_trace_cnt, adm_result_missing)
+        missing_spans, async_close, exact_trace_cnt, adm_result_missing, http_request_id)
 
 
 @CustomClusterTestSuite.with_args(
@@ -545,6 +546,56 @@ class TestOtelTraceSelectsDMLs(TestOtelTraceBase):
           err_span="AdmissionControl",
           adm_result_missing=True)
 
+  def test_http_request_id_attribute(self):
+    """Asserts that when X-Request-Id header is provided via hs2-http protocol,
+       it is added as an attribute named HttpRequestId on the root span with
+       the iteration count removed."""
+
+    # Python implementation of process_request_id_for_attribute
+    def process_request_id_py(request_id):
+      if not request_id:
+        return ""
+      last_hyphen = request_id.rfind('-')
+      if last_hyphen == -1:
+        return request_id
+      return request_id[:last_hyphen]
+
+    # Create hs2-http client with http_tracing enabled to send X-Request-Id headers
+    impalad_service = self.cluster.impalads[0].service
+    client = ImpalaHS2Client(
+        (impalad_service.external_interface, impalad_service.hs2_http_port),
+        fetch_size=1024,
+        kerberos_host_fqdn=None,
+        use_http_base_transport=True,
+        http_path='cliservice',
+        http_tracing=True)
+
+    try:
+      client.connect()
+      query = "SELECT COUNT(*) FROM functional.alltypes"
+      query_handle = client.execute_query(query, {})
+      query_id = client.get_query_id_str(query_handle)
+
+      client.wait_to_finish(query_handle)
+
+      runtime_profile, _ = client.get_runtime_profile(query_handle)
+      client.close_query(query_handle)
+
+      # Get the X-Request-Id from the client
+      raw_request_id = client._current_request_id
+      assert raw_request_id is not None, "Client request ID should be set"
+
+      expected_http_request_id = process_request_id_py(raw_request_id)
+
+      self.assert_trace(
+          query_id=query_id,
+          query_profile=runtime_profile,
+          cluster_id="select_dml",
+          http_request_id=expected_http_request_id)
+
+    finally:
+      client.close_connection()
+
 
 class TestOtelTraceSelectQueued(TestOtelTraceBase):
   """Tests that require setting additional startup flags to assert admission control
diff --git a/tests/util/otel_trace.py b/tests/util/otel_trace.py
index 08dd8fef9..3941b37d4 100644
--- a/tests/util/otel_trace.py
+++ b/tests/util/otel_trace.py
@@ -20,6 +20,7 @@ import logging
 import os
 import sys
 from time import sleep
+from uuid import UUID
 
 from tests.common.environ import IMPALA_LOCAL_BUILD_VERSION
 from tests.common.file_utils import grep_file_first, wait_for_file_line_count
@@ -348,7 +349,16 @@ def parse_trace_file(file_path, query_id):
 
 def assert_trace(log_file_path, trace_file_path, trace_file_count, query_id,
     query_profile, cluster_id, trace_cnt=1, err_span="", missing_spans=[],
-    async_close=False, exact_trace_cnt=False, adm_result_missing=False):
+    async_close=False, exact_trace_cnt=False, adm_result_missing=False,
+    http_request_id=None):
+  # Validate http_request_id is a valid UUID if provided
+  if http_request_id is not None:
+    try:
+      UUID(http_request_id)
+    except ValueError as e:
+      assert False, "http_request_id should be a valid UUID, got: '{}'. Error: {}".format(
+          http_request_id, str(e))
+
   # Parse common values needed in multiple asserts.
   session_id = parse_session_id(query_profile)
   db_user = parse_db_user(query_profile)
@@ -400,7 +410,7 @@ def assert_trace(log_file_path, trace_file_path, trace_file_count, query_id,
   # Assert root span.
   root_span_id = __assert_rootspan_attrs(trace.root_span, query_id, session_id,
     cluster_id, db_user, "default-pool", impala_query_state, query_status,
-    original_query_id, retried_query_id, coordinator, log_file_path)
+    original_query_id, retried_query_id, coordinator, log_file_path, http_request_id)
 
   # Assert Init span.
   if "Init" not in missing_spans:
@@ -411,7 +421,7 @@ def assert_trace(log_file_path, trace_file_path, trace_file_count, query_id,
     __assert_initspan_attrs(trace.child_spans, root_span_id, query_id, session_id,
         cluster_id, db_user, "default-pool", parse_default_db(query_profile),
         parse_sql(query_profile).replace('\n', ' '), original_query_id, coordinator,
-        log_file_path)
+        log_file_path, http_request_id)
 
   # Assert Submitted span.
   if "Submitted" not in missing_spans:
@@ -636,14 +646,16 @@ def __assert_span_events(span, expected_events=[]):
 
 def __assert_rootspan_attrs(span, query_id, session_id, cluster_id, user_name,
     request_pool, state, err_msg, original_query_id, retried_query_id, coordinator,
-    log_file_path):
+    log_file_path, http_request_id=None):
   """
     Helper function that asserts the common attributes in the root span.
   """
 
   root_span_id, _ = __find_span_log(log_file_path, "Root", query_id)
-  __assert_scopespan_common(span, query_id, True, "Root", 14, "", log_file_path, None,
-      err_msg)
+  # Root span has 14 base attributes, plus 1 if HttpRequestId is present
+  expected_attr_count = 15 if http_request_id is not None else 14
+  __assert_scopespan_common(span, query_id, True, "Root", expected_attr_count, "",
+      log_file_path, None, err_msg)
 
   __assert_attr(span.name, span.attributes, "QueryId", query_id)
   __assert_attr(span.name, span.attributes, "SessionId", session_id)
@@ -655,12 +667,24 @@ def __assert_rootspan_attrs(span, query_id, session_id, cluster_id, user_name,
   __assert_attr(span.name, span.attributes, "RetriedQueryId", retried_query_id)
   __assert_attr(span.name, span.attributes, "Coordinator", coordinator)
 
+  # If http_request_id is expected, validate it exists and matches the expected value
+  if http_request_id is not None:
+    assert "HttpRequestId" in span.attributes, \
+        "Root span should have HttpRequestId attribute"
+    actual_http_request_id = span.attributes["HttpRequestId"].value
+    assert actual_http_request_id == http_request_id, \
+        "HttpRequestId mismatch. Expected: '{}', Actual: '{}'".format(
+            http_request_id, actual_http_request_id)
+  else:
+    assert "HttpRequestId" not in span.attributes, \
+        "Root span should not have HttpRequestId attribute when not expected"
+
   return root_span_id
 
 
 def __assert_initspan_attrs(spans, root_span_id, query_id, session_id, cluster_id,
     user_name, request_pool, default_db, query_string, original_query_id, coordinator,
-    log_file_path):
+    log_file_path, http_request_id=None):
   """
     Helper function that asserts the common and span-specific attributes in the
     init span.
@@ -669,8 +693,10 @@ def __assert_initspan_attrs(spans, root_span_id, query_id, session_id, cluster_i
   # Locate the init span and assert.
   init_span = __find_span(spans, "Init", query_id)
 
-  __assert_scopespan_common(init_span, query_id, False, "Init", 9, INITIALIZED,
-      log_file_path, root_span_id)
+  # Init span has 9 base attributes, plus 1 if HttpRequestId is present
+  expected_attr_count = 10 if http_request_id is not None else 9
+  __assert_scopespan_common(init_span, query_id, False, "Init", expected_attr_count,
+      INITIALIZED, log_file_path, root_span_id)
 
   __assert_attr(init_span.name, init_span.attributes, "QueryId", query_id)
   __assert_attr(init_span.name, init_span.attributes, "SessionId", session_id)
@@ -683,6 +709,18 @@ def __assert_initspan_attrs(spans, root_span_id, query_id, session_id, cluster_i
       original_query_id)
   __assert_attr(init_span.name, init_span.attributes, "Coordinator", coordinator)
 
+  # If http_request_id is expected, validate it exists and matches the expected value
+  if http_request_id is not None:
+    assert "HttpRequestId" in init_span.attributes, \
+        "Init span should have HttpRequestId attribute"
+    actual_http_request_id = init_span.attributes["HttpRequestId"].value
+    assert actual_http_request_id == http_request_id, \
+        "Init span HttpRequestId mismatch. Expected: '{}', Actual: '{}'".format(
+            http_request_id, actual_http_request_id)
+  else:
+    assert "HttpRequestId" not in init_span.attributes, \
+        "Init span should not have HttpRequestId attribute when not expected"
+
   __assert_span_events(init_span)