opentelemetry-python icon indicating copy to clipboard operation
opentelemetry-python copied to clipboard

force_flush should provide a way to let the caller know whether it succeeded, failed or timed out.

Open IndiTheo opened this issue 8 months ago • 12 comments

From the MeterProvider specification, MetricReader specification and MetricExporter specification:

ForceFlush SHOULD provide a way to let the caller know whether it succeeded, failed or timed out.

Current implementations for readers simply return True, no matter what happened:

MetricReader: https://github.com/open-telemetry/opentelemetry-python/blob/eed100c3a6828a7cb42b7aa52880d6a355a9acd0/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/export/init.py#L397-L399

PeriodicExportingMetricReader: https://github.com/open-telemetry/opentelemetry-python/blob/eed100c3a6828a7cb42b7aa52880d6a355a9acd0/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/export/init.py#L598-L601

And the implementation doesn't allow getting the export result easily, so the only way to manually get the export status seems to be extending the MetricReader, or hooking with a wrapper / mixin. Is it the desired behavior, or can we return a more indicative status by default? It looks like _receive_metrics( should pass-through the return value from export( and convert it to bool.

Describe the solution you'd like

A way to let the caller know whether force_flush( succeeded, failed or timed out, i.e. return True iff export succeeded.

UPD: We better not only convert to bool, but return an Enum type that contains SUCCESS or FAILURE + a failure reason to specify TIMEOUT, for instance. I wonder if it's OK to return MetricExportResult or better create a new Enum.

Anyway, I think that the bool type for force_flush( is not sufficient to comply with the above specification. Maybe we can change it to an Enum that is bool-convertible and remain backwards-compatible this way. Let me know if it's possible.

Describe alternatives you've considered

Mixin class/inheritance/decorator to hook into MetricReader's export( and use the returned MetricExportResult.

Additional Context

The use case is extremely simple:

Export metrics in a push-based way and check if succeeded. I'm using the periodic reader in manual mode with the opentelemetry-exporter-prometheus-remote-write exporter, where it's important to NOT lose metrics.

Would you like to implement a fix?

Yes, after the maintainers agree with the change

IndiTheo avatar Mar 29 '26 14:03 IndiTheo

Great catch on this issue, definitely a footgun for production systems, especially when relying on push-based exporters.

I understand the desire to maintain backward compatibility, but implementing a magic wrapper type is a bit of a Python anti-pattern (ish). It will inevitably cause headaches for static type checkers (mypy/pyright).

Instead we could do:

The Explicit Kwarg Approach: Change the signature to def force_flush(..., detailed: bool = False) -> Union[bool, MetricExportResult]: By default, it returns a strict bool (but actually evaluates the real success/failure instead of lying). If detailed=True is passed, it returns the full MetricExportResult enum (assuming we add a TIMEOUT state to it).

Lemme know what you think @Asquator

pandaadir05 avatar Mar 29 '26 17:03 pandaadir05

Thank you @pandaadir05. Well, I think both options are anti-patterns, but the second one looks even less appealing to me atm, because changing return type based on a boolean flag passed to function is TWO anti-patterns in one... Also, type checkers will still break current users relying on the type to be specifically bool... It also looks ugly to return such a long type for a simple operation result.

I wonder if raising an exception specifically in force_flush( is against OTeL philosophy, and I assume yes...

Currently I see it right switching to a MetricExportResult (is it even exposed to the client? Or should we define a new type?), and make it __bool__able. A failure reason may be another Enum embedded inside.

Let me know if there are any problems with this implementation.

IndiTheo avatar Mar 29 '26 19:03 IndiTheo

It's a design flaw, so making a change backward compatible both for interpreter and linter is challenging.

IndiTheo avatar Mar 29 '26 19:03 IndiTheo

Agree @Asquator

I think creating a new, lightweight type (like ForceFlushResult) with an embedded Enum for the failure reason is cleaner than trying to expose or reuse MetricExportResult.

I'll go ahead and implement this approach so we can see how the linters handle it.

pandaadir05 avatar Mar 29 '26 21:03 pandaadir05

Hi @Asquator and @pandaadir05 — I've been working on a fix for this and wanted to check in before opening a PR to avoid duplicate effort.

I went with the minimal bool propagation approach rather than a new ForceFlushResult enum. My reasoning:

  • Fully spec-compliant — the spec says SHOULD, and a correct bool satisfies that
  • Zero breaking changes — existing callers that do if force_flush(): continue to work identically
  • Simpler surface area — no new public types to document, test, or maintain
  • The richer enum (with TIMEOUT as a distinct value) can always be layered on top in a follow-up once maintainers agree on the right shape

The concrete changes are:

  1. _receive_metrics return type None → bool (subclasses return True/False)
  2. collect() propagates that result up (Optional[bool], None = nothing to flush)
  3. MetricReader.force_flush returns result is not False
  4. PeriodicExportingMetricReader._receive_metrics captures MetricExportResult from export() and converts to bool
  5. PeriodicExportingMetricReader.force_flush returns collect_ok and exporter_ok

Also noticed a small pre-existing bug: detach(token) in PeriodicExportingMetricReader._receive_metrics was only called on the happy path — moved it to finally.

Before I open the PR: are maintainers OK with the bool approach, or is the richer enum a hard requirement? Happy to defer to @pandaadir05's implementation if that direction is already agreed upon.

ravitheja4531-cell avatar Mar 31 '26 23:03 ravitheja4531-cell

Hello @ravitheja4531-cell, thank you for your participation! Actually, we can go on with the bool approach as an immediate, partial solution. I think that knowing a failure reason is pretty important in general (to know whether to retry or not, for example), and it all depends on the versioning standards of the library - it would be great to have the bool option for now, and a more flexible solution as soon as we're allowed to push a breaking change.

The changes make sense, but I'm not sure if None value is good for "nothing to flush" scenario. Why do you think it's useful/worth attention?

Returning a __bool__able Enum is backward compatible for SDK (probably not for linters), and I don't know if it can be done before a major is bumped. In any case, it's a change in behavior. Would be great to hear from a maintainer on this one.

IndiTheo avatar Apr 01 '26 21:04 IndiTheo

Thanks for the feedback @Asquator

You're right to question the None case — on reflection I think it's unnecessary complexity. "Nothing to flush" is still a success from the caller's perspective, so force_flush() should just return True in that scenario. Leaking the internal detail that collect() found no metrics through the public API doesn't add value.

I'll simplify collect() to stay -> None (internal, unchanged) and have force_flush() own the bool result directly:

  • MetricReader.force_flush calls collect(), tracks whether _receive_metrics succeeded via a stored flag, returns True/False
  • Or alternatively, keep collect() returning Optional[bool] internally but document it as a private concern and treat None as True before it ever surfaces to callers

Either way the public contract stays clean: force_flush() returns bool, always — True on success or when there was nothing to do, False on export failure.

Also agree with your point on failure reasons for retries — that's a strong argument for the ForceFlushResult enum in a future major. The bool fix now unblocks users like yourself immediately without painting us into a corner on the richer API later.

I'll open the PR with this simplified approach unless a maintainer chimes in with a different direction

ravitheja4531-cell avatar Apr 05 '26 19:04 ravitheja4531-cell

Hello @Asquator can you assign this to me ?

ravitheja4531-cell avatar Apr 07 '26 17:04 ravitheja4531-cell

Hey @ravitheja4531-cell, this is the first time my name appears in OTeL context, so I can't assign issues to people :) I guess you can open a PR and we'll reach a maintainer to look at it. I'm here to help if you need.

IndiTheo avatar Apr 07 '26 23:04 IndiTheo

PR is up: #5085 — happy to address any review feedback.

ravitheja4531-cell avatar Apr 13 '26 21:04 ravitheja4531-cell

Hey @Asquator can you please look into the PR

ravitheja4531-cell avatar Apr 13 '26 21:04 ravitheja4531-cell

Addressed all review feedback:

Changed Optional[bool] → bool | None on collect and _receive_metrics (per @herin049) Removed Optional from imports entirely Fixed force_flush short-circuit: exporter.force_flush is now skipped if super().force_flush fails (per @Asquator) Added 4 unit tests covering success, failure, short-circuit, and detach always running in finally

Ready for re-review. Thanks!

ravitheja4531-cell avatar Apr 17 '26 22:04 ravitheja4531-cell