Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
19 changes: 19 additions & 0 deletions python/restate/agents/_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ class AgentOptions(TypedDict, total=False):
budget: How many tokens of the turns before the window the model
sees, as their messages and answers: the latest that fit.
Defaults to ``BUDGET``.
preemptable: When set to False, Restate never preempts invocations of
the agent, with all its handlers and views: it doesn't eagerly
suspend them while they wait on an await point to free concurrency
capacity for other invocations. They still suspend when the
inactivity timeout fires. Defaults to True.
NOTE: Only restate-server versions supporting service discovery
protocol V6 read it. Against older ones it is left out of the
discovery, which is safe since they never preempt invocations.
"""

description: str | None
Expand All @@ -113,6 +121,7 @@ class AgentOptions(TypedDict, total=False):
invocation_retry_policy: InvocationRetryPolicy | None
window: Window
budget: int
preemptable: bool | None


WAITS = timedelta(seconds=15)
Expand Down Expand Up @@ -240,6 +249,14 @@ class AgentObject(SessionObject):
are their messages and answers. Defaults to 1.
budget: How many tokens of the turns before the window the model
sees: the latest that fit. Defaults to ``BUDGET``.
preemptable: When set to False, Restate never preempts invocations of
the agent, with all its handlers and views: it doesn't eagerly
suspend them while they wait on an await point to free concurrency
capacity for other invocations. They still suspend when the
inactivity timeout fires. Defaults to True.
NOTE: Only restate-server versions supporting service discovery
protocol V6 read it. Against older ones it is left out of the
discovery, which is safe since they never preempt invocations.
"""

def __init__(
Expand All @@ -258,6 +275,7 @@ def __init__(
invocation_retry_policy: InvocationRetryPolicy | None = RETRIES,
window: Window = WINDOW,
budget: int = BUDGET,
preemptable: bool | None = None,
) -> None:
super().__init__(
name,
Expand All @@ -271,6 +289,7 @@ def __init__(
idempotency_retention=idempotency_retention,
ingress_private=ingress_private,
invocation_retry_policy=invocation_retry_policy,
preemptable=preemptable,
)
self.background: bool = background
self._clear: Callable[[SessionContext], Awaitable[None]] | None = None
Expand Down
14 changes: 14 additions & 0 deletions python/restate/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ def __init__(
enableLazyState: Optional[bool] = None,
eagerStateKeysWhitelist: Optional[List[str]] = None,
ingressPrivate: Optional[bool] = None,
preemptable: Optional[bool] = None,
retryPolicyInitialInterval: Optional[int] = None,
retryPolicyMaxInterval: Optional[int] = None,
retryPolicyMaxAttempts: Optional[int] = None,
Expand All @@ -108,6 +109,7 @@ def __init__(
self.enableLazyState = enableLazyState
self.eagerStateKeysWhitelist = eagerStateKeysWhitelist
self.ingressPrivate = ingressPrivate
self.preemptable = preemptable
self.retryPolicyInitialInterval = retryPolicyInitialInterval
self.retryPolicyMaxInterval = retryPolicyMaxInterval
self.retryPolicyMaxAttempts = retryPolicyMaxAttempts
Expand All @@ -131,6 +133,7 @@ def __init__(
enableLazyState: Optional[bool] = None,
eagerStateKeysWhitelist: Optional[List[str]] = None,
ingressPrivate: Optional[bool] = None,
preemptable: Optional[bool] = None,
retryPolicyInitialInterval: Optional[int] = None,
retryPolicyMaxInterval: Optional[int] = None,
retryPolicyMaxAttempts: Optional[int] = None,
Expand All @@ -149,6 +152,7 @@ def __init__(
self.enableLazyState = enableLazyState
self.eagerStateKeysWhitelist = eagerStateKeysWhitelist
self.ingressPrivate = ingressPrivate
self.preemptable = preemptable
self.retryPolicyInitialInterval = retryPolicyInitialInterval
self.retryPolicyMaxInterval = retryPolicyMaxInterval
self.retryPolicyMaxAttempts = retryPolicyMaxAttempts
Expand Down Expand Up @@ -260,6 +264,14 @@ def compute_discovery_json(

ep = compute_discovery(endpoint, discovered_as)

if version <= 5:
# preemptable is only supported since discovery protocol version 6. Drop it rather than failing:
# runtimes older than that never preempt invocations, so leaving it out doesn't change their behavior.
for service in ep.services:
service.preemptable = None
for handler in service.handlers:
handler.preemptable = None

# Validate that new discovery fields aren't used with older protocol versions
if version <= 4:
# Note: enableLazyState itself is available since v3; only the eager state whitelist requires v5.
Expand Down Expand Up @@ -400,6 +412,7 @@ def compute_discovery(endpoint: RestateEndpoint, discovered_as: typing.Literal["
enableLazyState=handler_enable_lazy_state,
eagerStateKeysWhitelist=handler_eager_state_keys_whitelist,
ingressPrivate=handler.ingress_private,
preemptable=handler.preemptable,
retryPolicyInitialInterval=int(
handler.invocation_retry_policy.initial_interval.total_seconds() * 1000
)
Expand Down Expand Up @@ -455,6 +468,7 @@ def compute_discovery(endpoint: RestateEndpoint, discovered_as: typing.Literal["
enableLazyState=service_enable_lazy_state,
eagerStateKeysWhitelist=service_eager_state_keys_whitelist,
ingressPrivate=service.ingress_private,
preemptable=service.preemptable,
retryPolicyInitialInterval=int(service.invocation_retry_policy.initial_interval.total_seconds() * 1000)
if service.invocation_retry_policy and service.invocation_retry_policy.initial_interval
else None,
Expand Down
5 changes: 5 additions & 0 deletions python/restate/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ class Handler(Generic[I, O]):
state_preload: Configures which state keys are preloaded ("eager state") at the start of each invocation.
True preloads all state, False preloads nothing, a list preloads only the listed keys.
ingress_private: If true, the handler cannot be invoked from the HTTP nor Kafka ingress.
preemptable: If false, Restate never preempts (eagerly suspends) invocations of this handler.
invocation_retry_policy: Optional retry policy configuration applied to this handler.
explicit_recovery: If true, the handler runs with explicit recovery (preview): a retried or resumed
invocation runs the handler again from the start, instead of replaying its journal. See the
Expand All @@ -279,6 +280,7 @@ class Handler(Generic[I, O]):
enable_lazy_state: Optional[bool] = None
state_preload: Optional[Union[bool, List[str]]] = None
ingress_private: Optional[bool] = None
preemptable: Optional[bool] = None
invocation_retry_policy: Optional[InvocationRetryPolicy] = None
context_managers: Optional[List[Callable[[], AsyncContextManager[None]]]] = None
explicit_recovery: bool = False
Expand Down Expand Up @@ -311,6 +313,7 @@ def make_handler(
context_managers: Optional[List[Callable[[], AsyncContextManager[None]]]] = None,
explicit_recovery: bool = False,
explicit_cancellation: bool = False,
preemptable: Optional[bool] = None,
) -> Handler[I, O]:
"""
Factory function to create a handler.
Expand All @@ -333,6 +336,7 @@ def make_handler(
state_preload: Configures which state keys are preloaded ("eager state") at the start of each invocation.
True preloads all state, False preloads nothing, a list preloads only the listed keys.
ingress_private: If true, the handler cannot be invoked from the HTTP nor Kafka ingress.
preemptable: If false, Restate never preempts (eagerly suspends) invocations of this handler.
invocation_retry_policy: Retry policy used by Restate when invoking this handler.
NOTE: only supported with restate-server >= 1.5.
explicit_recovery: If true, the handler runs with explicit recovery (preview).
Expand Down Expand Up @@ -370,6 +374,7 @@ def make_handler(
enable_lazy_state=enable_lazy_state,
state_preload=state_preload,
ingress_private=ingress_private,
preemptable=preemptable,
invocation_retry_policy=invocation_retry_policy,
context_managers=context_managers,
explicit_recovery=explicit_recovery,
Expand Down
16 changes: 16 additions & 0 deletions python/restate/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ class VirtualObject:
see the handler option of the same name. NOTE: in preview, it might change without notice.
explicit_cancellation (bool, optional): (Preview) Explicit cancellation for all handlers of this virtual object:
see the handler option of the same name. NOTE: in preview, it might change without notice.
preemptable (bool, optional): When set to False, Restate never preempts invocations of this virtual object,
with all its handlers: it doesn't eagerly suspend them while they wait on an await point to free
concurrency capacity for other invocations. They still suspend when the inactivity timeout fires.
Defaults to True, and can be overridden per handler.
NOTE: Only restate-server versions supporting service discovery protocol V6 read this field. Against older
ones it is left out of the discovery, which is safe since they never preempt invocations.
"""

handlers: typing.Dict[str, Handler[typing.Any, typing.Any]]
Expand Down Expand Up @@ -111,6 +117,7 @@ def __init__(
] = None,
explicit_recovery: bool = False,
explicit_cancellation: bool = False,
preemptable: typing.Optional[bool] = None,
):
self.service_tag = ServiceTag("object", name, description, metadata)
self.handlers = {}
Expand All @@ -126,6 +133,7 @@ def __init__(
self.context_managers = invocation_context_managers
self.explicit_recovery = explicit_recovery
self.explicit_cancellation = explicit_cancellation
self.preemptable = preemptable

@property
def name(self):
Expand Down Expand Up @@ -157,6 +165,7 @@ def handler(
] = None,
explicit_recovery: bool = False,
explicit_cancellation: bool = False,
preemptable: typing.Optional[bool] = None,
) -> typing.Callable[[T], T]:
"""
Decorator for defining a handler function.
Expand Down Expand Up @@ -211,6 +220,12 @@ def handler(
explicit_cancellation: (Preview) If true, Restate cancelling an invocation neither fails the handler's
awaits nor cancels its calls: the handler awaits `restate._preview.cancellation(ctx)` and decides
what to stop. NOTE: in preview, it might change without notice.
preemptable: When set to False, Restate never preempts invocations of this handler: it doesn't eagerly
suspend them while they wait on an await point to free concurrency capacity for other invocations.
They still suspend when the inactivity timeout fires. Overrides the value set on the service, which
defaults to True.
NOTE: Only restate-server versions supporting service discovery protocol V6 read this field. Against
older ones it is left out of the discovery, which is safe since they never preempt invocations.

Returns:
Callable: The decorated function.
Expand Down Expand Up @@ -258,6 +273,7 @@ def wrapped(*args, **kwargs):
combined_context_managers,
explicit_recovery=explicit_recovery,
explicit_cancellation=explicit_cancellation,
preemptable=preemptable,
)
if handler.name in self.handlers:
raise ValueError(f"Handler {handler.name} already exists in {self.name}")
Expand Down
4 changes: 3 additions & 1 deletion python/restate/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ async def send_discovery(scope: Scope, send: Send, endpoint: Endpoint):
# Negotiate discovery protocol version
version = 2
if accept_header:
if "application/vnd.restate.endpointmanifest.v5+json" in accept_header:
if "application/vnd.restate.endpointmanifest.v6+json" in accept_header:
version = 6
elif "application/vnd.restate.endpointmanifest.v5+json" in accept_header:
version = 5
elif "application/vnd.restate.endpointmanifest.v4+json" in accept_header:
version = 4
Expand Down
16 changes: 16 additions & 0 deletions python/restate/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ class Service:
see the handler option of the same name. NOTE: in preview, it might change without notice.
explicit_cancellation (bool, optional): (Preview) Explicit cancellation for all handlers of this service:
see the handler option of the same name. NOTE: in preview, it might change without notice.
preemptable (bool, optional): When set to False, Restate never preempts invocations of this service,
with all its handlers: it doesn't eagerly suspend them while they wait on an await point to free
concurrency capacity for other invocations. They still suspend when the inactivity timeout fires.
Defaults to True, and can be overridden per handler.
NOTE: Only restate-server versions supporting service discovery protocol V6 read this field. Against older
ones it is left out of the discovery, which is safe since they never preempt invocations.
"""

def __restate_services__(self) -> typing.Iterable["Servable"]:
Expand All @@ -101,6 +107,7 @@ def __init__(
] = None,
explicit_recovery: bool = False,
explicit_cancellation: bool = False,
preemptable: typing.Optional[bool] = None,
) -> None:
self.service_tag = ServiceTag("service", name, description, metadata)
self.handlers: typing.Dict[str, Handler] = {}
Expand All @@ -113,6 +120,7 @@ def __init__(
self.context_managers = invocation_context_managers
self.explicit_recovery = explicit_recovery
self.explicit_cancellation = explicit_cancellation
self.preemptable = preemptable

@property
def name(self):
Expand Down Expand Up @@ -140,6 +148,7 @@ def handler(
] = None,
explicit_recovery: bool = False,
explicit_cancellation: bool = False,
preemptable: typing.Optional[bool] = None,
) -> typing.Callable[[T], T]:
"""
Decorator for defining a handler function.
Expand Down Expand Up @@ -187,6 +196,12 @@ def handler(
explicit_cancellation: (Preview) If true, Restate cancelling an invocation neither fails the handler's
awaits nor cancels its calls: the handler awaits `restate._preview.cancellation(ctx)` and decides
what to stop. NOTE: in preview, it might change without notice.
preemptable: When set to False, Restate never preempts invocations of this handler: it doesn't eagerly
suspend them while they wait on an await point to free concurrency capacity for other invocations.
They still suspend when the inactivity timeout fires. Overrides the value set on the service, which
defaults to True.
NOTE: Only restate-server versions supporting service discovery protocol V6 read this field. Against
older ones it is left out of the discovery, which is safe since they never preempt invocations.

Returns:
Callable: The decorated function.
Expand Down Expand Up @@ -237,6 +252,7 @@ def wrapped(*args, **kwargs):
combined_context_managers,
explicit_recovery=explicit_recovery,
explicit_cancellation=explicit_cancellation,
preemptable=preemptable,
)
if handler.name in self.handlers:
raise ValueError(f"Handler {handler.name} already exists in {self.name}")
Expand Down
17 changes: 17 additions & 0 deletions python/restate/sessions/_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,15 @@ class SessionObject(VirtualObject):
invocation with an idempotency key.
ingress_private: Whether only other services may call it.
invocation_retry_policy: How Restate retries a failed invocation.
preemptable: When set to False, Restate never preempts invocations of
this object, with all its handlers and views: it doesn't eagerly
suspend them while they wait on an await point to free concurrency
capacity for other invocations. They still suspend when the
inactivity timeout fires. Defaults to True, and can be overridden
per handler or view.
NOTE: Only restate-server versions supporting service discovery
protocol V6 read it. Against older ones it is left out of the
discovery, which is safe since they never preempt invocations.

Raises:
TypeError: If ``migrations`` is a string rather than a list.
Expand All @@ -489,6 +498,7 @@ def __init__(
idempotency_retention: timedelta | None = None,
ingress_private: bool | None = None,
invocation_retry_policy: InvocationRetryPolicy | None = None,
preemptable: bool | None = None,
) -> None:
super().__init__(
name,
Expand All @@ -504,6 +514,7 @@ def __init__(
state_preload=[HEAD_KEY],
ingress_private=ingress_private,
invocation_retry_policy=invocation_retry_policy,
preemptable=preemptable,
)
self._config: ObjectConfig = ObjectConfig(schema=Schema(name, migrations) if steps_of(migrations) else None)
ENTRIES.on(self, {})
Expand Down Expand Up @@ -540,6 +551,7 @@ def handler(
ingress_private: bool | None = None,
invocation_retry_policy: InvocationRetryPolicy | None = None,
explicit_cancellation: bool = False,
preemptable: bool | None = None,
) -> Callable[[F], F]: ...

def handler( # pyright: ignore[reportIncompatibleMethodOverride]
Expand All @@ -558,6 +570,7 @@ def handler( # pyright: ignore[reportIncompatibleMethodOverride]
ingress_private: bool | None = None,
invocation_retry_policy: InvocationRetryPolicy | None = None,
explicit_cancellation: bool = False,
preemptable: bool | None = None,
) -> F | Callable[[F], F]:
"""Register a handler, used bare (``@obj.handler``) or with options (``@obj.handler(...)``).

Expand Down Expand Up @@ -608,6 +621,7 @@ async def add(ctx: sessions.SessionContext, text: str) -> None:
"idempotency_retention": idempotency_retention,
"ingress_private": ingress_private,
"invocation_retry_policy": invocation_retry_policy,
"preemptable": preemptable,
},
)

Expand All @@ -630,6 +644,7 @@ def view(
idempotency_retention: timedelta | None = None,
ingress_private: bool | None = None,
invocation_retry_policy: InvocationRetryPolicy | None = None,
preemptable: bool | None = None,
) -> Callable[[F], F]: ...

def view(
Expand All @@ -647,6 +662,7 @@ def view(
idempotency_retention: timedelta | None = None,
ingress_private: bool | None = None,
invocation_retry_policy: InvocationRetryPolicy | None = None,
preemptable: bool | None = None,
) -> F | Callable[[F], F]:
"""Register a view, used bare (``@obj.view``) or with options (``@obj.view(...)``).

Expand Down Expand Up @@ -690,6 +706,7 @@ async def count(ctx: sessions.ViewContext) -> int:
"idempotency_retention": idempotency_retention,
"ingress_private": ingress_private,
"invocation_retry_policy": invocation_retry_policy,
"preemptable": preemptable,
},
)

Expand Down
Loading
Loading