client_python icon indicating copy to clipboard operation
client_python copied to clipboard

RFC: support clearing of metric objects for custom collectors

Open calestyo opened this issue 6 months ago • 3 comments

Hey.

This is based on my second point in https://github.com/prometheus/client_python/pull/1173#issuecomment-4436585472.

Please see there and also the commit message which explains the rationale.

I think the biggest open point right now would be whether to use self.samples.clear() or rather self.samples = [], which would probably be way faster (see commit message for the reasoning). If .samples was actually be considered non-public, it should however be renamed (and I think the same goes for e.g. add_sample, whose doc-string already says it would be internal only... so just renamed it to _add_sample, or maybe warp around it and add a deprecation warning to the public one.

Cheers, Chris.

PS: @csmarchbanks and @k1chik might want to have a look. For the latter, if this PR would be considered worthy to add... it would probably make sense to present that way of use as an alternative to the current schema in the docs (which you've so greatly worked on recently)

calestyo avatar May 13 '26 21:05 calestyo

btw: I think we could perhaps even tell people that if they would want to use the "new" way (i.e. define metrics in __init__ and merely clear() them in collect(), they could rather easily keep backwards compatibility, by simply doing the self.samples.clear() themselves, if self has no clear-method - or was anything around samples changed recently so that this wouldn't work?

And perhaps one more rationale point: In my understanding, the memory issue is rather the many metrics (i.e. samples) and not having "many" the *MetricFamily-objects around, or is it? Cause if correct, then "keeping" them, as proposed here, shouldn't really kill memory, if we still allow to .clear() as soon as the data has been yielded.

calestyo avatar May 13 '26 21:05 calestyo

Oh and one more point to decide upon:

How should the function be named?

I went for clear now, but we might also choose something like clear_metrics or clear_samples, because the function clears only those and not the whole object (like name, documentation, etc. all stay).

calestyo avatar May 13 '26 21:05 calestyo

Agree on the memory point, the cost is the samples (the label-value data), not the MetricFamily wrapper objects themselves, so keeping them in __init__ and clearing samples after each yield is sound. self.samples.clear() as a fallback for backwards compatability makes sense too.

kkukadia avatar May 14 '26 01:05 kkukadia