Skip to content

Nexus prototype #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 58 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
64584f4
Clean up existing code
dandavison Apr 5, 2025
b254da8
Nexus
dandavison Apr 19, 2025
ad02dd2
Completion callbacks and links
dandavison Apr 19, 2025
f9c0500
Get rid of unnecessary `proceed` signal
dandavison Apr 19, 2025
34a2ecb
WIP: test links
dandavison Apr 19, 2025
71a500d
Fix links
dandavison Apr 19, 2025
e83ebb8
DEV: hyperlinked
dandavison Apr 19, 2025
5987ffe
DEV
dandavison Apr 19, 2025
d461e2e
TODO
dandavison Apr 21, 2025
86d2711
Clean up
dandavison Apr 21, 2025
18803ad
WIP
dandavison Apr 22, 2025
ce8c078
Introduce NexusOperationError to wrap nexus op errors
dandavison Apr 24, 2025
009edf6
Refactor
dandavison Apr 24, 2025
9f085e8
Support using service impl instead of interface
dandavison Apr 25, 2025
7e8da41
Refactor test
dandavison Apr 26, 2025
d43f29a
Delete print statements
dandavison Apr 26, 2025
d45b3b4
Test service interface/impl with/without name
dandavison Apr 26, 2025
0f41280
Add temporal SDK operation protocol
dandavison Apr 28, 2025
3ded3be
uv.lock
dandavison Apr 28, 2025
7eff062
Test service decorators
dandavison Apr 28, 2025
4704310
Move tests to nexusrpc
dandavison Apr 28, 2025
f13beae
Return dataclass in tests
dandavison Apr 28, 2025
f482f41
Delete unused
dandavison Apr 28, 2025
1ad3393
Update ruff config
dandavison Apr 28, 2025
db90521
Bump pyright
dandavison Apr 28, 2025
2f89ec1
Bump pyright
dandavison Apr 28, 2025
fbbbf8f
Silence pyright errors
dandavison Apr 28, 2025
4edf12a
Don't use StrEnum
dandavison Apr 28, 2025
103f2a6
Fix type errors
dandavison Apr 28, 2025
f6d037f
Cleanup
dandavison Apr 28, 2025
17632f8
Fix types
dandavison Apr 28, 2025
7934781
Run pyright first because it passes
dandavison Apr 28, 2025
f607aff
Clean up test
dandavison Apr 28, 2025
d366c57
Rename: workflow_run_operation
dandavison Apr 28, 2025
ce52610
Make NexusClient generic in service class
dandavison Apr 28, 2025
7af84ed
Stop prefixing everything with "my"
dandavison Apr 29, 2025
f05dcbb
cleanup test: staticmethod
dandavison Apr 29, 2025
9490c36
WorkflowRunOperation generic
dandavison Apr 29, 2025
663132e
Get rid of default {}
dandavison Apr 29, 2025
9b5663c
Cleanup
dandavison Apr 29, 2025
1e78a95
Test untyped caller
dandavison Apr 29, 2025
f38a53e
Test dataconverters by using distinct I/O types everywhere
dandavison Apr 29, 2025
1414bab
Support instantiating output type for untyped caller
dandavison Apr 29, 2025
6cd317e
Fix test
dandavison Apr 29, 2025
044ad4a
Fail workflow instead of task in tests
dandavison Apr 29, 2025
7fe16d6
Install pdbpp
dandavison Apr 29, 2025
8bd6011
Fix runtime type extraction
dandavison Apr 29, 2025
98a69fa
Use helpers from nexusrpc
dandavison Apr 29, 2025
cfcb35f
Move StartWorkflowOperationResult type helper into temporal sdk
dandavison Apr 29, 2025
0a3e5bd
type ignore
dandavison Apr 29, 2025
5c25b0b
Test non-async-def sync operations
dandavison Apr 29, 2025
8ea7e5f
TODOs
dandavison Apr 29, 2025
7260661
coverage
dandavison Apr 29, 2025
27ab162
Test execute_operation w/ output type and async untyped
dandavison Apr 29, 2025
e8b3925
Bug fix: support output type with execute_operation
dandavison Apr 29, 2025
b801044
Rearrange: put nexus next to activities
dandavison Apr 30, 2025
88cdd10
Improve existing docstrings
dandavison Apr 30, 2025
18e268a
Cleanup
dandavison Apr 30, 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
67 changes: 67 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ informal introduction to the features and their implementation.
- [Heartbeating and Cancellation](#heartbeating-and-cancellation)
- [Worker Shutdown](#worker-shutdown)
- [Testing](#testing-1)
- [Nexus](#nexus)
- [hello](#hello)
- [Workflow Replay](#workflow-replay)
- [Observability](#observability)
- [Metrics](#metrics)
Expand Down Expand Up @@ -1314,6 +1316,71 @@ 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


### Nexus

See [docs.temporal.io/nexus](https://docs.temporal.io/nexus).

#### Service Interface Definition

A Nexus Service interface definition is a set of named operations, where each operation is an
`(input_type, output_type)` pair:

```python
@nexusrpc.service
class MyNexusService:
my_operation: nexusrpc.Operation[MyOpInput, MyOpOutput]
```

### Operation implementation

```python
@nexusrpc.service(interface.MyNexusService)
class MyNexusService:

@nexusrpc.sync_operation
def echo(self, input: EchoInput) -> EchoOutput:
return EchoOutput(message=input.message)
```

```python
@nexusrpc.service(interface.MyNexusService)
class MyNexusService:

@temporalio.nexus.workflow_operation
async def hello(
self, input: HelloInput
) -> AsyncWorkflowOperationResult[HelloOutput]:
return await temporalio.nexus.handler.start_workflow(HelloWorkflow.run, input)
```


### Request options

```python
@dataclass
class OperationOptions:
"""Options passed by the Nexus caller when starting an operation."""

# A callback URL is required to deliver the completion of an async operation. This URL should be
# called by a handler upon completion if the started operation is async.
callback_url: Optional[str] = None

# Optional header fields set by the caller to be attached to the callback request when an
# asynchronous operation completes.
callback_header: dict[str, str] = field(default_factory=dict)

# Request ID that may be used by the server handler to dedupe a start request.
# By default a v4 UUID will be generated by the client.
request_id: Optional[str] = None

# Links contain arbitrary caller information. Handlers may use these links as
# metadata on resources associated with an operation.
links: list[Link] = field(default_factory=list)
```



### Workflow Replay

Given a workflow's history, it can be replayed locally to check for things like non-determinism errors. For example,
Expand Down
26 changes: 21 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@ keywords = [
"workflow",
]
dependencies = [
"hyperlinked",
"nexus-rpc",
"pdbpp>=0.11.6",
"protobuf>=3.20",
"python-dateutil>=2.8.2,<3 ; python_version < '3.11'",
"temporalio-xray",
"types-protobuf>=3.20",
"typing-extensions>=4.2.0,<5",
]
Expand Down Expand Up @@ -40,7 +44,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 +53,7 @@ dev = [
"twine>=4.0.1,<5",
"ruff>=0.5.0,<0.6",
"maturin>=1.8.2",
"pytest-cov>=6.1.1",
]

[tool.poe.tasks]
Expand All @@ -60,8 +65,8 @@ gen-protos = "uv run python scripts/gen_protos.py"
lint = [
{cmd = "uv run ruff check --select I"},
{cmd = "uv run ruff format --check"},
{ref = "lint-types"},
{cmd = "uv run pyright"},
{ref = "lint-types"},
{ref = "lint-docs"},
]
bridge-lint = { cmd = "cargo clippy -- -D warnings", cwd = "temporalio/bridge" }
Expand All @@ -70,7 +75,7 @@ bridge-lint = { cmd = "cargo clippy -- -D warnings", cwd = "temporalio/bridge" }
lint-docs = "uv run pydocstyle --ignore-decorators=overload"
lint-types = "uv run mypy --namespace-packages --check-untyped-defs ."
run-bench = "uv run python scripts/run_bench.py"
test = "uv run pytest"
test = "uv run pytest --cov temporalio --cov-report xml"


[tool.pytest.ini_options]
Expand All @@ -83,8 +88,6 @@ testpaths = ["tests"]
timeout = 600
timeout_func_only = true
filterwarnings = [
"error::temporalio.workflow.UnfinishedUpdateHandlersWarning",
"error::temporalio.workflow.UnfinishedSignalHandlersWarning",
"ignore::pytest.PytestDeprecationWarning",
"ignore::DeprecationWarning",
]
Expand Down Expand Up @@ -157,6 +160,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 @@ -168,6 +172,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 All @@ -186,6 +194,9 @@ exclude = [
[tool.ruff]
target-version = "py39"

[tool.ruff.lint]
extend-ignore = ["E741"] # Allow single-letter variable names like I, O

[build-system]
requires = ["maturin>=1.0,<2.0"]
build-backend = "maturin"
Expand All @@ -202,3 +213,8 @@ 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 }
temporalio-xray = { path = "../xray/sdks/python", editable = true }
hyperlinked = { path = "../../hyperlinked/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
28 changes: 27 additions & 1 deletion temporalio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,8 +459,15 @@ 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,
# The following options are deliberately not exposed in overloads
stack_level: int = 2,
nexus_completion_callbacks: Sequence[
temporalio.common.NexusCompletionCallback
] = [],
workflow_event_links: Sequence[
temporalio.api.common.v1.Link.WorkflowEvent
] = [],
) -> WorkflowHandle[Any, Any]:
"""Start a workflow and return its handle.

Expand Down Expand Up @@ -523,6 +530,11 @@ async def start_workflow(
temporalio.workflow._Definition.get_name_and_result_type(workflow)
)

for l in workflow_event_links:
print(
f"🌈@@ worker starting workflow with link: {google.protobuf.json_format.MessageToJson(l)}"
)

return await self._impl.start_workflow(
StartWorkflowInput(
workflow=name,
Expand All @@ -549,6 +561,8 @@ 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,
)
)

Expand Down Expand Up @@ -5156,6 +5170,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]


@dataclass
Expand Down Expand Up @@ -5770,6 +5786,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
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 @@ -195,6 +195,37 @@ def __setstate__(self, state: object) -> None:
)


@dataclass(frozen=True)
class NexusCompletionCallback:
"""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:
"""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
Loading
Loading