Skip to content

fix: ADDON-91243 change telemetry flush to async - #467

Merged
wtobis-splunk merged 10 commits into
developfrom
fix/ADDON-91243-change-telemetry-flush-to-async
Oct 21, 2026
Merged

wtobis-splunk merged 10 commits into
developfrom
fix/ADDON-91243-change-telemetry-flush-to-async

Conversation

@wtobis-splunk

Copy link
Copy Markdown
Contributor

Why

StanzaObservabilityRecorder previously called OpenTelemetry force_flush() on the modular input’s thread. A slow or unavailable OTLP collector could therefore delay TA processing whenever the recorder exited its with block.

What changed

  • Schedule explicit metric flushes on one daemon worker per observability service. Repeated requests are coalesced.
  • Replace OpenTelemetry’s synchronous exit hook for solnlib-created providers with one process-wide shutdown handler and a shared five-second grace period.
  • Drain a pending flush before shutdown, including when periodic export is disabled. Periodic export remains unchanged.

Compatibility and trade-offs

The public flush() signatures are unchanged, but returning now means the export was scheduled, not completed. timeout_millis limits the background attempt; it is not a caller-side wait. The last metrics may be lost if the exit grace period expires.

Fork handling remains limited: the child gets a new worker, but an OTel provider inherited during an in-flight export may retain a locked reader. Recreating the provider after fork() is outside this PR.

Testing

  • 173 observability tests passed on Python 3.9.19.
  • Tests cover blocked exports, request coalescing, the shared exit deadline, pending flush at shutdown, and a fork smoke test.
  • Python 3.13 runtime validation remains for CI.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T23:10:53.121865Z 9b3a2a5 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Comment thread solnlib/observability.py Resolved
Comment thread solnlib/observability.py Resolved
Comment thread solnlib/_observability_flush.py Resolved
Comment thread solnlib/_observability_flush.py Resolved
Comment thread solnlib/_observability_flush.py Resolved
Comment thread solnlib/observability.py Resolved
Comment thread solnlib/observability.py
return
try:
self._provider.force_flush(timeout_millis=int(timeout_millis))
self._flush_controller.request_flush(timeout_millis)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flush() no longer delivers metrics from multiprocessing workers on Python 3.9

flush() now only queues the export on a daemon thread and relies on the atexit handler to drain it. On Python 3.9 (the Splunk 9.x runtime), a multiprocessing child started with fork (the Linux default) exits via os._exit() without running atexit. The worker is killed before it exports. The same applies to any explicit os._exit() after flush().

This is a regression: on develop, flush() / StanzaObservabilityRecorder.__exit__ exported synchronously, so these metrics were delivered. Now they are silently dropped, with nothing in the logs.

Repro (Python 3.9): prints EXPORTED on develop, nothing on this branch
import logging, multiprocessing as mp, time
from opentelemetry.sdk.metrics.export import MetricExporter, MetricExportResult
from solnlib.observability import ObservabilityService

ObservabilityService._create_otlp_exporter = lambda self: None

class SlowExporter(MetricExporter):  # ~200 ms, like a real gRPC round-trip
    def export(self, metrics_data, timeout_millis=10_000, **kwargs):
        time.sleep(0.2)
        print("EXPORTED", flush=True)
        return MetricExportResult.SUCCESS
    def shutdown(self, timeout_millis=30_000, **kwargs): pass
    def force_flush(self, timeout_millis=10_000): return True

def worker():
    svc = ObservabilityService("t", logging.getLogger("t"), ta_name="ta",
                               ta_version="1", extra_exporters=[SlowExporter()])
    svc.event_count_counter.add(5)
    svc.flush()  # same call StanzaObservabilityRecorder.__exit__ makes

if __name__ == "__main__":
    mp.set_start_method("fork")
    p = mp.Process(target=worker)
    p.start()
    p.join()

Suggestion: keep a synchronous option for callers that need delivery, e.g. flush(wait=True) or flush_sync(timeout_millis), which blocks until the worker finishes that flush. Also document that the default async flush() gives no delivery guarantee under os._exit() or in forked multiprocessing workers.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed — I reproduced the loss of pending metrics when a forked multiprocessing worker exits before the background export completes.

We assess the operational risk as low for the current change: the demonstrated impact is limited to pending telemetry at worker exit. Short-lived workers can lose their entire batch, so this limitation should be documented.

We propose addressing multiprocessing shutdown support in a separate Story: ADDON-91546. It covers bounded shutdown waiting and regression tests on Python 3.9 and 3.13.

controller.join_until(deadline)

def _after_fork_child(self) -> None:
self._lock = threading.Lock()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_registered survives fork, so services created in a child never get the exit handler

_after_fork_child resets the lock and the workers, but not _registered. On newer Pythons (verified on 3.13), multiprocessing calls atexit._clear() in a forked child. The inherited _shutdown_all registration is gone, but _registered is still True. Any ObservabilityService created in the child then skips atexit.register(...), is never shut down, and its pending metrics are lost.

This happens whenever the parent created a service before forking, e.g. when the parent records its own metrics.

Repro (Python 3.13): develop prints EXPORTED twice, this branch prints nothing
import logging, multiprocessing as mp, time
from opentelemetry.sdk.metrics.export import MetricExporter, MetricExportResult
from solnlib.observability import ObservabilityService

ObservabilityService._create_otlp_exporter = lambda self: None

class SlowExporter(MetricExporter):
    def export(self, metrics_data, timeout_millis=10_000, **kwargs):
        time.sleep(0.2)
        print("EXPORTED", flush=True)
        return MetricExportResult.SUCCESS
    def shutdown(self, timeout_millis=30_000, **kwargs): pass
    def force_flush(self, timeout_millis=10_000): return True

def worker():
    svc = ObservabilityService("child", logging.getLogger("t"), ta_name="ta",
                               ta_version="1", extra_exporters=[SlowExporter()])
    svc.event_count_counter.add(5)
    svc.flush()

if __name__ == "__main__":
    mp.set_start_method("fork")
    ObservabilityService("parent", logging.getLogger("t"), ta_name="ta", ta_version="1")
    p = mp.Process(target=worker)
    p.start()
    p.join()

Fix:

Suggested change
self._lock = threading.Lock()
self._lock = threading.Lock()
self._registered = False

Re-registering is also safe after a plain os.fork(), where atexit is inherited: the second shutdown_all() call returns early on _closed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed — _registered can remain True after multiprocessing clears the inherited atexit handlers. Resetting it fixes registration when a new service is created in the child, but children using only an inherited service also need handling.

We assess the operational risk as low, with the observed impact limited to pending telemetry during process shutdown. We propose handling this together with the Python 3.9 shutdown issue in ADDON-91546, so the follow-up covers both inherited and newly created services.

@wtobis-splunk
wtobis-splunk merged commit 3e538df into develop Oct 21, 2026
14 checks passed
@wtobis-splunk
wtobis-splunk deleted the fix/ADDON-91243-change-telemetry-flush-to-async branch October 21, 2026 12:51
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 21, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants