Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
a85e35a
Type and label schema validation during registration
jaydeluca Jan 20, 2026
58dddc8
start adding exposition merging
jaydeluca Jan 20, 2026
5acc440
add some additional validation checks
jaydeluca Jan 21, 2026
c8eea69
optimize merge method
jaydeluca Jan 21, 2026
43ab4b1
handle other exposition formats
jaydeluca Jan 21, 2026
9289e4a
cleanups, ironing out edge cases
jaydeluca Jan 24, 2026
6765715
fix linting
jaydeluca Jan 24, 2026
004595f
merge main
jaydeluca Jan 29, 2026
11efcfb
fix merge
jaydeluca Jan 29, 2026
02c0db0
remove scrape time validation
jaydeluca Jan 29, 2026
8b6bf20
cleanup registration
jaydeluca Jan 30, 2026
54f5ecb
cleanup fallback
jaydeluca Jan 30, 2026
74a46f3
add tests
jaydeluca Jan 30, 2026
dfa2114
test visibility
jaydeluca Jan 30, 2026
cbcd1ec
cleanup
jaydeluca Jan 30, 2026
1e897dc
add otel sdk compatibility test
jaydeluca Jan 30, 2026
707e4dc
make copys of labels, fix multicollector processing with try catch, f…
jaydeluca Feb 2, 2026
73b47bd
fix histogram detection when merging snapshots, ensure created with t…
jaydeluca Feb 2, 2026
e3e0fe0
lint
jaydeluca Feb 2, 2026
64d64d4
pr review
jaydeluca Feb 3, 2026
89bac21
Merge branch 'main' into duplicate-names-registration-validation
jaydeluca Feb 3, 2026
e7aeef5
lint
jaydeluca Feb 3, 2026
b17cd0f
code review
jaydeluca Feb 3, 2026
31aebc3
Merge branch 'main' into duplicate-names-registration-validation
jaydeluca Feb 3, 2026
28a8514
proto update
jaydeluca Feb 3, 2026
9bf69c8
be consistent about help/unit validation, ensure deregister labels
jaydeluca Feb 4, 2026
6ebab1b
Merge branch 'main' into duplicate-names-registration-validation
jaydeluca Feb 4, 2026
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ docs/public
benchmark-results/
benchmark-results.json
benchmark-output.log

*.DS_Store
3 changes: 3 additions & 0 deletions docs/content/getting-started/metric-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,3 +276,6 @@ in the `prometheus-metrics-core` API.
However, `prometheus-metrics-model` implements the underlying data model for these types.
To use these types, you need to implement your own `Collector` where the `collect()` method returns
an `UnknownSnapshot` or a `HistogramSnapshot` with `.gaugeHistogram(true)`.
If your custom collector does not implement `getMetricType()` and `getLabelNames()`, ensure it does
not produce the same metric name and label set as another collector, or the exposition may contain
duplicate time series.
24 changes: 21 additions & 3 deletions docs/content/getting-started/registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ weight: 2
In order to expose metrics, you need to register them with a `PrometheusRegistry`. We are using a
counter as an example here, but the `register()` method is the same for all metric types.

## Registering a Metrics with the Default Registry
## Registering a Metric with the Default Registry

```java
Counter eventsTotal = Counter.builder()
Expand All @@ -18,7 +18,7 @@ Counter eventsTotal = Counter.builder()
The `register()` call above builds the counter and registers it with the global static
`PrometheusRegistry.defaultRegistry`. Using the default registry is recommended.

## Registering a Metrics with a Custom Registry
## Registering a Metric with a Custom Registry

You can also register your metric with a custom registry:

Expand Down Expand Up @@ -78,12 +78,30 @@ Counter eventsTotal2 = Counter.builder()
.register(); // IllegalArgumentException, because a metric with that name is already registered
```

## Validation at registration only

Validation of duplicate metric names and label schemas happens at registration time only.
Built-in metrics (Counter, Gauge, Histogram, etc.) participate in this validation.

Custom collectors that implement the `Collector` or `MultiCollector` interface can optionally
implement `getPrometheusName()` and `getMetricType()` (and the MultiCollector per-name variants) so
the registry can enforce consistency. **Validation is skipped when metric name or type is
unavailable:** if `getPrometheusName()` or `getMetricType()` returns `null`, the registry does not
validate that collector. If two such collectors produce the same metric name and same label set at
scrape time, the exposition output may contain duplicate time series and be invalid for Prometheus.

When validation _is_ performed (name and type are non-null), **null label names are treated as an
empty label schema:** `getLabelNames()` returning `null` is normalized to `Collections.emptySet()`
and full label-schema validation and duplicate detection still apply. A collector that returns a
non-null type but leaves `getLabelNames()` as `null` is still validated, with its labels treated as
empty.

## Unregistering a Metric

There is no automatic expiry of unused metrics (yet), once a metric is registered it will remain
registered forever.

However, you can programmatically unregistered an obsolete metric like this:
However, you can programmatically unregister an obsolete metric like this:

```java
PrometheusRegistry.defaultRegistry.unregister(eventsTotal);
Expand Down
5 changes: 4 additions & 1 deletion docs/content/internals/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ All metric types implement
the [Collector](/client_java/api/io/prometheus/metrics/model/registry/Collector.html) interface,
i.e. they provide
a [collect()](</client_java/api/io/prometheus/metrics/model/registry/Collector.html#collect()>)
method to produce snapshots.
method to produce snapshots. Implementers that do not provide metric type or label names (returning
null from `getMetricType()` and `getLabelNames()`) are not validated at registration; they must
avoid producing the same metric name and label schema as another collector, or exposition may be
invalid.

## prometheus-metrics-model

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import org.testcontainers.containers.GenericContainer;

public abstract class ExporterTest {
private final GenericContainer<?> sampleAppContainer;
protected final GenericContainer<?> sampleAppContainer;
private final Volume sampleAppVolume;
protected final String sampleApp;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>io.prometheus</groupId>
<artifactId>it-exporter</artifactId>
<version>1.5.0-SNAPSHOT</version>
</parent>

<artifactId>it-exporter-duplicate-metrics-sample</artifactId>

<name>Integration Tests - Duplicate Metrics Sample</name>
<description>
HTTPServer Sample demonstrating duplicate metric names with different label sets
</description>

<dependencies>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>prometheus-metrics-exporter-httpserver</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>prometheus-metrics-core</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>

<build>
<finalName>exporter-duplicate-metrics-sample</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>
io.prometheus.metrics.it.exporter.duplicatemetrics.DuplicateMetricsSample
</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package io.prometheus.metrics.it.exporter.duplicatemetrics;

import io.prometheus.metrics.core.metrics.Counter;
import io.prometheus.metrics.core.metrics.Gauge;
import io.prometheus.metrics.exporter.httpserver.HTTPServer;
import io.prometheus.metrics.model.snapshots.Unit;
import java.io.IOException;

/** Integration test sample demonstrating metrics with duplicate names but different label sets. */
public class DuplicateMetricsSample {

public static void main(String[] args) throws IOException, InterruptedException {
if (args.length != 2) {
System.err.println("Usage: java -jar duplicate-metrics-sample.jar <port> <outcome>");
System.err.println("Where outcome is \"success\" or \"error\".");
System.exit(1);
}

int port = parsePortOrExit(args[0]);
String outcome = args[1];
run(port, outcome);
}

private static void run(int port, String outcome) throws IOException, InterruptedException {
// Register multiple counters with the same Prometheus name "http_requests_total"
// but different label sets
Counter requestsSuccess =
Counter.builder()
.name("http_requests_total")
.help("Total HTTP requests by status")
.labelNames("status", "method")
.register();
requestsSuccess.labelValues("success", "GET").inc(150);
requestsSuccess.labelValues("success", "POST").inc(45);

Counter requestsError =
Counter.builder()
.name("http_requests_total")
.help("Total HTTP requests by status")
.labelNames("status", "endpoint")
.register();
requestsError.labelValues("error", "/api").inc(5);
requestsError.labelValues("error", "/health").inc(2);

// Register multiple gauges with the same Prometheus name "active_connections"
// but different label sets
Gauge connectionsByRegion =
Gauge.builder()
.name("active_connections")
.help("Active connections")
.labelNames("region", "protocol")
.register();
connectionsByRegion.labelValues("us-east", "http").set(42);
connectionsByRegion.labelValues("us-west", "http").set(38);
connectionsByRegion.labelValues("eu-west", "https").set(55);

Gauge connectionsByPool =
Gauge.builder()
.name("active_connections")
.help("Active connections")
.labelNames("pool", "type")
.register();
connectionsByPool.labelValues("primary", "read").set(30);
connectionsByPool.labelValues("replica", "write").set(10);

// Also add a regular metric without duplicates for reference
Counter uniqueMetric =
Counter.builder()
.name("unique_metric_total")
.help("A unique metric for reference")
.unit(Unit.BYTES)
.register();
uniqueMetric.inc(1024);

HTTPServer server = HTTPServer.builder().port(port).buildAndStart();

System.out.println(
"DuplicateMetricsSample listening on http://localhost:" + server.getPort() + "/metrics");
Thread.currentThread().join(); // wait forever
}

private static int parsePortOrExit(String port) {
try {
return Integer.parseInt(port);
} catch (NumberFormatException e) {
System.err.println("\"" + port + "\": Invalid port number.");
System.exit(1);
}
return 0; // this won't happen
}
}
Loading