Skip to content

Handle case where in_workflow is called in a synchronous activity #884

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jun 5, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion temporalio/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -940,7 +940,10 @@ def instance() -> Any:

def in_workflow() -> bool:
"""Whether the code is currently running in a workflow."""
return _Runtime.maybe_current() is not None
try:
return _Runtime.maybe_current() is not None
except RuntimeError:
return False


def memo() -> Mapping[str, Any]:
Expand Down
29 changes: 29 additions & 0 deletions tests/worker/test_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -7973,3 +7973,32 @@ async def test_quick_activity_swallows_cancellation(client: Client):
assert cause.message == "Workflow cancelled"

temporalio.worker._workflow_instance._raise_on_cancelling_completed_activity_override = False


@activity.defn
def use_in_workflow():
return workflow.in_workflow()


@workflow.defn
class UseInWorkflow:
@workflow.run
async def run(self):
res = await workflow.execute_activity(
use_in_workflow, schedule_to_close_timeout=timedelta(seconds=10)
)


async def test_in_workflow_sync(client: Client):
async with new_worker(
client,
UseInWorkflow,
activities=[use_in_workflow],
activity_executor=concurrent.futures.ThreadPoolExecutor(max_workers=1),
) as worker:
await client.execute_workflow(
UseInWorkflow.run,
id=f"test_in_workflow_sync",
task_queue=worker.task_queue,
execution_timeout=timedelta(minutes=1),
)
Loading