prefect-client 3.3.4.dev3__py3-none-any.whl → 3.3.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
prefect/_build_info.py CHANGED
@@ -1,5 +1,5 @@
1
1
  # Generated by versioningit
2
- __version__ = "3.3.4.dev3"
3
- __build_date__ = "2025-04-10 08:08:19.507291+00:00"
4
- __git_commit__ = "b2c74894cacb929a747cf8169975fd731e9c28cb"
2
+ __version__ = "3.3.5"
3
+ __build_date__ = "2025-04-17 21:24:54.247813+00:00"
4
+ __git_commit__ = "db4b7a338ee0030ad0905d803a5ea5167d2a0711"
5
5
  __dirty__ = False
@@ -8,6 +8,7 @@ import multiprocessing.context
8
8
  import os
9
9
  import subprocess
10
10
  import sys
11
+ from pathlib import Path
11
12
  from typing import Any, TypedDict
12
13
 
13
14
  import cloudpickle
@@ -99,7 +100,9 @@ def extract_flow_from_bundle(bundle: SerializedBundle) -> Flow[Any, Any]:
99
100
 
100
101
 
101
102
  def _extract_and_run_flow(
102
- bundle: SerializedBundle, env: dict[str, Any] | None = None
103
+ bundle: SerializedBundle,
104
+ cwd: Path | str | None = None,
105
+ env: dict[str, Any] | None = None,
103
106
  ) -> None:
104
107
  """
105
108
  Extracts a flow from a bundle and runs it.
@@ -108,6 +111,7 @@ def _extract_and_run_flow(
108
111
 
109
112
  Args:
110
113
  bundle: The bundle to extract and run.
114
+ cwd: The working directory to use when running the flow.
111
115
  env: The environment to use when running the flow.
112
116
  """
113
117
 
@@ -120,6 +124,9 @@ def _extract_and_run_flow(
120
124
  context = _deserialize_bundle_object(bundle["context"])
121
125
  flow_run = FlowRun.model_validate(bundle["flow_run"])
122
126
 
127
+ if cwd:
128
+ os.chdir(cwd)
129
+
123
130
  with SettingsContext(
124
131
  profile=settings_context.profile,
125
132
  settings=Settings(),
@@ -138,6 +145,8 @@ def _extract_and_run_flow(
138
145
 
139
146
  def execute_bundle_in_subprocess(
140
147
  bundle: SerializedBundle,
148
+ env: dict[str, Any] | None = None,
149
+ cwd: Path | str | None = None,
141
150
  ) -> multiprocessing.context.SpawnProcess:
142
151
  """
143
152
  Executes a bundle in a subprocess.
@@ -150,6 +159,7 @@ def execute_bundle_in_subprocess(
150
159
  """
151
160
 
152
161
  ctx = multiprocessing.get_context("spawn")
162
+ env = env or {}
153
163
 
154
164
  # Install dependencies if necessary
155
165
  if dependencies := bundle.get("dependencies"):
@@ -164,7 +174,9 @@ def execute_bundle_in_subprocess(
164
174
  kwargs={
165
175
  "bundle": bundle,
166
176
  "env": get_current_settings().to_environment_variables(exclude_unset=True)
167
- | os.environ,
177
+ | os.environ
178
+ | env,
179
+ "cwd": cwd,
168
180
  },
169
181
  )
170
182
 
prefect/cache_policies.py CHANGED
@@ -33,9 +33,9 @@ def _register_stable_transforms() -> None:
33
33
  so that cache keys that utilize them are deterministic across invocations.
34
34
  """
35
35
  try:
36
- import pandas as pd
36
+ import pandas as pd # pyright: ignore
37
37
 
38
- STABLE_TRANSFORMS[pd.DataFrame] = lambda df: [
38
+ STABLE_TRANSFORMS[pd.DataFrame] = lambda df: [ # pyright: ignore
39
39
  df[col] for col in sorted(df.columns)
40
40
  ]
41
41
  except (ImportError, ModuleNotFoundError):
@@ -183,7 +183,7 @@ class CompoundCachePolicy(CachePolicy):
183
183
  Any keys that return `None` will be ignored.
184
184
  """
185
185
 
186
- policies: list[CachePolicy] = field(default_factory=list)
186
+ policies: list[CachePolicy] = field(default_factory=lambda: [])
187
187
 
188
188
  def __post_init__(self) -> None:
189
189
  # flatten any CompoundCachePolicies
@@ -349,7 +349,7 @@ class Inputs(CachePolicy):
349
349
  Policy that computes a cache key based on a hash of the runtime inputs provided to the task..
350
350
  """
351
351
 
352
- exclude: list[str] = field(default_factory=list)
352
+ exclude: list[str] = field(default_factory=lambda: [])
353
353
 
354
354
  def compute_key(
355
355
  self,
prefect/events/clients.py CHANGED
@@ -39,6 +39,7 @@ import prefect.types._datetime
39
39
  from prefect.events import Event
40
40
  from prefect.logging import get_logger
41
41
  from prefect.settings import (
42
+ PREFECT_API_AUTH_STRING,
42
43
  PREFECT_API_KEY,
43
44
  PREFECT_API_SSL_CERT_FILE,
44
45
  PREFECT_API_TLS_INSECURE_SKIP_VERIFY,
@@ -367,7 +368,7 @@ class PrefectEventsClient(EventsClient):
367
368
  await self._connect.__aexit__(exc_type, exc_val, exc_tb)
368
369
  return await super().__aexit__(exc_type, exc_val, exc_tb)
369
370
 
370
- def _log_debug(self, message: str, *args, **kwargs) -> None:
371
+ def _log_debug(self, message: str, *args: Any, **kwargs: Any) -> None:
371
372
  message = f"EventsClient(id={id(self)}): " + message
372
373
  logger.debug(message, *args, **kwargs)
373
374
 
@@ -578,6 +579,7 @@ class PrefectEventSubscriber:
578
579
  _seen_events: MutableMapping[UUID, bool]
579
580
 
580
581
  _api_key: Optional[str]
582
+ _auth_token: Optional[str]
581
583
 
582
584
  def __init__(
583
585
  self,
@@ -593,6 +595,8 @@ class PrefectEventSubscriber:
593
595
  the client should attempt to reconnect
594
596
  """
595
597
  self._api_key = None
598
+ self._auth_token = PREFECT_API_AUTH_STRING.value()
599
+
596
600
  if not api_url:
597
601
  api_url = cast(str, PREFECT_API_URL.value())
598
602
 
@@ -641,8 +645,10 @@ class PrefectEventSubscriber:
641
645
  await pong
642
646
 
643
647
  logger.debug(" authenticating...")
648
+ # Use the API key (for Cloud) OR the auth token (for self-hosted with auth string)
649
+ token = self._api_key or self._auth_token
644
650
  await self._websocket.send(
645
- orjson.dumps({"type": "auth", "token": self._api_key}).decode()
651
+ orjson.dumps({"type": "auth", "token": token}).decode()
646
652
  )
647
653
 
648
654
  try:
@@ -652,13 +658,13 @@ class PrefectEventSubscriber:
652
658
  except AssertionError as e:
653
659
  raise Exception(
654
660
  "Unable to authenticate to the event stream. Please ensure the "
655
- "provided api_key you are using is valid for this environment. "
661
+ "provided api_key or auth_token you are using is valid for this environment. "
656
662
  f"Reason: {e.args[0]}"
657
663
  )
658
664
  except ConnectionClosedError as e:
659
665
  reason = getattr(e.rcvd, "reason", None)
660
666
  msg = "Unable to authenticate to the event stream. Please ensure the "
661
- msg += "provided api_key you are using is valid for this environment. "
667
+ msg += "provided api_key or auth_token you are using is valid for this environment. "
662
668
  msg += f"Reason: {reason}" if reason else ""
663
669
  raise Exception(msg) from e
664
670
 
prefect/flows.py CHANGED
@@ -40,6 +40,7 @@ from typing import (
40
40
  from uuid import UUID
41
41
 
42
42
  import pydantic
43
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup
43
44
  from pydantic.v1 import BaseModel as V1BaseModel
44
45
  from pydantic.v1.decorator import ValidatedFunction as V1ValidatedFunction
45
46
  from pydantic.v1.errors import ConfigError # TODO
@@ -105,6 +106,9 @@ from ._internal.pydantic.v2_validated_func import (
105
106
  V2ValidatedFunction as ValidatedFunction,
106
107
  )
107
108
 
109
+ if TYPE_CHECKING:
110
+ from prefect.workers.base import BaseWorker
111
+
108
112
  T = TypeVar("T") # Generic type var for capturing the inner return type of async funcs
109
113
  R = TypeVar("R") # The return type of the user's function
110
114
  P = ParamSpec("P") # The parameters of the flow
@@ -1130,7 +1134,7 @@ class Flow(Generic[P, R]):
1130
1134
  @classmethod
1131
1135
  async def afrom_source(
1132
1136
  cls,
1133
- source: Union[str, "RunnerStorage", ReadableDeploymentStorage],
1137
+ source: Union[str, Path, "RunnerStorage", ReadableDeploymentStorage],
1134
1138
  entrypoint: str,
1135
1139
  ) -> "Flow[..., Any]":
1136
1140
  """
@@ -1244,7 +1248,7 @@ class Flow(Generic[P, R]):
1244
1248
  @async_dispatch(afrom_source)
1245
1249
  def from_source(
1246
1250
  cls,
1247
- source: Union[str, "RunnerStorage", ReadableDeploymentStorage],
1251
+ source: Union[str, Path, "RunnerStorage", ReadableDeploymentStorage],
1248
1252
  entrypoint: str,
1249
1253
  ) -> "Flow[..., Any]":
1250
1254
  """
@@ -1976,7 +1980,7 @@ class FlowDecorator:
1976
1980
  # manually here.
1977
1981
  @staticmethod
1978
1982
  def from_source(
1979
- source: Union[str, "RunnerStorage", ReadableDeploymentStorage],
1983
+ source: Union[str, Path, "RunnerStorage", ReadableDeploymentStorage],
1980
1984
  entrypoint: str,
1981
1985
  ) -> Union["Flow[..., Any]", Coroutine[Any, Any, "Flow[..., Any]"]]: ...
1982
1986
 
@@ -1984,6 +1988,141 @@ class FlowDecorator:
1984
1988
  flow: FlowDecorator = FlowDecorator()
1985
1989
 
1986
1990
 
1991
+ class InfrastructureBoundFlow(Flow[P, R]):
1992
+ """
1993
+ EXPERIMENTAL: This class is experimental and may be removed or changed in future
1994
+ releases.
1995
+
1996
+ A flow that is bound to running on a specific infrastructure.
1997
+
1998
+ Attributes:
1999
+ work_pool: The name of the work pool to run the flow on. The base job
2000
+ configuration of the work pool will determine the configuration of the
2001
+ infrastructure the flow will run on.
2002
+ job_variables: Infrastructure configuration that will override the base job
2003
+ configuration of the work pool.
2004
+ worker_cls: The class of the worker to use to spin up infrastructure and submit
2005
+ the flow to it.
2006
+ """
2007
+
2008
+ def __init__(
2009
+ self,
2010
+ *args: Any,
2011
+ work_pool: str,
2012
+ job_variables: dict[str, Any],
2013
+ worker_cls: type["BaseWorker[Any, Any, Any]"],
2014
+ **kwargs: Any,
2015
+ ):
2016
+ super().__init__(*args, **kwargs)
2017
+ self.work_pool = work_pool
2018
+ self.job_variables = job_variables
2019
+ self.worker_cls = worker_cls
2020
+
2021
+ @overload
2022
+ def __call__(self: "Flow[P, NoReturn]", *args: P.args, **kwargs: P.kwargs) -> None:
2023
+ # `NoReturn` matches if a type can't be inferred for the function which stops a
2024
+ # sync function from matching the `Coroutine` overload
2025
+ ...
2026
+
2027
+ @overload
2028
+ def __call__(
2029
+ self: "Flow[P, Coroutine[Any, Any, T]]",
2030
+ *args: P.args,
2031
+ **kwargs: P.kwargs,
2032
+ ) -> Coroutine[Any, Any, T]: ...
2033
+
2034
+ @overload
2035
+ def __call__(
2036
+ self: "Flow[P, T]",
2037
+ *args: P.args,
2038
+ **kwargs: P.kwargs,
2039
+ ) -> T: ...
2040
+
2041
+ @overload
2042
+ def __call__(
2043
+ self: "Flow[P, Coroutine[Any, Any, T]]",
2044
+ *args: P.args,
2045
+ return_state: Literal[True],
2046
+ **kwargs: P.kwargs,
2047
+ ) -> Awaitable[State[T]]: ...
2048
+
2049
+ @overload
2050
+ def __call__(
2051
+ self: "Flow[P, T]",
2052
+ *args: P.args,
2053
+ return_state: Literal[True],
2054
+ **kwargs: P.kwargs,
2055
+ ) -> State[T]: ...
2056
+
2057
+ def __call__(
2058
+ self,
2059
+ *args: "P.args",
2060
+ return_state: bool = False,
2061
+ wait_for: Optional[Iterable[PrefectFuture[Any]]] = None,
2062
+ **kwargs: "P.kwargs",
2063
+ ):
2064
+ async def modified_call(
2065
+ *args: P.args,
2066
+ return_state: bool = False,
2067
+ # TODO: Handle wait_for once we have an asynchronous way to wait for futures
2068
+ # We should wait locally for futures to resolve before spinning up
2069
+ # infrastructure.
2070
+ wait_for: Optional[Iterable[PrefectFuture[Any]]] = None,
2071
+ **kwargs: P.kwargs,
2072
+ ) -> R | State[R]:
2073
+ try:
2074
+ async with self.worker_cls(work_pool_name=self.work_pool) as worker:
2075
+ parameters = get_call_parameters(self, args, kwargs)
2076
+ future = await worker.submit(
2077
+ flow=self,
2078
+ parameters=parameters,
2079
+ job_variables=self.job_variables,
2080
+ )
2081
+ if return_state:
2082
+ await future.wait_async()
2083
+ return future.state
2084
+ return await future.aresult()
2085
+ except (ExceptionGroup, BaseExceptionGroup) as exc:
2086
+ # For less verbose tracebacks
2087
+ exceptions = exc.exceptions
2088
+ if len(exceptions) == 1:
2089
+ raise exceptions[0] from None
2090
+ else:
2091
+ raise
2092
+
2093
+ if inspect.iscoroutinefunction(self.fn):
2094
+ return modified_call(
2095
+ *args, return_state=return_state, wait_for=wait_for, **kwargs
2096
+ )
2097
+ else:
2098
+ return run_coro_as_sync(
2099
+ modified_call(
2100
+ *args,
2101
+ return_state=return_state,
2102
+ wait_for=wait_for,
2103
+ **kwargs,
2104
+ )
2105
+ )
2106
+
2107
+
2108
+ def bind_flow_to_infrastructure(
2109
+ flow: Flow[P, R],
2110
+ work_pool: str,
2111
+ worker_cls: type["BaseWorker[Any, Any, Any]"],
2112
+ job_variables: dict[str, Any] | None = None,
2113
+ ) -> InfrastructureBoundFlow[P, R]:
2114
+ new = InfrastructureBoundFlow[P, R](
2115
+ flow.fn,
2116
+ work_pool=work_pool,
2117
+ job_variables=job_variables or {},
2118
+ worker_cls=worker_cls,
2119
+ )
2120
+ # Copy all attributes from the original flow
2121
+ for attr, value in flow.__dict__.items():
2122
+ setattr(new, attr, value)
2123
+ return new
2124
+
2125
+
1987
2126
  def _raise_on_name_with_banned_characters(name: Optional[str]) -> Optional[str]:
1988
2127
  """
1989
2128
  Raise an InvalidNameError if the given name contains any invalid
prefect/locking/memory.py CHANGED
@@ -1,6 +1,8 @@
1
+ from __future__ import annotations
2
+
1
3
  import asyncio
2
4
  import threading
3
- from typing import Any, Optional, TypedDict
5
+ from typing import Any, TypedDict
4
6
 
5
7
  from typing_extensions import Self
6
8
 
@@ -19,7 +21,7 @@ class _LockInfo(TypedDict):
19
21
 
20
22
  holder: str
21
23
  lock: threading.Lock
22
- expiration_timer: Optional[threading.Timer]
24
+ expiration_timer: threading.Timer | None
23
25
 
24
26
 
25
27
  class MemoryLockManager(LockManager):
@@ -63,8 +65,8 @@ class MemoryLockManager(LockManager):
63
65
  self,
64
66
  key: str,
65
67
  holder: str,
66
- acquire_timeout: Optional[float] = None,
67
- hold_timeout: Optional[float] = None,
68
+ acquire_timeout: float | None = None,
69
+ hold_timeout: float | None = None,
68
70
  ) -> bool:
69
71
  with self._locks_dict_lock:
70
72
  if key not in self._locks:
@@ -116,13 +118,13 @@ class MemoryLockManager(LockManager):
116
118
  self,
117
119
  key: str,
118
120
  holder: str,
119
- acquire_timeout: Optional[float] = None,
120
- hold_timeout: Optional[float] = None,
121
+ acquire_timeout: float | None = None,
122
+ hold_timeout: float | None = None,
121
123
  ) -> bool:
122
124
  with self._locks_dict_lock:
123
125
  if key not in self._locks:
124
126
  lock = threading.Lock()
125
- await asyncio.to_thread(lock.acquire)
127
+ lock.acquire()
126
128
  expiration_timer = None
127
129
  if hold_timeout is not None:
128
130
  expiration_timer = threading.Timer(
@@ -192,7 +194,7 @@ class MemoryLockManager(LockManager):
192
194
  and lock_info["holder"] == holder
193
195
  )
194
196
 
195
- def wait_for_lock(self, key: str, timeout: Optional[float] = None) -> bool:
197
+ def wait_for_lock(self, key: str, timeout: float | None = None) -> bool:
196
198
  lock_info: _LockInfo | None = self._locks.get(key)
197
199
  if lock_info is None:
198
200
  return True
@@ -206,7 +208,7 @@ class MemoryLockManager(LockManager):
206
208
  return lock_acquired
207
209
  return True
208
210
 
209
- async def await_for_lock(self, key: str, timeout: Optional[float] = None) -> bool:
211
+ async def await_for_lock(self, key: str, timeout: float | None = None) -> bool:
210
212
  lock_info: _LockInfo | None = self._locks.get(key, None)
211
213
  if lock_info is None:
212
214
  return True
prefect/results.py CHANGED
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import asyncio
3
4
  import inspect
4
5
  import os
5
6
  import socket
@@ -33,6 +34,7 @@ from typing_extensions import ParamSpec, Self
33
34
  import prefect
34
35
  import prefect.types._datetime
35
36
  from prefect._internal.compatibility.async_dispatch import async_dispatch
37
+ from prefect._internal.concurrency.event_loop import get_running_loop
36
38
  from prefect._result_records import R, ResultRecord, ResultRecordMetadata
37
39
  from prefect.blocks.core import Block
38
40
  from prefect.exceptions import (
@@ -475,10 +477,17 @@ class ResultStore(BaseModel):
475
477
  Returns:
476
478
  str: A unique identifier string.
477
479
  """
480
+ current_loop = get_running_loop()
478
481
  hostname = socket.gethostname()
479
482
  pid = os.getpid()
480
483
  thread_name = threading.current_thread().name
481
484
  thread_id = threading.get_ident()
485
+ if current_loop:
486
+ current_task = asyncio.current_task()
487
+ if current_task:
488
+ # include the task id to ensure uniqueness because there might be
489
+ # multiple tasks running in the same thread
490
+ return f"{hostname}:{pid}:{thread_id}:{thread_name}:{id(current_task)}"
482
491
  return f"{hostname}:{pid}:{thread_id}:{thread_name}"
483
492
 
484
493
  @sync_compatible
prefect/runner/runner.py CHANGED
@@ -636,7 +636,12 @@ class Runner:
636
636
 
637
637
  return process
638
638
 
639
- async def execute_bundle(self, bundle: SerializedBundle) -> None:
639
+ async def execute_bundle(
640
+ self,
641
+ bundle: SerializedBundle,
642
+ cwd: Path | str | None = None,
643
+ env: dict[str, str | None] | None = None,
644
+ ) -> None:
640
645
  """
641
646
  Executes a bundle in a subprocess.
642
647
  """
@@ -651,7 +656,7 @@ class Runner:
651
656
  if not self._acquire_limit_slot(flow_run.id):
652
657
  return
653
658
 
654
- process = execute_bundle_in_subprocess(bundle)
659
+ process = execute_bundle_in_subprocess(bundle, cwd=cwd, env=env)
655
660
 
656
661
  if process.pid is None:
657
662
  # This shouldn't happen because `execute_bundle_in_subprocess` starts the process
@@ -776,7 +781,7 @@ class Runner:
776
781
  if command is None:
777
782
  runner_command = [get_sys_executable(), "-m", "prefect.engine"]
778
783
  else:
779
- runner_command = shlex.split(command)
784
+ runner_command = shlex.split(command, posix=(os.name != "nt"))
780
785
 
781
786
  flow_run_logger = self._get_flow_run_logger(flow_run)
782
787
 
@@ -911,6 +911,7 @@ async def update_deployment_schedule(
911
911
  session=session,
912
912
  deployment_id=deployment_id,
913
913
  auto_scheduled_only=True,
914
+ future_only=True,
914
915
  )
915
916
 
916
917
 
prefect/states.py CHANGED
@@ -776,7 +776,7 @@ def AwaitingRetry(
776
776
  """Convenience function for creating `AwaitingRetry` states.
777
777
 
778
778
  Returns:
779
- State: a AwaitingRetry state
779
+ State: an AwaitingRetry state
780
780
  """
781
781
  return Scheduled(
782
782
  cls=cls, scheduled_time=scheduled_time, name="AwaitingRetry", **kwargs
@@ -791,7 +791,7 @@ def AwaitingConcurrencySlot(
791
791
  """Convenience function for creating `AwaitingConcurrencySlot` states.
792
792
 
793
793
  Returns:
794
- State: a AwaitingConcurrencySlot state
794
+ State: an AwaitingConcurrencySlot state
795
795
  """
796
796
  return Scheduled(
797
797
  cls=cls, scheduled_time=scheduled_time, name="AwaitingConcurrencySlot", **kwargs
prefect/task_engine.py CHANGED
@@ -81,7 +81,13 @@ from prefect.states import (
81
81
  return_value_to_state,
82
82
  )
83
83
  from prefect.telemetry.run_telemetry import RunTelemetry
84
- from prefect.transactions import IsolationLevel, Transaction, transaction
84
+ from prefect.transactions import (
85
+ AsyncTransaction,
86
+ IsolationLevel,
87
+ Transaction,
88
+ atransaction,
89
+ transaction,
90
+ )
85
91
  from prefect.utilities._engine import get_hook_name
86
92
  from prefect.utilities.annotations import NotSet
87
93
  from prefect.utilities.asyncutils import run_coro_as_sync
@@ -1020,7 +1026,7 @@ class AsyncTaskRunEngine(BaseTaskRunEngine[P, R]):
1020
1026
  # otherwise, return the exception
1021
1027
  return self._raised
1022
1028
 
1023
- async def handle_success(self, result: R, transaction: Transaction) -> R:
1029
+ async def handle_success(self, result: R, transaction: AsyncTransaction) -> R:
1024
1030
  if self.task.cache_expiration is not None:
1025
1031
  expiration = prefect.types._datetime.now("UTC") + self.task.cache_expiration
1026
1032
  else:
@@ -1302,7 +1308,7 @@ class AsyncTaskRunEngine(BaseTaskRunEngine[P, R]):
1302
1308
  await self.call_hooks()
1303
1309
 
1304
1310
  @asynccontextmanager
1305
- async def transaction_context(self) -> AsyncGenerator[Transaction, None]:
1311
+ async def transaction_context(self) -> AsyncGenerator[AsyncTransaction, None]:
1306
1312
  # refresh cache setting is now repurposes as overwrite transaction record
1307
1313
  overwrite = (
1308
1314
  self.task.refresh_cache
@@ -1317,7 +1323,7 @@ class AsyncTaskRunEngine(BaseTaskRunEngine[P, R]):
1317
1323
  else None
1318
1324
  )
1319
1325
 
1320
- with transaction(
1326
+ async with atransaction(
1321
1327
  key=self.compute_transaction_key(),
1322
1328
  store=get_result_store(),
1323
1329
  overwrite=overwrite,
@@ -1349,7 +1355,7 @@ class AsyncTaskRunEngine(BaseTaskRunEngine[P, R]):
1349
1355
  await self.handle_exception(exc)
1350
1356
 
1351
1357
  async def call_task_fn(
1352
- self, transaction: Transaction
1358
+ self, transaction: AsyncTransaction
1353
1359
  ) -> Union[R, Coroutine[Any, Any, R]]:
1354
1360
  """
1355
1361
  Convenience method to call the task function. Returns a coroutine if the
@@ -1357,7 +1363,7 @@ class AsyncTaskRunEngine(BaseTaskRunEngine[P, R]):
1357
1363
  """
1358
1364
  parameters = self.parameters or {}
1359
1365
  if transaction.is_committed():
1360
- result = transaction.read()
1366
+ result = await transaction.read()
1361
1367
  else:
1362
1368
  result = await call_with_parameters(self.task.fn, parameters)
1363
1369
  await self.handle_success(result, transaction=transaction)
prefect/tasks.py CHANGED
@@ -764,11 +764,6 @@ class Task(Generic[P, R]):
764
764
  def on_rollback(
765
765
  self, fn: Callable[["Transaction"], None]
766
766
  ) -> Callable[["Transaction"], None]:
767
- if asyncio.iscoroutinefunction(fn):
768
- raise ValueError(
769
- "Asynchronous rollback hooks are not yet supported. Rollback hooks must be synchronous functions."
770
- )
771
-
772
767
  self.on_rollback_hooks.append(fn)
773
768
  return fn
774
769
 
@@ -1,6 +1,6 @@
1
1
  import logging
2
- import os
3
2
  import re
3
+ import socket
4
4
  from typing import TYPE_CHECKING
5
5
  from urllib.parse import urljoin
6
6
  from uuid import UUID
@@ -74,7 +74,7 @@ def setup_exporters(
74
74
  resource = Resource.create(
75
75
  {
76
76
  "service.name": "prefect",
77
- "service.instance.id": os.uname().nodename,
77
+ "service.instance.id": socket.gethostname(),
78
78
  "prefect.account": str(account_id),
79
79
  "prefect.workspace": str(workspace_id),
80
80
  }