From 3a9417db13c9274ca6c0385b0b037d379547cb41 Mon Sep 17 00:00:00 2001 From: Aaditya Pratap Date: Sun, 22 Nov 2026 15:34:52 +0530 Subject: [PATCH] fix(logging): isolate per-run log handlers and prevent root logger pollution (#295) - Move OpenEvolve logging from the global root logger to the 'openevolve' package logger with propagate=False, avoiding host application namespace pollution. - Add current_run_id ContextVar and RunIsolationFilter to ensure handlers only emit records matching their active OpenEvolve run context during concurrent or sequential execution. - Prevent LoggerPrefixFilter from stacking prefixes when records pass through multiple handlers with different prefixes. - Implement _cleanup_logging(), close(), and __del__() to detach handlers and close file descriptors on completion or garbage collection. - Add comprehensive unit and regression tests in tests/test_parallel_logging_isolation.py. --- openevolve/cli.py | 4 +- openevolve/controller.py | 104 +++++++- openevolve/utils/logging_utils.py | 118 ++++++++- tests/test_parallel_logging_isolation.py | 322 +++++++++++++++++++++++ 4 files changed, 529 insertions(+), 19 deletions(-) create mode 100644 tests/test_parallel_logging_isolation.py diff --git a/openevolve/cli.py b/openevolve/cli.py index 26d5275be..431f9781d 100644 --- a/openevolve/cli.py +++ b/openevolve/cli.py @@ -186,7 +186,9 @@ async def main_async() -> int: # Override log level if specified if args.log_level: - logging.getLogger().setLevel(getattr(logging, args.log_level)) + log_level = getattr(logging, args.log_level) + logging.getLogger().setLevel(log_level) + logging.getLogger("openevolve").setLevel(log_level) # Run evolution best_program = await openevolve.run( diff --git a/openevolve/controller.py b/openevolve/controller.py index 5db6cf7e1..8c306f7b9 100644 --- a/openevolve/controller.py +++ b/openevolve/controller.py @@ -23,7 +23,11 @@ from openevolve.selection import IslandSelector from openevolve.utils.code_utils import extract_code_language from openevolve.utils.format_utils import format_improvement_safe, format_metrics_safe -from openevolve.utils.logging_utils import LoggerPrefixFilter +from openevolve.utils.logging_utils import ( + LoggerPrefixFilter, + RunIsolationFilter, + current_run_id, +) logger = logging.getLogger(__name__) @@ -69,8 +73,17 @@ def __init__( ) os.makedirs(self.output_dir, exist_ok=True) - # Set up logging - self._setup_logging() + # Generate unique run ID to isolate log handlers for concurrent or sequential runs (#295) + self.run_id = uuid.uuid4().hex[:8] + self._log_handlers: List[logging.Handler] = [] + self._log_file: Optional[str] = None + + # Set up logging within this run's context so startup logs are captured by this run + token = current_run_id.set(self.run_id) + try: + self._setup_logging() + finally: + current_run_id.reset(token) # Manual mode queue lives in /manual_tasks_queue self._setup_manual_mode_queue() @@ -201,13 +214,25 @@ def __init__( self.parallel_controller = None def _setup_logging(self) -> None: - """Set up logging""" + """Set up per-run logging attached to the 'openevolve' package logger. + + Attaching handlers to the 'openevolve' package logger with propagate=False + rather than the global root logger prevents polluting the host application's + logging namespace. A RunIsolationFilter ensures that each handler only + processes log records generated within this instance's execution context, + preventing duplicate console output and cross-written log files when multiple + OpenEvolve instances run in parallel (GitHub issue #295). + """ log_dir = self.config.log_dir or os.path.join(self.output_dir, "logs") os.makedirs(log_dir, exist_ok=True) - # Set up root logger - root_logger = logging.getLogger() - root_logger.setLevel(getattr(logging, self.config.log_level)) + # Target the 'openevolve' package logger rather than the root logger (#295) + pkg_logger = logging.getLogger("openevolve") + pkg_logger.setLevel(getattr(logging, self.config.log_level)) + pkg_logger.propagate = False + + # Per-run isolation filter matching this controller instance's run_id + run_filter = RunIsolationFilter(self.run_id) # Optional prefix for all logger names (issue #290): rewriting # record.name at the handler level means every downstream module @@ -218,13 +243,16 @@ def _setup_logging(self) -> None: # Add file handler log_file = os.path.join(log_dir, f"openevolve_{time.strftime('%Y%m%d_%H%M%S')}.log") + self._log_file = log_file file_handler = logging.FileHandler(log_file) file_handler.setFormatter( logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") ) + file_handler.addFilter(run_filter) if prefix_filter is not None: file_handler.addFilter(prefix_filter) - root_logger.addHandler(file_handler) + pkg_logger.addHandler(file_handler) + self._log_handlers.append(file_handler) # Add console handler console_handler = logging.StreamHandler() @@ -235,10 +263,43 @@ def _setup_logging(self) -> None: console_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" console_handler.addFilter(prefix_filter) console_handler.setFormatter(logging.Formatter(console_format)) - root_logger.addHandler(console_handler) + console_handler.addFilter(run_filter) + pkg_logger.addHandler(console_handler) + self._log_handlers.append(console_handler) logger.info(f"Logging to {log_file}") + def _cleanup_logging(self) -> None: + """Remove and close all logging handlers registered for this instance. + + Detaches handlers from the 'openevolve' package logger and closes their + underlying file streams, releasing resources and avoiding file locking contention (#295). + """ + pkg_logger = logging.getLogger("openevolve") + for handler in list(getattr(self, "_log_handlers", [])): + try: + pkg_logger.removeHandler(handler) + handler.close() + except Exception: + pass + self._log_handlers = [] + + def close(self) -> None: + """Release resources including evolution tracer and logging handlers.""" + if hasattr(self, "evolution_tracer") and self.evolution_tracer: + try: + self.evolution_tracer.close() + except Exception: + pass + self._cleanup_logging() + + def __del__(self) -> None: + """Ensure logging handlers are closed if instance is garbage collected.""" + try: + self._cleanup_logging() + except Exception: + pass + def _setup_manual_mode_queue(self) -> None: """ Set up manual task queue directory if llm.manual_mode is enabled @@ -325,6 +386,31 @@ async def run( Raises: EvolutionFailedError: If iterations ran but none produced a candidate program """ + # Ensure run_id exists even if instance was created without __init__ (e.g. in tests) + if not hasattr(self, "run_id") or not self.run_id: + self.run_id = uuid.uuid4().hex[:8] + if not hasattr(self, "_log_handlers"): + self._log_handlers = [] + + # If handlers were cleaned up or never initialized, set up logging for this run + if not self._log_handlers: + self._setup_logging() + + # Activate this instance's run ID in context so downstream logs are routed to our handlers + token = current_run_id.set(self.run_id) + try: + return await self._run_evolution(iterations, target_score, checkpoint_path) + finally: + current_run_id.reset(token) + self._cleanup_logging() + + async def _run_evolution( + self, + iterations: Optional[int] = None, + target_score: Optional[float] = None, + checkpoint_path: Optional[str] = None, + ) -> Optional[Program]: + """Internal evolution loop execution under active run context.""" max_iterations = self.config.max_iterations if iterations is None else iterations # Determine starting iteration start_iteration = 0 diff --git a/openevolve/utils/logging_utils.py b/openevolve/utils/logging_utils.py index e9d885cf4..48b349ba0 100644 --- a/openevolve/utils/logging_utils.py +++ b/openevolve/utils/logging_utils.py @@ -1,14 +1,93 @@ """Logging helpers shared across OpenEvolve. -Provides :class:`LoggerPrefixFilter`, a handler-level filter that rewrites -``record.name`` so every downstream module logger appears under a common -prefix. This lets users tell apart log output coming from multiple concurrent -``OpenEvolve`` runs (GitHub issue #290). +Provides: +- :data:`current_run_id`: Context variable tracking the currently active OpenEvolve run ID. +- :class:`RunIsolationFilter`: A handler-level filter that isolates log messages to their + respective run context, preventing cross-writing and duplicate log emissions when multiple + runs execute in parallel within the same Python process (GitHub issue #295). +- :class:`LoggerPrefixFilter`: A handler-level filter that rewrites ``record.name`` so every + downstream module logger appears under a common prefix (GitHub issue #290). """ +import contextvars import logging from typing import Optional +# Context variable holding the unique run ID for the currently executing OpenEvolve instance. +# In asynchronous (asyncio) or threaded workflows, context variables are copied per-task, +# allowing multiple concurrent runs in the same process to maintain their own isolated run ID. +current_run_id: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar( + "openevolve_current_run_id", default=None +) + + +def get_current_run_id() -> Optional[str]: + """Retrieve the currently active OpenEvolve run ID, or None if outside a run context.""" + return current_run_id.get() + + +def set_current_run_id(run_id: Optional[str]) -> contextvars.Token: + """Set the active OpenEvolve run ID for the current execution context. + + Args: + run_id: Unique string identifier for the run, or None to clear. + + Returns: + A contextvars.Token that can be passed to reset_current_run_id. + """ + return current_run_id.set(run_id) + + +def reset_current_run_id(token: contextvars.Token) -> None: + """Reset the active OpenEvolve run ID using the provided context token. + + Args: + token: The token returned by a prior set_current_run_id call. + """ + current_run_id.reset(token) + + +class RunIsolationFilter(logging.Filter): + """Filter log records so handlers only process records from their matching run. + + When multiple OpenEvolve instances run concurrently in the same process + (e.g., parallel runs in the same event loop or thread pool), they attach + handlers to the shared ``openevolve`` package logger. Without filtering, + each instance's handlers would receive log records from all other runs, + leading to duplicated console output and cross-written log files (GitHub issue #295). + + This filter ensures that a handler only emits records produced while its + associated run context is active. If no run context is active (e.g., + standalone logging during setup or in test suites outside ``run()``), + the record is permitted through so information is not lost. + """ + + def __init__(self, run_id: str) -> None: + """Initialize the filter for a specific run ID. + + Args: + run_id: The unique identifier of the OpenEvolve run instance. + """ + super().__init__() + self.run_id = run_id + + def filter(self, record: logging.LogRecord) -> bool: + """Filter log records by matching against the active run context. + + Args: + record: The log record to inspect. + + Returns: + True if the record belongs to this run or if no active run context is set; + False if another run context is currently active. + """ + active_run = current_run_id.get() + # If an active run is configured in context, only allow records matching this run ID + if active_run is not None: + return active_run == self.run_id + # If no active run is set (e.g., un-scoped calls or direct utility usage), allow through + return True + class LoggerPrefixFilter(logging.Filter): """Rewrite ``record.name`` to live under a configured prefix. @@ -19,16 +98,37 @@ class LoggerPrefixFilter(logging.Filter): then show the prefixed name, which makes concurrent runs distinguishable and greppable in shared log output. - The filter is idempotent: names that already carry the prefix are left - untouched, so a record flowing through several handlers that share the - same filter instance is only prefixed once. + The filter is idempotent and avoids prefix stacking across multiple + handlers: the original un-prefixed name is saved so that applying filters + with different prefixes does not create nested prefixes like + ``run2.run1.openevolve.controller``. """ def __init__(self, prefix: Optional[str] = None) -> None: + """Initialize the prefix filter. + + Args: + prefix: Optional prefix string to prepend to record logger names. + """ super().__init__() self.prefix = prefix or "" def filter(self, record: logging.LogRecord) -> bool: - if self.prefix and not record.name.startswith(self.prefix + "."): - record.name = f"{self.prefix}.{record.name}" + """Prepend prefix to record name without stacking multiple prefixes. + + Args: + record: The log record to format. + + Returns: + Always True (does not suppress records, only alters record.name). + """ + # Store original logger name so multiple handlers or filters do not stack prefixes + if not hasattr(record, "_openevolve_orig_name"): + record._openevolve_orig_name = record.name + + orig_name = record._openevolve_orig_name + if self.prefix: + record.name = f"{self.prefix}.{orig_name}" + else: + record.name = orig_name return True diff --git a/tests/test_parallel_logging_isolation.py b/tests/test_parallel_logging_isolation.py new file mode 100644 index 000000000..81e4985c6 --- /dev/null +++ b/tests/test_parallel_logging_isolation.py @@ -0,0 +1,322 @@ +""" +Regression and unit tests for concurrent OpenEvolve logging isolation (GitHub issue #295). + +Historically, multiple OpenEvolve instances attached their FileHandler and StreamHandler +to the root logger (logging.getLogger()) with propagate enabled and no run isolation filter. +As a result: +1. All parallel or sequential runs cross-wrote into each other's log files. +2. Console output was duplicated for every instantiated controller. +3. The process-wide root logger was polluted with OpenEvolve handlers, affecting host applications. +4. Handlers and open file descriptors leaked because they were never detached or closed. + +These tests verify that: +- Logging is attached to the 'openevolve' package logger with propagate=False. +- The root logger remains untouched. +- Handlers use RunIsolationFilter to only process records from their matching run context. +- Concurrent asyncio runs do not cross-write log files or duplicate console output. +- Handlers are cleanly detached and closed when run() completes or close() is called. +""" + +import asyncio +import io +import logging +import os +import shutil +import tempfile +import unittest +from unittest.mock import patch + +from openevolve.config import Config +from openevolve.controller import OpenEvolve +from openevolve.utils.logging_utils import ( + LoggerPrefixFilter, + RunIsolationFilter, + current_run_id, + get_current_run_id, + reset_current_run_id, + set_current_run_id, +) + + +class TestRunIsolationFilterUnit(unittest.TestCase): + """Unit tests for RunIsolationFilter and contextvar helpers.""" + + def setUp(self): + self.orig_token = current_run_id.set(None) + + def tearDown(self): + current_run_id.reset(self.orig_token) + + def test_filter_matches_active_run_id(self): + """Filter should accept records when the active run context matches self.run_id.""" + filt = RunIsolationFilter("run-abc") + token = set_current_run_id("run-abc") + try: + record = logging.LogRecord( + "openevolve.controller", logging.INFO, "path", 1, "msg", (), None + ) + self.assertTrue(filt.filter(record)) + finally: + reset_current_run_id(token) + + def test_filter_rejects_different_run_id(self): + """Filter should reject records when the active run context belongs to another run.""" + filt = RunIsolationFilter("run-abc") + token = set_current_run_id("run-xyz") + try: + record = logging.LogRecord( + "openevolve.controller", logging.INFO, "path", 1, "msg", (), None + ) + self.assertFalse(filt.filter(record)) + finally: + reset_current_run_id(token) + + def test_filter_allows_unscoped_records(self): + """Filter should allow records when no active run context is set (e.g. general utility logs).""" + filt = RunIsolationFilter("run-abc") + set_current_run_id(None) + record = logging.LogRecord( + "openevolve.controller", logging.INFO, "path", 1, "msg", (), None + ) + self.assertTrue(filt.filter(record)) + + def test_get_and_set_current_run_id_helpers(self): + """Verify helper functions get_current_run_id, set_current_run_id, and reset_current_run_id.""" + self.assertIsNone(get_current_run_id()) + tok = set_current_run_id("test-id-123") + self.assertEqual(get_current_run_id(), "test-id-123") + reset_current_run_id(tok) + self.assertIsNone(get_current_run_id()) + + +class TestParallelLoggingIsolation(unittest.TestCase): + """Integration and regression tests for per-run logging isolation.""" + + def setUp(self): + self.tmpdir = tempfile.mkdtemp(prefix="oe295_") + self.saved_root_handlers = list(logging.getLogger().handlers) + self.pkg_logger = logging.getLogger("openevolve") + self.saved_pkg_handlers = list(self.pkg_logger.handlers) + self.saved_pkg_level = self.pkg_logger.level + self.saved_pkg_propagate = self.pkg_logger.propagate + + def tearDown(self): + # Restore root logger handlers + logging.getLogger().handlers = self.saved_root_handlers + + # Clean up any residual package logger handlers + for handler in list(self.pkg_logger.handlers): + if handler not in self.saved_pkg_handlers: + self.pkg_logger.removeHandler(handler) + try: + handler.close() + except Exception: + pass + self.pkg_logger.setLevel(self.saved_pkg_level) + self.pkg_logger.propagate = self.saved_pkg_propagate + + shutil.rmtree(self.tmpdir, ignore_errors=True) + + def _write_dummy_files(self, dirname: str): + work_dir = os.path.join(self.tmpdir, dirname) + os.makedirs(work_dir, exist_ok=True) + program_path = os.path.join(work_dir, "initial.py") + with open(program_path, "w", encoding="utf-8") as f: + f.write("def run():\n return 42\n") + eval_path = os.path.join(work_dir, "eval.py") + with open(eval_path, "w", encoding="utf-8") as f: + f.write('def evaluate(p):\n return {"combined_score": 1.0}\n') + return program_path, eval_path, work_dir + + def _create_controller(self, name: str, **config_overrides) -> OpenEvolve: + program_path, eval_path, work_dir = self._write_dummy_files(name) + config = Config() + config.random_seed = None + config.log_dir = os.path.join(work_dir, "logs") + for k, v in config_overrides.items(): + setattr(config, k, v) + + with ( + patch("openevolve.controller.LLMEnsemble"), + patch("openevolve.controller.Evaluator"), + ): + controller = OpenEvolve( + initial_program_path=program_path, + evaluation_file=eval_path, + config=config, + output_dir=os.path.join(work_dir, "output"), + ) + return controller + + def _read_single_log(self, controller: OpenEvolve) -> str: + log_dir = controller.config.log_dir + log_files = [os.path.join(log_dir, f) for f in os.listdir(log_dir) if f.endswith(".log")] + self.assertEqual(len(log_files), 1, f"Expected 1 log file in {log_dir}, found {log_files}") + with open(log_files[0], "r", encoding="utf-8") as f: + return f.read() + + def test_root_logger_is_not_polluted(self): + """Constructing OpenEvolve must NOT attach handlers to the root logger (#295).""" + root_count_before = len(logging.getLogger().handlers) + controller = self._create_controller("root_test") + try: + root_count_after = len(logging.getLogger().handlers) + self.assertEqual( + root_count_after, + root_count_before, + "Root logger was polluted by OpenEvolve constructor handlers!", + ) + self.assertFalse( + self.pkg_logger.propagate, + "openevolve package logger must have propagate=False", + ) + finally: + controller.close() + + def test_concurrent_runs_do_not_cross_write_logs(self): + """Two concurrent OpenEvolve runs must only log to their respective log files.""" + c1 = self._create_controller("run_1") + c2 = self._create_controller("run_2") + + try: + # Simulate concurrent execution of two runs using asyncio + logger = logging.getLogger("openevolve.controller") + + async def mock_run_1(): + token = set_current_run_id(c1.run_id) + try: + logger.info("RUN_1_EVENT_START") + await asyncio.sleep(0.02) + logger.info("RUN_1_EVENT_END") + finally: + reset_current_run_id(token) + + async def mock_run_2(): + token = set_current_run_id(c2.run_id) + try: + logger.info("RUN_2_EVENT_START") + await asyncio.sleep(0.01) + logger.info("RUN_2_EVENT_END") + finally: + reset_current_run_id(token) + + async def run_both(): + await asyncio.gather(mock_run_1(), mock_run_2()) + + asyncio.run(run_both()) + + # Verify contents of log file 1 + content1 = self._read_single_log(c1) + self.assertIn("RUN_1_EVENT_START", content1) + self.assertIn("RUN_1_EVENT_END", content1) + self.assertNotIn("RUN_2_EVENT_START", content1) + self.assertNotIn("RUN_2_EVENT_END", content1) + + # Verify contents of log file 2 + content2 = self._read_single_log(c2) + self.assertIn("RUN_2_EVENT_START", content2) + self.assertIn("RUN_2_EVENT_END", content2) + self.assertNotIn("RUN_1_EVENT_START", content2) + self.assertNotIn("RUN_1_EVENT_END", content2) + + finally: + c1.close() + c2.close() + + def test_console_output_is_not_duplicated_across_instances(self): + """StreamHandler must not emit duplicate lines when multiple controllers are active.""" + c1 = self._create_controller("c1") + c2 = self._create_controller("c2") + + try: + # Capture console emissions on the console handlers + output_stream = io.StringIO() + for handler in c1._log_handlers + c2._log_handlers: + if isinstance(handler, logging.StreamHandler) and not isinstance( + handler, logging.FileHandler + ): + handler.stream = output_stream + + logger = logging.getLogger("openevolve.controller") + + token = set_current_run_id(c1.run_id) + try: + logger.info("UNIQUE_C1_CONSOLE_MESSAGE") + finally: + reset_current_run_id(token) + + console_output = output_stream.getvalue() + # The message should appear exactly once, not twice + count = console_output.count("UNIQUE_C1_CONSOLE_MESSAGE") + self.assertEqual( + count, 1, f"Expected 1 console emission, got {count}: {console_output}" + ) + + finally: + c1.close() + c2.close() + + def test_cleanup_removes_and_closes_handlers(self): + """close() must detach handlers from the package logger and close file descriptors.""" + initial_handlers_count = len(self.pkg_logger.handlers) + c = self._create_controller("cleanup_test") + + self.assertGreater(len(self.pkg_logger.handlers), initial_handlers_count) + self.assertEqual(len(c._log_handlers), 2) # FileHandler + StreamHandler + + # Call close + c.close() + self.assertEqual(len(c._log_handlers), 0) + self.assertEqual(len(self.pkg_logger.handlers), initial_handlers_count) + + def test_run_lifecycle_manages_logging_context_and_cleanup(self): + """await controller.run() should set run context during execution and clean up handlers on completion.""" + c = self._create_controller("lifecycle_test") + + # Mock _run_evolution to record whether run context was active during execution + captured_run_id = None + + async def fake_run_evolution(*args, **kwargs): + nonlocal captured_run_id + captured_run_id = get_current_run_id() + logging.getLogger("openevolve.controller").info("LIFECYCLE_MESSAGE") + return None + + with patch.object(c, "_run_evolution", side_effect=fake_run_evolution): + # Run the controller + asyncio.run(c.run(iterations=1)) + + # ContextVar was correctly active during run + self.assertEqual(captured_run_id, c.run_id) + + # ContextVar was reset after run + self.assertIsNone(get_current_run_id()) + + # Handlers were cleanly detached after run + self.assertEqual(len(c._log_handlers), 0) + + def test_logger_prefix_does_not_stack(self): + """LoggerPrefixFilter must not stack prefixes when records pass through multiple handlers.""" + filt1 = LoggerPrefixFilter("RUN1") + filt2 = LoggerPrefixFilter("RUN2") + + record = logging.LogRecord( + name="openevolve.controller", + level=logging.INFO, + pathname="test.py", + lineno=10, + msg="test msg", + args=(), + exc_info=None, + ) + + filt1.filter(record) + self.assertEqual(record.name, "RUN1.openevolve.controller") + + filt2.filter(record) + self.assertEqual(record.name, "RUN2.openevolve.controller") + self.assertNotIn("RUN2.RUN1", record.name) + + +if __name__ == "__main__": + unittest.main()