Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
// 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 <TargetConditionals.h>
#endif
 
#if defined(ORT_TELEMETRY_USES_STATIC_CURL)
#include <unistd.h>
#endif
 
// 1DS SDK
#include <LogManagerProvider.hpp>
#include <ILogConfiguration.hpp>
#if defined(__ANDROID__)
#include "http/HttpClient_Android.hpp"
#endif
 
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <string_view>
#include <utility>
#include <vector>
 
#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<uint32_t> 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<bool> OneDsTelemetry::enabled_{true};
std::atomic<bool> OneDsTelemetry::telemetry_disabled_{false};
std::atomic<bool> OneDsTelemetry::network_context_suppressed_{false};
std::atomic<uint32_t> OneDsTelemetry::projection_{0};
std::atomic<bool> 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<uint32_t>(val);
    bits += 6;
    if (bits >= 8) {
      bits -= 8;
      result.push_back(static_cast<char>((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<char>(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<EventLatency>(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<int64_t>(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<int64_t>(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<std::string>& vec) {
    if (!vec.empty()) {
      props_.SetProperty(key, telemetry_detail::JoinTelemetryStrings(vec));
    }
    return *this;
  }
 
  template <typename Map>
  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<int64_t, long long>& durations) {
    props_.SetProperty("totalRunDurationPerBatchSize", telemetry_detail::FormatTelemetryMap(durations, ", ", ": "));
    return *this;
  }
 
  EventProperties Build() { return std::move(props_); }
};
 
namespace {
 
class PendingLogManager {
 public:
  PendingLogManager(std::unique_ptr<ILogConfiguration> 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<ILogConfiguration>& 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<ILogConfiguration> 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<std::mutex> 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<std::mutex> 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<std::shared_mutex> 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<std::shared_mutex> 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<ILogConfiguration>();
  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<std::shared_mutex> 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<std::string, int>& 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<std::string, std::string>& model_metadata,
    const std::string& loadedFrom,
    const std::vector<std::string>& 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<std::string>& 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<int32_t>(status.Code()))
                     .AddInt32("errorCategory", static_cast<int32_t>(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<int32_t>(status.Code()))
                     .AddInt32("errorCategory", static_cast<int32_t>(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<int64_t, long long>& 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<std::string>& requested_execution_provider_ids,
    const std::vector<std::string>& 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<int32_t>(status.Code()))
                     .AddInt32("errorCategory", static_cast<int32_t>(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<int32_t>(status.Code()))
                     .AddInt32("errorCategory", static_cast<int32_t>(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<int32_t>(status.Code()))
                     .AddInt32("errorCategory", static_cast<int32_t>(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