Title: `StateSet.Builder.unit(...)` is accepted at build time, then every `collect()` throws · Issue #2632 · prometheus/client_java · GitHub
Open Graph Title: `StateSet.Builder.unit(...)` is accepted at build time, then every `collect()` throws · Issue #2632 · prometheus/client_java
X Title: `StateSet.Builder.unit(...)` is accepted at build time, then every `collect()` throws · Issue #2632 · prometheus/client_java
Description: Location (prometheus/client_java @ 7695470): prometheus-metrics-core/.../StateSet.java:150-185: StateSet.Builder does not override unit(...), so it inherits the plain setter from MetricWithFixedMetadata.Builder:166-169. prometheus-metric...
Open Graph Description: Location (prometheus/client_java @ 7695470): prometheus-metrics-core/.../StateSet.java:150-185: StateSet.Builder does not override unit(...), so it inherits the plain setter from MetricWithFixedMet...
X Description: Location (prometheus/client_java @ 7695470): prometheus-metrics-core/.../StateSet.java:150-185: StateSet.Builder does not override unit(...), so it inherits the plain setter from MetricWithFixedMet...
Opengraph URL: https://github.com/prometheus/client_java/issues/2632
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"`StateSet.Builder.unit(...)` is accepted at build time, then every `collect()` throws","articleBody":"**Location** (`prometheus/client_java` @ `7695470`):\n\n- [`prometheus-metrics-core/.../StateSet.java:150-185`](https://github.com/prometheus/client_java/blob/76954702079ded14718b84cbdde7f3bcf1bc03bd/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StateSet.java#L150-L185): `StateSet.Builder` does not override `unit(...)`, so it inherits the plain setter from [`MetricWithFixedMetadata.Builder:166-169`](https://github.com/prometheus/client_java/blob/76954702079ded14718b84cbdde7f3bcf1bc03bd/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/MetricWithFixedMetadata.java#L166-L169).\n- [`prometheus-metrics-model/.../StateSetSnapshot.java:35-38`](https://github.com/prometheus/client_java/blob/76954702079ded14718b84cbdde7f3bcf1bc03bd/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/StateSetSnapshot.java#L35-L38): the snapshot rejects the unit, and `StateSet.collect` builds this snapshot on every scrape ([`StateSet.java:87`](https://github.com/prometheus/client_java/blob/76954702079ded14718b84cbdde7f3bcf1bc03bd/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StateSet.java#L87)).\n- [`prometheus-metrics-core/.../Info.java:159-166`](https://github.com/prometheus/client_java/blob/76954702079ded14718b84cbdde7f3bcf1bc03bd/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Info.java#L159-L166): `Info.Builder` already rejects a unit right away; [`StateSetSnapshot.Builder.unit`](https://github.com/prometheus/client_java/blob/76954702079ded14718b84cbdde7f3bcf1bc03bd/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/StateSetSnapshot.java#L249-L252) does too.\n\n```java\n public B unit(@Nullable Unit unit) {\n this.unit = unit;\n return self();\n }\n```\n\n```java\n private void validate() {\n if (getMetadata().hasUnit()) {\n throw new IllegalArgumentException(\"An state set metric cannot have a unit.\");\n }\n```\n\n**Problem**\n\nStateSet metrics cannot have a unit in OpenMetrics, and the model enforces that in `StateSetSnapshot`. The metric builder does not, so this builds and registers fine:\n\n```java\nStateSet stateSet = StateSet.builder()\n .name(\"feature_flags\")\n .states(\"a\", \"b\")\n .unit(Unit.SECONDS)\n .build();\n```\n\nand the mistake only shows up later, when the metric is collected: every `stateSet.collect()` throws `IllegalArgumentException(\"An state set metric cannot have a unit.\")`. `Info.Builder.unit(...)` and `StateSetSnapshot.Builder.unit(...)` already fail immediately, so `StateSet.Builder` is the one builder that accepts it. (I have not checked how each exporter reports a collector that throws during a scrape. The claim here is only that the error appears at collect time and not at build time.)\n\n**Reproduction**\n\nAdded to `StateSetTest` (same shape as `InfoTest#unit`):\n\n```java\n @Test\n void unit() {\n assertThatExceptionOfType(UnsupportedOperationException.class)\n .isThrownBy(\n () -> StateSet.builder().name(\"test\").states(\"a\", \"b\").unit(Unit.SECONDS).build())\n .withMessage(\"StateSet metrics cannot have a unit.\");\n }\n```\n\n`./mvnw test -pl prometheus-metrics-core -am -Dtest=StateSetTest -Dsurefire.failIfNoSpecifiedTests=false`\n\n```\n[ERROR] io.prometheus.metrics.core.metrics.StateSetTest.unit -- Time elapsed: 0.037 s \u003c\u003c\u003c FAILURE!\njava.lang.AssertionError: \n\nExpecting code to raise a throwable.\n\tat io.prometheus.metrics.core.metrics.StateSetTest.unit(StateSetTest.java:79)\n```\n\nCalling `collect()` on the StateSet from the snippet above:\n\n```\njava.lang.IllegalArgumentException: An state set metric cannot have a unit.\n\tat io.prometheus.metrics.model.snapshots.StateSetSnapshot.validate(StateSetSnapshot.java:37)\n\tat io.prometheus.metrics.model.snapshots.StateSetSnapshot.\u003cinit>(StateSetSnapshot.java:27)\n\tat io.prometheus.metrics.core.metrics.StateSet.collect(StateSet.java:87)\n\tat io.prometheus.metrics.core.metrics.StateSet.collect(StateSet.java:55)\n\tat io.prometheus.metrics.core.metrics.StatefulMetric.collect(StatefulMetric.java:67)\n```\n\nEnvironment:\n- Commit: [`76954702079ded14718b84cbdde7f3bcf1bc03bd`](https://github.com/prometheus/client_java/commit/76954702079ded14718b84cbdde7f3bcf1bc03bd); the files involved are unchanged on current `main` (`e574d32`)\n- Toolchain: OpenJDK 25.0.5, Apache Maven 3.9.16\n\n**Already implemented in `prometheus/client_python`**\n\nPR: https://github.com/prometheus/client_python/pull/300 — \"Initial work on OpenMetrics\" (merged 2018-09-07T16:26:29Z, merge commit `10c8eb4a830`). Among the OpenMetrics groundwork it rejects a unit for `Info` and `Enum` (Python's StateSet) when the metric is created, and the OpenMetrics parser rejects units for `info` and `stateset`.\n\n**How client_python implemented it** (relevant hunks, verbatim):\n\n```diff\n--- a/tests/test_core.py\n+++ b/tests/test_core.py\n@@ -405,15 +462,26 @@ def test_invalid_names_raise(self):\n...\n+ def test_no_units_for_info_enum(self):\n+ self.assertRaises(ValueError, Info, 'foo', 'help', unit=\"x\")\n+ self.assertRaises(ValueError, Enum, 'foo', 'help', unit=\"x\")\n+\n```\n\n```diff\n--- a/prometheus_client/openmetrics/parser.py\n+++ b/prometheus_client/openmetrics/parser.py\n@@ -0,0 +1,339 @@\n...\n+ if unit and not name.endswith(\"_\" + unit):\n+ raise ValueError(\"Unit does not match metric name: \" + name)\n+ if unit and typ in ['info', 'stateset']:\n+ raise ValueError(\"Units not allowed for this metric type: \" + name)\n```\n\n**Suggested fix**\n\nOverride `unit(...)` in `StateSet.Builder` the same way `Info.Builder` does:\n\n```diff\ndiff --git a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StateSet.java b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StateSet.java\n--- a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StateSet.java\n+++ b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StateSet.java\n@@ -8,6 +8,7 @@ import io.prometheus.metrics.core.datapoints.StateSetDataPoint;\n import io.prometheus.metrics.model.registry.MetricType;\n import io.prometheus.metrics.model.snapshots.Labels;\n import io.prometheus.metrics.model.snapshots.StateSetSnapshot;\n+import io.prometheus.metrics.model.snapshots.Unit;\n import java.util.ArrayList;\n import java.util.Collections;\n import java.util.List;\n@@ -170,6 +171,17 @@ public class StateSet extends StatefulMetric\u003cStateSetDataPoint, StateSet.DataPoi\n return this;\n }\n \n+ /**\n+ * Throws an {@link UnsupportedOperationException} because StateSet metrics cannot have a unit.\n+ */\n+ @Override\n+ public Builder unit(@Nullable Unit unit) {\n+ if (unit != null) {\n+ throw new UnsupportedOperationException(\"StateSet metrics cannot have a unit.\");\n+ }\n+ return this;\n+ }\n+\n @Override\n public StateSet build() {\n if (names == null) {\n```\n\nVerified on `7695470` (OpenJDK 25.0.5, Maven 3.9.16): the test above fails without this patch and passes with it; no other test results change (`prometheus-metrics-core` and the modules it depends on).\n\nI can submit a PR for this.\n\nChecked: searches for `StateSet unit`, `cannot have a unit`, `unit UnsupportedOperationException` found only #2114 (metric family descriptors) and #1800 (same-name metrics), which do not cover this.\n","author":{"url":"https://github.com/hidingmyname","@type":"Person","name":"hidingmyname"},"datePublished":"2026-10-31T12:44:37Z","url":"https://github.com/prometheus/client_java/issues/2632"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:ae2ddcb8-be69-8968-b661-4c0149cc328e |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | CAFA:1824CC:232DE2:301AB1:6AFBAF8E |
| html-safe-nonce | 5bd6661a244a781f3e7c903818ee06467aab01b2aff9708efd9eb21d26ed443e |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDQUZBOjE4MjRDQzoyMzJERTI6MzAxQUIxOjZBRkJBRjhFIiwidmlzaXRvcl9pZCI6IjkwNzEwMzIwNjU1MTEzNzA2MzgiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 495306de914fd568b6c79701b86f835c12a3172a03e78f26f912fd6817c9f285 |
| hovercard-subject-tag | issue:6134933994 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/prometheus/client_java/2632/issue_layout |
| twitter:image | https://opengraph.githubassets.com/6f9e8b764fe6778b92ac5c8ee27d38d0001795cbeb7f2d1162fff525e088560b/prometheus/client_java/issues/2632 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/6f9e8b764fe6778b92ac5c8ee27d38d0001795cbeb7f2d1162fff525e088560b/prometheus/client_java/issues/2632 |
| og:image:alt | Location (prometheus/client_java @ 7695470): prometheus-metrics-core/.../StateSet.java:150-185: StateSet.Builder does not override unit(...), so it inherits the plain setter from MetricWithFixedMet... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | hidingmyname |
| hostname | github.com |
| expected-hostname | github.com |
| None | e25fbd830d3e6ad0e8935c105cf4fdc70c593dffcd27bb45b790ae4fece5ea55 |
| turbo-cache-control | no-preview |
| go-import | github.com/prometheus/client_java git https://github.com/prometheus/client_java.git |
| octolytics-dimension-user_id | 3380462 |
| octolytics-dimension-user_login | prometheus |
| octolytics-dimension-repository_id | 7997879 |
| octolytics-dimension-repository_nwo | prometheus/client_java |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 7997879 |
| octolytics-dimension-repository_network_root_nwo | prometheus/client_java |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 08c8f17f9d27054a108b8b6254e405de0151f660 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width