diff --git a/include/Void/Observability/AsyncContext.hpp b/include/Void/Observability/AsyncContext.hpp new file mode 100644 index 0000000..d1d86d6 --- /dev/null +++ b/include/Void/Observability/AsyncContext.hpp @@ -0,0 +1,109 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace Void::Observability +{ + +/// Wrap any callable/task with an owned ContextSnapshot so execution on a +/// worker or executor installs ScopedContext across the invocation and restores +/// the worker thread's previous context afterward. +template +class BoundContextCallable +{ +public: + BoundContextCallable(ContextSnapshot snapshot, Fn fn) + : snapshot_(std::move(snapshot)) + , fn_(std::move(fn)) + { + } + + template + requires std::invocable + decltype(auto) operator()(Args&&... args) + { + ScopedContext guard{snapshot_}; + return std::invoke(fn_, std::forward(args)...); + } + + template + requires std::invocable + decltype(auto) operator()(Args&&... args) const + { + ScopedContext guard{snapshot_}; + return std::invoke(fn_, std::forward(args)...); + } + + [[nodiscard]] const ContextSnapshot& context() const noexcept + { + return snapshot_; + } + +private: + ContextSnapshot snapshot_; + Fn fn_; +}; + +template +[[nodiscard]] BoundContextCallable> + bind_context(ContextSnapshot snapshot, Fn&& fn) +{ + return BoundContextCallable>{ + std::move(snapshot), + std::forward(fn)}; +} + +/// Coroutine awaitable adapter that binds an owned ContextSnapshot without +/// keeping a thread-local ScopedContext active across coroutine suspension. +template +class ContextAwaitable +{ +public: + ContextAwaitable(ContextSnapshot snapshot, Awaitable awaitable) + : snapshot_(std::move(snapshot)) + , inner_(std::move(awaitable)) + { + } + + [[nodiscard]] decltype(auto) await_ready() + { + return inner_.await_ready(); + } + + [[nodiscard]] decltype(auto) await_suspend(std::coroutine_handle<> handle) + { + return inner_.await_suspend(handle); + } + + decltype(auto) await_resume() + { + ScopedContext guard{snapshot_}; + return inner_.await_resume(); + } + + [[nodiscard]] const ContextSnapshot& context() const noexcept + { + return snapshot_; + } + +private: + ContextSnapshot snapshot_; + Awaitable inner_; +}; + +template +[[nodiscard]] ContextAwaitable> + with_context(ContextSnapshot snapshot, Awaitable&& awaitable) +{ + return ContextAwaitable>{ + std::move(snapshot), + std::forward(awaitable)}; +} + +} // namespace Void::Observability diff --git a/include/Void/Observability/Context.hpp b/include/Void/Observability/Context.hpp new file mode 100644 index 0000000..945cdee --- /dev/null +++ b/include/Void/Observability/Context.hpp @@ -0,0 +1,553 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Observability +{ + +enum class ObservabilityErrorCode : std::int32_t { + invalid_argument = 1, + invalid_traceparent = 2, + schema_conflict = 3, + capacity_exceeded = 4, + cardinality_exceeded = 5, + closed = 6, + cancelled = 7, + timeout = 8, + unsupported_capability = 9, + would_deadlock = 10, + quarantined = 11 +}; + +[[nodiscard]] inline Void::Result::Error + make_observability_error(ObservabilityErrorCode code, + std::string message = {}) +{ + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case ObservabilityErrorCode::invalid_argument: + case ObservabilityErrorCode::invalid_traceparent: + kind = ErrorKind::invalid_argument; + break; + case ObservabilityErrorCode::schema_conflict: + case ObservabilityErrorCode::would_deadlock: + kind = ErrorKind::conflict; + break; + case ObservabilityErrorCode::capacity_exceeded: + case ObservabilityErrorCode::cardinality_exceeded: + kind = ErrorKind::exhausted; + break; + case ObservabilityErrorCode::closed: + case ObservabilityErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case ObservabilityErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case ObservabilityErrorCode::unsupported_capability: + kind = ErrorKind::unsupported; + break; + case ObservabilityErrorCode::quarantined: + kind = ErrorKind::internal; + break; + } + + return Error{ + kind, + std::move(message), + ErrorCode{Void::Result::kObservabilityErrorDomain, + static_cast(code)}}; +} + +namespace Detail +{ + +[[nodiscard]] constexpr int hex_nibble(char c) noexcept +{ + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return 10 + (c - 'a'); + } + return -1; +} + +template +[[nodiscard]] inline std::string bytes_to_hex( + const std::array& bytes) +{ + constexpr char kHex[] = "0123456789abcdef"; + std::string out; + out.resize(N * 2); + for (std::size_t i = 0; i < N; ++i) { + const auto v = static_cast(bytes[i]); + out[i * 2] = kHex[(v >> 4) & 0x0Fu]; + out[i * 2 + 1] = kHex[v & 0x0Fu]; + } + return out; +} + +template +[[nodiscard]] inline Void::Result::Result> + hex_to_bytes(std::string_view hex, std::string_view label) +{ + if (hex.size() != N * 2) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_traceparent, + std::string{label} + " hex length is invalid")); + } + std::array out{}; + for (std::size_t i = 0; i < N; ++i) { + const int hi = hex_nibble(hex[i * 2]); + const int lo = hex_nibble(hex[i * 2 + 1]); + if (hi < 0 || lo < 0) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_traceparent, + std::string{label} + " contains non-hex or non-lowercase characters")); + } + out[i] = static_cast((hi << 4) | lo); + } + return out; +} + +template +[[nodiscard]] inline std::array generate_nonzero_bytes(G& gen) +{ + std::uniform_int_distribution dist{0, 255}; + std::array out{}; + bool non_zero = false; + do { + non_zero = false; + for (auto& b : out) { + const auto v = static_cast(dist(gen)); + b = static_cast(v); + non_zero = non_zero || (v != 0); + } + } while (!non_zero); + return out; +} + +} // namespace Detail + +struct TraceId { + std::array bytes{}; + + [[nodiscard]] constexpr bool operator==(const TraceId&) const noexcept = default; + + [[nodiscard]] constexpr bool is_zero() const noexcept + { + for (const auto b : bytes) { + if (b != std::byte{0}) { + return false; + } + } + return true; + } + + [[nodiscard]] std::string to_hex() const + { + return Detail::bytes_to_hex(bytes); + } + + [[nodiscard]] static Void::Result::Result + from_hex(std::string_view hex) + { + auto parsed = Detail::hex_to_bytes<16>(hex, "TraceId"); + if (!parsed) { + return Void::Result::fail(std::move(parsed).error()); + } + TraceId id{*parsed}; + if (id.is_zero()) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_traceparent, + "TraceId must not be all zeros")); + } + return id; + } + + [[nodiscard]] static Void::Result::Result generate() + { + try { + std::random_device rd; + return TraceId{Detail::generate_nonzero_bytes<16>(rd)}; + } catch (...) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::unsupported_capability, + "System entropy unavailable for TraceId generation")); + } + } + + [[nodiscard]] static TraceId generate_seeded(std::uint64_t seed) + { + std::mt19937_64 rng{seed}; + return TraceId{Detail::generate_nonzero_bytes<16>(rng)}; + } +}; + +struct SpanId { + std::array bytes{}; + + [[nodiscard]] constexpr bool operator==(const SpanId&) const noexcept = default; + + [[nodiscard]] constexpr bool is_zero() const noexcept + { + for (const auto b : bytes) { + if (b != std::byte{0}) { + return false; + } + } + return true; + } + + [[nodiscard]] std::string to_hex() const + { + return Detail::bytes_to_hex(bytes); + } + + [[nodiscard]] static Void::Result::Result + from_hex(std::string_view hex) + { + auto parsed = Detail::hex_to_bytes<8>(hex, "SpanId"); + if (!parsed) { + return Void::Result::fail(std::move(parsed).error()); + } + SpanId id{*parsed}; + if (id.is_zero()) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_traceparent, + "SpanId must not be all zeros")); + } + return id; + } + + [[nodiscard]] static Void::Result::Result generate() + { + try { + std::random_device rd; + return SpanId{Detail::generate_nonzero_bytes<8>(rd)}; + } catch (...) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::unsupported_capability, + "System entropy unavailable for SpanId generation")); + } + } + + [[nodiscard]] static SpanId generate_seeded(std::uint64_t seed) + { + std::mt19937_64 rng{seed}; + return SpanId{Detail::generate_nonzero_bytes<8>(rng)}; + } +}; + +inline constexpr std::uint8_t kTraceFlagSampled = 0x01; + +struct TraceContext { + TraceId trace_id{}; + SpanId span_id{}; + std::uint8_t flags{0}; + + [[nodiscard]] constexpr bool operator==(const TraceContext&) const noexcept = default; + + [[nodiscard]] constexpr bool valid() const noexcept + { + return !trace_id.is_zero() && !span_id.is_zero(); + } + + [[nodiscard]] constexpr bool sampled() const noexcept + { + return (flags & kTraceFlagSampled) != 0; + } + + [[nodiscard]] std::string to_traceparent() const + { + constexpr char kHex[] = "0123456789abcdef"; + std::string out; + out.reserve(55); + out += "00-"; + out += trace_id.to_hex(); + out += '-'; + out += span_id.to_hex(); + out += '-'; + out.push_back(kHex[(flags >> 4) & 0x0Fu]); + out.push_back(kHex[flags & 0x0Fu]); + return out; + } + + [[nodiscard]] static Void::Result::Result + from_traceparent(std::string_view header) + { + if (header.size() != 55 || header[0] != '0' || header[1] != '0' || + header[2] != '-' || header[35] != '-' || header[52] != '-') { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_traceparent, + "Malformed W3C traceparent framing or version")); + } + auto tid = TraceId::from_hex(header.substr(3, 32)); + if (!tid) { + return Void::Result::fail(std::move(tid).error()); + } + auto sid = SpanId::from_hex(header.substr(36, 16)); + if (!sid) { + return Void::Result::fail(std::move(sid).error()); + } + auto flags_bytes = Detail::hex_to_bytes<1>(header.substr(53, 2), "TraceFlags"); + if (!flags_bytes) { + return Void::Result::fail(std::move(flags_bytes).error()); + } + return TraceContext{ + *tid, + *sid, + static_cast((*flags_bytes)[0])}; + } +}; + +struct ContextLimits { + std::size_t max_baggage_items{16}; + std::size_t max_baggage_bytes{2048}; + std::size_t max_key_bytes{128}; + std::size_t max_value_bytes{256}; + + [[nodiscard]] Void::Result::Result validate() const + { + if (max_baggage_items == 0 || max_baggage_bytes == 0 || + max_key_bytes == 0 || max_value_bytes == 0) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "ContextLimits values must be non-zero")); + } + return {}; + } +}; + +struct BaggageItem { + std::string key; + std::string value; + + [[nodiscard]] bool operator==(const BaggageItem&) const = default; +}; + +/// Immutable owning snapshot of TraceContext and bounded baggage carried across +/// threads, tasks, and coroutine resumptions. +class ContextSnapshot +{ +public: + ContextSnapshot() = default; + + [[nodiscard]] static Void::Result::Result create( + std::optional trace = std::nullopt, + std::span baggage = {}, + ContextLimits limits = {}) + { + if (auto v = limits.validate(); !v) { + return Void::Result::fail(std::move(v).error()); + } + if (trace.has_value() && !trace->valid()) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "TraceContext in ContextSnapshot must have non-zero IDs")); + } + auto data = std::make_shared(); + data->limits = limits; + data->trace = trace; + + for (const auto& item : baggage) { + if (auto r = add_or_replace(*data, item.key, item.value); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + return ContextSnapshot{std::move(data)}; + } + + [[nodiscard]] ContextSnapshot with_trace(TraceContext trace) const + { + auto next = data_ ? std::make_shared(*data_) + : std::make_shared(); + next->trace = trace; + return ContextSnapshot{std::move(next)}; + } + + [[nodiscard]] Void::Result::Result + with_baggage(std::string_view key, std::string_view value) const + { + auto next = data_ ? std::make_shared(*data_) + : std::make_shared(); + if (auto r = add_or_replace(*next, key, value); !r) { + return Void::Result::fail(std::move(r).error()); + } + return ContextSnapshot{std::move(next)}; + } + + [[nodiscard]] std::optional + find_baggage(std::string_view key) const noexcept + { + if (!data_) { + return std::nullopt; + } + for (const auto& item : data_->baggage) { + if (item.key == key) { + return std::string_view{item.value}; + } + } + return std::nullopt; + } + + [[nodiscard]] std::span baggage() const noexcept + { + if (!data_) { + return {}; + } + return data_->baggage; + } + + [[nodiscard]] std::size_t baggage_bytes() const noexcept + { + return data_ ? data_->baggage_bytes : 0; + } + + [[nodiscard]] const std::optional& trace() const noexcept + { + static const std::optional kEmpty; + return data_ ? data_->trace : kEmpty; + } + + [[nodiscard]] bool empty() const noexcept + { + return !data_ || (!data_->trace.has_value() && data_->baggage.empty()); + } + +private: + struct Data { + ContextLimits limits{}; + std::optional trace{}; + std::vector baggage{}; + std::size_t baggage_bytes{0}; + }; + + explicit ContextSnapshot(std::shared_ptr data) noexcept + : data_(std::move(data)) + { + } + + static bool valid_key_or_value(std::string_view sv) noexcept + { + for (const unsigned char ch : sv) { + if (ch < 0x20 || ch == 0x7F) { + return false; + } + } + return true; + } + + static Void::Result::Result + add_or_replace(Data& data, std::string_view key, std::string_view value) + { + if (key.empty() || key.size() > data.limits.max_key_bytes || + !valid_key_or_value(key)) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid baggage key length or control character")); + } + if (value.size() > data.limits.max_value_bytes || + !valid_key_or_value(value)) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid baggage value length or control character")); + } + + for (auto& existing : data.baggage) { + if (existing.key == key) { + const std::size_t without = + data.baggage_bytes - existing.value.size(); + if (value.size() > data.limits.max_baggage_bytes - without) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::capacity_exceeded, + "ContextSnapshot baggage byte budget exceeded")); + } + existing.value.assign(value); + data.baggage_bytes = without + existing.value.size(); + return {}; + } + } + + if (data.baggage.size() >= data.limits.max_baggage_items) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::capacity_exceeded, + "ContextSnapshot baggage item limit exceeded")); + } + const std::size_t added = key.size() + value.size(); + if (added > data.limits.max_baggage_bytes - data.baggage_bytes) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::capacity_exceeded, + "ContextSnapshot baggage byte budget exceeded")); + } + data.baggage.push_back(BaggageItem{std::string{key}, std::string{value}}); + data.baggage_bytes += added; + return {}; + } + + std::shared_ptr data_{}; +}; + +/// Move-only RAII thread-local context scope that always restores the prior +/// snapshot on normal exit or stack unwind. +class ScopedContext +{ +public: + explicit ScopedContext(ContextSnapshot snapshot) noexcept + : previous_(std::exchange(tls_slot(), std::move(snapshot))) + , active_(true) + { + } + + ~ScopedContext() noexcept + { + if (active_) { + tls_slot() = std::move(previous_); + } + } + + ScopedContext(ScopedContext&& other) noexcept + : previous_(std::move(other.previous_)) + , active_(std::exchange(other.active_, false)) + { + } + + ScopedContext& operator=(ScopedContext&&) = delete; + ScopedContext(const ScopedContext&) = delete; + ScopedContext& operator=(const ScopedContext&) = delete; + + [[nodiscard]] static ContextSnapshot current() noexcept + { + return tls_slot(); + } + +private: + static ContextSnapshot& tls_slot() noexcept + { + static thread_local ContextSnapshot current_context{}; + return current_context; + } + + ContextSnapshot previous_{}; + bool active_{false}; +}; + +} // namespace Void::Observability diff --git a/include/Void/Observability/Hooks.hpp b/include/Void/Observability/Hooks.hpp new file mode 100644 index 0000000..1ccecaf --- /dev/null +++ b/include/Void/Observability/Hooks.hpp @@ -0,0 +1,428 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Observability +{ + +enum class MetricKind : std::uint8_t { + counter = 0, + gauge, + histogram +}; + +struct AttributeView { + std::string_view key{}; + std::string_view value{}; +}; + +struct MetricPoint { + std::string_view name{}; + MetricKind kind{MetricKind::counter}; + double value{0.0}; + std::uint64_t integer_delta{0}; + std::span attributes{}; +}; + +struct DiagnosticEvent { + std::string_view component{}; + std::string_view message{}; + bool is_error{false}; +}; + +/// Zero-dependency synchronous observation callback table. +/// Null hooks perform no allocation or backend initialization. +struct ObservationHooks { + void* state{nullptr}; + void (*record)(void* state, const MetricPoint& point) noexcept{nullptr}; + void (*diagnostic)(void* state, const DiagnosticEvent& event) noexcept{nullptr}; + + [[nodiscard]] constexpr bool active() const noexcept + { + return record != nullptr || diagnostic != nullptr; + } + + void emit_metric(const MetricPoint& point) const noexcept + { + if (record != nullptr) { + record(state, point); + } + } + + void emit_diagnostic(const DiagnosticEvent& event) const noexcept + { + if (diagnostic != nullptr) { + diagnostic(state, event); + } + } +}; + +inline constexpr ObservationHooks kNullObservationHooks{}; + +enum class DrainStatus : std::uint8_t { + drained = 0, + not_found, + would_deadlock +}; + +using HookRegistrationId = std::uint64_t; + +namespace Detail +{ + +struct HookControl { + HookRegistrationId id{0}; + ObservationHooks raw_hooks{}; + std::function guarded_record{}; + std::function guarded_diagnostic{}; + bool is_guarded{false}; + std::shared_ptr owner{}; + std::atomic detached{false}; + std::atomic quarantined{false}; + std::atomic active_calls{0}; + std::atomic failed_calls{0}; + std::mutex drain_mutex; + std::condition_variable drain_cv; +}; + +inline thread_local std::vector t_active_hook_controls; + +struct HookCallScope { + const HookControl* control{nullptr}; + + explicit HookCallScope(const HookControl* ctrl) : control(ctrl) + { + if (control != nullptr) { + t_active_hook_controls.push_back(control); + } + } + + ~HookCallScope() noexcept + { + if (control != nullptr && !t_active_hook_controls.empty()) { + t_active_hook_controls.pop_back(); + } + } + + HookCallScope(const HookCallScope&) = delete; + HookCallScope& operator=(const HookCallScope&) = delete; + + [[nodiscard]] static bool is_active_on_thread(const HookControl* ctrl) noexcept + { + for (const auto* entry : t_active_hook_controls) { + if (entry == ctrl) { + return true; + } + } + return false; + } +}; + +} // namespace Detail + +/// Move-only RAII lease retaining hook callback/owner state across an invocation +/// outside any internal configuration mutex. +class HookLease +{ +public: + HookLease() noexcept = default; + + ~HookLease() noexcept { reset(); } + + HookLease(HookLease&& other) noexcept + : control_(std::exchange(other.control_, nullptr)) + { + } + + HookLease& operator=(HookLease&& other) noexcept + { + if (this != &other) { + reset(); + control_ = std::exchange(other.control_, nullptr); + } + return *this; + } + + HookLease(const HookLease&) = delete; + HookLease& operator=(const HookLease&) = delete; + + [[nodiscard]] explicit operator bool() const noexcept + { + return control_ != nullptr; + } + + [[nodiscard]] HookRegistrationId registration_id() const noexcept + { + return control_ != nullptr ? control_->id : 0; + } + + [[nodiscard]] bool is_quarantined() const noexcept + { + return control_ != nullptr && + control_->quarantined.load(std::memory_order_acquire); + } + + void reset() noexcept + { + auto ctrl = std::exchange(control_, nullptr); + if (!ctrl) { + return; + } + if (ctrl->active_calls.fetch_sub(1, std::memory_order_acq_rel) == 1) { + std::lock_guard lock{ctrl->drain_mutex}; + ctrl->drain_cv.notify_all(); + } + } + +private: + friend class HookSlot; + + explicit HookLease(std::shared_ptr ctrl) noexcept + : control_(std::move(ctrl)) + { + } + + std::shared_ptr control_{}; +}; + +/// Thread-safe hook registration owner supporting safe replacement, explicit +/// detach-and-drain synchronization, recursion suppression, and exception quarantine. +class HookSlot +{ +public: + HookSlot() = default; + + ~HookSlot() noexcept { (void)detach_and_drain(0); } + + HookSlot(const HookSlot&) = delete; + HookSlot& operator=(const HookSlot&) = delete; + HookSlot(HookSlot&&) = delete; + HookSlot& operator=(HookSlot&&) = delete; + + HookRegistrationId install(ObservationHooks hooks, + std::shared_ptr owner = {}) + { + if (!hooks.active() && !owner) { + std::shared_ptr old; + { + std::lock_guard lock{mutex_}; + old = std::exchange(active_, nullptr); + if (old) { + old->detached.store(true, std::memory_order_release); + } + } + return 0; + } + auto next = std::make_shared(); + next->raw_hooks = hooks; + next->owner = std::move(owner); + next->is_guarded = false; + return swap_active(std::move(next)); + } + + HookRegistrationId install_guarded( + std::function record_fn, + std::function diagnostic_fn = {}, + std::shared_ptr owner = {}) + { + auto next = std::make_shared(); + next->guarded_record = std::move(record_fn); + next->guarded_diagnostic = std::move(diagnostic_fn); + next->owner = std::move(owner); + next->is_guarded = true; + return swap_active(std::move(next)); + } + + [[nodiscard]] HookLease acquire_lease() const noexcept + { + std::lock_guard lock{mutex_}; + if (!active_ || active_->detached.load(std::memory_order_acquire)) { + return {}; + } + active_->active_calls.fetch_add(1, std::memory_order_acq_rel); + return HookLease{active_}; + } + + DrainStatus detach_and_drain(HookRegistrationId id = 0) noexcept + { + std::shared_ptr target; + { + std::lock_guard lock{mutex_}; + prune_retired_locked(); + if (id == 0) { + target = active_; + } else if (active_ && active_->id == id) { + target = active_; + } else if (const auto it = known_.find(id); it != known_.end()) { + target = it->second.lock(); + } + + if (!target) { + return DrainStatus::not_found; + } + if (Detail::HookCallScope::is_active_on_thread(target.get())) { + return DrainStatus::would_deadlock; + } + + target->detached.store(true, std::memory_order_release); + if (target == active_) { + active_.reset(); + } + known_.erase(target->id); + } + + { + std::unique_lock drain_lock{target->drain_mutex}; + target->drain_cv.wait(drain_lock, [&target] { + return target->active_calls.load(std::memory_order_acquire) == 0; + }); + } + target.reset(); + return DrainStatus::drained; + } + + void invoke_metric(const MetricPoint& point) noexcept + { + auto lease = acquire_lease(); + if (!lease) { + return; + } + auto* ctrl = lease.control_.get(); + if (ctrl->quarantined.load(std::memory_order_acquire)) { + return; + } + if (Detail::HookCallScope::is_active_on_thread(ctrl)) { + reentrant_calls_.fetch_add(1, std::memory_order_relaxed); + return; + } + Detail::HookCallScope scope{ctrl}; + if (!ctrl->is_guarded) { + ctrl->raw_hooks.emit_metric(point); + return; + } + if (!ctrl->guarded_record) { + return; + } + try { + ctrl->guarded_record(point); + } catch (...) { + ctrl->failed_calls.fetch_add(1, std::memory_order_relaxed); + failed_calls_.fetch_add(1, std::memory_order_relaxed); + ctrl->quarantined.store(true, std::memory_order_release); + } + } + + void invoke_diagnostic(const DiagnosticEvent& event) noexcept + { + auto lease = acquire_lease(); + if (!lease) { + return; + } + auto* ctrl = lease.control_.get(); + if (ctrl->quarantined.load(std::memory_order_acquire)) { + return; + } + if (Detail::HookCallScope::is_active_on_thread(ctrl)) { + reentrant_calls_.fetch_add(1, std::memory_order_relaxed); + return; + } + Detail::HookCallScope scope{ctrl}; + if (!ctrl->is_guarded) { + ctrl->raw_hooks.emit_diagnostic(event); + return; + } + if (!ctrl->guarded_diagnostic) { + return; + } + try { + ctrl->guarded_diagnostic(event); + } catch (...) { + ctrl->failed_calls.fetch_add(1, std::memory_order_relaxed); + failed_calls_.fetch_add(1, std::memory_order_relaxed); + ctrl->quarantined.store(true, std::memory_order_release); + } + } + + [[nodiscard]] bool active() const noexcept + { + std::lock_guard lock{mutex_}; + return active_ != nullptr && !active_->detached.load(std::memory_order_acquire); + } + + [[nodiscard]] bool is_quarantined() const noexcept + { + std::lock_guard lock{mutex_}; + return active_ != nullptr && + active_->quarantined.load(std::memory_order_acquire); + } + + void reset_quarantine() noexcept + { + std::lock_guard lock{mutex_}; + if (active_) { + active_->quarantined.store(false, std::memory_order_release); + } + } + + [[nodiscard]] std::uint64_t failed_calls() const noexcept + { + return failed_calls_.load(std::memory_order_relaxed); + } + + [[nodiscard]] std::uint64_t reentrant_calls() const noexcept + { + return reentrant_calls_.load(std::memory_order_relaxed); + } + +private: + HookRegistrationId swap_active(std::shared_ptr next) + { + std::shared_ptr old; + HookRegistrationId id = 0; + { + std::lock_guard lock{mutex_}; + prune_retired_locked(); + id = ++next_id_; + next->id = id; + known_.emplace(id, next); + old = std::exchange(active_, std::move(next)); + if (old) { + old->detached.store(true, std::memory_order_release); + } + } + old.reset(); + return id; + } + + void prune_retired_locked() + { + for (auto it = known_.begin(); it != known_.end();) { + if (it->second.expired()) { + it = known_.erase(it); + } else { + ++it; + } + } + } + + mutable std::mutex mutex_; + HookRegistrationId next_id_{0}; + std::shared_ptr active_{}; + std::unordered_map> known_; + std::atomic failed_calls_{0}; + std::atomic reentrant_calls_{0}; +}; + +} // namespace Void::Observability diff --git a/include/Void/Observability/Metrics.hpp b/include/Void/Observability/Metrics.hpp new file mode 100644 index 0000000..5d3ae05 --- /dev/null +++ b/include/Void/Observability/Metrics.hpp @@ -0,0 +1,144 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Observability +{ + +struct MetricsLimits { + std::size_t max_instruments{256}; + std::size_t max_series_per_instrument{1024}; + std::size_t max_total_series{4096}; + std::size_t max_labels_per_point{8}; + std::size_t max_key_bytes{128}; + std::size_t max_value_bytes{256}; + std::size_t max_producer_shards{32}; + std::size_t max_storage_bytes{32ULL * 1024ULL * 1024ULL}; + + [[nodiscard]] Void::Result::Result validate() const; +}; + +[[nodiscard]] inline std::vector default_duration_buckets_seconds() +{ + return {0.0001, 0.0005, 0.001, 0.005, 0.01, 0.025, 0.05, + 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0}; +} + +struct InstrumentSpec { + std::string name{}; + std::string unit{}; + MetricKind kind{MetricKind::counter}; + std::vector label_keys{}; + std::vector bucket_bounds{}; +}; + +struct InstrumentHandle { + std::size_t index{0}; + std::uint64_t registry_id{0}; + + [[nodiscard]] constexpr bool valid() const noexcept + { + return registry_id != 0; + } +}; + +struct HistogramSnapshot { + std::vector bounds{}; + std::vector bucket_counts{}; + std::uint64_t count{0}; + double sum{0.0}; +}; + +struct SeriesSnapshot { + std::vector> labels{}; + bool is_overflow{false}; + std::uint64_t counter_value{0}; + bool counter_saturated{false}; + double gauge_value{0.0}; + bool has_gauge_sample{false}; + Void::Time::MonotonicClock::time_point gauge_timestamp{}; + HistogramSnapshot histogram{}; +}; + +struct InstrumentSnapshot { + InstrumentSpec spec{}; + std::vector series{}; + std::uint64_t dropped_series{0}; + std::uint64_t overflow_events{0}; +}; + +struct MetricsSnapshot { + std::uint64_t epoch{1}; + std::vector instruments{}; + std::uint64_t dropped_series{0}; + std::uint64_t overflow_events{0}; + std::uint64_t rejected_invalid_points{0}; + std::uint64_t shared_shard_fallbacks{0}; + std::uint64_t unregistered_hook_points{0}; + std::size_t shard_count{0}; + std::size_t estimated_bytes{0}; +}; + +/// Thread-safe, sharded, cardinality- and byte-bounded metric registry with +/// frozen schemas and cumulative snapshot export. +class MetricRegistry +{ +public: + [[nodiscard]] static Void::Result::Result create( + MetricsLimits limits = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + + MetricRegistry(MetricRegistry&&) noexcept = default; + MetricRegistry& operator=(MetricRegistry&&) noexcept = default; + MetricRegistry(const MetricRegistry&) = delete; + MetricRegistry& operator=(const MetricRegistry&) = delete; + ~MetricRegistry(); + + [[nodiscard]] Void::Result::Result + register_instrument(InstrumentSpec spec); + + [[nodiscard]] Void::Result::Result add_counter( + InstrumentHandle handle, + std::uint64_t delta, + std::span attributes = {}); + + [[nodiscard]] Void::Result::Result set_gauge( + InstrumentHandle handle, + double value, + std::span attributes = {}); + + [[nodiscard]] Void::Result::Result observe_histogram( + InstrumentHandle handle, + double value, + std::span attributes = {}); + + [[nodiscard]] MetricsSnapshot snapshot() const; + void reset_epoch(); + + [[nodiscard]] ObservationHooks make_hooks() const noexcept; + [[nodiscard]] std::shared_ptr keepalive() const noexcept; + [[nodiscard]] const MetricsLimits& limits() const noexcept; + +private: + struct Impl; + explicit MetricRegistry(std::shared_ptr impl) noexcept; + + std::shared_ptr impl_; +}; + +} // namespace Void::Observability diff --git a/include/Void/Observability/Observability.hpp b/include/Void/Observability/Observability.hpp new file mode 100644 index 0000000..1440dd0 --- /dev/null +++ b/include/Void/Observability/Observability.hpp @@ -0,0 +1,7 @@ +#pragma once + +#include +#include +#include +#include +#include diff --git a/include/Void/Observability/Tracing.hpp b/include/Void/Observability/Tracing.hpp new file mode 100644 index 0000000..951eb2f --- /dev/null +++ b/include/Void/Observability/Tracing.hpp @@ -0,0 +1,243 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Observability +{ + +struct TracingLimits { + std::size_t max_active_spans{1024}; + std::size_t max_active_bytes{8ULL * 1024ULL * 1024ULL}; + std::size_t max_completed_spans{8192}; + std::size_t max_completed_bytes{16ULL * 1024ULL * 1024ULL}; + std::size_t max_attributes_per_span{32}; + std::size_t max_events_per_span{32}; + std::size_t max_bytes_per_span{8ULL * 1024ULL}; + std::size_t max_key_bytes{128}; + std::size_t max_value_bytes{256}; + std::size_t max_export_batch_spans{256}; + std::size_t max_export_batch_bytes{512ULL * 1024ULL}; + std::uint64_t root_sample_denominator{100}; + std::size_t max_export_retries{2}; + std::chrono::nanoseconds export_retry_budget{std::chrono::seconds{5}}; + + [[nodiscard]] Void::Result::Result validate() const; +}; + +enum class SpanStatus : std::uint8_t { + unset = 0, + ok, + error, + abandoned +}; + +struct SpanSpec { + std::string name{}; + std::vector> attributes{}; + std::optional explicit_root_trace_id{}; +}; + +struct SpanEvent { + std::string name{}; + Void::Time::MonotonicClock::time_point timestamp{}; +}; + +struct CompletedSpan { + TraceContext context{}; + std::optional parent_span_id{}; + std::string name{}; + Void::Time::MonotonicClock::time_point start_time{}; + Void::Time::MonotonicClock::time_point end_time{}; + Void::Time::CivilClock::time_point civil_start_time{}; + SpanStatus status{SpanStatus::unset}; + std::vector> attributes{}; + std::vector events{}; + bool truncated{false}; + std::size_t estimated_bytes{0}; +}; + +struct ExportBatch { + std::vector spans{}; + std::size_t estimated_bytes{0}; +}; + +struct ExportReport { + std::uint64_t exported_spans{0}; + std::uint64_t failed_spans{0}; + std::uint64_t dropped_spans{0}; + std::uint64_t duplicate_ends{0}; + std::uint64_t retries{0}; + bool timed_out{false}; + bool cancelled{false}; +}; + +struct ExportOptions { + std::stop_token stop{}; + std::optional deadline{}; +}; + +struct TracerStats { + std::size_t active_spans{0}; + std::size_t active_bytes{0}; + std::size_t completed_spans{0}; + std::size_t completed_bytes{0}; + std::size_t in_flight_export_bytes{0}; + std::uint64_t dropped_active_spans{0}; + std::uint64_t dropped_completed_spans{0}; + std::uint64_t duplicate_ends{0}; + std::uint64_t abandoned_spans{0}; + std::uint64_t exported_spans{0}; + std::uint64_t failed_exports{0}; + std::uint64_t reentrant_export_drops{0}; + bool closed{false}; +}; + +class SpanExporter +{ +public: + virtual ~SpanExporter() = default; + + [[nodiscard]] virtual Void::Result::Result + export_spans(std::span spans) = 0; +}; + +class CallbackSpanExporter final : public SpanExporter +{ +public: + using Callback = + std::function(std::span)>; + + explicit CallbackSpanExporter(Callback callback); + + [[nodiscard]] Void::Result::Result + export_spans(std::span spans) override; + + [[nodiscard]] std::uint64_t reentrant_drops() const noexcept + { + return reentrant_drops_.load(std::memory_order_relaxed); + } + +private: + Callback callback_; + std::atomic reentrant_drops_{0}; +}; + +class TextSnapshotExporter final : public SpanExporter +{ +public: + explicit TextSnapshotExporter( + std::size_t max_output_bytes = 64ULL * 1024ULL); + + [[nodiscard]] Void::Result::Result + export_spans(std::span spans) override; + + [[nodiscard]] static std::string render_metrics( + const MetricsSnapshot& metrics, + std::size_t max_output_bytes = 64ULL * 1024ULL); + + [[nodiscard]] static std::string render_spans( + std::span spans, + std::size_t max_output_bytes = 64ULL * 1024ULL); + + [[nodiscard]] std::string text() const; + void clear(); + +private: + std::size_t max_output_bytes_; + mutable std::mutex mutex_; + std::string buffer_; +}; + +class Tracer; + +/// Move-only span handle owning child TraceContext (never a raw parent pointer). +/// Destroying an active unended handle terminates it with SpanStatus::abandoned. +class Span +{ +public: + Span() = default; + ~Span() noexcept; + + Span(Span&& other) noexcept; + Span& operator=(Span&& other) noexcept; + Span(const Span&) = delete; + Span& operator=(const Span&) = delete; + + [[nodiscard]] const ContextSnapshot& context() const noexcept + { + return context_; + } + + [[nodiscard]] bool is_recording() const noexcept + { + return state_ != nullptr && !ended_; + } + + void set_attribute(std::string_view key, std::string_view value); + void add_event(std::string_view name); + void end(SpanStatus status = SpanStatus::ok) noexcept; + +private: + friend class Tracer; + struct State; + + Span(ContextSnapshot context, std::shared_ptr state) noexcept; + + ContextSnapshot context_{}; + std::shared_ptr state_{}; + bool ended_{false}; +}; + +/// Head-sampled, byte-bounded tracer with explicit synchronous batch export +/// and no implicit background worker threads. +class Tracer +{ +public: + [[nodiscard]] static Void::Result::Result create( + TracingLimits limits = {}, + std::shared_ptr exporter = nullptr, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance(), + const Void::Time::CivilClock& civil_clock = + Void::Time::SystemCivilClock::instance()); + + Tracer(Tracer&&) noexcept = default; + Tracer& operator=(Tracer&&) noexcept = default; + Tracer(const Tracer&) = delete; + Tracer& operator=(const Tracer&) = delete; + ~Tracer(); + + [[nodiscard]] Span start_span(const ContextSnapshot& parent, SpanSpec spec); + + [[nodiscard]] ExportReport flush(ExportOptions options = {}); + [[nodiscard]] ExportReport close(ExportOptions options = {}); + [[nodiscard]] TracerStats stats() const; + +private: + friend class Span; + struct Impl; + + explicit Tracer(std::shared_ptr impl) noexcept; + + std::shared_ptr impl_; +}; + +} // namespace Void::Observability diff --git a/src/Observability/Metrics.cpp b/src/Observability/Metrics.cpp new file mode 100644 index 0000000..15f6779 --- /dev/null +++ b/src/Observability/Metrics.cpp @@ -0,0 +1,808 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Observability +{ + +namespace +{ + +constexpr std::size_t kPerSeriesOverheadBytes = 128; + +[[nodiscard]] bool valid_token(std::string_view sv) noexcept +{ + for (const unsigned char ch : sv) { + if (ch < 0x20 || ch == 0x7F) { + return false; + } + } + return true; +} + +[[nodiscard]] bool valid_label_name(std::string_view sv) noexcept +{ + if (sv.empty() || !valid_token(sv)) { + return false; + } + for (const char ch : sv) { + if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') { + return false; + } + } + return true; +} + +struct CanonicalLabels { + std::string key; + std::vector values; +}; + +[[nodiscard]] std::uint64_t saturating_add_u64( + std::uint64_t lhs, + std::uint64_t rhs, + bool& saturated) noexcept +{ + constexpr auto kMax = std::numeric_limits::max(); + if (rhs > kMax - lhs) { + saturated = true; + return kMax; + } + return lhs + rhs; +} + +} // namespace + +Void::Result::Result MetricsLimits::validate() const +{ + if (max_instruments == 0 || max_series_per_instrument == 0 || + max_total_series == 0 || max_labels_per_point == 0 || + max_key_bytes == 0 || max_value_bytes == 0 || + max_producer_shards == 0 || max_storage_bytes == 0) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "MetricsLimits values must be non-zero")); + } + return {}; +} + +struct MetricRegistry::Impl { + struct SeriesMeta { + std::size_t series_id{0}; + bool is_overflow{false}; + std::vector> labels{}; + std::size_t byte_cost{0}; + }; + + struct InstrumentData { + InstrumentSpec spec{}; + std::vector series{}; + std::unordered_map key_to_series{}; + std::atomic overflow_seen{false}; + std::atomic dropped_series{0}; + std::atomic overflow_events{0}; + }; + + struct SeriesAccumulator { + std::uint64_t counter_value{0}; + bool counter_saturated{false}; + double gauge_value{0.0}; + bool has_gauge_sample{false}; + std::uint64_t gauge_seq{0}; + Void::Time::MonotonicClock::time_point gauge_timestamp{}; + std::vector hist_buckets{}; + std::uint64_t hist_count{0}; + double hist_sum{0.0}; + }; + + struct Shard { + std::mutex mutex; + // Indexed by [instrument_idx][series_id] + std::vector> data; + }; + + struct TlsShardEntry { + std::uint64_t registry_id{0}; + std::weak_ptr shard{}; + }; + + static std::uint64_t next_id() noexcept + { + static std::atomic seq{1}; + return seq.fetch_add(1, std::memory_order_relaxed); + } + + explicit Impl(MetricsLimits lim, const Void::Time::MonotonicClock* clk) + : id(next_id()) + , limits(lim) + , clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance()) + , fallback_shard(std::make_shared()) + { + } + + std::shared_ptr acquire_shard() + { + static thread_local std::vector tls_cache; + + for (auto it = tls_cache.begin(); it != tls_cache.end();) { + if (it->shard.expired()) { + it = tls_cache.erase(it); + continue; + } + if (it->registry_id == id) { + if (auto locked = it->shard.lock()) { + return locked; + } + it = tls_cache.erase(it); + continue; + } + ++it; + } + + std::shared_ptr assigned; + { + std::lock_guard lock{shards_mutex}; + if (shards.size() < limits.max_producer_shards) { + assigned = std::make_shared(); + shards.push_back(assigned); + } else { + shared_shard_fallbacks.fetch_add(1, std::memory_order_relaxed); + assigned = fallback_shard; + } + } + tls_cache.push_back(TlsShardEntry{id, assigned}); + return assigned; + } + + [[nodiscard]] Void::Result::Result build_canonical_labels( + const InstrumentData& inst, + std::span attributes) const + { + if (attributes.size() > limits.max_labels_per_point) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Attribute count exceeds max_labels_per_point")); + } + + CanonicalLabels result; + result.values.resize(inst.spec.label_keys.size()); + std::vector seen(inst.spec.label_keys.size(), false); + + for (const auto& attr : attributes) { + if (attr.key.empty() || attr.key.size() > limits.max_key_bytes || + !valid_token(attr.key)) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid attribute key")); + } + if (attr.value.size() > limits.max_value_bytes || + !valid_token(attr.value)) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid attribute value")); + } + const auto key_it = std::find(inst.spec.label_keys.begin(), + inst.spec.label_keys.end(), + attr.key); + if (key_it == inst.spec.label_keys.end()) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Undeclared metric label key")); + } + const auto pos = static_cast( + std::distance(inst.spec.label_keys.begin(), key_it)); + if (seen[pos]) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Duplicate metric label key in single observation")); + } + seen[pos] = true; + result.values[pos].assign(attr.value); + } + + std::size_t total_len = result.values.size() * 4; + for (const auto& v : result.values) { + total_len += v.size(); + } + result.key.reserve(total_len); + for (const auto& v : result.values) { + result.key.append(std::to_string(v.size())); + result.key.push_back(':'); + result.key.append(v); + result.key.push_back('\x1f'); + } + return result; + } + + [[nodiscard]] std::size_t resolve_or_create_series( + std::size_t inst_idx, + const CanonicalLabels& canonical) + { + std::unique_lock dir_lock{dir_mutex}; + auto& inst = *instruments[inst_idx]; + + if (const auto it = inst.key_to_series.find(canonical.key); + it != inst.key_to_series.end()) { + return it->second; + } + + const std::size_t current_normal = + inst.series.empty() ? 0 : (inst.series.size() - 1); + std::size_t label_bytes = 0; + for (std::size_t i = 0; i < inst.spec.label_keys.size(); ++i) { + label_bytes += inst.spec.label_keys[i].size() + canonical.values[i].size(); + } + const std::size_t series_cost = + kPerSeriesOverheadBytes + canonical.key.size() + label_bytes + + (inst.spec.bucket_bounds.size() + 1) * sizeof(std::uint64_t); + + const std::size_t used_bytes = estimated_bytes.load(std::memory_order_relaxed); + const std::size_t used_series = total_series.load(std::memory_order_relaxed); + + if (current_normal >= limits.max_series_per_instrument || + used_series >= limits.max_total_series || + series_cost > limits.max_storage_bytes - std::min(used_bytes, limits.max_storage_bytes)) { + inst.overflow_seen.store(true, std::memory_order_release); + inst.dropped_series.fetch_add(1, std::memory_order_relaxed); + inst.overflow_events.fetch_add(1, std::memory_order_relaxed); + dropped_series.fetch_add(1, std::memory_order_relaxed); + overflow_events.fetch_add(1, std::memory_order_relaxed); + return 0; // pre-registered __overflow__ slot + } + + const std::size_t new_id = inst.series.size(); + SeriesMeta meta; + meta.series_id = new_id; + meta.is_overflow = false; + meta.byte_cost = series_cost; + meta.labels.reserve(inst.spec.label_keys.size()); + for (std::size_t i = 0; i < inst.spec.label_keys.size(); ++i) { + meta.labels.emplace_back(inst.spec.label_keys[i], canonical.values[i]); + } + inst.key_to_series.emplace(canonical.key, new_id); + inst.series.push_back(std::move(meta)); + total_series.fetch_add(1, std::memory_order_relaxed); + estimated_bytes.fetch_add(series_cost, std::memory_order_relaxed); + return new_id; + } + + template + void mutate_slot(std::size_t inst_idx, + std::size_t series_id, + std::size_t hist_bucket_count, + Fn&& fn) + { + auto shard = acquire_shard(); + std::lock_guard lock{shard->mutex}; + if (shard->data.size() <= inst_idx) { + shard->data.resize(inst_idx + 1); + } + auto& inst_vec = shard->data[inst_idx]; + if (inst_vec.size() <= series_id) { + inst_vec.resize(series_id + 1); + } + auto& slot = inst_vec[series_id]; + if (hist_bucket_count > 0 && slot.hist_buckets.size() != hist_bucket_count) { + slot.hist_buckets.assign(hist_bucket_count, 0); + } + fn(slot); + } + + Void::Result::Result add_counter_impl( + std::size_t inst_idx, + std::uint64_t delta, + std::span attributes) + { + std::shared_lock dir_lock{dir_mutex}; + if (inst_idx >= instruments.size()) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid InstrumentHandle index")); + } + const auto& inst = *instruments[inst_idx]; + if (inst.spec.kind != MetricKind::counter) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::schema_conflict, + "Instrument is not a counter")); + } + auto canonical = build_canonical_labels(inst, attributes); + if (!canonical) { + rejected_invalid_points.fetch_add(1, std::memory_order_relaxed); + return Void::Result::fail(std::move(canonical).error()); + } + dir_lock.unlock(); + + const auto sid = resolve_or_create_series(inst_idx, *canonical); + mutate_slot(inst_idx, sid, 0, [delta](SeriesAccumulator& slot) { + slot.counter_value = saturating_add_u64( + slot.counter_value, delta, slot.counter_saturated); + }); + return {}; + } + + Void::Result::Result set_gauge_impl( + std::size_t inst_idx, + double value, + std::span attributes) + { + if (!std::isfinite(value)) { + rejected_invalid_points.fetch_add(1, std::memory_order_relaxed); + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Gauge value must be finite")); + } + std::shared_lock dir_lock{dir_mutex}; + if (inst_idx >= instruments.size()) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid InstrumentHandle index")); + } + const auto& inst = *instruments[inst_idx]; + if (inst.spec.kind != MetricKind::gauge) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::schema_conflict, + "Instrument is not a gauge")); + } + auto canonical = build_canonical_labels(inst, attributes); + if (!canonical) { + rejected_invalid_points.fetch_add(1, std::memory_order_relaxed); + return Void::Result::fail(std::move(canonical).error()); + } + dir_lock.unlock(); + + const auto sid = resolve_or_create_series(inst_idx, *canonical); + const auto ts = clock->now(); + const auto seq = gauge_seq_gen.fetch_add(1, std::memory_order_relaxed) + 1; + mutate_slot(inst_idx, sid, 0, [value, ts, seq](SeriesAccumulator& slot) { + slot.gauge_value = value; + slot.has_gauge_sample = true; + slot.gauge_timestamp = ts; + slot.gauge_seq = seq; + }); + return {}; + } + + Void::Result::Result observe_histogram_impl( + std::size_t inst_idx, + double value, + std::span attributes) + { + if (!std::isfinite(value)) { + rejected_invalid_points.fetch_add(1, std::memory_order_relaxed); + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Histogram observation must be finite")); + } + std::shared_lock dir_lock{dir_mutex}; + if (inst_idx >= instruments.size()) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid InstrumentHandle index")); + } + const auto& inst = *instruments[inst_idx]; + if (inst.spec.kind != MetricKind::histogram) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::schema_conflict, + "Instrument is not a histogram")); + } + const auto bounds = inst.spec.bucket_bounds; + auto canonical = build_canonical_labels(inst, attributes); + if (!canonical) { + rejected_invalid_points.fetch_add(1, std::memory_order_relaxed); + return Void::Result::fail(std::move(canonical).error()); + } + dir_lock.unlock(); + + const auto sid = resolve_or_create_series(inst_idx, *canonical); + std::size_t bucket_idx = bounds.size(); + for (std::size_t i = 0; i < bounds.size(); ++i) { + if (value <= bounds[i]) { + bucket_idx = i; + break; + } + } + const std::size_t total_buckets = bounds.size() + 1; + mutate_slot(inst_idx, sid, total_buckets, [value, bucket_idx](SeriesAccumulator& slot) { + ++slot.hist_buckets[bucket_idx]; + ++slot.hist_count; + slot.hist_sum += value; + }); + return {}; + } + + static void hook_record(void* state, const MetricPoint& pt) noexcept + { + if (state == nullptr) { + return; + } + auto* self = static_cast(state); + try { + std::optional idx; + { + std::shared_lock lock{self->dir_mutex}; + if (const auto it = self->name_to_index.find(std::string{pt.name}); + it != self->name_to_index.end()) { + idx = it->second; + } + } + if (!idx.has_value()) { + self->unregistered_hook_points.fetch_add(1, std::memory_order_relaxed); + return; + } + switch (pt.kind) { + case MetricKind::counter: { + const std::uint64_t delta = pt.integer_delta != 0 + ? pt.integer_delta + : (pt.value >= 0.0 && std::isfinite(pt.value) + ? static_cast(pt.value) + : 0ULL); + (void)self->add_counter_impl(*idx, delta, pt.attributes); + break; + } + case MetricKind::gauge: + (void)self->set_gauge_impl(*idx, pt.value, pt.attributes); + break; + case MetricKind::histogram: + (void)self->observe_histogram_impl(*idx, pt.value, pt.attributes); + break; + } + } catch (...) { + self->rejected_invalid_points.fetch_add(1, std::memory_order_relaxed); + } + } + + const std::uint64_t id; + MetricsLimits limits; + const Void::Time::MonotonicClock* clock; + + mutable std::shared_mutex dir_mutex; + std::vector> instruments; + std::unordered_map name_to_index; + + mutable std::mutex shards_mutex; + std::vector> shards; + std::shared_ptr fallback_shard; + + std::atomic epoch{1}; + std::atomic total_series{0}; + std::atomic estimated_bytes{0}; + std::atomic dropped_series{0}; + std::atomic overflow_events{0}; + std::atomic rejected_invalid_points{0}; + std::atomic shared_shard_fallbacks{0}; + std::atomic unregistered_hook_points{0}; + std::atomic gauge_seq_gen{0}; +}; + +MetricRegistry::MetricRegistry(std::shared_ptr impl) noexcept + : impl_(std::move(impl)) +{ +} + +MetricRegistry::~MetricRegistry() = default; + +Void::Result::Result MetricRegistry::create( + MetricsLimits limits, + const Void::Time::MonotonicClock& clock) +{ + if (auto v = limits.validate(); !v) { + return Void::Result::fail(std::move(v).error()); + } + auto impl = std::make_shared(limits, &clock); + return MetricRegistry{std::move(impl)}; +} + +Void::Result::Result + MetricRegistry::register_instrument(InstrumentSpec spec) +{ + if (!impl_) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::closed, + "MetricRegistry is moved-from")); + } + if (spec.name.empty() || spec.name.size() > impl_->limits.max_key_bytes || + !valid_label_name(spec.name)) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid instrument name")); + } + if (spec.unit.size() > impl_->limits.max_key_bytes || !valid_token(spec.unit)) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid instrument unit")); + } + if (spec.label_keys.size() > impl_->limits.max_labels_per_point) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Instrument label key count exceeds max_labels_per_point")); + } + for (std::size_t i = 0; i < spec.label_keys.size(); ++i) { + const auto& k = spec.label_keys[i]; + if (k.size() > impl_->limits.max_key_bytes || !valid_label_name(k)) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Invalid instrument label key")); + } + for (std::size_t j = 0; j < i; ++j) { + if (spec.label_keys[j] == k) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Duplicate label key in InstrumentSpec")); + } + } + } + if (spec.kind == MetricKind::histogram) { + if (spec.bucket_bounds.empty()) { + spec.bucket_bounds = default_duration_buckets_seconds(); + } else { + for (std::size_t i = 0; i < spec.bucket_bounds.size(); ++i) { + if (!std::isfinite(spec.bucket_bounds[i]) || + (i > 0 && spec.bucket_bounds[i] <= spec.bucket_bounds[i - 1])) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Histogram bucket bounds must be strictly increasing finite numbers")); + } + } + } + } else if (!spec.bucket_bounds.empty()) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "Only histogram instruments accept bucket bounds")); + } + + std::unique_lock lock{impl_->dir_mutex}; + if (const auto it = impl_->name_to_index.find(spec.name); + it != impl_->name_to_index.end()) { + const auto idx = it->second; + const auto& existing = impl_->instruments[idx]->spec; + if (existing.kind != spec.kind || existing.unit != spec.unit || + existing.label_keys != spec.label_keys || + existing.bucket_bounds != spec.bucket_bounds) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::schema_conflict, + "Instrument already registered with conflicting schema: " + spec.name)); + } + return InstrumentHandle{idx, impl_->id}; + } + + if (impl_->instruments.size() >= impl_->limits.max_instruments) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::capacity_exceeded, + "MetricRegistry max_instruments reached")); + } + + const std::size_t meta_cost = + kPerSeriesOverheadBytes + spec.name.size() + spec.unit.size() + + (spec.bucket_bounds.size() + 1) * sizeof(double); + const std::size_t used_bytes = impl_->estimated_bytes.load(std::memory_order_relaxed); + if (meta_cost > impl_->limits.max_storage_bytes - std::min(used_bytes, impl_->limits.max_storage_bytes)) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::capacity_exceeded, + "MetricRegistry max_storage_bytes exceeded")); + } + + auto inst = std::make_unique(); + inst->spec = std::move(spec); + + // Pre-register dedicated __overflow__ slot at index 0. + Impl::SeriesMeta overflow_meta; + overflow_meta.series_id = 0; + overflow_meta.is_overflow = true; + overflow_meta.labels = {{"__overflow__", "true"}}; + overflow_meta.byte_cost = meta_cost; + inst->series.push_back(std::move(overflow_meta)); + + const std::size_t idx = impl_->instruments.size(); + impl_->name_to_index.emplace(inst->spec.name, idx); + impl_->instruments.push_back(std::move(inst)); + impl_->estimated_bytes.fetch_add(meta_cost, std::memory_order_relaxed); + return InstrumentHandle{idx, impl_->id}; +} + +Void::Result::Result MetricRegistry::add_counter( + InstrumentHandle handle, + std::uint64_t delta, + std::span attributes) +{ + if (!impl_ || handle.registry_id != impl_->id) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "InstrumentHandle does not belong to this MetricRegistry")); + } + return impl_->add_counter_impl(handle.index, delta, attributes); +} + +Void::Result::Result MetricRegistry::set_gauge( + InstrumentHandle handle, + double value, + std::span attributes) +{ + if (!impl_ || handle.registry_id != impl_->id) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "InstrumentHandle does not belong to this MetricRegistry")); + } + return impl_->set_gauge_impl(handle.index, value, attributes); +} + +Void::Result::Result MetricRegistry::observe_histogram( + InstrumentHandle handle, + double value, + std::span attributes) +{ + if (!impl_ || handle.registry_id != impl_->id) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "InstrumentHandle does not belong to this MetricRegistry")); + } + return impl_->observe_histogram_impl(handle.index, value, attributes); +} + +MetricsSnapshot MetricRegistry::snapshot() const +{ + MetricsSnapshot snap; + if (!impl_) { + return snap; + } + + std::shared_lock dir_lock{impl_->dir_mutex}; + std::vector> all_shards; + { + std::lock_guard slock{impl_->shards_mutex}; + all_shards = impl_->shards; + all_shards.push_back(impl_->fallback_shard); + } + + snap.epoch = impl_->epoch.load(std::memory_order_acquire); + snap.dropped_series = impl_->dropped_series.load(std::memory_order_relaxed); + snap.overflow_events = impl_->overflow_events.load(std::memory_order_relaxed); + snap.rejected_invalid_points = + impl_->rejected_invalid_points.load(std::memory_order_relaxed); + snap.shared_shard_fallbacks = + impl_->shared_shard_fallbacks.load(std::memory_order_relaxed); + snap.unregistered_hook_points = + impl_->unregistered_hook_points.load(std::memory_order_relaxed); + snap.estimated_bytes = impl_->estimated_bytes.load(std::memory_order_relaxed); + snap.shard_count = all_shards.size() - 1; + + snap.instruments.resize(impl_->instruments.size()); + std::vector> gauge_seqs(impl_->instruments.size()); + for (std::size_t i = 0; i < impl_->instruments.size(); ++i) { + const auto& inst = *impl_->instruments[i]; + auto& out_inst = snap.instruments[i]; + out_inst.spec = inst.spec; + out_inst.dropped_series = inst.dropped_series.load(std::memory_order_relaxed); + out_inst.overflow_events = inst.overflow_events.load(std::memory_order_relaxed); + out_inst.series.resize(inst.series.size()); + gauge_seqs[i].assign(inst.series.size(), 0); + for (std::size_t s = 0; s < inst.series.size(); ++s) { + out_inst.series[s].labels = inst.series[s].labels; + out_inst.series[s].is_overflow = inst.series[s].is_overflow; + if (inst.spec.kind == MetricKind::histogram) { + out_inst.series[s].histogram.bounds = inst.spec.bucket_bounds; + out_inst.series[s].histogram.bucket_counts.assign( + inst.spec.bucket_bounds.size() + 1, 0); + } + } + } + + for (const auto& shard : all_shards) { + std::lock_guard lock{shard->mutex}; + const std::size_t max_inst = + std::min(shard->data.size(), impl_->instruments.size()); + for (std::size_t i = 0; i < max_inst; ++i) { + const auto& kind = impl_->instruments[i]->spec.kind; + const auto& src_series = shard->data[i]; + const std::size_t max_ser = + std::min(src_series.size(), snap.instruments[i].series.size()); + for (std::size_t s = 0; s < max_ser; ++s) { + const auto& src = src_series[s]; + auto& dst = snap.instruments[i].series[s]; + switch (kind) { + case MetricKind::counter: + dst.counter_value = saturating_add_u64( + dst.counter_value, src.counter_value, dst.counter_saturated); + dst.counter_saturated = dst.counter_saturated || src.counter_saturated; + break; + case MetricKind::gauge: + if (src.has_gauge_sample && src.gauge_seq >= gauge_seqs[i][s]) { + gauge_seqs[i][s] = src.gauge_seq; + dst.gauge_value = src.gauge_value; + dst.gauge_timestamp = src.gauge_timestamp; + dst.has_gauge_sample = true; + } + break; + case MetricKind::histogram: + dst.histogram.count += src.hist_count; + dst.histogram.sum += src.hist_sum; + for (std::size_t b = 0; + b < std::min(src.hist_buckets.size(), + dst.histogram.bucket_counts.size()); + ++b) { + dst.histogram.bucket_counts[b] += src.hist_buckets[b]; + } + break; + } + } + } + } + + // Omit the pre-registered __overflow__ entry when no overflow occurred. + for (std::size_t i = 0; i < impl_->instruments.size(); ++i) { + auto& out_inst = snap.instruments[i]; + if (!impl_->instruments[i]->overflow_seen.load(std::memory_order_acquire) && + !out_inst.series.empty() && out_inst.series.front().is_overflow) { + out_inst.series.erase(out_inst.series.begin()); + } + } + return snap; +} + +void MetricRegistry::reset_epoch() +{ + if (!impl_) { + return; + } + std::unique_lock dir_lock{impl_->dir_mutex}; + std::vector> all_shards; + { + std::lock_guard slock{impl_->shards_mutex}; + all_shards = impl_->shards; + all_shards.push_back(impl_->fallback_shard); + } + for (const auto& shard : all_shards) { + std::lock_guard lock{shard->mutex}; + for (auto& inst_vec : shard->data) { + for (auto& slot : inst_vec) { + slot.counter_value = 0; + slot.counter_saturated = false; + slot.gauge_value = 0.0; + slot.has_gauge_sample = false; + slot.gauge_seq = 0; + std::fill(slot.hist_buckets.begin(), slot.hist_buckets.end(), 0); + slot.hist_count = 0; + slot.hist_sum = 0.0; + } + } + } + for (const auto& inst : impl_->instruments) { + inst->overflow_seen.store(false, std::memory_order_release); + inst->dropped_series.store(0, std::memory_order_relaxed); + inst->overflow_events.store(0, std::memory_order_relaxed); + } + impl_->dropped_series.store(0, std::memory_order_relaxed); + impl_->overflow_events.store(0, std::memory_order_relaxed); + impl_->epoch.fetch_add(1, std::memory_order_release); +} + +ObservationHooks MetricRegistry::make_hooks() const noexcept +{ + if (!impl_) { + return kNullObservationHooks; + } + return ObservationHooks{ + impl_.get(), + &Impl::hook_record, + nullptr}; +} + +std::shared_ptr MetricRegistry::keepalive() const noexcept +{ + return impl_; +} + +const MetricsLimits& MetricRegistry::limits() const noexcept +{ + static const MetricsLimits kDefault{}; + return impl_ ? impl_->limits : kDefault; +} + +} // namespace Void::Observability diff --git a/src/Observability/Tracing.cpp b/src/Observability/Tracing.cpp new file mode 100644 index 0000000..4d7cf8f --- /dev/null +++ b/src/Observability/Tracing.cpp @@ -0,0 +1,700 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Observability +{ + +namespace +{ + +constexpr std::size_t kBaseSpanBytes = 192; + +[[nodiscard]] bool is_valid_text(std::string_view sv) noexcept +{ + for (const unsigned char ch : sv) { + if (ch < 0x20 || ch == 0x7F) { + return false; + } + } + return true; +} + +[[nodiscard]] std::string truncate_with_marker(std::string_view sv, + std::size_t max_bytes, + bool& truncated) +{ + if (sv.size() <= max_bytes) { + return std::string{sv}; + } + truncated = true; + constexpr std::string_view kMarker = "...[truncated]"; + if (max_bytes <= kMarker.size()) { + return std::string{sv.substr(0, max_bytes)}; + } + std::string out{sv.substr(0, max_bytes - kMarker.size())}; + out += kMarker; + return out; +} + +[[nodiscard]] std::string_view status_str(SpanStatus s) noexcept +{ + switch (s) { + case SpanStatus::unset: return "unset"; + case SpanStatus::ok: return "ok"; + case SpanStatus::error: return "error"; + case SpanStatus::abandoned: return "abandoned"; + } + return "unset"; +} + +inline thread_local std::vector t_active_exporters; + +struct ExporterRecursionGuard { + const void* ptr{nullptr}; + bool reentered{false}; + + explicit ExporterRecursionGuard(const void* p) : ptr(p) + { + for (const auto* active : t_active_exporters) { + if (active == ptr) { + reentered = true; + return; + } + } + t_active_exporters.push_back(ptr); + } + + ~ExporterRecursionGuard() noexcept + { + if (!reentered && !t_active_exporters.empty()) { + t_active_exporters.pop_back(); + } + } + + ExporterRecursionGuard(const ExporterRecursionGuard&) = delete; + ExporterRecursionGuard& operator=(const ExporterRecursionGuard&) = delete; +}; + +} // namespace + +Void::Result::Result TracingLimits::validate() const +{ + if (max_active_spans == 0 || max_active_bytes == 0 || + max_completed_spans == 0 || max_completed_bytes == 0 || + max_attributes_per_span == 0 || max_events_per_span == 0 || + max_bytes_per_span == 0 || max_key_bytes == 0 || + max_value_bytes == 0 || max_export_batch_spans == 0 || + max_export_batch_bytes == 0 || root_sample_denominator == 0 || + export_retry_budget.count() < 0) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::invalid_argument, + "TracingLimits values must be positive")); + } + return {}; +} + +CallbackSpanExporter::CallbackSpanExporter(Callback callback) + : callback_(std::move(callback)) +{ +} + +Void::Result::Result CallbackSpanExporter::export_spans( + std::span spans) +{ + ExporterRecursionGuard guard{this}; + if (guard.reentered) { + reentrant_drops_.fetch_add(1, std::memory_order_relaxed); + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::would_deadlock, + "Reentrant span export suppressed")); + } + if (!callback_) { + return {}; + } + try { + return callback_(spans); + } catch (const std::exception& e) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::quarantined, + std::string{"Span exporter callback threw: "} + e.what())); + } catch (...) { + return Void::Result::fail(make_observability_error( + ObservabilityErrorCode::quarantined, + "Span exporter callback threw unknown exception")); + } +} + +TextSnapshotExporter::TextSnapshotExporter(std::size_t max_output_bytes) + : max_output_bytes_(max_output_bytes) +{ +} + +Void::Result::Result TextSnapshotExporter::export_spans( + std::span spans) +{ + const auto rendered = render_spans(spans, max_output_bytes_); + std::lock_guard lock{mutex_}; + if (buffer_.size() < max_output_bytes_) { + const std::size_t rem = max_output_bytes_ - buffer_.size(); + if (rendered.size() <= rem) { + buffer_ += rendered; + } else { + buffer_.append(rendered.data(), rem); + } + } + return {}; +} + +std::string TextSnapshotExporter::render_metrics( + const MetricsSnapshot& metrics, + std::size_t max_output_bytes) +{ + std::string out; + out += std::format("epoch={} instruments={} dropped_series={} overflow_events={}\n", + metrics.epoch, + metrics.instruments.size(), + metrics.dropped_series, + metrics.overflow_events); + for (const auto& inst : metrics.instruments) { + for (const auto& ser : inst.series) { + std::string line = inst.spec.name; + line += '{'; + for (std::size_t i = 0; i < ser.labels.size(); ++i) { + if (i > 0) { + line += ','; + } + line += ser.labels[i].first; + line += '='; + line += ser.labels[i].second; + } + line += '}'; + switch (inst.spec.kind) { + case MetricKind::counter: + line += std::format(" {}\n", ser.counter_value); + break; + case MetricKind::gauge: + line += std::format(" {}\n", ser.gauge_value); + break; + case MetricKind::histogram: + line += std::format(" count={} sum={}\n", + ser.histogram.count, + ser.histogram.sum); + break; + } + if (out.size() + line.size() > max_output_bytes) { + return out; + } + out += line; + } + } + return out; +} + +std::string TextSnapshotExporter::render_spans( + std::span spans, + std::size_t max_output_bytes) +{ + std::string out; + for (const auto& sp : spans) { + const auto dur_us = + std::chrono::duration_cast( + sp.end_time >= sp.start_time ? (sp.end_time - sp.start_time) + : std::chrono::nanoseconds{0}) + .count(); + std::string line = std::format( + "span trace={} span={} name={} status={} duration_us={} attrs={} events={} truncated={}\n", + sp.context.trace_id.to_hex(), + sp.context.span_id.to_hex(), + sp.name, + status_str(sp.status), + dur_us, + sp.attributes.size(), + sp.events.size(), + sp.truncated ? 1 : 0); + if (out.size() + line.size() > max_output_bytes) { + break; + } + out += line; + } + return out; +} + +std::string TextSnapshotExporter::text() const +{ + std::lock_guard lock{mutex_}; + return buffer_; +} + +void TextSnapshotExporter::clear() +{ + std::lock_guard lock{mutex_}; + buffer_.clear(); +} + +struct Tracer::Impl { + Impl(TracingLimits lim, + std::shared_ptr exp, + const Void::Time::MonotonicClock* clk, + const Void::Time::CivilClock* civil) + : limits(lim) + , exporter(std::move(exp)) + , clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance()) + , civil_clock(civil != nullptr ? civil : &Void::Time::SystemCivilClock::instance()) + { + } + + void complete_span(CompletedSpan span, std::size_t reserved_active_bytes) noexcept + { + std::lock_guard lock{mutex}; + if (active_spans > 0) { + --active_spans; + } + active_bytes = + active_bytes >= reserved_active_bytes + ? (active_bytes - reserved_active_bytes) + : 0; + + if (span.status == SpanStatus::abandoned) { + ++abandoned_spans; + } + + const std::size_t budget_used = completed_bytes + in_flight_export_bytes; + if (completed.size() >= limits.max_completed_spans || + span.estimated_bytes > + limits.max_completed_bytes - + std::min(budget_used, limits.max_completed_bytes)) { + ++dropped_completed_spans; + return; + } + completed_bytes += span.estimated_bytes; + completed.push_back(std::move(span)); + } + + TracingLimits limits; + std::shared_ptr exporter; + const Void::Time::MonotonicClock* clock; + const Void::Time::CivilClock* civil_clock; + + mutable std::mutex mutex; + std::size_t active_spans{0}; + std::size_t active_bytes{0}; + std::deque completed{}; + std::size_t completed_bytes{0}; + std::size_t in_flight_export_bytes{0}; + bool closed{false}; + + std::uint64_t dropped_active_spans{0}; + std::uint64_t dropped_completed_spans{0}; + std::uint64_t duplicate_ends{0}; + std::uint64_t abandoned_spans{0}; + std::uint64_t exported_spans{0}; + std::uint64_t failed_exports{0}; + std::uint64_t reentrant_export_drops{0}; +}; + +struct Span::State { + std::shared_ptr tracer; + std::mutex mutex; + CompletedSpan data{}; + std::size_t reserved_bytes{0}; + std::atomic ended{false}; +}; + +Span::Span(ContextSnapshot context, std::shared_ptr state) noexcept + : context_(std::move(context)) + , state_(std::move(state)) +{ +} + +Span::~Span() noexcept +{ + if (state_ && !ended_) { + end(SpanStatus::abandoned); + } +} + +Span::Span(Span&& other) noexcept + : context_(std::move(other.context_)) + , state_(std::move(other.state_)) + , ended_(std::exchange(other.ended_, true)) +{ +} + +Span& Span::operator=(Span&& other) noexcept +{ + if (this != &other) { + if (state_ && !ended_) { + end(SpanStatus::abandoned); + } + context_ = std::move(other.context_); + state_ = std::move(other.state_); + ended_ = std::exchange(other.ended_, true); + } + return *this; +} + +void Span::set_attribute(std::string_view key, std::string_view value) +{ + if (!state_ || ended_ || key.empty() || !is_valid_text(key)) { + return; + } + const auto& lim = state_->tracer->limits; + std::lock_guard lock{state_->mutex}; + if (state_->ended.load(std::memory_order_acquire) || + state_->data.attributes.size() >= lim.max_attributes_per_span || + key.size() > lim.max_key_bytes) { + return; + } + bool trunc = false; + auto val_str = truncate_with_marker(value, lim.max_value_bytes, trunc); + const std::size_t delta = key.size() + val_str.size(); + if (delta > lim.max_bytes_per_span - + std::min(state_->data.estimated_bytes, lim.max_bytes_per_span)) { + state_->data.truncated = true; + return; + } + if (trunc) { + state_->data.truncated = true; + } + state_->data.estimated_bytes += delta; + state_->data.attributes.emplace_back(std::string{key}, std::move(val_str)); +} + +void Span::add_event(std::string_view name) +{ + if (!state_ || ended_ || name.empty() || !is_valid_text(name)) { + return; + } + const auto& lim = state_->tracer->limits; + std::lock_guard lock{state_->mutex}; + if (state_->ended.load(std::memory_order_acquire) || + state_->data.events.size() >= lim.max_events_per_span) { + return; + } + bool trunc = false; + auto evt_name = truncate_with_marker(name, lim.max_key_bytes, trunc); + const std::size_t delta = evt_name.size() + sizeof(SpanEvent); + if (delta > lim.max_bytes_per_span - + std::min(state_->data.estimated_bytes, lim.max_bytes_per_span)) { + state_->data.truncated = true; + return; + } + if (trunc) { + state_->data.truncated = true; + } + state_->data.estimated_bytes += delta; + state_->data.events.push_back( + SpanEvent{std::move(evt_name), state_->tracer->clock->now()}); +} + +void Span::end(SpanStatus status) noexcept +{ + if (!state_) { + return; + } + bool expected = false; + if (!state_->ended.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) { + ended_ = true; + std::lock_guard lock{state_->tracer->mutex}; + ++state_->tracer->duplicate_ends; + return; + } + ended_ = true; + CompletedSpan finalized; + std::size_t reserved = 0; + { + std::lock_guard lock{state_->mutex}; + state_->data.end_time = state_->tracer->clock->now(); + state_->data.status = status; + finalized = std::move(state_->data); + reserved = state_->reserved_bytes; + } + state_->tracer->complete_span(std::move(finalized), reserved); +} + +Tracer::Tracer(std::shared_ptr impl) noexcept + : impl_(std::move(impl)) +{ +} + +Tracer::~Tracer() = default; + +Void::Result::Result Tracer::create( + TracingLimits limits, + std::shared_ptr exporter, + const Void::Time::MonotonicClock& clock, + const Void::Time::CivilClock& civil_clock) +{ + if (auto v = limits.validate(); !v) { + return Void::Result::fail(std::move(v).error()); + } + return Tracer{ + std::make_shared(limits, std::move(exporter), &clock, &civil_clock)}; +} + +Span Tracer::start_span(const ContextSnapshot& parent, SpanSpec spec) +{ + if (!impl_) { + return Span{}; + } + + TraceId tid{}; + std::optional parent_sid; + bool sampled = false; + if (const auto& ptrace = parent.trace(); ptrace.has_value() && ptrace->valid()) { + tid = ptrace->trace_id; + parent_sid = ptrace->span_id; + sampled = ptrace->sampled(); + } else { + if (spec.explicit_root_trace_id.has_value() && + !spec.explicit_root_trace_id->is_zero()) { + tid = *spec.explicit_root_trace_id; + } else if (auto gen = TraceId::generate()) { + tid = *gen; + } else { + tid = TraceId::generate_seeded(1); + } + const std::uint64_t h = Void::Hash::fnv1a64( + std::span{tid.bytes.data(), tid.bytes.size()}); + sampled = (h % impl_->limits.root_sample_denominator) == 0; + } + + SpanId sid{}; + if (auto gen_sid = SpanId::generate()) { + sid = *gen_sid; + } else { + sid = SpanId::generate_seeded(1); + } + + const std::uint8_t flags = sampled ? kTraceFlagSampled : 0; + ContextSnapshot child_ctx = + parent.with_trace(TraceContext{tid, sid, flags}); + + if (!sampled) { + return Span{std::move(child_ctx), nullptr}; + } + + const auto& lim = impl_->limits; + bool trunc = false; + std::string clean_name = + spec.name.empty() ? std::string{"unnamed"} + : truncate_with_marker(spec.name, lim.max_key_bytes, trunc); + + std::size_t initial_bytes = kBaseSpanBytes + clean_name.size(); + std::vector> clean_attrs; + for (const auto& [k, v] : spec.attributes) { + if (clean_attrs.size() >= lim.max_attributes_per_span) { + trunc = true; + break; + } + if (k.empty() || k.size() > lim.max_key_bytes || !is_valid_text(k)) { + continue; + } + bool attr_trunc = false; + auto val = truncate_with_marker(v, lim.max_value_bytes, attr_trunc); + const std::size_t add = k.size() + val.size(); + if (initial_bytes + add > lim.max_bytes_per_span) { + trunc = true; + break; + } + if (attr_trunc) { + trunc = true; + } + initial_bytes += add; + clean_attrs.emplace_back(k, std::move(val)); + } + + const std::size_t active_reserve = lim.max_bytes_per_span; + { + std::lock_guard lock{impl_->mutex}; + if (impl_->closed || + impl_->active_spans >= lim.max_active_spans || + active_reserve > + lim.max_active_bytes - + std::min(impl_->active_bytes, lim.max_active_bytes)) { + ++impl_->dropped_active_spans; + child_ctx = parent.with_trace(TraceContext{tid, sid, 0}); + return Span{std::move(child_ctx), nullptr}; + } + ++impl_->active_spans; + impl_->active_bytes += active_reserve; + } + + auto state = std::make_shared(); + state->tracer = impl_; + state->reserved_bytes = active_reserve; + state->data.context = TraceContext{tid, sid, flags}; + state->data.parent_span_id = parent_sid; + state->data.name = std::move(clean_name); + state->data.start_time = impl_->clock->now(); + state->data.end_time = state->data.start_time; + state->data.civil_start_time = impl_->civil_clock->now(); + state->data.attributes = std::move(clean_attrs); + state->data.truncated = trunc; + state->data.estimated_bytes = initial_bytes; + return Span{std::move(child_ctx), std::move(state)}; +} + +ExportReport Tracer::flush(ExportOptions options) +{ + ExportReport report; + if (!impl_) { + return report; + } + + std::size_t remaining_to_drain = 0; + { + std::lock_guard lock{impl_->mutex}; + report.duplicate_ends = impl_->duplicate_ends; + report.dropped_spans = + impl_->dropped_active_spans + impl_->dropped_completed_spans; + remaining_to_drain = impl_->completed.size(); + } + + while (remaining_to_drain > 0) { + if (options.stop.stop_requested()) { + report.cancelled = true; + break; + } + if (options.deadline.has_value() && impl_->clock->now() >= *options.deadline) { + report.timed_out = true; + break; + } + + ExportBatch batch; + { + std::lock_guard lock{impl_->mutex}; + if (impl_->completed.empty()) { + break; + } + const std::size_t cap_spans = + std::min(remaining_to_drain, impl_->limits.max_export_batch_spans); + while (!impl_->completed.empty() && batch.spans.size() < cap_spans) { + const auto& front = impl_->completed.front(); + if (!batch.spans.empty() && + batch.estimated_bytes + front.estimated_bytes > + impl_->limits.max_export_batch_bytes) { + break; + } + batch.estimated_bytes += front.estimated_bytes; + impl_->completed_bytes = + impl_->completed_bytes >= front.estimated_bytes + ? (impl_->completed_bytes - front.estimated_bytes) + : 0; + batch.spans.push_back(std::move(impl_->completed.front())); + impl_->completed.pop_front(); + --remaining_to_drain; + } + impl_->in_flight_export_bytes += batch.estimated_bytes; + } + + if (batch.spans.empty()) { + break; + } + + bool ok = true; + if (impl_->exporter) { + const auto retry_start = impl_->clock->now(); + ok = false; + for (std::size_t attempt = 0; + attempt <= impl_->limits.max_export_retries; + ++attempt) { + if (options.stop.stop_requested()) { + report.cancelled = true; + break; + } + if (options.deadline.has_value() && + impl_->clock->now() >= *options.deadline) { + report.timed_out = true; + break; + } + if (attempt > 0) { + if (impl_->clock->now() - retry_start >= + impl_->limits.export_retry_budget) { + report.timed_out = true; + break; + } + ++report.retries; + } + const auto res = impl_->exporter->export_spans(batch.spans); + if (res.has_value()) { + ok = true; + break; + } + if (res.error().code().value == + static_cast(ObservabilityErrorCode::would_deadlock)) { + std::lock_guard lock{impl_->mutex}; + ++impl_->reentrant_export_drops; + break; + } + } + } + + { + std::lock_guard lock{impl_->mutex}; + impl_->in_flight_export_bytes = + impl_->in_flight_export_bytes >= batch.estimated_bytes + ? (impl_->in_flight_export_bytes - batch.estimated_bytes) + : 0; + if (ok) { + impl_->exported_spans += batch.spans.size(); + report.exported_spans += batch.spans.size(); + } else { + ++impl_->failed_exports; + report.failed_spans += batch.spans.size(); + } + } + + if (report.cancelled || report.timed_out) { + break; + } + } + + return report; +} + +ExportReport Tracer::close(ExportOptions options) +{ + if (!impl_) { + return {}; + } + { + std::lock_guard lock{impl_->mutex}; + impl_->closed = true; + } + return flush(options); +} + +TracerStats Tracer::stats() const +{ + TracerStats st; + if (!impl_) { + return st; + } + std::lock_guard lock{impl_->mutex}; + st.active_spans = impl_->active_spans; + st.active_bytes = impl_->active_bytes; + st.completed_spans = impl_->completed.size(); + st.completed_bytes = impl_->completed_bytes; + st.in_flight_export_bytes = impl_->in_flight_export_bytes; + st.dropped_active_spans = impl_->dropped_active_spans; + st.dropped_completed_spans = impl_->dropped_completed_spans; + st.duplicate_ends = impl_->duplicate_ends; + st.abandoned_spans = impl_->abandoned_spans; + st.exported_spans = impl_->exported_spans; + st.failed_exports = impl_->failed_exports; + st.reentrant_export_drops = impl_->reentrant_export_drops; + st.closed = impl_->closed; + return st; +} + +} // namespace Void::Observability diff --git a/src/Observability/module.cmake b/src/Observability/module.cmake new file mode 100644 index 0000000..8bc39f8 --- /dev/null +++ b/src/Observability/module.cmake @@ -0,0 +1,4 @@ +void_add_module(Observability + INTERNAL_DEPS ObservabilityHooks Core Functional Time Memory + EXCLUDE_HEADERS Void/Observability/Hooks.hpp +) diff --git a/src/ObservabilityHooks/module.cmake b/src/ObservabilityHooks/module.cmake new file mode 100644 index 0000000..32d1946 --- /dev/null +++ b/src/ObservabilityHooks/module.cmake @@ -0,0 +1,3 @@ +void_add_module(ObservabilityHooks + EXTRA_HEADERS Void/Observability/Hooks.hpp +) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 33eddf8..8ee7f8c 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -116,6 +116,16 @@ if(_has_runtime) run_consumer(RuntimeOnly "${install_prefix}" "RuntimeOnly" ${_no_external_deps}) endif() +has_modules(_has_obs_hooks ObservabilityHooks) +if(_has_obs_hooks) + run_consumer(ObservabilityHooksOnly "${install_prefix}" "ObservabilityHooksOnly" ${_no_external_deps}) +endif() + +has_modules(_has_obs Observability ObservabilityHooks Memory Time Functional Core) +if(_has_obs) + run_consumer(ObservabilityOnly "${install_prefix}" "ObservabilityOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/ObservabilityHooksOnly/CMakeLists.txt b/tests/package/ObservabilityHooksOnly/CMakeLists.txt new file mode 100644 index 0000000..e17696a --- /dev/null +++ b/tests/package/ObservabilityHooksOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidObservabilityHooksOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS ObservabilityHooks) + +add_executable(void_observability_hooks_only_consumer main.cpp) +target_link_libraries(void_observability_hooks_only_consumer PRIVATE Void::ObservabilityHooks) + +enable_testing() +add_test(NAME VoidObservabilityHooksOnlyConsumer COMMAND void_observability_hooks_only_consumer) diff --git a/tests/package/ObservabilityHooksOnly/main.cpp b/tests/package/ObservabilityHooksOnly/main.cpp new file mode 100644 index 0000000..749d287 --- /dev/null +++ b/tests/package/ObservabilityHooksOnly/main.cpp @@ -0,0 +1,11 @@ +#include + +int main() +{ + Void::Observability::HookSlot slot; + Void::Observability::kNullObservationHooks.emit_metric( + Void::Observability::MetricPoint{.name = "probe", .integer_delta = 1}); + slot.invoke_metric( + Void::Observability::MetricPoint{.name = "probe", .integer_delta = 1}); + return slot.active() ? 1 : 0; +} diff --git a/tests/package/ObservabilityOnly/CMakeLists.txt b/tests/package/ObservabilityOnly/CMakeLists.txt new file mode 100644 index 0000000..73d860a --- /dev/null +++ b/tests/package/ObservabilityOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidObservabilityOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Observability) + +add_executable(void_observability_only_consumer main.cpp) +target_link_libraries(void_observability_only_consumer PRIVATE Void::Observability) + +enable_testing() +add_test(NAME VoidObservabilityOnlyConsumer COMMAND void_observability_only_consumer) diff --git a/tests/package/ObservabilityOnly/main.cpp b/tests/package/ObservabilityOnly/main.cpp new file mode 100644 index 0000000..7388fff --- /dev/null +++ b/tests/package/ObservabilityOnly/main.cpp @@ -0,0 +1,29 @@ +#include + +#include + +int main() +{ + auto reg = Void::Observability::MetricRegistry::create(); + if (!reg) { + return 1; + } + auto ctr = reg->register_instrument(Void::Observability::InstrumentSpec{ + .name = "consumer_ops", + .unit = "1", + .kind = Void::Observability::MetricKind::counter}); + if (!ctr || !reg->add_counter(*ctr, 1)) { + return 2; + } + auto exp = std::make_shared(); + auto tr = Void::Observability::Tracer::create({}, exp); + if (!tr) { + return 3; + } + auto sp = tr->start_span( + Void::Observability::ContextSnapshot{}, + Void::Observability::SpanSpec{.name = "root"}); + sp.end(); + const auto rep = tr->close(); + return rep.failed_spans == 0 ? 0 : 4; +} diff --git a/tests/standalone/Observability/Observability.cpp b/tests/standalone/Observability/Observability.cpp new file mode 100644 index 0000000..09d3229 --- /dev/null +++ b/tests/standalone/Observability/Observability.cpp @@ -0,0 +1,476 @@ +#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()); +}