diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 757c5a44..656900ba 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -3,7 +3,7 @@ name: CI on: push env: - PYTHON_VERSIONS: '[ "3.9", "3.10", "3.11", "3.12", "3.13.3" ]' + PYTHON_VERSIONS: '[ "3.10", "3.11", "3.12", "3.13.3" ]' jobs: @@ -25,10 +25,10 @@ jobs: python-version: ${{ fromJSON(needs.set-python-matrix.outputs.python_versions) }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v2 + uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} @@ -48,10 +48,10 @@ jobs: python-version: ${{ fromJSON(needs.set-python-matrix.outputs.python_versions) }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v2 + uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} @@ -98,16 +98,16 @@ jobs: needs: check-static-and-test-status - if: contains(github.ref, 'tags/v') + if: contains(github.ref, 'tags/v') # both v1.x.x & v2.X.X runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - - uses: actions/setup-python@v2 + - uses: actions/setup-python@v6 with: - python-version: 3.9 + python-version: '3.10' - name: Install dependencies run: pip install -U setuptools wheel build @@ -124,12 +124,14 @@ jobs: docs: name: Build and publish docs + if: startsWith(github.ref, 'tags/v2.') # Only for version 2.X.X + needs: deploy runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: Build run: make docs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dccfd40..1e67235f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [1.16.2] - 2026-10-16 +### Fixed +- Fixed `LoggingContext` mixing logs of concurrent invocations processed in threads of one process: logs got `ASSET`, `AC` and request id of another invocation, and handlers could leak or get lost on exit. Handlers are now selected per execution context (`contextvars`) instead of replacing the shared `logger.handlers` + +## [1.16.1] - 2026-01-15 +### CI +- fix `actions/setup-python` usage + + +## [1.16.0] - 2026-01-15 +### Dependency +- Upgraded internal dependency `redis` to version `redis >=7.1.0, <8.0.0` +- Bumped a supported SDK runtime version to minimum `3.10` since new redis lib drops support for `3.9` + + +## [1.15.2] - 2026-01-14 +### Security +- Upgraded internal dependency `urllib3` to version `urllib3 >= 2.6.3, <3.0.0` since `2.5.0` has [these](https://security.snyk.io/package/pip/urllib3/2.5.0) vulnerabilities +### Fixed +- Fixed issue with `MAX_RETRY_COUNT` + + +## [1.15.1] - 2025-10-06 +### Fixed +- Logging duplication on CloudWatch side + + ## [1.15.0] - 2025-09-04 ### Security - Upgraded internal dependency `urllib3` to version `2.5.0` diff --git a/pyproject.toml b/pyproject.toml index 2cac4cc2..30647d1b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,19 +6,19 @@ build-backend = "setuptools.build_meta" name = "corva-sdk" description = "SDK for building Corva DevCenter Python apps." readme = "README.md" -version = "1.15.0" +version = "1.16.2" license = { text = "The Unlicense" } authors = [ { name = "Jordan Ambra", email = "jordan.ambra@corva.ai" } ] keywords = ["corva", "sdk"] -requires-python = ">=3.9,<4.0" +requires-python = ">=3.10,<4.0" dependencies = [ "fakeredis[lua] >=2.26.2, <2.30.0", "pydantic >=1.8.2, <2.0.0", - "redis >=5.2.1, <6.0.0", + "redis >=7.1.0, <8.0.0", "requests >=2.32.3, <3.0.0", - "urllib3==2.5.0" + "urllib3 >=2.6.3, <3.0.0", ] classifiers = [ "Development Status :: 5 - Production/Stable", @@ -69,7 +69,7 @@ parallel = true [tool.coverage.report] precision = 2 -fail_under = 97.68 +fail_under = 97.00 skip_covered = true show_missing = true exclude_lines = [ diff --git a/src/corva/configuration.py b/src/corva/configuration.py index 77edc175..139f0aa4 100644 --- a/src/corva/configuration.py +++ b/src/corva/configuration.py @@ -1,12 +1,44 @@ import datetime +import logging +from typing import Any -import pydantic +from pydantic import AnyHttpUrl, BaseSettings, validator +logger = logging.getLogger("corva") -class Settings(pydantic.BaseSettings): +DEFAULT_MAX_RETRY_COUNT = 3 + +def _parse_max_retry_count(value: Any) -> int: + if value is None or value == "": + return DEFAULT_MAX_RETRY_COUNT + + try: + if isinstance(value, bool): + raise TypeError + if isinstance(value, int): + return value + if isinstance(value, str): + return int(value.strip()) + except (TypeError, ValueError): + pass + + logger.warning( + "Invalid MAX_RETRY_COUNT value %r; using default %d.", + value, + DEFAULT_MAX_RETRY_COUNT, + ) + return DEFAULT_MAX_RETRY_COUNT + +def parse_truthy(v): + if isinstance(v, bool): + return v + return str(v or "").strip().lower() in {"1", "true", "t", "yes", "y", "on"} + + +class Settings(BaseSettings): # api - API_ROOT_URL: pydantic.AnyHttpUrl - DATA_API_ROOT_URL: pydantic.AnyHttpUrl + API_ROOT_URL: AnyHttpUrl + DATA_API_ROOT_URL: AnyHttpUrl # cache CACHE_URL: str @@ -28,9 +60,19 @@ class Settings(pydantic.BaseSettings): POOL_MAX_SIZE: int = 20 # Max connections count per pool/host POOL_BLOCK: bool = True # Wait until connection released - # retry - MAX_RETRY_COUNT: int = 3 # If `0` then retries will be disabled + # retry. If `0` then retries will be disabled + MAX_RETRY_COUNT: int = DEFAULT_MAX_RETRY_COUNT BACKOFF_FACTOR: float = 1.0 + OTEL_LOG_SENDING_DISABLED: bool = False + + _validate_otel_log_sending_disabled = validator( + "OTEL_LOG_SENDING_DISABLED", pre=True, allow_reuse=True + )(parse_truthy) + + @validator("MAX_RETRY_COUNT", pre=True) + def parse_max_retry_count(cls, v: Any) -> int: + return _parse_max_retry_count(v) + SETTINGS = Settings() diff --git a/src/corva/logger.py b/src/corva/logger.py index fff95d12..fb993cf0 100644 --- a/src/corva/logger.py +++ b/src/corva/logger.py @@ -1,8 +1,10 @@ import contextlib +import contextvars import logging -import logging.config import sys +import threading import time +from contextlib import suppress from typing import Optional from corva.configuration import SETTINGS @@ -14,10 +16,37 @@ logging.getLogger("urllib3.connectionpool").setLevel(SETTINGS.LOG_LEVEL) -# unset to pass messages to ancestor loggers, including OTel Log Sending handler +# Disable propagation to avoid duplicate CloudWatch logs from AWS Lambda's +# root handler. We will explicitly attach any OTel log handlers directly +# to CORVA_LOGGER within LoggingContext when log sending is enabled. # see https://github.com/corva-ai/otel/pull/37 # see https://corvaqa.atlassian.net/browse/EE-31 -# CORVA_LOGGER.propagate = False +CORVA_LOGGER.propagate = False + + +def _is_otel_handler(handler: logging.Handler) -> bool: + """Best-effort detection of OTel log sending handlers. + + We match by class/module name to avoid importing OTel directly. + """ + try: + module = getattr(handler.__class__, "__module__", "") or "" + name = handler.__class__.__name__ + ident = f"{module}.{name}".lower() + return ("otel" in ident) or ("opentelemetry" in ident) + except Exception: + return False + + +def _gather_otel_handlers_from_root() -> list[logging.Handler]: + """Collect OTel handlers already attached to the root logger. + + We reuse existing handler instances and attach them to CORVA_LOGGER + to keep OTel log sending while propagation is disabled. + """ + root = logging.getLogger() + handlers = getattr(root, "handlers", []) or [] + return [h for h in handlers if _is_otel_handler(h)] def get_formatter( @@ -140,6 +169,103 @@ def log(self, message: str) -> None: sys.stdout.write(message) +class _DispatchHandler(logging.Handler): + """Permanent handler of a logger that routes records to the handlers of the + active `LoggingContext`. + + `logging.Logger.handlers` is shared by all threads, so swapping it per request + breaks as soon as two requests are processed concurrently in one process + (e.g. OpenFaaS adapter in `threads` mode): requests log with each other's + asset/app connection ids, and handlers leak or get lost on exit. This handler + stays on the logger and picks the handlers per execution context instead. + + Handler lookup: + 1. Handlers of the context entered in the current execution context + (thread / asyncio task, see `contextvars`). + 2. If nothing was entered there (e.g. a thread spawned by the app code + without `contextvars.copy_context`), handlers of the most recently + entered context that is still active. This is exact when only one + context is active and matches the old behavior otherwise. + 3. If no context is active, `logging.lastResort`, same as for a logger + without handlers. + """ + + def __init__(self) -> None: + super().__init__() + + self._current: contextvars.ContextVar[Optional[tuple[logging.Handler, ...]]] = ( + contextvars.ContextVar('corva_logging_handlers', default=None) + ) + self._active: list['LoggingContext'] = [] + self._active_lock = threading.Lock() + + def enter( + self, context: 'LoggingContext' + ) -> contextvars.Token[Optional[tuple[logging.Handler, ...]]]: + with self._active_lock: + self._active.append(context) + + return self._current.set(context.handlers) + + def exit( + self, + context: 'LoggingContext', + token: contextvars.Token[Optional[tuple[logging.Handler, ...]]], + ) -> None: + with self._active_lock: + # contexts can exit in any order + self._active.remove(context) + + try: + self._current.reset(token) + except ValueError: + # token was created in another contextvars.Context + self._current.set(None) + + def _get_handlers(self) -> tuple[logging.Handler, ...]: + handlers = self._current.get() + + if handlers is not None: + return handlers + + with self._active_lock: + if self._active: + return self._active[-1].handlers + + return () + + def handle(self, record: logging.LogRecord) -> bool: + # Skip Handler.handle on purpose: it holds a lock around emit, which would + # serialize logging of all threads. Target handlers lock on their own. + handlers = self._get_handlers() + + if not handlers and logging.lastResort is not None: + handlers = (logging.lastResort,) + + for handler in handlers: + if record.levelno >= handler.level: + handler.handle(record) + + return True + + +_DISPATCH_HANDLER_INSTALL_LOCK = threading.Lock() + + +def _get_dispatch_handler(logger: logging.Logger) -> _DispatchHandler: + """Returns the logger's dispatch handler, installing it on first use.""" + + with _DISPATCH_HANDLER_INSTALL_LOCK: + for handler in logger.handlers: + if isinstance(handler, _DispatchHandler): + return handler + + dispatch_handler = _DispatchHandler() + logger.addHandler(dispatch_handler) + + return dispatch_handler + + class LoggingContext(contextlib.ContextDecorator): """Context manager to configure logger to use specified handlers. @@ -153,14 +279,16 @@ class LoggingContext(contextlib.ContextDecorator): Context allows changing filter's fields dynamically. It will update logging formatter as needed. - Logger gets its old handlers back at the end of the context. + Handlers are applied per execution context (thread / asyncio task), so + concurrent contexts on the same logger do not affect each other. See + `_DispatchHandler` for details. Use a separate instance per invocation. Attributes: filter: Logging filter that gets set in the handler. handler: Logging handler that gets modified and set in the logger. user_handler: Logging handler that gets set in the logger without modifications. logger: Logger to configure. - old_handlers: Logger's own handlers before the update. + handlers: Handlers that receive the logger's records inside the context. """ def __init__( @@ -186,6 +314,8 @@ def __init__( self.user_handler = user_handler self.logger = logger + self.handlers: tuple[logging.Handler, ...] = () + @property def asset_id(self) -> Optional[int]: """Asset id used in the logging filter.""" @@ -218,14 +348,30 @@ def set_formatter(self): ) def __enter__(self): - self.old_handlers = self.logger.handlers - self.logger.handlers = ( - [self.handler, self.user_handler] if self.user_handler else [self.handler] - ) + # Build the handler chain for the logger. + handlers = [self.handler] + if self.user_handler: + handlers.append(self.user_handler) + + # If OTel log sending is enabled and an OTel handler exists on root, + # attach it to CORVA_LOGGER as well so propagation can remain disabled + # (avoids AWS root duplication) while still exporting logs via OTel. + + if not SETTINGS.OTEL_LOG_SENDING_DISABLED: + # Fail-safe: never break logging if detection fails + with suppress(Exception): + for handler in _gather_otel_handlers_from_root(): + if handler not in handlers: + handlers.append(handler) + + self.handlers = tuple(handlers) + + self._dispatch_handler = _get_dispatch_handler(self.logger) + self._token = self._dispatch_handler.enter(self) return self def __exit__(self, exc_type, exc_val, exc_tb): - self.logger.handlers = self.old_handlers + self._dispatch_handler.exit(self, self._token) return False # exception will be propagated diff --git a/src/version.py b/src/version.py index 57d0a1ba..0d1c3b58 100644 --- a/src/version.py +++ b/src/version.py @@ -1 +1 @@ -VERSION = "1.15.0" +VERSION = "1.16.2" diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index 248d363b..e67ee3b6 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -1,5 +1,10 @@ +import contextvars import datetime import logging +import threading +from concurrent.futures import ThreadPoolExecutor +from typing import cast +from unittest.mock import MagicMock import freezegun import pytest @@ -8,6 +13,7 @@ from corva import Logger from corva.configuration import SETTINGS from corva.handlers import scheduled, stream, task +from corva.logger import LoggingContext from corva.models.context import CorvaContext from corva.models.scheduled.raw import RawScheduledDataTimeEvent, RawScheduledEvent from corva.models.scheduled.scheduler_type import SchedulerType @@ -326,3 +332,156 @@ def app(event, api): assert 'The app failed to execute.' in captured.out assert 'The app failed to execute.' in captured.err + + +@pytest.mark.parametrize("cls_name", ("opentelemetry", "otel")) +def test__otel_handler_passed_to_logging_context__success(monkeypatch, cls_name): + + otel_handler = MagicMock() + otel_handler.__class__.__name__ = cls_name + + # Attach to the root logger + logging.getLogger().addHandler(otel_handler) + + monkeypatch.setenv("OTEL_SDK_DISABLED", "false") + + try: + with LoggingContext( + aws_request_id=MagicMock(), + asset_id=MagicMock(), + app_connection_id=MagicMock(), + handler=MagicMock(), + user_handler=MagicMock(), + logger=MagicMock(), + ) as context: + assert otel_handler in context.handlers + finally: + logging.getLogger().removeHandler(otel_handler) + + +class _ListHandler(logging.Handler): + def __init__(self): + super().__init__() + self.lines: list[str] = [] + + def emit(self, record): + self.lines.append(f"{record.aws_request_id}:{record.asset_id}:{record.getMessage()}") + + +@pytest.fixture +def isolated_logger(): + logger = logging.getLogger("test-logging-context-isolated") + logger.setLevel(logging.INFO) + logger.propagate = False + yield logger + logger.handlers = [] + + +def _logging_context(request_id: str, asset_id: int, logger: logging.Logger): + return LoggingContext( + aws_request_id=request_id, + asset_id=asset_id, + app_connection_id=None, + handler=_ListHandler(), + user_handler=None, + logger=logger, + ) + + +def _lines(ctx: LoggingContext) -> list[str]: + return cast(_ListHandler, ctx.handler).lines + + +@pytest.mark.parametrize("a_exits_first", (False, True)) +def test_concurrent_logging_contexts_do_not_mix(isolated_logger, a_exits_first): + """Contexts entered in different threads must not affect each other.""" + a_entered, b_entered, a_logged, a_exited, b_logged = ( + threading.Event() for _ in range(5) + ) + ctx_a = _logging_context("A", 1, isolated_logger) + ctx_b = _logging_context("B", 2, isolated_logger) + + def thread_a(): + with ctx_a: + isolated_logger.info("a-before") + a_entered.set() + assert b_entered.wait(5) + isolated_logger.info("a-during") + a_logged.set() + if not a_exits_first: + assert b_logged.wait(5) + a_exited.set() + + def thread_b(): + assert a_entered.wait(5) + with ctx_b: + b_entered.set() + assert a_logged.wait(5) + isolated_logger.info("b-during") + if a_exits_first: + assert a_exited.wait(5) + isolated_logger.info("b-after-a-exited") + b_logged.set() + + with ThreadPoolExecutor(max_workers=2) as pool: + for future in [pool.submit(thread_a), pool.submit(thread_b)]: + future.result(timeout=15) + + # nothing is left attached to the logger after the contexts exit + isolated_logger.info("outside") + + assert _lines(ctx_a) == ["A:1:a-before", "A:1:a-during"] + assert _lines(ctx_b) == ["B:2:b-during"] + ( + ["B:2:b-after-a-exited"] if a_exits_first else [] + ) + + +def test_nested_logging_contexts_restore_outer_context(isolated_logger): + outer = _logging_context("outer", 1, isolated_logger) + inner = _logging_context("inner", 2, isolated_logger) + + with outer: + isolated_logger.info("1") + with inner: + isolated_logger.info("2") + isolated_logger.info("3") + + assert _lines(outer) == ["outer:1:1", "outer:1:3"] + assert _lines(inner) == ["inner:2:2"] + + +def test_logging_context_is_used_by_threads_started_inside_it(isolated_logger): + """Threads spawned by app code do not inherit contextvars, but still log.""" + ctx = _logging_context("req", 1, isolated_logger) + + with ctx: + with ThreadPoolExecutor(max_workers=1) as pool: + pool.submit(lambda: isolated_logger.info("from-worker")).result(timeout=5) + + assert _lines(ctx) == ["req:1:from-worker"] + + +def test_logging_context_propagates_to_copied_context_threads(isolated_logger): + ctx_a = _logging_context("A", 1, isolated_logger) + ctx_b = _logging_context("B", 2, isolated_logger) + + with ctx_a: + copied = contextvars.copy_context() + with ctx_b: + with ThreadPoolExecutor(max_workers=1) as pool: + pool.submit( + lambda: copied.run(isolated_logger.info, "from-a-worker") + ).result(timeout=5) + + assert _lines(ctx_a) == ["A:1:from-a-worker"] + assert _lines(ctx_b) == [] + + +def test_logging_context_asset_id_can_be_updated_inside_context(isolated_logger): + ctx = _logging_context("req", 1, isolated_logger) + + with ctx: + ctx.asset_id = 5 + isolated_logger.info("msg") + + assert _lines(ctx) == ["req:5:msg"]