Skip to content

Nexus worker and workflow-backed operations #813

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

Draft
wants to merge 25 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
1e53211
Nexus
dandavison Apr 19, 2025
6ec8782
Nexus workflow caller
dandavison Jun 10, 2025
9ca2b53
Import types from nexusrpc
dandavison Jun 12, 2025
f8bd453
Rename: WorkflowRunOperation
dandavison Jun 12, 2025
873a866
Use Client.start_workflow with Temporal-specific context classes
dandavison Jun 12, 2025
f25a06e
Revert accidental change to protobuf version
dandavison Jun 12, 2025
a45c258
Improve error messages
dandavison Jun 12, 2025
7760057
Use temporal {Start,Cancel}OperationContext
dandavison Jun 12, 2025
b9158f5
Failing test
dandavison Jun 12, 2025
586a6ec
Handle errors during cancellation
dandavison Jun 12, 2025
181266a
Rename variable
dandavison Jun 13, 2025
b5235e4
Failing test for requestID-based idempotency
dandavison Jun 13, 2025
7d145fa
Propagate Nexus request ID when starting a workflow
dandavison Jun 13, 2025
60a207d
Move nexus http client into tests/helpers
dandavison Jun 13, 2025
d032b74
Tests: rename wf operations
dandavison Jun 13, 2025
4213f6b
Testing: Fix env http port
dandavison Jun 13, 2025
1f132bb
Improve error message in test
dandavison Jun 13, 2025
6fc7b7f
Tests: use workflow ID from async context
dandavison Jun 14, 2025
43aab59
Test that Nexus request ID becomes Temporal StartWorkflow request ID
dandavison Jun 14, 2025
1c3780a
UNRELATED: minor activity worker renaming and docstrings
dandavison Jun 14, 2025
8de7772
Reorder methods
dandavison Jun 14, 2025
f1e3568
Refactor Nexus worker
dandavison Jun 14, 2025
071ebbd
Test non-serializable operation output
dandavison Jun 14, 2025
0a527dc
Test: Rename field
dandavison Jun 15, 2025
0f22e1b
Don't require HandlerError cause and fix test assertions
dandavison Jun 14, 2025
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ informal introduction to the features and their implementation.
- [Heartbeating and Cancellation](#heartbeating-and-cancellation)
- [Worker Shutdown](#worker-shutdown)
- [Testing](#testing-1)
- [Nexus](#nexus)
- [Workflow Replay](#workflow-replay)
- [Observability](#observability)
- [Metrics](#metrics)
Expand Down Expand Up @@ -1313,6 +1314,7 @@ affect calls activity code might make to functions on the `temporalio.activity`
* `cancel()` can be invoked to simulate a cancellation of the activity
* `worker_shutdown()` can be invoked to simulate a worker shutdown during execution of the activity


### Workflow Replay

Given a workflow's history, it can be replayed locally to check for things like non-determinism errors. For example,
Expand Down
13 changes: 12 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ keywords = [
"workflow",
]
dependencies = [
"nexus-rpc",
"protobuf>=3.20",
"python-dateutil>=2.8.2,<3 ; python_version < '3.11'",
"types-protobuf>=3.20",
Expand Down Expand Up @@ -40,7 +41,7 @@ dev = [
"psutil>=5.9.3,<6",
"pydocstyle>=6.3.0,<7",
"pydoctor>=24.11.1,<25",
"pyright==1.1.377",
"pyright==1.1.400",
"pytest~=7.4",
"pytest-asyncio>=0.21,<0.22",
"pytest-timeout~=2.2",
Expand All @@ -49,6 +50,8 @@ dev = [
"twine>=4.0.1,<5",
"ruff>=0.5.0,<0.6",
"maturin>=1.8.2",
"pytest-cov>=6.1.1",
"httpx>=0.28.1",
"pytest-pretty>=1.3.0",
]

Expand Down Expand Up @@ -158,6 +161,7 @@ exclude = [
"tests/worker/workflow_sandbox/testmodules/proto",
"temporalio/bridge/worker.py",
"temporalio/contrib/opentelemetry.py",
"temporalio/contrib/pydantic.py",
"temporalio/converter.py",
"temporalio/testing/_workflow.py",
"temporalio/worker/_activity.py",
Expand All @@ -169,6 +173,10 @@ exclude = [
"tests/api/test_grpc_stub.py",
"tests/conftest.py",
"tests/contrib/test_opentelemetry.py",
"tests/contrib/pydantic/models.py",
"tests/contrib/pydantic/models_2.py",
"tests/contrib/pydantic/test_pydantic.py",
"tests/contrib/pydantic/workflows.py",
"tests/test_converter.py",
"tests/test_service.py",
"tests/test_workflow.py",
Expand Down Expand Up @@ -203,3 +211,6 @@ exclude = [
[tool.uv]
# Prevent uv commands from building the package by default
package = false

[tool.uv.sources]
nexus-rpc = { path = "../nexus-sdk-python", editable = true }
28 changes: 27 additions & 1 deletion temporalio/bridge/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use temporal_sdk_core_api::worker::{
};
use temporal_sdk_core_api::Worker;
use temporal_sdk_core_protos::coresdk::workflow_completion::WorkflowActivationCompletion;
use temporal_sdk_core_protos::coresdk::{ActivityHeartbeat, ActivityTaskCompletion};
use temporal_sdk_core_protos::coresdk::{ActivityHeartbeat, ActivityTaskCompletion, nexus::NexusTaskCompletion};
use temporal_sdk_core_protos::temporal::api::history::v1::History;
use tokio::sync::mpsc::{channel, Sender};
use tokio_stream::wrappers::ReceiverStream;
Expand Down Expand Up @@ -570,6 +570,19 @@ impl WorkerRef {
})
}

fn poll_nexus_task<'p>(&self, py: Python<'p>) -> PyResult<&'p PyAny> {
let worker = self.worker.as_ref().unwrap().clone();
self.runtime.future_into_py(py, async move {
let bytes = match worker.poll_nexus_task().await {
Ok(task) => task.encode_to_vec(),
Err(PollError::ShutDown) => return Err(PollShutdownError::new_err(())),
Err(err) => return Err(PyRuntimeError::new_err(format!("Poll failure: {}", err))),
};
let bytes: &[u8] = &bytes;
Ok(Python::with_gil(|py| bytes.into_py(py)))
})
}

fn complete_workflow_activation<'p>(
&self,
py: Python<'p>,
Expand Down Expand Up @@ -600,6 +613,19 @@ impl WorkerRef {
})
}

fn complete_nexus_task<'p>(&self, py: Python<'p>, proto: &PyBytes) -> PyResult<&'p PyAny> {
let worker = self.worker.as_ref().unwrap().clone();
let completion = NexusTaskCompletion::decode(proto.as_bytes())
.map_err(|err| PyValueError::new_err(format!("Invalid proto: {}", err)))?;
self.runtime.future_into_py(py, async move {
worker
.complete_nexus_task(completion)
.await
.context("Completion failure")
.map_err(Into::into)
})
}

fn record_activity_heartbeat(&self, proto: &PyBytes) -> PyResult<()> {
enter_sync!(self.runtime);
let heartbeat = ActivityHeartbeat::decode(proto.as_bytes())
Expand Down
17 changes: 16 additions & 1 deletion temporalio/bridge/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import temporalio.bridge.client
import temporalio.bridge.proto
import temporalio.bridge.proto.activity_task
import temporalio.bridge.proto.nexus
import temporalio.bridge.proto.workflow_activation
import temporalio.bridge.proto.workflow_completion
import temporalio.bridge.runtime
Expand All @@ -35,7 +36,7 @@
from temporalio.bridge.temporal_sdk_bridge import (
CustomSlotSupplier as BridgeCustomSlotSupplier,
)
from temporalio.bridge.temporal_sdk_bridge import PollShutdownError
from temporalio.bridge.temporal_sdk_bridge import PollShutdownError # type: ignore


@dataclass
Expand Down Expand Up @@ -216,6 +217,14 @@ async def poll_activity_task(
await self._ref.poll_activity_task()
)

async def poll_nexus_task(
self,
) -> temporalio.bridge.proto.nexus.NexusTask:
"""Poll for a nexus task."""
return temporalio.bridge.proto.nexus.NexusTask.FromString(
await self._ref.poll_nexus_task()
)

async def complete_workflow_activation(
self,
comp: temporalio.bridge.proto.workflow_completion.WorkflowActivationCompletion,
Expand All @@ -229,6 +238,12 @@ async def complete_activity_task(
"""Complete an activity task."""
await self._ref.complete_activity_task(comp.SerializeToString())

async def complete_nexus_task(
self, comp: temporalio.bridge.proto.nexus.NexusTaskCompletion
) -> None:
"""Complete a nexus task."""
await self._ref.complete_nexus_task(comp.SerializeToString())

def record_activity_heartbeat(
self, comp: temporalio.bridge.proto.ActivityHeartbeat
) -> None:
Expand Down
41 changes: 38 additions & 3 deletions temporalio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import temporalio.common
import temporalio.converter
import temporalio.exceptions
import temporalio.nexus
import temporalio.runtime
import temporalio.service
import temporalio.workflow
Expand Down Expand Up @@ -464,9 +465,10 @@ async def start_workflow(
rpc_metadata: Mapping[str, str] = {},
rpc_timeout: Optional[timedelta] = None,
request_eager_start: bool = False,
stack_level: int = 2,
priority: temporalio.common.Priority = temporalio.common.Priority.default,
versioning_override: Optional[temporalio.common.VersioningOverride] = None,
# The following options are deliberately not exposed in overloads
stack_level: int = 2,
) -> WorkflowHandle[Any, Any]:
"""Start a workflow and return its handle.

Expand Down Expand Up @@ -529,8 +531,16 @@ async def start_workflow(
name, result_type_from_type_hint = (
temporalio.workflow._Definition.get_name_and_result_type(workflow)
)
nexus_start_ctx = None
if nexus_ctx := temporalio.nexus.current_context.get(None):
if nexus_start_ctx := nexus_ctx.start_operation_context:
nexus_completion_callbacks = nexus_start_ctx.get_completion_callbacks()
workflow_event_links = nexus_start_ctx.get_workflow_event_links()
else:
nexus_completion_callbacks = []
workflow_event_links = []

return await self._impl.start_workflow(
wf_handle = await self._impl.start_workflow(
StartWorkflowInput(
workflow=name,
args=temporalio.common._arg_or_args(arg, args),
Expand All @@ -557,9 +567,16 @@ async def start_workflow(
rpc_timeout=rpc_timeout,
request_eager_start=request_eager_start,
priority=priority,
nexus_completion_callbacks=nexus_completion_callbacks,
workflow_event_links=workflow_event_links,
)
)

if nexus_start_ctx:
nexus_start_ctx.add_outbound_links(wf_handle)

return wf_handle

# Overload for no-param workflow
@overload
async def execute_workflow(
Expand Down Expand Up @@ -5193,6 +5210,8 @@ class StartWorkflowInput:
rpc_timeout: Optional[timedelta]
request_eager_start: bool
priority: temporalio.common.Priority
nexus_completion_callbacks: Sequence[temporalio.common.NexusCompletionCallback]
workflow_event_links: Sequence[temporalio.api.common.v1.Link.WorkflowEvent]
versioning_override: Optional[temporalio.common.VersioningOverride] = None


Expand Down Expand Up @@ -5809,6 +5828,16 @@ async def _build_start_workflow_execution_request(
req = temporalio.api.workflowservice.v1.StartWorkflowExecutionRequest()
req.request_eager_execution = input.request_eager_start
await self._populate_start_workflow_execution_request(req, input)
for callback in input.nexus_completion_callbacks:
c = temporalio.api.common.v1.Callback()
c.nexus.url = callback.url
c.nexus.header.update(callback.header)
req.completion_callbacks.append(c)

req.links.extend(
temporalio.api.common.v1.Link(workflow_event=link)
for link in input.workflow_event_links
)
return req

async def _build_signal_with_start_workflow_execution_request(
Expand Down Expand Up @@ -5855,7 +5884,13 @@ async def _populate_start_workflow_execution_request(
if input.task_timeout is not None:
req.workflow_task_timeout.FromTimedelta(input.task_timeout)
req.identity = self._client.identity
req.request_id = str(uuid.uuid4())
# Use Nexus request ID if we're handling a Nexus Start operation
if nexus_ctx := temporalio.nexus.current_context.get(None):
if nexus_start_ctx := nexus_ctx.start_operation_context:
if nexus_request_id := nexus_start_ctx.request_id:
req.request_id = nexus_request_id
if not req.request_id:
req.request_id = str(uuid.uuid4())
req.workflow_id_reuse_policy = cast(
"temporalio.api.enums.v1.WorkflowIdReusePolicy.ValueType",
int(input.id_reuse_policy),
Expand Down
33 changes: 32 additions & 1 deletion temporalio/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum, IntEnum
from enum import IntEnum
from typing import (
Any,
Callable,
Expand Down Expand Up @@ -197,6 +197,37 @@ def __setstate__(self, state: object) -> None:
)


@dataclass(frozen=True)
class NexusCompletionCallback:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if this is best in the client if it's only for clients

"""Nexus callback to attach to events such as workflow completion."""

url: str
"""Callback URL."""

header: Mapping[str, str]
"""Header to attach to callback request."""


@dataclass(frozen=True)
class WorkflowEventLink:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this class used?

"""A link to a history event that can be attached to a different history event."""

namespace: str
"""Namespace of the workflow to link to."""

workflow_id: str
"""ID of the workflow to link to."""

run_id: str
"""Run ID of the workflow to link to."""

event_type: temporalio.api.enums.v1.EventType
"""Type of the event to link to."""

event_id: int
"""ID of the event to link to."""


# We choose to make this a list instead of an sequence so we can catch if people
# are not sending lists each time but maybe accidentally sending a string (which
# is a sequence)
Expand Down
26 changes: 26 additions & 0 deletions temporalio/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,12 @@ def _error_to_failure(
failure.child_workflow_execution_failure_info.retry_state = (
temporalio.api.enums.v1.RetryState.ValueType(error.retry_state or 0)
)
# TODO(nexus-prerelease): test coverage for this
elif isinstance(error, temporalio.exceptions.NexusOperationError):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For symmetry reasons, I suspect we also need to convert NexusHandlerError (in theory a failure conversion from a failure should be able to convert back to a failure)

failure.nexus_operation_execution_failure_info.SetInParent()
failure.nexus_operation_execution_failure_info.operation_token = (
error.operation_token
)

def from_failure(
self,
Expand Down Expand Up @@ -1006,6 +1012,26 @@ def from_failure(
if child_info.retry_state
else None,
)
elif failure.HasField("nexus_handler_failure_info"):
nexus_handler_failure_info = failure.nexus_handler_failure_info
err = temporalio.exceptions.NexusHandlerError(
failure.message or "Nexus handler error",
type=nexus_handler_failure_info.type,
retryable={
temporalio.api.enums.v1.NexusHandlerErrorRetryBehavior.NEXUS_HANDLER_ERROR_RETRY_BEHAVIOR_RETRYABLE: True,
temporalio.api.enums.v1.NexusHandlerErrorRetryBehavior.NEXUS_HANDLER_ERROR_RETRY_BEHAVIOR_NON_RETRYABLE: False,
}.get(nexus_handler_failure_info.retry_behavior),
)
elif failure.HasField("nexus_operation_execution_failure_info"):
nexus_op_failure_info = failure.nexus_operation_execution_failure_info
err = temporalio.exceptions.NexusOperationError(
failure.message or "Nexus operation error",
scheduled_event_id=nexus_op_failure_info.scheduled_event_id,
endpoint=nexus_op_failure_info.endpoint,
service=nexus_op_failure_info.service,
operation=nexus_op_failure_info.operation,
operation_token=nexus_op_failure_info.operation_token,
)
else:
err = temporalio.exceptions.FailureError(failure.message or "Failure error")
err._failure = failure
Expand Down
Loading