#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { using namespace Void::Observability; using Void::Testing::expect; using Void::Testing::expect_eq; using Void::Testing::require; [[nodiscard]] bool hex_matches_bucket_zero(const TraceId& tid, std::uint64_t denom) noexcept { std::uint64_t h = Void::Hash::fnv1a64( std::span{tid.bytes.data(), tid.bytes.size()}); return (h % denom) == 0; } [[nodiscard]] TraceId find_seeded_trace_id(std::uint64_t denom, bool want_sampled) { for (std::uint64_t s = 1; s < 50000; ++s) { auto tid = TraceId::generate_seeded(s); if (hex_matches_bucket_zero(tid, denom) == want_sampled) { return tid; } } return TraceId::generate_seeded(1); } struct DetachState { bool suspended{false}; bool resume_saw_empty_tls{false}; bool resumed_ok{false}; }; struct DetachAwaiter { bool ready{false}; DetachState* state{nullptr}; [[nodiscard]] bool await_ready() const noexcept { return ready; } void await_suspend(std::coroutine_handle<> h) noexcept { state->suspended = true; state->resume_saw_empty_tls = ScopedContext::current().empty(); h.resume(); } int await_resume() noexcept { state->resumed_ok = !ScopedContext::current().empty(); return 42; } }; struct OneShotCoro { struct promise_type { int result{0}; OneShotCoro get_return_object() { return OneShotCoro{ std::coroutine_handle::from_promise(*this)}; } std::suspend_never initial_suspend() noexcept { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void return_value(int v) noexcept { result = v; } void unhandled_exception() { std::terminate(); } }; std::coroutine_handle handle; ~OneShotCoro() { if (handle) { handle.destroy(); } } }; OneShotCoro run_context_awaitable(ContextSnapshot snap, DetachAwaiter& awaiter) { const int v = co_await with_context(std::move(snap), awaiter); co_return v; } } // namespace Void::Testing::Test observability_null_hooks_and_slot_lifecycle() { expect(!kNullObservationHooks.active()); const MetricPoint mp{ .name = "req", .kind = MetricKind::counter, .integer_delta = 1}; kNullObservationHooks.emit_metric(mp); kNullObservationHooks.emit_diagnostic( DiagnosticEvent{"obs", "ignored", false}); HookSlot slot; expect(!slot.active()); slot.invoke_metric(mp); auto owner = std::make_shared>(false); struct LifetimeTracker { std::shared_ptr> flag; ~LifetimeTracker() { flag->store(true, std::memory_order_release); } }; auto tracker = std::make_shared(owner); std::mutex mu; std::condition_variable cv; bool in_callback = false; bool proceed = false; std::atomic reentrant_drain_blocked{false}; const HookRegistrationId reg_id = slot.install_guarded( [&](const MetricPoint&) { // Reentrant emit is suppressed cleanly. slot.invoke_metric(mp); // Synchronous self-drain must fail with would_deadlock. if (slot.detach_and_drain(0) == DrainStatus::would_deadlock) { reentrant_drain_blocked.store(true, std::memory_order_release); } { std::unique_lock lock{mu}; in_callback = true; cv.notify_all(); cv.wait(lock, [&] { return proceed; }); } }, {}, tracker); tracker.reset(); expect(slot.active()); std::thread worker{[&] { slot.invoke_metric(mp); }}; { std::unique_lock lock{mu}; cv.wait(lock, [&] { return in_callback; }); } std::atomic drain_status{DrainStatus::not_found}; std::atomic drain_finished{false}; std::thread drainer{[&] { drain_status.store(slot.detach_and_drain(reg_id), std::memory_order_release); drain_finished.store(true, std::memory_order_release); }}; std::this_thread::sleep_for(std::chrono::milliseconds{10}); expect(!drain_finished.load(std::memory_order_acquire)); expect(!owner->load(std::memory_order_acquire)); { std::lock_guard lock{mu}; proceed = true; } cv.notify_all(); worker.join(); drainer.join(); expect(reentrant_drain_blocked.load()); expect(drain_status.load() == DrainStatus::drained); expect(owner->load(std::memory_order_acquire)); expect_eq(slot.reentrant_calls(), std::uint64_t{1}); // Throwing guarded hook quarantines after first exception. int calls_before_quarantine = 0; (void)slot.install_guarded([&](const MetricPoint&) { ++calls_before_quarantine; throw std::runtime_error{"boom"}; }); slot.invoke_metric(mp); slot.invoke_metric(mp); expect_eq(calls_before_quarantine, 1); expect(slot.is_quarantined()); expect_eq(slot.failed_calls(), std::uint64_t{1}); slot.reset_quarantine(); expect(!slot.is_quarantined()); slot.invoke_metric(mp); expect_eq(calls_before_quarantine, 2); } Void::Testing::Test observability_context_traceparent_baggage_and_async() { const TraceId tid = TraceId::generate_seeded(123); const SpanId sid = SpanId::generate_seeded(456); const TraceContext tc{tid, sid, kTraceFlagSampled}; expect(tc.valid()); expect(tc.sampled()); const auto header = tc.to_traceparent(); const auto parsed = TraceContext::from_traceparent(header); require(parsed.has_value()); expect(*parsed == tc); // Reject malformed, wrong version, uppercase, and zero-ID traceparent inputs. expect(!TraceContext::from_traceparent("short").has_value()); expect(!TraceContext::from_traceparent( "00-00000000000000000000000000000000-0102030405060708-01").has_value()); expect(!TraceContext::from_traceparent( "00-0102030405060708090a0b0c0d0e0f10-0000000000000000-01").has_value()); std::string upper = header; upper[3] = 'A'; expect(!TraceContext::from_traceparent(upper).has_value()); std::string bad_ver = header; bad_ver[0] = 'f'; bad_ver[1] = 'f'; expect(!TraceContext::from_traceparent(bad_ver).has_value()); ContextLimits slim_limits{}; slim_limits.max_baggage_items = 2; slim_limits.max_baggage_bytes = 20; const BaggageItem items[] = {{"env", "prod"}, {"tenant", "acme"}}; auto snap = ContextSnapshot::create(tc, items, slim_limits); require(snap.has_value()); expect_eq(snap->find_baggage("tenant").value_or(""), std::string_view{"acme"}); auto over_item = snap->with_baggage("extra", "1"); expect(!over_item.has_value()); // Scope restore across thrown exception. expect(ScopedContext::current().empty()); try { ScopedContext outer{*snap}; expect(!ScopedContext::current().empty()); throw std::runtime_error{"unwind"}; } catch (...) { } expect(ScopedContext::current().empty()); // bind_context preserves snapshot on worker thread and restores afterwards. std::optional observed_on_worker; auto task = bind_context(*snap, [&] { observed_on_worker = ScopedContext::current().trace(); }); bool empty_after_worker = false; std::thread t{[&] { task(); empty_after_worker = ScopedContext::current().empty(); }}; t.join(); require(observed_on_worker.has_value()); expect(*observed_on_worker == tc); expect(empty_after_worker); // ContextAwaitable restores TLS during await_resume without holding it over suspend. DetachState await_state; DetachAwaiter awaiter{false, &await_state}; auto coro = run_context_awaitable(*snap, awaiter); expect(await_state.suspended); expect(await_state.resume_saw_empty_tls); expect(await_state.resumed_ok); expect_eq(coro.handle.promise().result, 42); expect(ScopedContext::current().empty()); } Void::Testing::Test observability_metrics_shards_overflow_and_epoch() { Void::Time::ManualClock clock; MetricsLimits limits{}; limits.max_series_per_instrument = 2; limits.max_total_series = 4; std::uint64_t snapshot_total = 0; { auto reg_res = MetricRegistry::create(limits, clock); require(reg_res.has_value()); auto reg = std::move(*reg_res); auto ctr_res = reg.register_instrument(InstrumentSpec{ .name = "http_requests_total", .unit = "1", .kind = MetricKind::counter, .label_keys = {"route"}}); require(ctr_res.has_value()); const auto ctr = *ctr_res; // Schema mismatch conflict must fail. auto conflict = reg.register_instrument(InstrumentSpec{ .name = "http_requests_total", .unit = "1", .kind = MetricKind::gauge, .label_keys = {"route"}}); expect(!conflict.has_value()); auto lat_res = reg.register_instrument(InstrumentSpec{ .name = "request_duration_seconds", .unit = "s", .kind = MetricKind::histogram, .label_keys = {"route"}}); require(lat_res.has_value()); auto g_res = reg.register_instrument(InstrumentSpec{ .name = "inflight", .unit = "1", .kind = MetricKind::gauge}); require(g_res.has_value()); // Reject NaN gauge and histogram. expect(!reg.set_gauge(*g_res, std::numeric_limits::quiet_NaN()).has_value()); expect(!reg.observe_histogram(*lat_res, std::numeric_limits::infinity()).has_value()); // Hook integration. HookSlot slot; (void)slot.install(reg.make_hooks(), reg.keepalive()); const AttributeView r1[] = {{"route", "/a"}}; const AttributeView r2[] = {{"route", "/b"}}; const AttributeView r3[] = {{"route", "/c"}}; const AttributeView r4[] = {{"route", "/d"}}; // Exiting producer thread writes into its shard before terminating. std::thread producer{[&] { slot.invoke_metric(MetricPoint{ .name = "http_requests_total", .kind = MetricKind::counter, .integer_delta = 5, .attributes = r1}); }}; producer.join(); expect(reg.add_counter(ctr, 3, r1).has_value()); expect(reg.add_counter(ctr, 7, r2).has_value()); // Series 3 and 4 overflow into __overflow__. expect(reg.add_counter(ctr, 2, r3).has_value()); expect(reg.add_counter(ctr, 4, r4).has_value()); expect(reg.observe_histogram(*lat_res, 0.0005, r1).has_value()); expect(reg.observe_histogram(*lat_res, 25.0, r1).has_value()); expect(reg.set_gauge(*g_res, 9.5).has_value()); const auto snap = reg.snapshot(); expect_eq(snap.epoch, std::uint64_t{1}); expect_eq(snap.dropped_series, std::uint64_t{2}); expect_eq(snap.overflow_events, std::uint64_t{2}); const auto& ctr_snap = snap.instruments[0]; bool saw_overflow = false; std::uint64_t r1_count = 0; std::uint64_t overflow_count = 0; for (const auto& s : ctr_snap.series) { if (s.is_overflow) { saw_overflow = true; overflow_count = s.counter_value; } else if (!s.labels.empty() && s.labels[0].second == "/a") { r1_count = s.counter_value; } snapshot_total += s.counter_value; } expect(saw_overflow); expect_eq(r1_count, std::uint64_t{8}); expect_eq(overflow_count, std::uint64_t{6}); expect_eq(snapshot_total, std::uint64_t{21}); const auto text = TextSnapshotExporter::render_metrics(snap); expect(text.find("http_requests_total") != std::string::npos); reg.reset_epoch(); const auto after_reset = reg.snapshot(); expect_eq(after_reset.epoch, std::uint64_t{2}); expect_eq(after_reset.dropped_series, std::uint64_t{0}); (void)slot.detach_and_drain(0); } } Void::Testing::Test observability_tracer_sampling_budgets_and_exporter() { Void::Time::ManualClock mono_clock; Void::Time::ManualCivilClock civil_clock; auto exporter_calls = std::make_shared>(0); auto text_exp = std::make_shared(4096); TracingLimits limits{}; limits.root_sample_denominator = 100; limits.max_active_spans = 2; limits.max_completed_spans = 3; limits.max_export_retries = 2; limits.export_retry_budget = std::chrono::seconds{5}; bool fail_first = true; auto cb_exp = std::make_shared( [&](std::span batch) -> Void::Result::Result { exporter_calls->fetch_add(1, std::memory_order_relaxed); if (fail_first) { fail_first = false; return Void::Result::fail("transient export failure"); } return text_exp->export_spans(batch); }); auto tr_res = Tracer::create(limits, cb_exp, mono_clock, civil_clock); require(tr_res.has_value()); auto tracer = std::move(*tr_res); const ContextSnapshot empty_ctx{}; const TraceId unsampled_tid = find_seeded_trace_id(100, false); const TraceId sampled_tid = find_seeded_trace_id(100, true); { auto unsampled = tracer.start_span( empty_ctx, SpanSpec{.name = "root-unsampled", .explicit_root_trace_id = unsampled_tid}); expect(!unsampled.is_recording()); expect(unsampled.context().trace().has_value()); expect(!unsampled.context().trace()->sampled()); } auto root = tracer.start_span( empty_ctx, SpanSpec{.name = "root-sampled", .explicit_root_trace_id = sampled_tid}); expect(root.is_recording()); root.set_attribute("k", "v"); root.add_event("evt"); auto child = tracer.start_span(root.context(), SpanSpec{.name = "child-abandoned"}); expect(child.is_recording()); // Third active span exceeds max_active_spans (2) and returns inert span. { auto dropped = tracer.start_span(root.context(), SpanSpec{.name = "dropped-active"}); expect(!dropped.is_recording()); expect(dropped.context().trace().has_value()); } root.end(SpanStatus::ok); root.end(SpanStatus::error); // duplicate end counted without overwriting status { auto doomed = tracer.start_span(empty_ctx, SpanSpec{.name = "abandoned", .explicit_root_trace_id = sampled_tid}); expect(doomed.is_recording()); } // destructor abandons it const auto st_before_flush = tracer.stats(); expect_eq(st_before_flush.duplicate_ends, std::uint64_t{1}); expect_eq(st_before_flush.abandoned_spans, std::uint64_t{1}); expect_eq(st_before_flush.dropped_active_spans, std::uint64_t{1}); const auto report = tracer.close(); expect_eq(report.exported_spans, std::uint64_t{2}); expect_eq(report.retries, std::uint64_t{1}); expect_eq(report.failed_spans, std::uint64_t{0}); expect_eq(exporter_calls->load(), 2); const auto dumped = text_exp->text(); expect(dumped.find("root-sampled") != std::string::npos); expect(dumped.find("abandoned") != std::string::npos); // Closed tracer rejects active admission cleanly. auto after_close = tracer.start_span( empty_ctx, SpanSpec{.name = "after-close", .explicit_root_trace_id = sampled_tid}); expect(!after_close.is_recording()); }