fix: respect timeout_millis in BatchProcessor.force_flush (#4568) by chimchim89 · Pull Request #4982 · open-telemetry/opentelemetry-python

Description

force_flush in BatchProcessor accepted a timeout_millis parameter but completely ignored it, blocking until all telemetry was exported regardless of the timeout passed by the caller.

The fix has two parts:

  1. _export() now accepts a flush_should_end parameter (an absolute time.time() deadline). Before each batch export, it
    checks whether the deadline has been reached and returns False early if so. Returns True when all batches are exported
    normally.

  2. force_flush() now computes a deadline from timeout_millis and passes it to _export(), then propagates the result back to
    the caller.

Note: the timeout is checked between batches, not during a single exporter.export() call. Passing the timeout into exporter.export() itself is a separate issue tracked in #4555.

Fixes #4568

Type of change

  • Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

Three new unit tests were added to opentelemetry-sdk/tests/shared_internal/test_batch_processor.py. Each test runs for both BatchLogRecordProcessor and BatchSpanProcessor via the existing @pytest.mark.parametrize decorator (6 test runs total):

  • test_force_flush_returns_true_when_all_exported — verifies that force_flush returns True when all telemetry is exported
    within the timeout.
  • test_force_flush_returns_false_when_timeout_exceeded — verifies that force_flush returns False when the deadline is
    exceeded before the queue is fully drained. Uses a slow exporter (time.sleep(0.2)) with a 100ms timeout to reliably trigger the
    timeout between batches.
  • test_force_flush_returns_false_when_shutdown — verifies that force_flush returns False immediately when the processor is
    already shut down and nothing is exported.

Ran new tests only:

pytest opentelemetry-sdk/tests/shared_internal/test_batch_processor.py -k force_flush -v

Ran full test file to verify no regressions:

pytest opentelemetry-sdk/tests/shared_internal/test_batch_processor.py -v

Ran ruff linter to verify style:

ruff check opentelemetry-sdk --fix

Ran tox to verify full lint and type check pipeline:

Does This PR Require a Contrib Repo Change?

  • No.

Checklist:

  • Followed the style guidelines of this project
  • Changelogs have been updated
  • Unit tests have been added
  • Documentation has been updated