Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion docs/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ ship a Prometheus exporter. Preserve the shared labels, names and units below.

### Histogram buckets

Bucket boundaries are fixed; the adapter has no bucket customization option:
Every adapter uses these finite bucket boundaries by default. The TypeScript and
Rust adapters have no bucket option.

| Metric family | Unit | Finite bucket boundaries |
| --- | --- | --- |
Expand All @@ -144,6 +145,28 @@ Bucket boundaries are fixed; the adapter has no bucket customization option:
| Shadow and recovery value ages | Seconds | `1, 5, 15, 60, 300, 900, 3600, 10800, 43200, 86400, 259200, 604800` |
| Future timestamp offsets | Seconds | `0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 5, 15, 60, 300, 900, 3600, 10800, 43200` |

<LanguageContent language="go">

`PrometheusBuckets(kind, bounds)` replaces the boundaries of one histogram.
`kind` is the histogram's `PrometheusCollectorSchema.Kind`, such as `get`,
`fallback`, `serialization` or `compressionDuration`. Pass the same options to
`NewPrometheusMetrics`, `NewPrometheusMetricsWithBindings` and
`PrometheusCollectorSchemas`: adapters and bindings that share a registry and
prefix must use the same buckets. Construction fails for an unknown or counter
kind, a repeated kind, and boundaries that are empty, not finite or not
increasing. Fewer boundaries give fewer series per label set, and boundaries
that differ from the table do not aggregate with other services that use the
defaults. This excerpt shows example boundaries, not recommended ones:

```go
timer := []float64{0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.25}
metrics, err := dialcache.NewPrometheusMetrics(registry, "",
dialcache.PrometheusBuckets("get", timer),
dialcache.PrometheusBuckets("fallback", timer))
```

</LanguageContent>

### Prometheus metrics

See the [metric catalog](#metric-catalog) for names, types, labels, and meanings.
Expand Down
24 changes: 15 additions & 9 deletions formal/catalogs/feature-coverage.json
Original file line number Diff line number Diff line change
Expand Up @@ -1033,7 +1033,7 @@
"test": "TestObserverIsolationAndBoundedNativeJSONLogs",
"path": "go/metrics_test.go",
"scope": "Native observer panic/error and logger panics are isolated; JSON/key previews obey UTF-8 byte caps and unsupported/cyclic values have null previews.",
"sha256": "55657dc4165d0c5fd40b796a904472d6b65402b2b0704f593cf4c618d3ba3639"
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
}
],
"adaptation": "Observability must remain diagnostic even when both the primary operation and logger fail.",
Expand Down Expand Up @@ -1352,7 +1352,13 @@
"test": "TestPrometheusWireSchemaMatchesTypeScriptBinding",
"path": "go/metrics_test.go",
"scope": "All twenty Go collector names, help text, label order, kinds and bucket boundaries are checked against the TS binding schema.",
"sha256": "55657dc4165d0c5fd40b796a904472d6b65402b2b0704f593cf4c618d3ba3639"
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
},
{
"test": "TestPrometheusBucketOptions",
"path": "go/metrics_test.go",
"scope": "PrometheusBuckets replaces only the named histograms' bounds; reuse and bindings compare the effective schema, and invalid options fail before any collector registers.",
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
}
],
"adaptation": "Exporter schema changes break dashboards even when portable event semantics still pass; current Go schema check derives its expectation from TS source, not Quint.",
Expand Down Expand Up @@ -1392,7 +1398,7 @@
"test": "TestPrometheusReuseAndConflictIsolation",
"path": "go/metrics_test.go",
"scope": "Compatible adapters reuse counters and histograms in one caller registry; incompatible pre-existing metrics cause no partial collector registration.",
"sha256": "55657dc4165d0c5fd40b796a904472d6b65402b2b0704f593cf4c618d3ba3639"
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
}
],
"adaptation": "Registry ownership and collector reuse avoid global pollution and duplicate collectors in multi-instance deployments.",
Expand Down Expand Up @@ -1432,19 +1438,19 @@
"test": "TestPrometheusReuseAndConflictIsolation",
"path": "go/metrics_test.go",
"scope": "Compatible adapters reuse counters and histograms in one caller registry; incompatible pre-existing metrics cause no partial collector registration.",
"sha256": "55657dc4165d0c5fd40b796a904472d6b65402b2b0704f593cf4c618d3ba3639"
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
},
{
"test": "TestPrometheusExplicitBindingsPreserveExistingObservations",
"path": "go/metrics_test.go",
"scope": "Explicit compatible externally created collectors preserve pre-existing counter and histogram observations when bound by an adapter.",
"sha256": "55657dc4165d0c5fd40b796a904472d6b65402b2b0704f593cf4c618d3ba3639"
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
},
{
"test": "TestPrometheusBindingsRejectIncompatibleOrUnregisteredCollectors",
"path": "go/metrics_test.go",
"scope": "Explicit collector bindings reject malformed schema, conflicting registry state or unregistered collector identities.",
"sha256": "55657dc4165d0c5fd40b796a904472d6b65402b2b0704f593cf4c618d3ba3639"
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
}
],
"adaptation": "Go requires explicit collector bindings/schema because client_golang cannot expose empty histogram bucket schema; no destructive compatibility probing is permitted.",
Expand Down Expand Up @@ -1486,7 +1492,7 @@
"test": "TestDatadogMetricNamesUnitsAndLabels",
"path": "go/metrics_test.go",
"scope": "Native DogStatsD method/name/unit tables, representative bounded labels, histogram mode, namespace restrictions and nil-client validation are checked.",
"sha256": "55657dc4165d0c5fd40b796a904472d6b65402b2b0704f593cf4c618d3ba3639"
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
}
],
"adaptation": "Different observation modes have different backend semantics and require a namespace migration; current schema source remains native integration code.",
Expand Down Expand Up @@ -1527,7 +1533,7 @@
"test": "TestDatadogMetricNamesUnitsAndLabels",
"path": "go/metrics_test.go",
"scope": "Native DogStatsD method/name/unit tables, representative bounded labels, histogram mode, namespace restrictions and nil-client validation are checked.",
"sha256": "55657dc4165d0c5fd40b796a904472d6b65402b2b0704f593cf4c618d3ba3639"
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
}
],
"adaptation": "Typed Go methods replace TS duck-typed method validation, but namespace and cardinality constraints remain observable integration contracts.",
Expand Down Expand Up @@ -1567,7 +1573,7 @@
"test": "TestObserverIsolationAndBoundedNativeJSONLogs",
"path": "go/metrics_test.go",
"scope": "Native observer panic/error and logger panics are isolated; JSON/key previews obey UTF-8 byte caps and unsupported/cyclic values have null previews.",
"sha256": "55657dc4165d0c5fd40b796a904472d6b65402b2b0704f593cf4c618d3ba3639"
"sha256": "43e1151b3d8f6b14efdae89be31785c39a9130a54ff6205a502477c0f0493093"
}
],
"adaptation": "C60 covers whether a warning happens; bounded formatting and native JSON failures are separate observability behavior.",
Expand Down
8 changes: 5 additions & 3 deletions formal/catalogs/go-parity.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"semanticCasesSha256": "380273598e1d956a3f9fce270cc84424b342e456139b279bd56576bd3b837f65",
"executionSha256": "eaf117c3e8630013cc8df0524f84af440c470f42e8711ab4dd07b931161c784f",
"sourceAuditDispositionsSha256": "942eab018ae0d8fa189ff16c322f6d9b3301aadc7c46d00b311018728c62f34e",
"featureCoverageSha256": "a49438a0fab8997518956565f391486a569aab304f2057a667d28c5d41bde834",
"featureCoverageSha256": "7bfe01e9ed074fc4661e6db2d3397341f7f691f476e2358e4af082c8117570de",
"coverageWitnessesSha256": "745cebececddbfa97912621ada94072d648e8e60e8b3eb013b91eefd16f352a1",
"profilesSha256": "888a522f8ad97862ebcb0b5fe363ec7bec60367fa42c60e1623141814b1991b3"
},
Expand Down Expand Up @@ -4309,7 +4309,7 @@
],
"mappingReview": {
"status": "reviewed-mapping-not-execution",
"rationale": "PrometheusMetrics preserves metric names, labels, histogram units and buckets using client_golang. Existing individually registered collectors require explicit schema-bearing bindings plus descriptor and registry-identity validation; this replaces prom-client registry introspection and makes histogram-schema knowledge an explicit caller precondition. dialcache_shadow_mismatch_logging_counter is a twentieth collector schema.",
"rationale": "PrometheusMetrics preserves metric names, labels, histogram units and buckets using client_golang. Existing individually registered collectors require explicit schema-bearing bindings plus descriptor and registry-identity validation; this replaces prom-client registry introspection and makes histogram-schema knowledge an explicit caller precondition. dialcache_shadow_mismatch_logging_counter is a twentieth collector schema. PrometheusBuckets is a Go-only option that replaces one histogram's bounds; without it every bucket matches TypeScript, and reuse and bindings compare the schema the options build.",
"nativeAdaptations": [
"B01",
"X01"
Expand All @@ -4320,12 +4320,14 @@
"symbols": [
"PrometheusCollectorSchema",
"PrometheusCollectorSchemas",
"PrometheusOption",
"PrometheusBuckets",
"PrometheusCollectorBinding",
"NewPrometheusMetrics",
"NewPrometheusMetricsWithBindings",
"ObserveEvent"
],
"sha256": "1027779b913bb890cd06ffe314d80840ce67c522bc12dad9b6e12b4224a9d340"
"sha256": "ccbb46eea578033e4f1c3f6c5fb50bea53b40e90a22f6cdce20509781c9eea56"
}
]
}
Expand Down
6 changes: 3 additions & 3 deletions formal/catalogs/source-audit.json
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@
},
{
"path": "docs/observability.md",
"sha256": "11fb60820a7736f9ff1f3658262ec2803efde56281d453218e6b93f574fd1114",
"sha256": "230f8597110bad4d6327f03d31cb4e045bd26a5b7036cfbc6314add50eae18d2",
"entries": [
{"title":"Observability","contracts":["C30","X01"]},
{"title":"Reading the signals","contracts":["C58"]},
Expand Down Expand Up @@ -1507,7 +1507,7 @@
},
{
"path": "formal/guides/GO-PARITY.md",
"sha256": "0ab9505cb3cb1185887f080882bb50b16cf88dc7134305e144478ece178c7a7b",
"sha256": "c245fd24071f3503447c0f5a43a984a36a447672a261d741a1af83b8c1f17771",
"entries": [
{"title":"Go parity acceptance"},
{"title":"Required evidence"},
Expand Down Expand Up @@ -1800,7 +1800,7 @@
},
{
"path": "go/README.md",
"sha256": "c3352fa63c06222cb8399c4141e0d654c0bb0481b93a82dde125c58dbdf25be4",
"sha256": "01224a60c2a05dabdf150351e03115445b69d936f538d17014c94a562e734a86",
"entries": [
{"title":"DialCache for Go"},
{"title":"Use"},
Expand Down
7 changes: 5 additions & 2 deletions formal/guides/GO-PARITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,14 +220,17 @@ rendering or computation fails is nil. A `Warn` panic stays isolated, and the
`shadowMismatchLogging` event reports it as `logger_error` unless a hook or
render failure outranks it. The Prometheus and DogStatsD adapters preserve
metric names, units, labels, bucket boundaries, and counter increments. Logical
cache keys never become metric labels.
cache keys never become metric labels. `PrometheusBuckets` is a Go-only option
that replaces one histogram's boundaries; without it the Prometheus schema
matches TypeScript, and the other ports have no such option yet.

The Go Prometheus binding accepts an explicit native registry. Reconstructing
this adapter with the same registry and prefix reuses its collectors and
observations. `NewPrometheusMetricsWithBindings` additionally reuses externally
created, individually registered `CounterVec` and `HistogramVec` collectors.
Each `PrometheusCollectorBinding` supplies the actual collector and its
construction schema. All declared schemas, public descriptors, and registered
construction schema, compared with the schema the same bucket options build.
All declared schemas, public descriptors, and registered
collector identities are checked before the remaining collectors are
registered as an atomic group. A failed compatibility check creates no metric
series or partial collector group.
Expand Down
3 changes: 2 additions & 1 deletion go/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ receives the same verdict event the observers do, so wire an exporter through
one of those paths to avoid double-counting it.
`WithRecoveryOutcomes` is an optional separate recovery hook. Prometheus and
DogStatsD adapters preserve metric names, labels, units and buckets; logical
keys never become labels. `WithLogger` replaces the standard logger, which
keys never become labels. `PrometheusBuckets` replaces the default buckets of
one Prometheus histogram. `WithLogger` replaces the standard logger, which
writes each entry on one line with control characters escaped; either is
failure-isolated. Mismatch logging is opt-in, confirmed, and bounded.

Expand Down
65 changes: 59 additions & 6 deletions go/metrics_prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package dialcache
import (
"errors"
"fmt"
"math"
"reflect"
"slices"
"sync"

"github.com/prometheus/client_golang/prometheus"
Expand All @@ -16,8 +18,25 @@ type PrometheusCollectorSchema struct {
Buckets []float64
}

func PrometheusCollectorSchemas(prefix string) []PrometheusCollectorSchema {
return []PrometheusCollectorSchema{
// PrometheusOption changes the buckets of one adapter histogram.
type PrometheusOption struct {
kind string
buckets []float64
}

// PrometheusBuckets sets the finite bucket boundaries of the histogram whose
// PrometheusCollectorSchema.Kind is kind; +Inf is implicit. The constructors
// reject an unknown or counter kind, a repeated kind, and boundaries that are
// empty, not finite or not strictly increasing. Adapters and bindings that
// share a registry and prefix must use the same buckets.
func PrometheusBuckets(kind string, buckets []float64) PrometheusOption {
return PrometheusOption{kind: kind, buckets: buckets}
}

// PrometheusCollectorSchemas returns the schemas the adapter builds with these
// options. It does not validate the options; the constructors do.
func PrometheusCollectorSchemas(prefix string, options ...PrometheusOption) []PrometheusCollectorSchema {
schemas := []PrometheusCollectorSchema{
{Kind: "disabled", Name: prefix + "dialcache_disabled_counter", Help: "Requests where DialCache skipped a cache layer.", Labels: []string{"cache_namespace", "use_case", "key_type", "layer", "reason"}},
{Kind: "miss", Name: prefix + "dialcache_miss_counter", Help: "DialCache cache misses.", Labels: []string{"cache_namespace", "use_case", "key_type", "layer", "reason"}},
{Kind: "request", Name: prefix + "dialcache_request_counter", Help: "Total DialCache cache-layer requests.", Labels: []string{"cache_namespace", "use_case", "key_type", "layer"}},
Expand All @@ -39,6 +58,37 @@ func PrometheusCollectorSchemas(prefix string) []PrometheusCollectorSchema {
{Kind: "compressionRatio", Name: prefix + "dialcache_compression_ratio_histogram", Help: "Compressed-to-original DialCache payload size ratio for compressed writes.", Labels: []string{"cache_namespace", "use_case", "key_type", "layer"}, Buckets: []float64{0.05, 0.1, 0.2, 0.3, 0.5, 0.7, 0.9, 1}},
{Kind: "compressionDuration", Name: prefix + "dialcache_compression_timer", Help: "DialCache payload compression and decompression latency in seconds.", Labels: []string{"cache_namespace", "use_case", "key_type", "layer", "operation"}, Buckets: []float64{0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}},
}
for _, option := range options {
for i := range schemas {
if schemas[i].Kind == option.kind && schemas[i].Buckets != nil {
// client_golang keeps the slice it is given as live bucket bounds.
schemas[i].Buckets = slices.Clone(option.buckets)
}
}
}
return schemas
}

func checkPrometheusOptions(options []PrometheusOption) error {
settable := make(map[string]bool)
for _, schema := range PrometheusCollectorSchemas("") {
settable[schema.Kind] = schema.Buckets != nil
}
for _, option := range options {
if !settable[option.kind] {
return fmt.Errorf("Prometheus buckets: %q is not a histogram kind, or is set twice", option.kind)
}
settable[option.kind] = false
if len(option.buckets) == 0 {
return fmt.Errorf("Prometheus buckets for %q are empty", option.kind)
}
for i, bound := range option.buckets {
if math.IsNaN(bound) || math.IsInf(bound, 0) || i > 0 && bound <= option.buckets[i-1] {
return fmt.Errorf("Prometheus buckets for %q must be finite and strictly increasing", option.kind)
}
}
}
return nil
}

type prometheusMetricsCollector struct {
Expand Down Expand Up @@ -83,8 +133,8 @@ var prometheusConstruction sync.Mutex

// NewPrometheusMetrics creates collectors or reuses an earlier DialCache group.
// Use NewPrometheusMetricsWithBindings to reuse externally created collectors.
func NewPrometheusMetrics(registry *prometheus.Registry, prefix string) (*PrometheusMetrics, error) {
return NewPrometheusMetricsWithBindings(registry, prefix, nil)
func NewPrometheusMetrics(registry *prometheus.Registry, prefix string, options ...PrometheusOption) (*PrometheusMetrics, error) {
return NewPrometheusMetricsWithBindings(registry, prefix, nil, options...)
}

func collectorDescriptions(collector prometheus.Collector) []string {
Expand All @@ -102,7 +152,7 @@ func collectorDescriptions(collector prometheus.Collector) []string {
// remain on the same collector objects. As with registry configuration itself,
// callers must not concurrently unregister/reconfigure the supplied collectors
// during construction; concurrent observations remain safe.
func NewPrometheusMetricsWithBindings(registry *prometheus.Registry, prefix string, bindings []PrometheusCollectorBinding) (adapter *PrometheusMetrics, err error) {
func NewPrometheusMetricsWithBindings(registry *prometheus.Registry, prefix string, bindings []PrometheusCollectorBinding, options ...PrometheusOption) (adapter *PrometheusMetrics, err error) {
prometheusConstruction.Lock()
defer prometheusConstruction.Unlock()
defer func() {
Expand All @@ -114,7 +164,10 @@ func NewPrometheusMetricsWithBindings(registry *prometheus.Registry, prefix stri
if registry == nil {
return nil, errors.New("Prometheus registry is required")
}
collector := &prometheusMetricsCollector{schemas: PrometheusCollectorSchemas(prefix), counters: make(map[string]*prometheus.CounterVec), histograms: make(map[string]*prometheus.HistogramVec)}
if err := checkPrometheusOptions(options); err != nil {
return nil, err
}
collector := &prometheusMetricsCollector{schemas: PrometheusCollectorSchemas(prefix, options...), counters: make(map[string]*prometheus.CounterVec), histograms: make(map[string]*prometheus.HistogramVec)}
for _, schema := range collector.schemas {
if counterKinds[schema.Kind] {
collector.counters[schema.Kind] = prometheus.NewCounterVec(prometheus.CounterOpts{Name: schema.Name, Help: schema.Help}, schema.Labels)
Expand Down
Loading
Loading