// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/platform/telemetry_1ds.h" #include "core/platform/device_id.h" #include "core/platform/telemetry_context.h" #include "core/platform/telemetry_no_throw.h" #include "core/platform/telemetry_sampling.h" #include "core/platform/telemetry_sha256.h" #include "core/platform/telemetry_environment.h" #include "core/platform/telemetry_guid.h" #include "core/platform/telemetry_1ds_platform.h" #include "core/platform/telemetry_redaction.h" #ifdef __APPLE__ #include #endif #if defined(ORT_TELEMETRY_USES_STATIC_CURL) #include #endif // 1DS SDK #include #include #if defined(__ANDROID__) #include "http/HttpClient_Android.hpp" #endif #include #include #include #include #include #include #include "core/common/common.h" #include "core/common/inlined_containers_fwd.h" #include "core/common/logging/logging.h" #include "core/common/status.h" #include "onnxruntime_config.h" // Optional compile-time tenant-token override, generated by CMake into the build tree (keeps an // injected token off the compiler command line). See the tenant-token handling below. #include "onnxruntime_telemetry_tenant_token.h" // Optional caller-framework label provided at build time via -Donnxruntime_CALLER_FRAMEWORK // (empty by default). Redistributors that embed ORT set it to attribute their telemetry, matching // the Windows provider's frameworkName field. #ifndef ORT_CALLER_FRAMEWORK #define ORT_CALLER_FRAMEWORK "" #endif using namespace Microsoft::Applications::Events; namespace onnxruntime { // OneDsTelemetry can be constructed during early Env initialization (before logging registers a // default logger) and destroyed late at process exit, so only emit warnings when a default logger // exists, to avoid touching a missing/destroyed LoggingManager. #define ORT_TELEMETRY_WARN(stream_expr) \ do { \ if (::onnxruntime::logging::LoggingManager::HasDefaultLogger()) { \ LOGS_DEFAULT(WARNING) << stream_expr; \ } \ } while (0) // Static member initialization std::atomic OneDsTelemetry::global_register_count_{0}; std::mutex OneDsTelemetry::global_mutex_; std::shared_mutex OneDsTelemetry::mutex_; ::Microsoft::Applications::Events::ILogManager* OneDsTelemetry::log_manager_ = nullptr; std::atomic<::Microsoft::Applications::Events::ILogger*> OneDsTelemetry::logger_{nullptr}; std::unique_ptr<::Microsoft::Applications::Events::ILogConfiguration> OneDsTelemetry::config_; std::atomic OneDsTelemetry::enabled_{true}; std::atomic OneDsTelemetry::telemetry_disabled_{false}; std::atomic OneDsTelemetry::network_context_suppressed_{false}; std::atomic OneDsTelemetry::projection_{0}; std::atomic OneDsTelemetry::process_info_logged_{false}; #if !defined(ORT_TELEMETRY_TENANT_TOKEN) namespace { // Decode a base64-encoded string at runtime. std::string DecodeBase64(const std::string& encoded) { auto DecodeChar = [](char c) -> int { if (c >= 'A' && c <= 'Z') return c - 'A'; if (c >= 'a' && c <= 'z') return c - 'a' + 26; if (c >= '0' && c <= '9') return c - '0' + 52; if (c == '+') return 62; if (c == '/') return 63; return -1; }; std::string result; result.reserve(encoded.size() * 3 / 4); uint32_t accum = 0; int bits = 0; for (char c : encoded) { int val = DecodeChar(c); if (val < 0) continue; accum = (accum << 6) | static_cast(val); bits += 6; if (bits >= 8) { bits -= 8; result.push_back(static_cast((accum >> bits) & 0xFF)); } } return result; } // In-repo default 1DS ingestion token used when no build-time override is provided. std::string GetToken() { static constexpr char kXorKey[] = "OnnxRuntime"; constexpr size_t klen = sizeof(kXorKey) - 1; std::string decoded = DecodeBase64(telemetry_internal::GetDefaultEncodedToken()); for (size_t i = 0; i < decoded.size(); ++i) { decoded[i] = static_cast(decoded[i] ^ kXorKey[i % klen]); } return decoded; } } // namespace #endif // !defined(ORT_TELEMETRY_TENANT_TOKEN) // Event priority mapping (1DS priorities) enum class EventPriority { NORMAL = EventLatency_Normal, // Most events HIGH = EventLatency_RealTime, // RuntimeError CRITICAL = EventLatency_RealTime // ProcessInfo, SessionCreation }; // Helper class to build events with common properties class EventBuilder { private: EventProperties props_; public: explicit EventBuilder(std::string event_name, EventPriority priority) : props_(std::move(event_name)) { // Set latency/priority props_.SetLatency(static_cast(priority)); props_.SetPopsample(100.0); // All ORT telemetry is required system metadata (no PII) props_.SetLevel(DIAG_LEVEL_REQUIRED); } EventBuilder& SetPopsample(double sample_rate_percent) { props_.SetPopsample(sample_rate_percent); return *this; } EventBuilder& AddString(const char* key, std::string_view value) { if (!value.empty()) { props_.SetProperty(key, telemetry_detail::BoundedTelemetryString(value)); } return *this; } EventBuilder& AddString(const char* key, const char* value) { return AddString(key, telemetry_detail::TelemetryCStringView(value, kMaxTelemetryStringLength + 3)); } EventBuilder& AddInt32(const char* key, int32_t value) { props_.SetProperty(key, static_cast(value)); return *this; } EventBuilder& AddInt64(const char* key, int64_t value) { props_.SetProperty(key, value); return *this; } EventBuilder& AddBool(const char* key, bool value) { props_.SetProperty(key, value); return *this; } EventBuilder& AddUInt32(const char* key, uint32_t value) { props_.SetProperty(key, static_cast(value)); return *this; } EventBuilder& AddDouble(const char* key, double value) { props_.SetProperty(key, value); return *this; } // Helper for vector to comma-separated string EventBuilder& AddStringList(const char* key, const std::vector& vec) { if (!vec.empty()) { props_.SetProperty(key, telemetry_detail::JoinTelemetryStrings(vec)); } return *this; } template EventBuilder& AddMap(const char* key, const Map& map) { if (!map.empty()) { props_.SetProperty(key, telemetry_detail::FormatTelemetryMap(map)); } return *this; } // Helper for batch size duration map EventBuilder& AddBatchSizeDurations(const std::unordered_map& durations) { props_.SetProperty("totalRunDurationPerBatchSize", telemetry_detail::FormatTelemetryMap(durations, ", ", ": ")); return *this; } EventProperties Build() { return std::move(props_); } }; namespace { class PendingLogManager { public: PendingLogManager(std::unique_ptr config, ILogManager* manager) : config_(std::move(config)), manager_(manager) {} ~PendingLogManager() noexcept { if (manager_ != nullptr && config_ != nullptr) { ORT_TRY { LogManagerProvider::Release(*config_); } ORT_CATCH(...) { } } } ILogManager* Get() const { return manager_; } void Commit(std::unique_ptr& config, ILogManager*& manager) noexcept { config = std::move(config_); manager = manager_; manager_ = nullptr; } PendingLogManager(const PendingLogManager&) = delete; PendingLogManager& operator=(const PendingLogManager&) = delete; private: std::unique_ptr config_; ILogManager* manager_; }; const std::string& GetAppSessionGuidInternal() { static const std::string guid = GenerateGuidV4(); return guid; } #if defined(ORT_TELEMETRY_USES_STATIC_CURL) std::string GetCertificateAuthorityBundlePath() { const auto ssl_cert_file = telemetry_detail::ReadTelemetryEnvironment("SSL_CERT_FILE", telemetry_detail::kMaxTelemetryPathBytes); if (!ssl_cert_file) { ORT_TELEMETRY_WARN("Ignoring oversized or unreadable telemetry SSL_CERT_FILE"); } else if (!ssl_cert_file->empty() && access(ssl_cert_file->c_str(), R_OK) == 0) { return *ssl_cert_file; } constexpr const char* kCertificateAuthorityBundlePaths[] = { "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", "/etc/ssl/ca-bundle.pem", "/etc/pki/tls/cacert.pem", "/etc/ssl/cert.pem", "/var/lib/ca-certificates/ca-bundle.pem", }; for (const char* path : kCertificateAuthorityBundlePaths) { if (access(path, R_OK) == 0) { return path; } } return {}; } #endif bool PrepareSampledEvent(EventBuilder& event, uint32_t session_id) { if (!telemetry_internal::ShouldSampleSession(GetAppSessionGuidInternal(), session_id)) { return false; } event.SetPopsample(telemetry_internal::kModelSessionSampleRatePercent); return true; } bool PrepareHighVolumeEvent(EventBuilder& event, uint32_t session_id) { if (!telemetry_internal::ShouldSampleSession( GetAppSessionGuidInternal(), session_id, telemetry_internal::kHighVolumeEventSampleRatePercent)) { return false; } event.SetPopsample(telemetry_internal::kHighVolumeEventSampleRatePercent); return true; } bool PrepareSampledProcessEvent(EventBuilder& event) { if (!telemetry_internal::ShouldSampleSession( GetAppSessionGuidInternal(), 0, telemetry_internal::kOtherProcessEventSampleRatePercent)) { return false; } event.SetPopsample(telemetry_internal::kOtherProcessEventSampleRatePercent); return true; } } // namespace namespace telemetry_internal { const std::string& GetAppSessionGuid() { return GetAppSessionGuidInternal(); } } // namespace telemetry_internal void OneDsTelemetry::ReportFailure(const char* operation_name, const char* message) { if (message != nullptr) { ORT_TELEMETRY_WARN("[Telemetry] " << operation_name << " failed: " << message); } else { ORT_TELEMETRY_WARN("[Telemetry] " << operation_name << " failed with an unknown exception"); } } OneDsTelemetry::OneDsTelemetry() { std::lock_guard lock(global_mutex_); // Always increment so destructor pairing is symmetric global_register_count_++; if (global_register_count_ == 1) { RunTelemetryOperation("Initialize", [&]() { Initialize(); }); } } OneDsTelemetry::OneDsTelemetry(const Telemetry& local_telemetry) : OneDsTelemetry() { local_telemetry_ = &local_telemetry; } OneDsTelemetry::~OneDsTelemetry() { std::lock_guard lock(global_mutex_); global_register_count_--; if (global_register_count_ == 0) { ORT_TRY { Shutdown(); } ORT_CATCH(...) { // Don't throw from a destructor. This can run during process teardown after logging and/or // 1DS static state has started shutting down, so avoid touching any other infrastructure here. } } } void OneDsTelemetry::LogEventAsync(Microsoft::Applications::Events::EventProperties&& props) const { // Hold a shared (reader) lock for the duration of the LogEvent call so the logger and its owning // log manager cannot be torn down underneath us: Initialize()/Shutdown() take this lock // exclusively. The shared lock still allows multiple threads to log concurrently. std::shared_lock lock(mutex_); auto* logger = logger_.load(std::memory_order_acquire); if (logger == nullptr) { return; } const bool is_process_info = props.GetName() == "ProcessInfo"; if (!is_process_info && !network_context_suppressed_.load(std::memory_order_acquire)) { const bool suppressed = telemetry_internal::TryTelemetryOperationNoThrow([&]() { telemetry_internal::SuppressNetworkContext(*logger->GetSemanticContext()); }); if (suppressed) { network_context_suppressed_.store(true, std::memory_order_release); } } logger->LogEvent(std::move(props)); if (is_process_info) { // ProcessInfo captures PAL network context. Clearing it afterward is best effort. const bool suppressed = telemetry_internal::TryTelemetryOperationNoThrow([&]() { telemetry_internal::SuppressNetworkContext(*logger->GetSemanticContext()); }); if (suppressed) { network_context_suppressed_.store(true, std::memory_order_release); } } } void OneDsTelemetry::Initialize() { std::unique_lock lock(mutex_); // Full suppression is process-wide and irreversible: never create the uploader, emit an event, or // persist a device id. Latching also covers later ORT reinitialization after an environment change. if (telemetry_disabled_.load(std::memory_order_acquire) || IsRunningInCI() || IsRunningUnitTests() || IsTelemetryDisabledByEnvironment()) { telemetry_disabled_.store(true, std::memory_order_release); enabled_.store(false, std::memory_order_release); return; } // The official Android AAR initializes the SDK's Java HttpClient before ORT is loaded. Native-only // integrators must provide the same application-context initialization before creating an OrtEnv. #if defined(__ANDROID__) if (!HttpClient_Android::GetClientInstance()) { ORT_TELEMETRY_WARN("Android telemetry is unavailable because the 1DS Java HttpClient was not initialized"); return; } #endif // Keep configuration and manager local until setup completes. If any later operation throws, // PendingLogManager releases the partial SDK state before the outer no-throw boundary handles it. auto pending_config = std::make_unique(); auto& config = *pending_config; config[CFG_STR_COLLECTOR_URL] = "https://mobile.events.data.microsoft.com/OneCollector/1.0"; config[CFG_BOOL_ENABLE_TRACE] = false; config[CFG_INT_TRACE_LEVEL_MASK] = 0; config[CFG_INT_SDK_MODE] = SdkModeTypes::SdkModeTypes_CS; #if defined(_WIN32) // The 1DS network detector leaves a netprofm.dll allocation at process exit. config[CFG_BOOL_ENABLE_NET_DETECT] = false; #endif #if defined(__APPLE__) // System SQLite is shared with other libraries; let it manage its own lifetime. config["skipSqliteInitAndShutdown"] = "true"; #endif // Persist pending events without blocking process teardown on uploads. config[CFG_INT_MAX_TEARDOWN_TIME] = 0; config[CFG_INT_RAM_QUEUE_SIZE] = 512 * 1024; #if defined(ORT_TELEMETRY_USES_STATIC_CURL) if (std::string ca_bundle = GetCertificateAuthorityBundlePath(); !ca_bundle.empty()) { config[CFG_MAP_HTTP][CFG_STR_HTTP_SSL_CAINFO] = ca_bundle; } else { ORT_TELEMETRY_WARN("No readable CA bundle was found; telemetry HTTPS uploads will be unavailable"); } #endif #if !defined(__ANDROID__) // Configure the desktop cache in the same directory as device ID storage. Android's Java // HttpClient supplies the app-private cache directory to 1DS. { std::string cache_dir = DeviceId::EnsureStorageDirectory(); if (!cache_dir.empty()) { std::string cache_path = telemetry_internal::GetCachePath(cache_dir); if (cache_path.size() > telemetry_detail::kMaxTelemetryPathBytes) { ORT_TELEMETRY_WARN("Telemetry is unavailable because the cache path exceeds the byte limit"); return; } config[CFG_STR_CACHE_FILE_PATH] = cache_path; } } #endif // Create log manager via LogManagerProvider (recommended for production use, // per LogManager_Creation_and_Lifecycle_Management.md). status_t status; auto* pending_manager = LogManagerProvider::CreateLogManager("OnnxRuntime", true, config, status); PendingLogManager pending_log_manager(std::move(pending_config), pending_manager); if (status != STATUS_SUCCESS || pending_log_manager.Get() == nullptr) { ORT_TELEMETRY_WARN("Failed to create telemetry LogManager, status: " << status); return; } // Get logger for our tenant: an official build's override from the generated header // (ORT_TELEMETRY_TENANT_TOKEN) if present, otherwise the in-repo default. #if defined(ORT_TELEMETRY_TENANT_TOKEN) const std::string tenant_token = ORT_TELEMETRY_TENANT_TOKEN; #else const std::string tenant_token = GetToken(); #endif auto* logger = pending_log_manager.Get()->GetLogger(tenant_token.c_str()); if (logger == nullptr) { ORT_TELEMETRY_WARN("Failed to get telemetry logger"); return; } (void)telemetry_internal::TryTelemetryOperationNoThrow([&]() { auto& context = *logger->GetSemanticContext(); telemetry_internal::SuppressUnneededCommonContext(context); telemetry_internal::SetApplicationNameFromProcessName( context, ScrubStringForTelemetry(GetProcessName())); }); bool network_context_suppressed = false; if (process_info_logged_.load(std::memory_order_acquire)) { // ProcessInfo is once per process; a reinitialized logger no longer needs network context. network_context_suppressed = telemetry_internal::TryTelemetryOperationNoThrow([&]() { telemetry_internal::SuppressNetworkContext(*logger->GetSemanticContext()); }); } network_context_suppressed_.store(network_context_suppressed, std::memory_order_release); // Use BEST_EFFORT transmit profile to minimize battery and network impact. // Events are batched and uploaded at a lower cadence. pending_log_manager.Get()->SetTransmitProfile(TransmitProfile_BestEffort); // Device ID. #if defined(__ANDROID__) || (defined(__APPLE__) && TARGET_OS_IOS) // Mobile (Android/iOS): leave the device ID to the 1DS SDK, which uses the platform's own // identifier (identifierForVendor on iOS, ANDROID_ID on Android). Do not override it. #else // Desktop: send a hashed version of our persistent UUID (the "c:" prefix marks it as a // caller-supplied identifier); the raw UUID itself is never transmitted. auto& device_id = DeviceId::Instance(); std::string raw_device_id = device_id.GetValue(); if (!raw_device_id.empty()) { // All Microsoft AI developer tools derive the same upload identifier; never transmit the raw UUID. logger->GetSemanticContext()->SetDeviceId("c:" + telemetry_internal::Sha256::HashStringHex(raw_device_id)); } #endif // Add only ORT version and process-wide correlation context. logger->SetContext("AppSessionGuid", GetAppSessionGuidInternal()); logger->SetContext("LibraryVersion", ORT_VERSION); // Caller-framework label from the build-time ORT_CALLER_FRAMEWORK option; only stamped when a // redistributor sets it, so standard builds add nothing. Matches the Windows provider's field. if (std::string framework = ORT_CALLER_FRAMEWORK; !framework.empty()) { logger->SetContext("frameworkName", framework); } // Publish the fully-configured logger atomically; concurrent readers observe it only now. // enabled_ is left to its default / the runtime EnableTelemetryEvents()/DisableTelemetryEvents() // opt-in state rather than being force-set here. pending_log_manager.Commit(config_, log_manager_); logger_.store(logger, std::memory_order_release); } void OneDsTelemetry::Shutdown() { std::unique_lock lock(mutex_); // Clear the logger so concurrent LogEventAsync() readers (which take the shared lock) observe // nullptr and skip. enabled_ is intentionally left untouched: it reflects the user's // EnableTelemetryEvents()/DisableTelemetryEvents() opt-in state, so a later Initialize() (e.g. in // dynamic load/unload of the last instance) can resume telemetry without a forced re-enable. logger_ = nullptr; // Owned by log_manager_, will be destroyed with it if (log_manager_ && config_) { // Per SDK use-after-free docs (use-after-free.md): // Flush() must be called before FlushAndTeardown() to ensure all pending // events are persisted to offline storage. FlushAndTeardown() internally // calls PauseActivity() + WaitPause() to quiesce the SDK. log_manager_->Flush(); log_manager_->FlushAndTeardown(); // Release the log manager instance via LogManagerProvider LogManagerProvider::Release(*config_); log_manager_ = nullptr; config_.reset(); } } void OneDsTelemetry::EnableTelemetryEvents() const { if (!telemetry_disabled_.load(std::memory_order_acquire)) { enabled_.store(true, std::memory_order_release); } } void OneDsTelemetry::DisableTelemetryEvents() const { enabled_.store(false, std::memory_order_release); } void OneDsTelemetry::SetLanguageProjection(uint32_t projection) const { RunTelemetryOperation("SetLanguageProjection", [&]() { projection_ = projection; if (local_telemetry_ != nullptr) { local_telemetry_->SetLanguageProjection(projection); } }); } bool OneDsTelemetry::IsEnabled() const { // Reflect actual readiness: the opt-out flag AND a successfully-initialized logger. return enabled_.load(std::memory_order_acquire) && logger_.load(std::memory_order_acquire) != nullptr; } unsigned char OneDsTelemetry::Level() const { // POSIX telemetry has no ETW-style level/keyword control plane; report zero. return 0; } uint64_t OneDsTelemetry::Keyword() const { return 0; } void OneDsTelemetry::LogProcessInfo() const { RunTelemetryOperation("LogProcessInfo", [&]() { if (!IsEnabled()) { return; } // Log process info only once if (process_info_logged_.exchange(true)) { return; } #if !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) auto& device_id = DeviceId::Instance(); const DeviceIdStatus device_id_status = device_id.GetStatus(); if (device_id_status == DeviceIdStatus::Failed) { ORT_TELEMETRY_WARN("Failed to persist telemetry device ID; using an in-memory identifier"); } #endif auto builder = EventBuilder("ProcessInfo", EventPriority::CRITICAL); const auto host_environment = GetHostEnvironmentInfo(); builder.AddString("runtimeVersion", ORT_VERSION) #if defined(__ANDROID__) || (defined(__APPLE__) && TARGET_OS_IOS) .AddString("DeviceInfo.Status", "Mobile") #else .AddString("DeviceInfo.Status", DeviceId::Instance().GetStatusString()) #endif .AddString("osDescription", GetOsDescription()) .AddString("architecture", GetArchitecture()) .AddString("cpuModel", GetCpuModel()) .AddString("deviceClass", GetDeviceClass()) .AddBool("isContainer", host_environment.is_container) .AddString("containerType", host_environment.container_type) .AddBool("isVirtualMachine", host_environment.is_virtual_machine) .AddString("virtualizationType", host_environment.virtualization_type) .AddBool("isEmulator", host_environment.is_emulator) .AddString("hostEnvironment", host_environment.environment_class) .AddString("environmentDetectionConfidence", host_environment.detection_confidence) .AddString("deviceIdScope", host_environment.device_id_scope) .AddInt32("processorCount", telemetry_internal::GetProcessorCount()) .AddInt64("totalMemoryMB", GetTotalMemoryMB()); LogEventAsync(builder.Build()); }); } void OneDsTelemetry::LogSessionCreationStart(uint32_t session_id) const { // Start/stop markers are retained by TraceLogging. 1DS completion events carry local durations. (void)session_id; } void OneDsTelemetry::LogEvaluationStop(uint32_t session_id) const { // Per-run start/stop markers are useful for ETW tracing, but RuntimePerf already aggregates every // successful run for 1DS without putting synchronous telemetry work on the inference hot path. (void)session_id; } void OneDsTelemetry::LogEvaluationStart(uint32_t session_id) const { (void)session_id; } void OneDsTelemetry::LogSessionCreation( uint32_t session_id, int64_t ir_version, const std::string& model_producer_name, const std::string& model_producer_version, const std::string& model_domain, const std::unordered_map& domain_to_version_map, const std::string& model_file_name, const std::string& model_graph_name, const std::string& model_weight_type, const std::string& model_graph_hash, const std::string& model_weight_hash, const std::unordered_map& model_metadata, const std::string& loadedFrom, const std::vector& execution_provider_ids, const std::string& hardware_device_types, const std::string& hardware_vendor_ids, const std::string& ep_versions, bool use_fp16, bool captureState) const { RunTelemetryOperation("LogSessionCreation", [&]() { if (captureState) { if (local_telemetry_ != nullptr && enabled_.load(std::memory_order_acquire) && !telemetry_disabled_.load(std::memory_order_acquire)) { local_telemetry_->LogSessionCreation( session_id, ir_version, model_producer_name, model_producer_version, model_domain, domain_to_version_map, model_file_name, model_graph_name, model_weight_type, model_graph_hash, model_weight_hash, model_metadata, loadedFrom, execution_provider_ids, hardware_device_types, hardware_vendor_ids, ep_versions, use_fp16, true); } return; } if (!IsEnabled()) { return; } auto builder = EventBuilder("SessionCreation", EventPriority::CRITICAL); if (!PrepareSampledEvent(builder, session_id)) { return; } builder.AddUInt32("sessionId", session_id) .AddInt64("irVersion", ir_version) .AddUInt32("OrtProgrammingProjection", projection_.load()) .AddString("modelProducerName", model_producer_name) .AddString("modelProducerVersion", model_producer_version) .AddString("modelDomain", model_domain) .AddMap("domainToVersionMap", domain_to_version_map) .AddString("modelFileName", model_file_name) .AddString("modelGraphName", model_graph_name) .AddString("modelWeightType", model_weight_type) .AddString("modelGraphHash", model_graph_hash) .AddString("modelWeightHash", model_weight_hash) .AddString("loadedFrom", loadedFrom) .AddStringList("executionProviderIds", execution_provider_ids) .AddString("hardwareDeviceTypes", hardware_device_types) .AddString("hardwareVendorIds", hardware_vendor_ids) .AddString("executionProviderVersions", ep_versions) .AddBool("usefp16", use_fp16); LogEventAsync(builder.Build()); }); } void OneDsTelemetry::LogCompileModelStart( uint32_t session_id, const std::string& input_source, const std::string& output_target, uint32_t flags, int graph_optimization_level, bool embed_ep_context, bool has_external_initializers_file, const std::vector& execution_provider_ids) const { RunTelemetryOperation("LogCompileModelStart", [&]() { if (!IsEnabled()) { return; } auto builder = EventBuilder("CompileModelStart", EventPriority::NORMAL); if (!PrepareSampledEvent(builder, session_id)) { return; } auto event = builder.AddUInt32("sessionId", session_id) .AddString("inputSource", input_source) .AddString("outputTarget", output_target) .AddUInt32("flags", flags) .AddInt32("graphOptimizationLevel", graph_optimization_level) .AddBool("embedEpContext", embed_ep_context) .AddBool("hasExternalInitializersFile", has_external_initializers_file) .AddStringList("executionProviderIds", execution_provider_ids) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogCompileModelComplete( uint32_t session_id, bool success, uint32_t error_code, uint32_t error_category, const std::string& error_message) const { RunTelemetryOperation("LogCompileModelComplete", [&]() { if (!IsEnabled()) { return; } auto builder = EventBuilder("CompileModelComplete", EventPriority::NORMAL); if (!PrepareSampledEvent(builder, session_id)) { return; } auto event = builder.AddUInt32("sessionId", session_id) .AddBool("success", success) .AddUInt32("errorCode", error_code) .AddUInt32("errorCategory", error_category) .AddString("errorMessage", ScrubStringForTelemetry(error_message)) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogRuntimeError( uint32_t session_id, const common::Status& status, const char* file, const char* function, uint32_t line) const { RunTelemetryOperation("LogRuntimeError", [&]() { if (!IsEnabled()) { return; } // __FILE__ may be an absolute build path that embeds developer/build directory names; emit only // the basename so remote telemetry doesn't leak usernames or local paths. std::string_view file_view = telemetry_detail::TelemetryCStringView(file, telemetry_detail::kMaxTelemetryPathBytes); if (file_view.size() > telemetry_detail::kMaxTelemetryPathBytes) { file_view = {}; } if (const size_t slash = file_view.find_last_of("/\\"); slash != std::string_view::npos) { file_view.remove_prefix(slash + 1); } const std::string scrubbed_file = ScrubStringForTelemetry(file_view); auto builder = EventBuilder("RuntimeError", EventPriority::HIGH); auto event = builder.AddUInt32("sessionId", session_id) .AddInt32("errorCode", static_cast(status.Code())) .AddInt32("errorCategory", static_cast(status.Category())) .AddString("errorMessage", ScrubStringForTelemetry(status.ErrorMessage())) .AddString("file", scrubbed_file) .AddString("function", function ? function : "") .AddUInt32("line", line) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogRuntimeInferenceError(uint32_t session_id, const common::Status& status, const std::string& ep_versions, const std::string& ep_device_types) const { RunTelemetryOperation("LogRuntimeInferenceError", [&]() { if (!IsEnabled()) { return; } auto builder = EventBuilder("RuntimeInferenceError", EventPriority::HIGH); auto event = builder.AddUInt32("sessionId", session_id) .AddInt32("errorCode", static_cast(status.Code())) .AddInt32("errorCategory", static_cast(status.Category())) .AddString("errorMessage", ScrubStringForTelemetry(status.ErrorMessage())) .AddString("executionProviderVersions", ep_versions) .AddString("executionProviderDeviceTypes", ep_device_types) .AddString("runtimeVersion", ORT_VERSION) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogRuntimePerf( uint32_t session_id, uint32_t total_runs_since_last, int64_t total_run_duration_since_last, const std::unordered_map& duration_per_batch_size) const { RunTelemetryOperation("LogRuntimePerf", [&]() { if (!IsEnabled()) { return; } auto builder = EventBuilder("RuntimePerf", EventPriority::NORMAL); if (!PrepareHighVolumeEvent(builder, session_id)) { return; } auto event = builder.AddUInt32("sessionId", session_id) .AddUInt32("totalRuns", total_runs_since_last) .AddInt64("totalRunDuration", total_run_duration_since_last) .AddBatchSizeDurations(duration_per_batch_size) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogAutoEpSelection( uint32_t session_id, const std::string& selection_policy, const std::vector& requested_execution_provider_ids, const std::vector& available_execution_provider_ids) const { RunTelemetryOperation("LogAutoEpSelection", [&]() { if (!IsEnabled()) { return; } auto builder = EventBuilder("EpAutoSelection", EventPriority::NORMAL); if (!PrepareSampledEvent(builder, session_id)) { return; } auto event = builder.AddUInt32("sessionId", session_id) .AddString("selectionPolicy", selection_policy) .AddStringList("requestedExecutionProviderIds", requested_execution_provider_ids) .AddStringList("availableExecutionProviderIds", available_execution_provider_ids) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogModelLoadStart(uint32_t session_id) const { (void)session_id; } void OneDsTelemetry::LogProviderOptions( const std::string& provider_id, const std::string& provider_options, bool capture_state) const { RunTelemetryOperation("LogProviderOptions", [&]() { // Custom provider values are not safe to upload, even after filesystem-path redaction. if (local_telemetry_ != nullptr && enabled_.load(std::memory_order_acquire) && !telemetry_disabled_.load(std::memory_order_acquire)) { local_telemetry_->LogProviderOptions(provider_id, provider_options, capture_state); } }); } void OneDsTelemetry::LogModelLoadEnd(uint32_t session_id, const common::Status& status, int64_t duration_us) const { RunTelemetryOperation("LogModelLoadEnd", [&]() { if (!IsEnabled()) { return; } auto builder = EventBuilder("ModelLoadEnd", EventPriority::NORMAL); if (!PrepareSampledEvent(builder, session_id)) { return; } auto event = builder.AddUInt32("sessionId", session_id) .AddBool("isSuccess", status.IsOK()) .AddInt32("errorCode", static_cast(status.Code())) .AddInt32("errorCategory", static_cast(status.Category())) .AddString("errorMessage", ScrubStringForTelemetry(status.ErrorMessage())) .AddInt64("durationUs", duration_us) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogSessionCreationEnd(uint32_t session_id, const common::Status& status, int64_t duration_us) const { RunTelemetryOperation("LogSessionCreationEnd", [&]() { if (!IsEnabled()) { return; } auto builder = EventBuilder("SessionCreationEnd", EventPriority::CRITICAL); if (!PrepareSampledEvent(builder, session_id)) { return; } auto event = builder.AddUInt32("sessionId", session_id) .AddBool("isSuccess", status.IsOK()) .AddInt32("errorCode", static_cast(status.Code())) .AddInt32("errorCategory", static_cast(status.Category())) .AddString("errorMessage", ScrubStringForTelemetry(status.ErrorMessage())) .AddInt64("durationUs", duration_us) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogEpDeviceUsage( uint32_t session_id, const std::string& ep_type, const std::string& hardware_device_type, uint32_t hardware_vendor_id, uint32_t hardware_device_id, const std::string& hardware_vendor, const std::string& ep_vendor, const std::string& ep_version, int assigned_node_count, uint32_t total_runs_since_last, int64_t total_run_duration_since_last) const { RunTelemetryOperation("LogEpDeviceUsage", [&]() { if (!IsEnabled()) { return; } auto builder = EventBuilder("EpDeviceUsage", EventPriority::NORMAL); if (!PrepareSampledEvent(builder, session_id)) { return; } auto event = builder.AddUInt32("sessionId", session_id) .AddString("executionProviderType", ep_type) .AddString("hardwareDeviceType", hardware_device_type) .AddUInt32("hardwareVendorId", hardware_vendor_id) .AddUInt32("hardwareDeviceId", hardware_device_id) .AddString("hardwareVendor", hardware_vendor) .AddString("epVendor", ep_vendor) .AddString("epVersion", ep_version) .AddInt32("assignedNodeCount", assigned_node_count) .AddUInt32("totalRunsSinceLast", total_runs_since_last) .AddInt64("totalRunDurationSinceLast", total_run_duration_since_last) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogRegisterEpLibraryStart(const std::string& registration_name) const { (void)registration_name; } void OneDsTelemetry::LogRegisterEpLibraryEnd(const std::string& registration_name, const common::Status& status, int64_t duration_us) const { RunTelemetryOperation("LogRegisterEpLibraryEnd", [&]() { if (!IsEnabled()) { return; } auto builder = EventBuilder("RegisterEpLibraryEnd", EventPriority::NORMAL); if (!PrepareSampledProcessEvent(builder)) { return; } auto event = builder.AddString("registrationName", registration_name) .AddBool("isSuccess", status.IsOK()) .AddInt32("errorCode", static_cast(status.Code())) .AddInt32("errorCategory", static_cast(status.Category())) .AddString("errorMessage", ScrubStringForTelemetry(status.ErrorMessage())) .AddInt64("durationUs", duration_us) .Build(); LogEventAsync(std::move(event)); }); } void OneDsTelemetry::LogRegisterEpLibraryWithLibPath(const std::string& registration_name, const std::string& lib_path) const { RunTelemetryOperation("LogRegisterEpLibraryWithLibPath", [&]() { if (!IsEnabled()) { return; } const std::string scrubbed_lib_path = ScrubStringForTelemetry(lib_path); auto builder = EventBuilder("RegisterEpLibraryWithLibPath", EventPriority::NORMAL); if (!PrepareSampledProcessEvent(builder)) { return; } auto event = builder.AddString("registrationName", registration_name) .AddString("libPath", scrubbed_lib_path) .Build(); LogEventAsync(std::move(event)); }); } } // namespace onnxruntime