From bba3c545e7979c243a62a64144c6e72788d43501 Mon Sep 17 00:00:00 2001 From: Anurag Singh Date: Sun, 29 Nov 2026 19:34:42 +0530 Subject: [PATCH] [Python] Honor ProfilingOptions in BundleBasedDirectRunner Build the profiler factory from ProfilingOptions in BundleBasedDirectRunner and pass it to the executor. The profiler wraps the executor worker thread, since cProfile only profiles the calling thread and the bundle work runs there. --- CHANGES.md | 1 + .../runners/direct/direct_runner.py | 6 +++- .../runners/direct/direct_runner_test.py | 35 +++++++++++++++++++ .../apache_beam/runners/direct/executor.py | 31 +++++++++++++--- 4 files changed, 67 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 3fbc0a0b184a..63c47b5ed0b3 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -115,6 +115,7 @@ * (Go) Added pass-through registration for fixed and variable length string and bytes logical types ([#39684](https://github.com/apache/beam/issues/39684)). * (Java) Added `LogElements.stdout()`, which prints elements with `System.out.println` instead of logging them through SLF4J, so they still show up when no SLF4J provider is on the classpath ([#41573](https://github.com/apache/beam/pull/41573)). * (Python) `OnnxModelHandlerNumpy` and the XGBoost model handlers now support model updates through `model_metadata_pcoll`, for example with `WatchFilePattern`. ONNX predictions now also set `model_id` ([#41384](https://github.com/apache/beam/issues/41384)). +* (Python) The DirectRunner's bundle-based runner now honors `ProfilingOptions` (`--profile_cpu`, `--profile_memory`, `--profile_location`, `--profile_sample_rate`), writing profiles for the work executed on its worker thread ([#18011](https://github.com/apache/beam/issues/18011)). ### Performance diff --git a/sdks/python/apache_beam/runners/direct/direct_runner.py b/sdks/python/apache_beam/runners/direct/direct_runner.py index 443dbd63063d..aa74d759572f 100644 --- a/sdks/python/apache_beam/runners/direct/direct_runner.py +++ b/sdks/python/apache_beam/runners/direct/direct_runner.py @@ -34,6 +34,7 @@ from apache_beam import typehints from apache_beam.internal.util import ArgumentPlaceholder from apache_beam.options.pipeline_options import DirectOptions +from apache_beam.options.pipeline_options import ProfilingOptions from apache_beam.options.pipeline_options import StandardOptions from apache_beam.options.value_provider import RuntimeValueProvider from apache_beam.pvalue import PCollection @@ -52,6 +53,7 @@ from apache_beam.transforms.timeutil import TimeDomain from apache_beam.typehints import trivial_inference from apache_beam.utils.interactive_utils import is_in_ipython +from apache_beam.utils.profiler import Profile __all__ = ['BundleBasedDirectRunner', 'DirectRunner', 'SwitchingDirectRunner'] @@ -610,7 +612,9 @@ def visit_transform(self, applied_ptransform): executor = Executor( self.consumer_tracking_visitor.value_to_consumers, TransformEvaluatorRegistry(evaluation_context), - evaluation_context) + evaluation_context, + profiler_factory=Profile.factory_from_options( + options.view_as(ProfilingOptions))) # DirectRunner does not support injecting # PipelineOptions values at runtime RuntimeValueProvider.set_runtime_options({}) diff --git a/sdks/python/apache_beam/runners/direct/direct_runner_test.py b/sdks/python/apache_beam/runners/direct/direct_runner_test.py index 008a1bd47215..90b8da6fae59 100644 --- a/sdks/python/apache_beam/runners/direct/direct_runner_test.py +++ b/sdks/python/apache_beam/runners/direct/direct_runner_test.py @@ -17,6 +17,9 @@ # pytype: skip-file +import os +import pstats +import tempfile import threading import unittest from collections import defaultdict @@ -31,10 +34,12 @@ from apache_beam.metrics.metric import Metrics from apache_beam.metrics.metric import MetricsFilter from apache_beam.metrics.metricbase import MetricName +from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.pipeline import Pipeline from apache_beam.runners import DirectRunner from apache_beam.runners import TestDirectRunner from apache_beam.runners import create_runner +from apache_beam.runners.direct.direct_runner import BundleBasedDirectRunner from apache_beam.runners.direct.evaluation_context import _ExecutionContext from apache_beam.runners.direct.transform_evaluator import _GroupByKeyOnlyEvaluator from apache_beam.runners.direct.transform_evaluator import _TransformEvaluator @@ -154,6 +159,36 @@ def test_create_runner(self): isinstance(create_runner('TestDirectRunner'), TestDirectRunner)) +class BundleBasedDirectRunnerProfilingTest(unittest.TestCase): + def _run_pipeline(self, options): + with beam.Pipeline(runner=BundleBasedDirectRunner(), + options=options) as pipeline: + _ = pipeline | beam.Create([1, 2, 3]) | beam.Map(lambda x: x + 1) + + def test_writes_profile_when_profiling_enabled(self): + with tempfile.TemporaryDirectory() as profile_location: + options = PipelineOptions( + ['--profile_cpu', '--profile_location=%s' % profile_location]) + self._run_pipeline(options) + + profile_files = [ + os.path.join(root, name) + for root, _, names in os.walk(profile_location) for name in names + ] + cpu_profiles = [path for path in profile_files if 'cpu_profile' in path] + self.assertTrue( + cpu_profiles, + 'Expected a CPU profile to be written, got: %s' % profile_files) + self.assertGreater(len(pstats.Stats(cpu_profiles[0]).stats), 0) + + def test_writes_no_profile_when_profiling_disabled(self): + with tempfile.TemporaryDirectory() as profile_location: + options = PipelineOptions(['--profile_location=%s' % profile_location]) + self._run_pipeline(options) + + self.assertEqual([], os.listdir(profile_location)) + + class BundleBasedRunnerTest(unittest.TestCase): def test_type_hints(self): with test_pipeline.TestPipeline(runner='BundleBasedDirectRunner') as p: diff --git a/sdks/python/apache_beam/runners/direct/executor.py b/sdks/python/apache_beam/runners/direct/executor.py index 6bc2b0e4c3f1..7b3497d385dc 100644 --- a/sdks/python/apache_beam/runners/direct/executor.py +++ b/sdks/python/apache_beam/runners/direct/executor.py @@ -20,6 +20,7 @@ # pytype: skip-file import collections +import contextlib import itertools import logging import queue @@ -27,6 +28,7 @@ import traceback from typing import TYPE_CHECKING from typing import Any +from typing import Callable from typing import Optional from weakref import WeakValueDictionary @@ -40,6 +42,7 @@ from apache_beam.runners.direct.bundle_factory import _Bundle from apache_beam.runners.direct.evaluation_context import EvaluationContext from apache_beam.runners.direct.transform_evaluator import TransformEvaluatorRegistry + from apache_beam.utils.profiler import Profile _LOGGER = logging.getLogger(__name__) @@ -61,10 +64,14 @@ class _ExecutorServiceWorker(threading.Thread): TIMEOUT = 5 def __init__( - self, queue: 'queue.Queue[_ExecutorService.CallableTask]', index): + self, + queue: 'queue.Queue[_ExecutorService.CallableTask]', + index, + profiler_factory: Optional[Callable[..., 'Profile']] = None): super().__init__() self.queue = queue self._index = index + self._profiler_factory = profiler_factory self._default_name = 'ExecutorServiceWorker-' + str(index) self._update_name() self.shutdown_requested = False @@ -91,6 +98,14 @@ def _get_task_or_none(self) -> Optional['_ExecutorService.CallableTask']: return None def run(self): + profiler = None + if self._profiler_factory: + profiler = self._profiler_factory( + 'direct-worker-%d' % self._index, time_prefix='') + with profiler if profiler else contextlib.nullcontext(): + self._run_tasks() + + def _run_tasks(self): state_sampler = statesampler.StateSampler('', counters.CounterFactory()) statesampler.set_current_tracker(state_sampler) while not self.shutdown_requested: @@ -107,10 +122,14 @@ def run(self): def shutdown(self): self.shutdown_requested = True - def __init__(self, num_workers): + def __init__( + self, + num_workers, + profiler_factory: Optional[Callable[..., 'Profile']] = None): self.queue: queue.Queue[_ExecutorService.CallableTask] = queue.Queue() self.workers = [ - _ExecutorService._ExecutorServiceWorker(self.queue, i) + _ExecutorService._ExecutorServiceWorker( + self.queue, i, profiler_factory=profiler_factory) for i in range(num_workers) ] self.shutdown_requested = False @@ -427,9 +446,11 @@ def __init__( self, value_to_consumers, transform_evaluator_registry, - evaluation_context: 'EvaluationContext'): + evaluation_context: 'EvaluationContext', + profiler_factory: Optional[Callable[..., 'Profile']] = None): self.executor_service = _ExecutorService( - _ExecutorServiceParallelExecutor.NUM_WORKERS) + _ExecutorServiceParallelExecutor.NUM_WORKERS, + profiler_factory=profiler_factory) self.transform_executor_services = _TransformExecutorServices( self.executor_service) self.value_to_consumers = value_to_consumers