Skip to content

sys.monitoring callbacks (coverage, etc.) cause workflow sandbox hang on Python 3.14 #1326

Closed

Description

@dsfaccini

hey guys I just want you to know I don't know what any of the words below mean (they were not in the bible)

the reason I'm opening this is because the pydantic-ai test suite was hanging in our PR to support python 3.14 pydantic/pydantic-ai#4138

the hang came from the temporal tests, so me and opus started investigating and though it was very difficult we were finally I able to produce an MRE

so what you'll read (if you read it) below is opus' explanation, I'll put up a solution forward in a moment that I verified worked using the MRE and also running the test again with the patched temporal sdk


summary

on python 3.14, coverage switched from sys.settrace to sys.monitoring (PEP 669). sys.monitoring callbacks are global — they fire on all threads, including the workflow thread pool thread where the sandbox importer is active.

coverage's branch callback (sysmon_branch_either) lazily imports coverage.python the first time a BRANCH event fires. when this happens inside the sandbox, the import chain hits platform.python_implementation() which is restricted → RestrictedWorkflowAccessError → workflow task fails repeatedly → process hangs.

causal chain

greet() → `if name:` (BRANCH event)
→ coverage.sysmon.sysmon_branch_either
→ coverage.sysmon.get_multiline_map
→ coverage.parser.PythonParser.__init__
→ `from coverage.python import get_python_source`  ← lazy import
→ sandbox intercepts (coverage not in passthrough list)
→ coverage.__init__ → coverage.control → coverage.env
→ `platform.python_implementation()` ← restricted in sandbox
→ RestrictedWorkflowAccessError

this affects any sys.monitoring-based tool, not just coverage. any tool that registers monitoring callbacks and triggers a lazy import can hit this.

MRE

two files — the workflow must be in a separate module (not __main__) so the sandbox imports it normally and the branch callback fires during workflow execution rather than during import.

mre_workflow.py

from temporalio import workflow


def greet(name: str) -> str:
    if name:
        return f"Hello, {name}!"
    return "Hello!"


@workflow.defn
class SimpleWorkflow:
    @workflow.run
    async def run(self, name: str) -> str:
        return greet(name)

mre_coverage.py

import asyncio
import sys

from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker

from mre_workflow import SimpleWorkflow


async def main() -> None:
    async with await WorkflowEnvironment.start_local() as env:
        task_queue = "mre-task-queue"
        async with Worker(
            env.client,
            task_queue=task_queue,
            workflows=[SimpleWorkflow],
        ):
            result = await asyncio.wait_for(
                env.client.execute_workflow(
                    SimpleWorkflow.run,
                    "world",
                    id="mre-workflow",
                    task_queue=task_queue,
                ),
                timeout=10,
            )
            print(f"Result: {result}")
            assert result == "Hello, world!", f"Unexpected: {result}"
            print("OK")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except (asyncio.TimeoutError, TimeoutError):
        print(
            f"HANG DETECTED: workflow timed out (Python {sys.version_info.major}.{sys.version_info.minor})",
            file=sys.stderr,
        )
        sys.exit(1)

setup & reproduce

uv venv --python 3.14 .venv314
uv pip install --python .venv314/bin/python "temporalio[testing]" coverage

# hangs:
.venv314/bin/coverage run --source=. --branch mre_coverage.py

# works (no coverage):
.venv314/bin/python mre_coverage.py

# works (3.13 + coverage):
# uv venv --python 3.13 .venv313
# uv pip install --python .venv313/bin/python "temporalio[testing]" coverage
# .venv313/bin/coverage run --source=. --branch mre_coverage.py

why previous attempts at reproducing failed

  • workflow with no branching code → branch callback never fires
  • workflow defined in __main__ → sandbox re-imports it as __temporal_main__, and coverage's branch callback fires during import (before sandbox activation) rather than during workflow execution

environment

  • python 3.14.2
  • temporalio 1.20.0
  • coverage 7.13.4

suggested fix

suspend sys.monitoring events inside Importer.applied(). save and clear all events on enter, restore on exit. this prevents any monitoring callback from firing inside the sandbox regardless of which tool registered it.

this is better than adding coverage to passthrough because:

  • it's general — fixes all sys.monitoring-based tools
  • monitoring callbacks are non-deterministic external state that shouldn't fire inside the sandbox anyway
  • no user configuration needed

I'll put up a PR with this approach.

Activity

  1. added a commit that references this issue on Feb 11, 2026
    0f76418
  2. chrikrah commented on Sep 10, 2026

    @chrikrah

    Measured band, on Python 3.14.7 with temporalio 1.32.0 and your MRE unchanged, run as
    coverage run --source=. --branch mre_coverage.py from /tmp/t1326:

    coverage result
    7.10.7 OK
    7.12.0 OK
    7.13.4 (the version in your Environment block) RestrictedWorkflowAccessError, then HANG DETECTED
    7.14.0 same failure
    7.15.0 same failure
    7.15.1 OK
    7.16.0 (current release) OK

    --branch is load-bearing: drop it and 7.14.0 passes, which narrows the trigger to the branch callback
    rather than to coverage as such. sys.monitoring was active in every run
    (sys.monitoring.get_tool(COVERAGE_ID) == 'coverage.py', sys.gettrace() is None), so this is not a
    settrace fallback.

    The chain in 7.14.0 ends where you traced it, at coverage/env.py:27:

    coverage/sysmon.py:446  sysmon_branch_either
    coverage/sysmon.py:488  get_multiline_map
    coverage/parser.py:55   from coverage.python import get_python_source
    ...
    coverage/env.py:27      CPYTHON = (platform.python_implementation() == "CPython")
    RestrictedWorkflowAccessError: Cannot access platform.python_implementation.__call__ from inside a workflow.
    

    So a passing run on 7.15.1 or later is a coverage-side change, not a fix here: coverage is still absent
    from SandboxRestrictions.passthrough_modules_default.

    Your #1327 took the general route, _importer.py only, and closed unmerged on 2026-08-13 with zero
    reviews, in a batch that closed four outsider pull requests inside 24 minutes. tconley1428's only
    substantive words on it are still open: "We still need to determine if this is how we would like to
    address this, and it will definitely need tests if we do decide to go with it."

    The narrow alternative works on 7.14.0, and it is one line:

    SandboxedWorkflowRunner(
        restrictions=SandboxRestrictions.default.with_passthrough_modules("coverage")
    )

    Result: Hello, world! and OK, same coverage version that fails without it.

    Your own objection to that stands, and it is the decision to make: passing coverage through fixes
    coverage, while suspending monitoring events in Importer.applied() at _importer.py:140 fixes every
    sys.monitoring tool. Which of the two do you want tests for?

  3. chrikrah commented on Oct 3, 2026

    @chrikrah

    @tconley1428, you said on #1327 that it would definitely need tests if you decided to go that way. I never tagged you in September, so here is the offer again.

    coverage fixed itself at 7.15.1, so its users are clear. The sandbox still suspends nothing, and the next sys.monitoring tool hangs the same way. Both candidates still live at e47c962, main today:

    $ grep -n 'passthrough_modules_default = \|stdlib_module_names' temporalio/worker/workflow_sandbox/_restrictions.py
    529:        for v in sys.stdlib_module_names
    534:SandboxRestrictions.passthrough_modules_default = (
    $ python3 -c 'import sys; print(sys.version_info[:3], "coverage" in sys.stdlib_module_names)'
    (3, 12, 3) False
    $ grep -rn monitoring temporalio/worker/workflow_sandbox/
    $
    # not run: the sandbox suite, which wants the test server
    

    I will write the test for the one-line passthrough fix. It goes in tests/worker/workflow_sandbox/test_importer.py, which drives Importer(...).applied() with no server. Say the word if you want the _importer.py route instead.

  4. tconley1428 commented on Oct 5, 2026

    @tconley1428
    Contributor

    If it is true that it works on 7.15.1, then it sounds like that is sufficient solution to close this. I would want to see a well outlined argument for why it is sensible to use monitoring callbacks inside a workflow and how that interacts with replay/task timeouts, etc, before taking any kind of action on auto passing it through.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions