From 6b2e9dbbad19ae4e80260afb86e15a422b7e2991 Mon Sep 17 00:00:00 2001 From: Stephan Ewen Date: Mon, 23 Nov 2026 13:54:20 +0100 Subject: [PATCH] Let services and handlers declare themselves non-preemptable Adds a `preemptable` option on services and handlers (default true, the handler setting overrides the service one), sent in the endpoint manifest under service discovery protocol V6. When false, the runtime never eagerly suspends invocations of the handler to free concurrency capacity; they still suspend on the inactivity timeout. For runtimes that negotiate an older discovery version the field is dropped instead of failing discovery, since those runtimes never preempt invocations. --- python/restate/agents/_object.py | 19 ++++++++++ python/restate/discovery.py | 14 ++++++++ python/restate/handler.py | 5 +++ python/restate/object.py | 16 +++++++++ python/restate/server.py | 4 ++- python/restate/service.py | 16 +++++++++ python/restate/sessions/_object.py | 17 +++++++++ python/restate/workflow.py | 32 +++++++++++++++++ tests/discovery.py | 57 ++++++++++++++++++++++++++++++ 9 files changed, 179 insertions(+), 1 deletion(-) diff --git a/python/restate/agents/_object.py b/python/restate/agents/_object.py index f19b774a..791cbdf4 100644 --- a/python/restate/agents/_object.py +++ b/python/restate/agents/_object.py @@ -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 @@ -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) @@ -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__( @@ -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, @@ -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 diff --git a/python/restate/discovery.py b/python/restate/discovery.py index 38d26e2b..b49bb636 100644 --- a/python/restate/discovery.py +++ b/python/restate/discovery.py @@ -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, @@ -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 @@ -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, @@ -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 @@ -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. @@ -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 ) @@ -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, diff --git a/python/restate/handler.py b/python/restate/handler.py index c4d69c7a..2be3f765 100644 --- a/python/restate/handler.py +++ b/python/restate/handler.py @@ -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 @@ -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 @@ -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. @@ -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). @@ -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, diff --git a/python/restate/object.py b/python/restate/object.py index 7adb00c7..bfa018e1 100644 --- a/python/restate/object.py +++ b/python/restate/object.py @@ -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]] @@ -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 = {} @@ -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): @@ -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. @@ -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. @@ -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}") diff --git a/python/restate/server.py b/python/restate/server.py index ebd39272..119dfc13 100644 --- a/python/restate/server.py +++ b/python/restate/server.py @@ -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 diff --git a/python/restate/service.py b/python/restate/service.py index f6c85d72..c56f8b28 100644 --- a/python/restate/service.py +++ b/python/restate/service.py @@ -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"]: @@ -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] = {} @@ -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): @@ -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. @@ -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. @@ -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}") diff --git a/python/restate/sessions/_object.py b/python/restate/sessions/_object.py index ba96a5ce..f6ec5182 100644 --- a/python/restate/sessions/_object.py +++ b/python/restate/sessions/_object.py @@ -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. @@ -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, @@ -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, {}) @@ -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] @@ -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(...)``). @@ -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, }, ) @@ -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( @@ -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(...)``). @@ -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, }, ) diff --git a/python/restate/workflow.py b/python/restate/workflow.py index c3873664..0da24565 100644 --- a/python/restate/workflow.py +++ b/python/restate/workflow.py @@ -88,6 +88,12 @@ class Workflow: 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 workflow: 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 workflow, + 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]] @@ -117,6 +123,7 @@ def __init__( ] = None, explicit_recovery: bool = False, explicit_cancellation: bool = False, + preemptable: typing.Optional[bool] = None, ): self.service_tag = ServiceTag("workflow", name, description, metadata) self.handlers = {} @@ -132,6 +139,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): @@ -161,6 +169,7 @@ def main( ] = None, explicit_recovery: bool = False, explicit_cancellation: bool = False, + preemptable: typing.Optional[bool] = None, ) -> typing.Callable[[T], T]: """ Mark this handler as a workflow entry point. @@ -214,6 +223,12 @@ def main( 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. """ return self._add_handler( name, @@ -235,6 +250,7 @@ def main( invocation_context_managers=invocation_context_managers, explicit_recovery=explicit_recovery, explicit_cancellation=explicit_cancellation, + preemptable=preemptable, ) def handler( @@ -258,6 +274,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. @@ -312,6 +329,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. """ return self._add_handler( name, @@ -333,6 +356,7 @@ def handler( invocation_context_managers, explicit_recovery=explicit_recovery, explicit_cancellation=explicit_cancellation, + preemptable=preemptable, ) # pylint: disable=R0914 @@ -359,6 +383,7 @@ def _add_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. @@ -407,6 +432,12 @@ def _add_handler( NOTE: You can set this field only if you register this service against restate-server >= 1.4, otherwise the service discovery will fail. invocation_retry_policy (InvocationRetryPolicy, optional): Retry policy applied for all invocations to this handler. + 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. @@ -455,6 +486,7 @@ def wrapped(*args, **kwargs): context_managers=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}") diff --git a/tests/discovery.py b/tests/discovery.py index 4ef17979..0053fd9b 100644 --- a/tests/discovery.py +++ b/tests/discovery.py @@ -10,12 +10,14 @@ # import json from datetime import timedelta +from typing import Any import pytest import restate from restate.discovery import compute_discovery, compute_discovery_json from restate.endpoint import Endpoint +from restate.server import send_discovery def test_zero_durations_are_preserved_in_manifest(): @@ -199,3 +201,58 @@ async def handle(ctx: restate.ObjectContext): manifest = json.loads(compute_discovery_json(Endpoint().bind(obj), 4, "bidi")) assert manifest["services"][0]["enableLazyState"] is True assert "eagerStateKeysWhitelist" not in manifest["services"][0] + + +def _preemptable_endpoint() -> Endpoint: + service = restate.Service("Svc", preemptable=False) + + @service.handler(preemptable=True) + async def overridden(ctx: restate.Context): + pass + + @service.handler() + async def inherited(ctx: restate.Context): + pass + + wf = restate.Workflow("Wf") + + @wf.main(preemptable=False) + async def run(ctx: restate.WorkflowContext): + pass + + return Endpoint().bind(service, wf) + + +def test_preemptable_is_emitted_only_when_set(): + svc, wf = json.loads(compute_discovery_json(_preemptable_endpoint(), 6, "bidi"))["services"] + assert svc["preemptable"] is False + handlers = {h["name"]: h for h in svc["handlers"]} + assert handlers["overridden"]["preemptable"] is True + assert "preemptable" not in handlers["inherited"] + assert "preemptable" not in wf + assert wf["handlers"][0]["preemptable"] is False + + +@pytest.mark.anyio +@pytest.mark.parametrize( + "accept, version", + [ + ("application/vnd.restate.endpointmanifest.v5+json, application/vnd.restate.endpointmanifest.v6+json", 6), + ("application/vnd.restate.endpointmanifest.v5+json", 5), + ], +) +async def test_discovery_negotiates_v6_and_drops_preemptable_below_it(accept: str, version: int): + sent: list[dict[str, Any]] = [] + + async def send(message): + sent.append(message) + + scope = {"http_version": "2", "headers": [(b"accept", accept.encode())]} + await send_discovery(scope, send, _preemptable_endpoint()) # type: ignore[arg-type] + + assert sent[0]["status"] == 200 + assert (b"content-type", f"application/vnd.restate.endpointmanifest.v{version}+json".encode()) in sent[0]["headers"] + services = json.loads(sent[1]["body"])["services"] + emitted = [entity for svc in services for entity in [svc, *svc["handlers"]] if "preemptable" in entity] + # Runtimes older than V6 never preempt invocations: the flag is dropped, not rejected. + assert len(emitted) == (3 if version >= 6 else 0)