Skip to content

Commit 69ea6fa

Browse files
committed
Remove nameless collectors from the registry on unregister
When a collector is registered under support_collectors_without_names with no metric names, register() appends it to _collectors_without_names in addition to the usual bookkeeping. unregister() only cleaned up _collector_to_names and _names_to_collectors, so the collector stayed in _collectors_without_names and kept being collected. A normal collect() no longer returned the collector's metrics, but RestrictedRegistry.collect() -- which seeds its collector set from _collectors_without_names -- still did, so an unregistered collector's samples reappeared under restricted_registry(). unregister() now also drops the collector from that list. Add test_unregister_removes_no_names_collector, asserting a nameless collector is no longer collected by a restricted registry after it has been unregistered. Signed-off-by: Sean Kim <skim8705@gmail.com>
1 parent a96f6f4 commit 69ea6fa

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

prometheus_client/registry.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ def unregister(self, collector: Collector) -> None:
6161
for name in self._collector_to_names[collector]:
6262
del self._names_to_collectors[name]
6363
del self._collector_to_names[collector]
64+
if collector in self._collectors_without_names:
65+
self._collectors_without_names.remove(collector)
6466

6567
def _get_names(self, collector):
6668
"""Get names of timeseries the collector produces and clashes with."""

tests/test_core.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -960,6 +960,21 @@ def test_unregister_works(self):
960960
registry.unregister(s)
961961
Gauge('s_count', 'help', registry=registry)
962962

963+
def test_unregister_removes_no_names_collector(self):
964+
registry = CollectorRegistry(support_collectors_without_names=True)
965+
966+
class NamelessCollector:
967+
def collect(self):
968+
return [GaugeMetricFamily('foo', 'help', value=42)]
969+
970+
collector = NamelessCollector()
971+
registry.register(collector)
972+
registry.unregister(collector)
973+
# A nameless collector must be removed from the collectors-without-names
974+
# list too, otherwise a restricted registry keeps collecting it after it
975+
# was unregistered.
976+
self.assertEqual([], list(registry.restricted_registry(['foo']).collect()))
977+
963978
def custom_collector(self, metric_family, registry):
964979
class CustomCollector:
965980
def collect(self):

0 commit comments

Comments
 (0)