← Back to Pull requests

Add MetricDescriptor and descriptor-based factory APIs (PoC for #236) #239

Open
ManjunathAnawal opened this pull request with 874 lines diff across 6 files
View on GitHub
ManjunathAnawal ManjunathAnawal commented on Aug 21, 2026 09:55 UTC
Author

Motivation

Relates to #236. Swift Metrics currently passes only a label and dimensions to backends, so there is no portable way to express a Prometheus/OpenMetrics HELP line or an OTLP instrument description. Today swift-prometheus exposes a separate registry API taking help:, and swift-otel works around it via dimensions.

Status: proof of concept, not a merge request

Per the review feedback on #237 — "I strongly recommend to provide a PoC with the proposed solution" — this is the PoC implementation to accompany an SMT proposal, rather than something to land ahead of that process. Opening it as a PR so the diff is reviewable and CI runs against it; happy to convert it to a draft, or close it and keep it as a branch link under the proposal's Implementation heading, whichever fits the Proposals workflow better.

Design

  • MetricDescriptor (Sendable, Equatable) in CoreMetrics: label, dimensions, and an optional description, with an evolvable memberwise init — the "hypothetical struct" from the issue, so future fields (unit, etc.) don't require new factory methods.

  • Five new MetricsFactory requirements — makeCounter(descriptor:), makeFloatingPointCounter(descriptor:), makeMeter(descriptor:), makeRecorder(descriptor:aggregate:), makeTimer(descriptor:) — each with a default implementation that forwards label and dimensions to the existing makeXXX(label:dimensions:) methods. Existing backends compile and behave unchanged; descriptor-aware backends override to receive the description.

  • Descriptor-based convenience initializers on Counter, FloatingPointCounter, Meter, Gauge, Recorder, and Timer (including the preferredDisplayUnit variant). No existing signature was changed or removed.

  • MultiplexMetricsHandler forwards descriptors to every sub-factory; MappingMetricsFactory transforms label/dimensions while preserving the description; TestMetrics stores the full descriptor (with label/dimensions becoming computed properties, so existing reads still work) so tests can assert on descriptions.
  • Validation

  • swift test — 132 tests pass (22 new), including coverage for legacy-only factories, descriptor-aware dispatch, multiplex and mapping propagation, dimension dedupe, and the floating-point-counter fallback.

  • swift package diagnose-api-breaking-changes — no breaking changes in CoreMetrics, Metrics, or MetricsTestKit.

  • Builds clean under -warnings-as-errors -require-explicit-sendable.

  • swift format lint clean apart from two findings that are pre-existing on main.

  • Sources/CoreMetrics/CMakeLists.txt updated for the cmake-lists check added in #238.
  • Open questions for review

  • Naming: MetricDescriptor here, versus MetricDescription as floated in the issue.

  • Whether aggregate belongs inside the descriptor for Recorder, rather than staying a separate parameter.

  • Whether the default-implementation fallback should be silent, as here, or surface that a description was dropped.
  • Diff: 874 lines (+842 / -32) across 6 files Reviewer: kukushechkin Review duration: 74858m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.57) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.57 · 874 lines diff across 6 files
    0.57
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.91 · 4 substantive comment(s)
    0.91
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    88%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    5 items
    ManjunathAnawal ManjunathAnawal commented on Sep 21, 2026 06:46 UTC
    Author

    Hi @ktoso @FranzBusch @tomerd .
    The "PR label" workflow expired before anyone approved it, so it never ran. Could you approve the workflows and add the appropriate semver label (I think minor, as this adds new API)? I'm happy to rebase or push an update if that helps. Thanks!

    kukushechkin kukushechkin commented on Sep 22, 2026 09:26 UTC
    Contributor

    @ManjunathAnawal thank you for working on this! This would be a great addition to a proposal. I would recommend converting this PR to a draft while you're working on the proposal similar to one in #237.

    ManjunathAnawal ManjunathAnawal commented on Sep 22, 2026 11:42 UTC
    Author

    Hi @kukushechkin Proposal is up: #245 — reusing the SMT-0003 slot since #237 was
    closed without merging. This PR is now in draft; the proposal links it as the
    implementation reference.

    kukushechkin kukushechkin commented on code on Sep 24, 2026 12:38 UTC
    Code Review
    Sources/CoreMetrics/MetricDescriptor.swift:1
    @@ -0,0 +1,295 @@
    +//===----------------------------------------------------------------------===//
    +//
    +// This source file is part of the Swift Metrics API open source project
    +//
    +// Copyright (c) 2026 Apple Inc. and the Swift Metrics API project authors
    +// Licensed under Apache License v2.0
    +//
    +// See LICENSE.txt for license information
    +// See CONTRIBUTORS.txt for the list of Swift Metrics API project authors
    +//
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +//===----------------------------------------------------------------------===//
    +
    +// MARK: - MetricDescriptor
    +
    +/// A description of a metric's identity and metadata.
    +///
    +/// A `MetricDescriptor` bundles everything needed to create a metric — its label, dimensions,
    +/// and optional human-readable metadata such as a ``description`` — into a single value that is
    +/// easy to evolve without breaking the ``MetricsFactory`` API.
    +///
    +/// Backends can map ``description`` to their native concept of metric help text, for example a
    +/// `HELP` line in Prometheus/OpenMetrics exposition, or the `description` field of an
    +/// OpenTelemetry instrument.
    +///
    +/// ```swift
    +/// let counter = Counter(
    +///     descriptor: MetricDescriptor(
    +///         label: "http_requests_total",
    +///         dimensions: [("method", "GET")],
    +///         description: "Total number of HTTP requests received."
    +///     )
    +/// )
    +/// ```
    +public struct MetricDescriptor: Sendable {
    +    /// The label (name) of the metric.
    +    public var label: String
    +    /// The dimensions of the metric, as `(name, value)` tuples.
    +    public var dimensions: [(String, String)]
    +    /// An optional human-readable description of what the metric measures.
    +    ///
    +    /// Backends are encouraged to surface this as their native help/description metadata,
    +    /// for example a Prometheus `HELP` line or an OpenTelemetry instrument description.
    +    /// The description is metadata only: it is not a dimension and does not contribute to
    +    /// the metric's identity or cardinality.
    +    public var description: String?
    +
    +    /// Create a new metric descriptor.
    +    ///
    +    /// - parameters:
    +    ///   - label: The label (name) of the metric.
    +    ///   - dimensions: The dimensions of the metric, as `(name, value)` tuples.
    +    ///   - description: An optional human-readable description of what the metric measures.
    +    public init(label: String, dimensions: [(String, String)] = [], description: String? = nil) {
    +        self.label = label
    +        self.dimensions = dimensions
    +        self.description = description
    +    }
    +}
    +
    +extension MetricDescriptor: Equatable {
    +    public static func == (lhs: MetricDescriptor, rhs: MetricDescriptor) -> Bool {

    This is more of an implementation review, rather that design, but still worth discussing. The current implementation compares dimensions positionally, which is order-sensitive. That's inconsistent with for example TestMetrics.FullKey, where we deliberately made dimension comparison order-insensitive and duplicate-tolerant in #244.

    Could you:
    1. Make MetricDescriptor.== operator sort dimensions before comparing.
    2. Extract the sorting/comparison logic into one shared package helper in CoreMetrics so that both MetricDescriptor and TestMetrics use.
    3. Add a test mirroring countersRepeatedDimensionNames from #244, but for MetricDescriptor.== operator.

    Reviewers
    Assignees
    ManjunathAnawal ManjunathAnawal
    Labels
    risk: low confidence: 88% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 57.3% (MEDIUM) · Higher = larger blast radius
    57.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88% · Lower = rushed or shallow review
    88%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.9% · Safe to merge
    6.9%