prefect 3.9.1.dev8__py3-none-any.whl → 3.9.2.dev2__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.
Files changed (102) hide show
  1. prefect/AGENTS.md +1 -1
  2. prefect/_build_info.py +3 -3
  3. prefect/cli/AGENTS.md +1 -1
  4. prefect/cli/artifact.py +2 -2
  5. prefect/cli/block.py +4 -4
  6. prefect/concurrency/AGENTS.md +1 -1
  7. prefect/concurrency/_leases.py +64 -8
  8. prefect/flow_engine.py +8 -2
  9. prefect/flow_runs.py +14 -1
  10. prefect/flows.py +5 -5
  11. prefect/server/AGENTS.md +3 -2
  12. prefect/server/api/deployments.py +8 -2
  13. prefect/server/api/flow_runs.py +18 -8
  14. prefect/server/api/server.py +61 -7
  15. prefect/server/api/work_queues.py +19 -5
  16. prefect/server/api/workers.py +52 -8
  17. prefect/server/models/deployments.py +31 -0
  18. prefect/server/models/work_queues.py +36 -10
  19. prefect/server/orchestration/core_policy.py +34 -1
  20. prefect/server/schemas/schedules.py +19 -73
  21. prefect/server/services/task_run_recorder.py +56 -6
  22. prefect/server/ui-v2/assets/{artifact-data-view-ChmGUw5g.js → artifact-data-view-BvNVCoeh.js} +1 -1
  23. prefect/server/ui-v2/assets/{artifact._id-gTkmxwMz.js → artifact._id-kn4FfYeS.js} +1 -1
  24. prefect/server/ui-v2/assets/{artifacts-DWhoPQIF.js → artifacts-B-0bc-yH.js} +1 -1
  25. prefect/server/ui-v2/assets/{automation-wizard-DPhsjWWB.js → automation-wizard-DIHGfhzY.js} +1 -1
  26. prefect/server/ui-v2/assets/{automation._id-5a1i0jbO.js → automation._id-CMdNKW9_.js} +1 -1
  27. prefect/server/ui-v2/assets/{automation_._id.edit-D-X40qPn.js → automation_._id.edit-MWO3JC4p.js} +1 -1
  28. prefect/server/ui-v2/assets/{automations-C3d3UkSS.js → automations-ClVYZZl7.js} +1 -1
  29. prefect/server/ui-v2/assets/{automations-header-oZET2MAp.js → automations-header-DI4iaAAk.js} +1 -1
  30. prefect/server/ui-v2/assets/{automations-D0UMPApa.js → automations-j-O0F0nW.js} +1 -1
  31. prefect/server/ui-v2/assets/{automations-wizard-DRvF_EJK.js → automations-wizard-BHzU9JfF.js} +1 -1
  32. prefect/server/ui-v2/assets/{base-job-template-form-section-BRaQnrX_.js → base-job-template-form-section-DnDhjRMt.js} +1 -1
  33. prefect/server/ui-v2/assets/{block-type-details-Ddi1rLDz.js → block-type-details-D8j70s2E.js} +1 -1
  34. prefect/server/ui-v2/assets/{block._id-BuXnt1s-.js → block._id-DK288xHT.js} +1 -1
  35. prefect/server/ui-v2/assets/{block_._id.edit-B2P2_Zex.js → block_._id.edit-Bb0eDqFe.js} +1 -1
  36. prefect/server/ui-v2/assets/{blocks-D0bbHmgX.js → blocks-C7124FVg.js} +1 -1
  37. prefect/server/ui-v2/assets/{catalog-rBE6NswA.js → catalog-BVYORobl.js} +1 -1
  38. prefect/server/ui-v2/assets/{catalog_._slug-CTrl0a9l.js → catalog_._slug-C_W0sjwY.js} +1 -1
  39. prefect/server/ui-v2/assets/{catalog_._slug_.create-DeMmZ2-_.js → catalog_._slug_.create-CJUaVKJr.js} +1 -1
  40. prefect/server/ui-v2/assets/{concurrency-limit._id-BhgLzKX8.js → concurrency-limit._id-DCb7SW9T.js} +1 -1
  41. prefect/server/ui-v2/assets/{concurrency-limits-Bb3LT0YG.js → concurrency-limits-C71LVKx7.js} +1 -1
  42. prefect/server/ui-v2/assets/{create-hy2OyD-k.js → create-BDj28gbP.js} +1 -1
  43. prefect/server/ui-v2/assets/{create-LL3a_-1F.js → create-DeELn4zG.js} +1 -1
  44. prefect/server/ui-v2/assets/data-table-CcNAeSEr.js +1 -0
  45. prefect/server/ui-v2/assets/{date-range-select-kKoaxRGF.js → date-range-select-BRqKS7Gl.js} +1 -1
  46. prefect/server/ui-v2/assets/{date-time-picker-B_sYB-Y8.js → date-time-picker-DjiPatkZ.js} +1 -1
  47. prefect/server/ui-v2/assets/{deployment-form-DapJQTCF.js → deployment-form-C-vkE_74.js} +2 -2
  48. prefect/server/ui-v2/assets/{deployment._id-DaVLZs68.js → deployment._id-CeNC-xE1.js} +1 -1
  49. prefect/server/ui-v2/assets/{deployment_._id.duplicate-DM-U60Yu.js → deployment_._id.duplicate-Chqr81Za.js} +1 -1
  50. prefect/server/ui-v2/assets/{deployment_._id.edit-FBF-Oa66.js → deployment_._id.edit-DPVT7rtt.js} +1 -1
  51. prefect/server/ui-v2/assets/{deployment_._id.run-DAGQkF1u.js → deployment_._id.run-spYhS_hx.js} +1 -1
  52. prefect/server/ui-v2/assets/{deployments-C1muLdqL.js → deployments-Dju5jBTi.js} +1 -1
  53. prefect/server/ui-v2/assets/{event._eventDate._eventId-B0EBf4Wb.js → event._eventDate._eventId-sa-x9y0k.js} +1 -1
  54. prefect/server/ui-v2/assets/{events-DPlolcFJ.js → events-C_QVbm6d.js} +1 -1
  55. prefect/server/ui-v2/assets/{events-timeline-CDzwqtMX.js → events-timeline-DRyir5tS.js} +1 -1
  56. prefect/server/ui-v2/assets/{flow-run-action-BfdvxiLE.js → flow-run-action-BwPVELPM.js} +1 -1
  57. prefect/server/ui-v2/assets/{flow-run-graph-g1bOArZ6.js → flow-run-graph-CPbBOYK4.js} +1 -1
  58. prefect/server/ui-v2/assets/{flow-run._id-BYybfO6u.js → flow-run._id-CX03eOAY.js} +2 -2
  59. prefect/server/ui-v2/assets/{flow-run._id-5GvAqZ2U.js → flow-run._id-iSlFOk9P.js} +1 -1
  60. prefect/server/ui-v2/assets/{flow-runs-list-CGT3fuQK.js → flow-runs-list-6qJo_VIJ.js} +1 -1
  61. prefect/server/ui-v2/assets/{flow._id-B7mfjS7b.js → flow._id-BB-aZLlC.js} +1 -1
  62. prefect/server/ui-v2/assets/flow._id-CC1C-_N9.js +1 -0
  63. prefect/server/ui-v2/assets/{flows-DUtmDozp.js → flows-UpoTVXra.js} +1 -1
  64. prefect/server/ui-v2/assets/{index-Bi3QMDRh.js → index-C_iMHDKH.js} +3 -3
  65. prefect/server/ui-v2/assets/{json-input-wwqIkfNM.js → json-input-BZOHUDyS.js} +1 -1
  66. prefect/server/ui-v2/assets/{json-input-lazy-BqYvdvI5.js → json-input-lazy-FkvpiPOK.js} +2 -2
  67. prefect/server/ui-v2/assets/{key._key-CRYDbFWW.js → key._key-UalRHWYB.js} +1 -1
  68. prefect/server/ui-v2/assets/{lazy-markdown-DxaEEH51.js → lazy-markdown-CWdfKZzn.js} +1 -1
  69. prefect/server/ui-v2/assets/{login-B6lI7fGt.js → login-D4fS5A4k.js} +1 -1
  70. prefect/server/ui-v2/assets/{markdown-input-BS5Mifkv.js → markdown-input--eUdC7G2.js} +1 -1
  71. prefect/server/ui-v2/assets/{python-example-snippet-MKGRiXZc.js → python-example-snippet-nroYZ7FN.js} +2 -2
  72. prefect/server/ui-v2/assets/{python-input-BwOo9zEN.js → python-input-CZM186ZE.js} +1 -1
  73. prefect/server/ui-v2/assets/{run-flow-button-D4Btqchb.js → run-flow-button-CB4td9UG.js} +1 -1
  74. prefect/server/ui-v2/assets/{runs-DTUGpWHL.js → runs-CJP9oOX1.js} +1 -1
  75. prefect/server/ui-v2/assets/{schedule-badge-Ef1CXeBQ.js → schedule-badge-zgVE3_3K.js} +1 -1
  76. prefect/server/ui-v2/assets/schema-form-DJ8a5LW4.js +5 -0
  77. prefect/server/ui-v2/assets/{settings-BpaGn39S.js → settings-un3IDXs2.js} +1 -1
  78. prefect/server/ui-v2/assets/{task-run._id-tCo8AOpD.js → task-run._id-Df0ucR8e.js} +1 -1
  79. prefect/server/ui-v2/assets/{toggle-group-Vd21Pb-T.js → toggle-group-D6LezfEX.js} +1 -1
  80. prefect/server/ui-v2/assets/{use-delete-automation-confirmation-dialog-BYtqBexo.js → use-delete-automation-confirmation-dialog-DUM4epVY.js} +1 -1
  81. prefect/server/ui-v2/assets/{use-page-size-preference-BOmrT5Yw.js → use-page-size-preference-BX_JyRGQ.js} +1 -1
  82. prefect/server/ui-v2/assets/{use-quick-run-Bj03x9Lw.js → use-quick-run-CSM2zUxG.js} +1 -1
  83. prefect/server/ui-v2/assets/{variables-B-u_F_v-.js → variables-BLHSN7_z.js} +1 -1
  84. prefect/server/ui-v2/assets/{work-pool-queue-form-C-fx7CZC.js → work-pool-queue-form-CTUC8f6C.js} +1 -1
  85. prefect/server/ui-v2/assets/{work-pool-queue-toggle-DMkt6in-.js → work-pool-queue-toggle-DTbSZYAW.js} +1 -1
  86. prefect/server/ui-v2/assets/{work-pool._workPoolName-R0obuaRG.js → work-pool._workPoolName-9RLJ8uaa.js} +1 -1
  87. prefect/server/ui-v2/assets/{work-pool_._workPoolName.edit-Bsj1MHOR.js → work-pool_._workPoolName.edit-o01ZNu2Q.js} +1 -1
  88. prefect/server/ui-v2/assets/{work-pool_._workPoolName.queue._workQueueName-QXkC7ZOI.js → work-pool_._workPoolName.queue._workQueueName-lTAu2KMh.js} +1 -1
  89. prefect/server/ui-v2/assets/{work-pool_._workPoolName.queue.create-gLDwu3pC.js → work-pool_._workPoolName.queue.create-BmLm0MQK.js} +1 -1
  90. prefect/server/ui-v2/assets/{work-pool_._workPoolName.queue_._workQueueName.edit-qupVrrBO.js → work-pool_._workPoolName.queue_._workQueueName.edit-2G8kwDGC.js} +1 -1
  91. prefect/server/ui-v2/assets/{work-pools-D7kYSjtc.js → work-pools-Dr4PX4eK.js} +1 -1
  92. prefect/server/ui-v2/index.html +5 -5
  93. prefect/server/utilities/server.py +61 -0
  94. prefect/types/_datetime.py +4 -1
  95. {prefect-3.9.1.dev8.dist-info → prefect-3.9.2.dev2.dist-info}/METADATA +1 -1
  96. {prefect-3.9.1.dev8.dist-info → prefect-3.9.2.dev2.dist-info}/RECORD +99 -99
  97. prefect/server/ui-v2/assets/data-table-CSbwWJmW.js +0 -1
  98. prefect/server/ui-v2/assets/flow._id-C8op3fJc.js +0 -1
  99. prefect/server/ui-v2/assets/schema-form-DcYL4Rv3.js +0 -5
  100. {prefect-3.9.1.dev8.dist-info → prefect-3.9.2.dev2.dist-info}/WHEEL +0 -0
  101. {prefect-3.9.1.dev8.dist-info → prefect-3.9.2.dev2.dist-info}/entry_points.txt +0 -0
  102. {prefect-3.9.1.dev8.dist-info → prefect-3.9.2.dev2.dist-info}/licenses/LICENSE +0 -0
prefect/AGENTS.md CHANGED
@@ -29,7 +29,7 @@ Runtime flow/task parameter values must come from `utilities.callables.get_call_
29
29
  - **Sync and async must stay in sync.** Both `flow_engine.py` and `task_engine.py` have sync and async paths. Any behavior change must be applied to both.
30
30
  - **Event and log WebSocket subscribers are parallel implementations.** `events/clients.py::PrefectEventSubscriber` and `logging/clients.py::PrefectLogsSubscriber` duplicate the same reconnect/backoff/dedup logic, including the `reconnect_on_clean_close` option (used by `events/subscribers.py::FlowRunSubscriber` so a clean disconnect doesn't hide a terminal event). Mirror any reconnection-behavior change across both.
31
31
  - **Flow run observers own their stream recovery.** `_internal/observers.py` observers create subscribers with `reconnection_attempts=0` and delegate polling fallback, reconnect backoff, and setup deadlines to `_internal/_observation_delivery.py::ObservationDelivery`. Subscribers close any socket left by a failed or cancelled `__aenter__`, since callers never exit a context that failed to enter.
32
- - **Use `whenever` compat helpers for all datetime conversions on Python 3.13+.** `prefect-client` depends on `whenever` only on Python 3.13+, so modules it ships must keep `whenever` imports behind `sys.version_info >= (3, 13)`; only server code that the client build strips may import it unconditionally (see `client/AGENTS.md`). `types/_datetime.py` provides `now()`, `_whenever_to_stdlib()`, `_whenever_zdt_from_py()`, and `_whenever_pdt_from_py()` to abstract over API differences across supported whenever releases. Version-specific code is guarded by feature-detection flags (`_WHENEVER_NEW_API` for ≥ 0.10.0, `_SYSTEM_TZ` for ≥ 0.11), not version checks. Never call `DateTime.now()` or `pendulum.now()` directly — use `now()` from `types/_datetime.py` instead. Avoid no-argument `datetime.datetime.now()` because it returns a tz-naive datetime that raises `TypeError` when compared to the tz-aware datetimes produced by `now()`. Explicitly timezone-aware stdlib calls such as `datetime.now(ZoneInfo("UTC"))` are allowed when needed to preserve timezone information. Never call `ZonedDateTime.from_py_datetime()`, `PlainDateTime.from_py_datetime()`, or `.py_datetime()` directly — use the helpers instead. Likewise avoid `.assume_system_tz()`/`.to_system_tz()` (deprecated in 0.11; the warning fails tests under `filterwarnings = error`) — use `in_local_tz()` — and direct `DateTimeDelta` imports (removed in 0.11) — use the `Interval` alias. Violations will silently break on whichever whenever version the helpers weren't written for.
32
+ - **Use `whenever` compat helpers for all datetime conversions on Python 3.13+.** `prefect-client` depends on `whenever` only on Python 3.13+, so modules it ships must keep `whenever` imports behind `sys.version_info >= (3, 13)`; only code that the client build strips may import it unconditionally (see the repo-root `client/AGENTS.md`). `types/_datetime.py` provides `now()`, `_whenever_to_stdlib()`, `_whenever_zdt_from_py()`, and `_whenever_pdt_from_py()` to abstract over API differences across supported whenever releases. Version-specific code is guarded by feature-detection flags (`_WHENEVER_NEW_API` for ≥ 0.10.0, `_SYSTEM_TZ` for ≥ 0.11), not version checks. These flags are only probed on Python 3.13+ (`_WHENEVER_NEW_API` is `False` and `_SYSTEM_TZ` is undefined on 3.11/3.12), so a helper that server-only code calls on every Python must feature-detect on the `whenever` class itself. Never call `DateTime.now()` or `pendulum.now()` directly — use `now()` from `types/_datetime.py` instead. Avoid no-argument `datetime.datetime.now()` because it returns a tz-naive datetime that raises `TypeError` when compared to the tz-aware datetimes produced by `now()`. Explicitly timezone-aware stdlib calls such as `datetime.now(ZoneInfo("UTC"))` are allowed when needed to preserve timezone information. Never call `ZonedDateTime.from_py_datetime()`, `PlainDateTime.from_py_datetime()`, or `.py_datetime()` directly — use the helpers instead. Likewise avoid `.assume_system_tz()`/`.to_system_tz()` (deprecated in 0.11; the warning fails tests under `filterwarnings = error`) — use `in_local_tz()` — and direct `DateTimeDelta` imports (removed in 0.11) — use the `Interval` alias. Violations will silently break on whichever whenever version the helpers weren't written for.
33
33
  - **Call Pendulum-only members via `types/_datetime.py::_pendulum_call` on Python 3.11/3.12.** Prefect's `DateTime`/`Date`/`Duration` wrap Pendulum-only members (and some shared stdlib methods like `replace`) with user-facing deprecation warnings; `_pendulum_call` bypasses them so users only see warnings for their own calls. `pyproject.toml` ignores these warnings in pytest, so direct calls from Prefect code pass tests silently unless covered by the guards in `tests/test_datetime.py`.
34
34
  - **Flow and task engines advance state differently.** The flow engine makes blocking API calls to the server to propose and advance states. The task engine emits `prefect.task_run.*` events (delivered via WebSockets) but advances state locally through `set_state` calls with polling/backoff — do not assume the two engines work the same way.
35
35
  - **Flow state transitions go through the server.** The flow engine proposes states to the server, which accepts or rejects them via orchestration rules. The task engine, by contrast, manages state transitions locally via `set_state` and emits `prefect.task_run.*` events — it does not propose states to the server.
prefect/_build_info.py CHANGED
@@ -1,5 +1,5 @@
1
1
  # Generated by versioningit
2
- __version__ = "3.9.1.dev8"
3
- __build_date__ = "2026-10-30 08:15:31.522670+00:00"
4
- __git_commit__ = "599697348089e83823cb4ef63ff219c53eefec22"
2
+ __version__ = "3.9.2.dev2"
3
+ __build_date__ = "2026-11-02 08:16:54.718332+00:00"
4
+ __git_commit__ = "da9d9dc15f647f10135a8ff79ce93c4bdb2dbf6a"
5
5
  __dirty__ = False
prefect/cli/AGENTS.md CHANGED
@@ -7,7 +7,7 @@ Prefect command-line interface, powered by **cyclopts**.
7
7
  - **Use `rich` for all output.** Console output via `rich.console`, tables via `rich.table`, progress bars via `rich.progress`. Always use `exit_with_error` for error exits.
8
8
  - **Support JSON output whenever possible.** Commands should have a `--json` flag or equivalent for machine-readable output. Any diagnostic or informational `print()` calls must be suppressed when JSON output is active — mixing human-readable text with the JSON payload breaks machine consumers.
9
9
  - **Print JSON and other verbatim user data with `markup=False, emoji=False`.** `console.print` otherwise parses `[...]` as Rich markup and `:name:` as emoji aliases, silently rewriting payloads (or raising `MarkupError` on stray closing tags). `print_json` and `Pretty` are not affected.
10
- - **Page through "all records" reads.** Client `read_*` list calls without `limit` return at most `PREFECT_SERVER_API_DEFAULT_LIMIT` (200) rows (server `LimitBody`), so `--all`/bulk commands must loop on `offset`. When deleting while paging, re-read from offset 0 each pass — advancing `offset` skips rows that shifted into earlier pages.
10
+ - **Page through "all records" reads.** Client `read_*` list calls without `limit` return at most `PREFECT_SERVER_API_DEFAULT_LIMIT` (200) rows (server `LimitBody`) — or fewer when the client method has its own default `limit` (e.g. `read_global_concurrency_limits` defaults to 10) — so `--all`/bulk commands must loop on `offset`. When deleting while paging, re-read from offset 0 each pass — advancing `offset` skips rows that shifted into earlier pages.
11
11
  - **Excluded from `prefect-client`** — the entire `cli/` directory is stripped during the client package build.
12
12
 
13
13
  ## Structure
prefect/cli/artifact.py CHANGED
@@ -77,7 +77,7 @@ async def list_artifacts(
77
77
  if output and output.lower() == "json":
78
78
  artifacts_json = [artifact.model_dump(mode="json") for artifact in artifacts]
79
79
  json_output = orjson.dumps(artifacts_json, option=orjson.OPT_INDENT_2).decode()
80
- _cli.console.print(json_output, soft_wrap=True)
80
+ _cli.console.print(json_output, soft_wrap=True, markup=False, emoji=False)
81
81
  else:
82
82
  table = Table(
83
83
  title="Artifacts",
@@ -181,7 +181,7 @@ async def inspect(
181
181
  json_output = orjson.dumps(
182
182
  artifacts_json, option=orjson.OPT_INDENT_2
183
183
  ).decode()
184
- _cli.console.print(json_output, soft_wrap=True)
184
+ _cli.console.print(json_output, soft_wrap=True, markup=False, emoji=False)
185
185
  else:
186
186
  _cli.console.print(Pretty(artifacts_json))
187
187
 
prefect/cli/block.py CHANGED
@@ -344,9 +344,9 @@ async def block_delete(
344
344
  except ObjectNotFound:
345
345
  exit_with_error(f"Block '{block_id}' not found!")
346
346
  elif slug is not None:
347
- if "/" not in slug:
347
+ if slug.count("/") != 1:
348
348
  exit_with_error(
349
- f"{slug!r} is not valid. Slug must contain a '/', e.g. 'json/my-json-block'"
349
+ f"{slug!r} is not valid. Slug must contain exactly one '/', e.g. 'json/my-json-block'"
350
350
  )
351
351
  block_type_slug, block_document_name = slug.split("/")
352
352
  try:
@@ -447,9 +447,9 @@ async def block_inspect(
447
447
  except ObjectNotFound:
448
448
  exit_with_error(f"Block '{block_id}' not found!")
449
449
  elif slug is not None:
450
- if "/" not in slug:
450
+ if slug.count("/") != 1:
451
451
  exit_with_error(
452
- f"{slug!r} is not valid. Slug must contain a '/', e.g. 'json/my-json-block'"
452
+ f"{slug!r} is not valid. Slug must contain exactly one '/', e.g. 'json/my-json-block'"
453
453
  )
454
454
  block_type_slug, block_document_name = slug.split("/")
455
455
  try:
@@ -18,7 +18,7 @@ Does NOT define concurrency limits (server-side in `server/`). Does NOT handle t
18
18
 
19
19
  **`raise_on_lease_renewal_failure` (public parameter):** Controls lease renewal failure behavior independently from `strict`. When `None` (default), falls back to the value of `strict` for backward compatibility. Set to `False` to let long-running tasks continue even if a transient renewal error occurs; set to `True` to terminate immediately on renewal failure regardless of `strict`. This means `strict=True, raise_on_lease_renewal_failure=False` gives strict slot acquisition but non-fatal renewal failures, and vice versa.
20
20
 
21
- **Lease renewal:** `_leases.py` starts a daemon thread that renews immediately on entry, then waits for 75% of `lease_duration` between renewals. The renewal thread uses the standard `get_client(sync_client=True)` path and retries each renewal up to 3 times with exponential backoff. If all attempts fail, a shared failure handler either cancels execution with the existing sync/async cancel scope or logs a warning, depending on `raise_on_lease_renewal_failure`.
21
+ **Lease renewal:** `_leases.py` starts a daemon thread that renews immediately on entry, then waits for 75% of `lease_duration` between renewals. The renewal thread uses the standard `get_client(sync_client=True)` path and retries each renewal up to 3 times with exponential backoff. If all attempts fail, a shared failure handler either cancels execution with the existing sync/async cancel scope or logs a warning, depending on `raise_on_lease_renewal_failure`. Exception: when a `flow_run_id` is given and renewal fails with `410 Gone`, the thread reads the flow run and stops without cancelling if its server state is final, because the terminal transition releases the lease before the engine receives the proposal response.
22
22
 
23
23
  **Sync/async lockstep invariant:** `asyncio.py`/`sync.py` and `_asyncio.py`/`_sync.py` are parallel implementations. Any behavior change to one must be mirrored in the other.
24
24
 
@@ -4,6 +4,9 @@ from contextlib import asynccontextmanager, contextmanager
4
4
  from typing import TYPE_CHECKING, AsyncGenerator, Generator
5
5
  from uuid import UUID
6
6
 
7
+ import httpx
8
+
9
+ from prefect._internal.compatibility.starlette import status
7
10
  from prefect._internal.concurrency.cancellation import (
8
11
  AsyncCancelScope,
9
12
  WatcherThreadCancelScope,
@@ -90,6 +93,45 @@ def _lease_renewal_loop(
90
93
  stop_event.wait(lease_duration * _RENEWAL_FRACTION)
91
94
 
92
95
 
96
+ def _lease_released_by_final_flow_run(
97
+ exc: BaseException, lease_id: UUID, flow_run_id: UUID | None
98
+ ) -> bool:
99
+ """
100
+ Check whether a lease renewal failure is explained by the flow run having
101
+ reached a final state on the server, which releases the lease before the
102
+ engine has received the response to its terminal state proposal.
103
+ """
104
+ if flow_run_id is None or not (
105
+ isinstance(exc, httpx.HTTPStatusError)
106
+ and exc.response.status_code == status.HTTP_410_GONE
107
+ ):
108
+ return False
109
+
110
+ logger = get_logger("concurrency")
111
+ try:
112
+ with get_client(sync_client=True) as client:
113
+ flow_run = client.read_flow_run(flow_run_id)
114
+ except Exception:
115
+ logger.debug(
116
+ "Failed to read flow run %s after its concurrency lease was not found",
117
+ flow_run_id,
118
+ exc_info=True,
119
+ )
120
+ return False
121
+
122
+ if flow_run.state is None or not flow_run.state.is_final():
123
+ return False
124
+
125
+ logger.debug(
126
+ "Concurrency lease %s was released because flow run %s reached final "
127
+ "state %s; stopping lease renewal",
128
+ lease_id,
129
+ flow_run_id,
130
+ flow_run.state.type.value,
131
+ )
132
+ return True
133
+
134
+
93
135
  def _handle_lease_renewal_failure(
94
136
  exc: BaseException,
95
137
  lease_id: UUID,
@@ -139,6 +181,7 @@ def _start_lease_renewal_thread(
139
181
  raise_on_lease_renewal_failure: bool,
140
182
  suppress_warnings: bool,
141
183
  cancel_scope: AsyncCancelScope | WatcherThreadCancelScope,
184
+ flow_run_id: UUID | None = None,
142
185
  ) -> tuple[threading.Event, threading.Thread]:
143
186
  stop_event = threading.Event()
144
187
  renewal_ctx = contextvars.copy_context()
@@ -152,14 +195,17 @@ def _start_lease_renewal_thread(
152
195
  try:
153
196
  _lease_renewal_loop(lease_id, lease_duration, stop_event)
154
197
  except Exception as exc:
155
- if not stop_event.is_set():
156
- _handle_lease_renewal_failure(
157
- exc,
158
- lease_id,
159
- raise_on_lease_renewal_failure,
160
- suppress_warnings,
161
- cancel_scope,
162
- )
198
+ if stop_event.is_set() or _lease_released_by_final_flow_run(
199
+ exc, lease_id, flow_run_id
200
+ ):
201
+ return
202
+ _handle_lease_renewal_failure(
203
+ exc,
204
+ lease_id,
205
+ raise_on_lease_renewal_failure,
206
+ suppress_warnings,
207
+ cancel_scope,
208
+ )
163
209
 
164
210
  def renewal_loop() -> None:
165
211
  renewal_ctx.run(_run_with_failure_handler)
@@ -179,6 +225,7 @@ def maintain_concurrency_lease(
179
225
  lease_duration: float,
180
226
  raise_on_lease_renewal_failure: bool = False,
181
227
  suppress_warnings: bool = False,
228
+ flow_run_id: UUID | None = None,
182
229
  ) -> Generator[None, None, None]:
183
230
  """
184
231
  Maintain a concurrency lease for the given lease ID.
@@ -187,6 +234,9 @@ def maintain_concurrency_lease(
187
234
  lease_id: The ID of the lease to maintain.
188
235
  lease_duration: The duration of the lease in seconds.
189
236
  raise_on_lease_renewal_failure: A boolean specifying whether to raise an error if the lease renewal fails.
237
+ flow_run_id: The ID of the flow run holding the lease. When the lease is
238
+ not found and this flow run is final on the server, the lease was
239
+ released by the terminal transition and execution is not terminated.
190
240
  """
191
241
  with WatcherThreadCancelScope() as cancel_scope:
192
242
  stop_event: threading.Event | None = None
@@ -198,6 +248,7 @@ def maintain_concurrency_lease(
198
248
  raise_on_lease_renewal_failure,
199
249
  suppress_warnings,
200
250
  cancel_scope,
251
+ flow_run_id,
201
252
  )
202
253
  yield
203
254
  finally:
@@ -213,6 +264,7 @@ async def amaintain_concurrency_lease(
213
264
  lease_duration: float,
214
265
  raise_on_lease_renewal_failure: bool = False,
215
266
  suppress_warnings: bool = False,
267
+ flow_run_id: UUID | None = None,
216
268
  ) -> AsyncGenerator[None, None]:
217
269
  """
218
270
  Maintain a concurrency lease for the given lease ID.
@@ -221,6 +273,9 @@ async def amaintain_concurrency_lease(
221
273
  lease_id: The ID of the lease to maintain.
222
274
  lease_duration: The duration of the lease in seconds.
223
275
  raise_on_lease_renewal_failure: A boolean specifying whether to raise an error if the lease renewal fails.
276
+ flow_run_id: The ID of the flow run holding the lease. When the lease is
277
+ not found and this flow run is final on the server, the lease was
278
+ released by the terminal transition and execution is not terminated.
224
279
  """
225
280
  with AsyncCancelScope() as cancel_scope:
226
281
  stop_event: threading.Event | None = None
@@ -231,6 +286,7 @@ async def amaintain_concurrency_lease(
231
286
  raise_on_lease_renewal_failure,
232
287
  suppress_warnings,
233
288
  cancel_scope,
289
+ flow_run_id,
234
290
  )
235
291
  yield
236
292
  finally:
prefect/flow_engine.py CHANGED
@@ -1137,7 +1137,10 @@ class FlowRunEngine(BaseFlowRunEngine[P, R]):
1137
1137
  if lease_id := self.state.state_details.deployment_concurrency_lease_id:
1138
1138
  stack.enter_context(
1139
1139
  maintain_concurrency_lease(
1140
- lease_id, 300, raise_on_lease_renewal_failure=True
1140
+ lease_id,
1141
+ 300,
1142
+ raise_on_lease_renewal_failure=True,
1143
+ flow_run_id=self.flow_run.id,
1141
1144
  )
1142
1145
  )
1143
1146
 
@@ -1865,7 +1868,10 @@ class AsyncFlowRunEngine(BaseFlowRunEngine[P, R]):
1865
1868
  if lease_id := self.state.state_details.deployment_concurrency_lease_id:
1866
1869
  await stack.enter_async_context(
1867
1870
  amaintain_concurrency_lease(
1868
- lease_id, 300, raise_on_lease_renewal_failure=True
1871
+ lease_id,
1872
+ 300,
1873
+ raise_on_lease_renewal_failure=True,
1874
+ flow_run_id=self.flow_run.id,
1869
1875
  )
1870
1876
  )
1871
1877
 
prefect/flow_runs.py CHANGED
@@ -133,6 +133,7 @@ async def wait_for_flow_run(
133
133
  )
134
134
 
135
135
  with anyio.move_on_after(timeout):
136
+ received_final_event = False
136
137
  async with get_events_subscriber(filter=event_filter) as subscriber:
137
138
  flow_run = await client.read_flow_run(flow_run_id)
138
139
  if flow_run.state and flow_run.state.is_final():
@@ -151,7 +152,19 @@ async def wait_for_flow_run(
151
152
  logger.info(f"Flow run is in state {state.name!r}")
152
153
 
153
154
  if state.is_final():
154
- return await client.read_flow_run(flow_run_id)
155
+ received_final_event = True
156
+ break
157
+
158
+ if received_final_event:
159
+ # A final state event can be delivered before the state change is
160
+ # visible to API reads, so read until the run reports a final state
161
+ poll_delay = 0.1
162
+ while True:
163
+ flow_run = await client.read_flow_run(flow_run_id)
164
+ if flow_run.state and flow_run.state.is_final():
165
+ return flow_run
166
+ await anyio.sleep(poll_delay)
167
+ poll_delay = min(poll_delay * 2, 5)
155
168
 
156
169
  raise FlowRunWaitTimeout(
157
170
  f"Flow run with ID {flow_run_id} exceeded watch timeout of {timeout} seconds"
prefect/flows.py CHANGED
@@ -706,11 +706,11 @@ class Flow(Generic[P, R]):
706
706
  from fastapi.encoders import jsonable_encoder
707
707
 
708
708
  serialized_parameters[key] = jsonable_encoder(value)
709
- except (TypeError, ValueError, RecursionError):
710
- # `jsonable_encoder` recurses into unknown objects with no cycle
711
- # or depth limit, so a deeply-nested or self-referential value
712
- # raises `RecursionError`. Treat it like any other unserializable
713
- # value and fall back to the placeholder below.
709
+ except Exception:
710
+ # `jsonable_encoder` can raise arbitrary errors for values it
711
+ # cannot encode (e.g. `RecursionError` for self-referential
712
+ # objects, or any error from `__reduce__` while deep-copying a
713
+ # dataclass). Fall back to the placeholder below.
714
714
  logger.debug(
715
715
  f"Parameter {key!r} for flow {self.name!r} is unserializable. "
716
716
  f"Type {type(value).__name__!r} and will not be stored "
prefect/server/AGENTS.md CHANGED
@@ -54,7 +54,7 @@ alembic_revision("description") # Create a new migration
54
54
  - **Deployment concurrency has a TLA+ model.** Before changing its behavior,
55
55
  review `formal/tla/deployment-concurrency/README.md` and its mapped regressions.
56
56
 
57
- - **Pydantic v2 treats null JSON fields as explicitly set.** When a worker sends a state update with `field: null`, Pydantic v2 sets that field to `None`, silently overwriting any existing value. To preserve `state_details` fields across transitions (e.g. `deployment_concurrency_lease_id`), add a `FlowRunUniversalTransform` to `CoreFlowPolicy` that copies the field forward when the proposed state has `None`. See `PreserveDeploymentConcurrencyLeaseId` in `orchestration/core_policy.py` as the canonical pattern. Any new field added to `state_details` that workers may omit faces this same risk.
57
+ - **Pydantic v2 treats null JSON fields as explicitly set.** When a worker sends a state update with `field: null`, Pydantic v2 sets that field to `None`, silently overwriting any existing value. To preserve `state_details` fields across transitions (e.g. `deployment_concurrency_lease_id`), add a `FlowRunUniversalTransform` to both `CoreFlowPolicy` and `MinimalFlowPolicy` (used for `force=True`, otherwise forced transitions drop the field) that copies the field forward when the proposed state has `None`. See `PreserveDeploymentConcurrencyLeaseId` in `orchestration/core_policy.py` as the canonical pattern. Any new field added to `state_details` that workers may omit faces this same risk.
58
58
 
59
59
  - **`update_deployment` uses `model_fields_set` to distinguish explicit `None` from "not provided" for `work_pool_name`.** In `models/deployments.py`, when `deployment.work_pool_name is None` AND `"work_pool_name" in deployment.model_fields_set`, the work queue association is cleared (`work_queue_id = None`). If `work_pool_name` is simply absent from `model_fields_set`, the existing work pool association is left intact. This is the intentional counterpart to the Pydantic v2 null-overwrite pitfall above — here the explicit `model_fields_set` entry signals *desired* clearing. `RunnerDeployment` factory methods omit `None`-valued work pool fields from constructor kwargs; `Runner.add_flow()` then post-assigns `None` to opt into clearing. Follow this same pattern for any future field that should distinguish "clear it" from "leave it alone."
60
60
 
@@ -68,11 +68,12 @@ alembic_revision("description") # Create a new migration
68
68
 
69
69
  - **CANCELLING state transitions must call `maybe_schedule_cancelling_timeout_check_for_state()`.** Any new API path that accepts a CANCELLING transition should call this after `SetStateStatus.ACCEPT`; failures are intentionally non-fatal — log and swallow, do not raise. `cancel_subflow_run` deliberately skips subflows already in CANCELLING to preserve their existing timeout deadline — this guard has no inline comment but removing it resets the deadline. The `ensure_cancelling_timeout_checks` perpetual service re-seeds missed checks on server restart.
70
70
 
71
- - **`record_bulk_task_run_events` batches must be sorted by conflict key before upserting.** In `services/task_run_recorder.py`, task runs are sorted by conflict key — natural key `(flow_run_id, task_key, dynamic_key)` when available, otherwise `("id", task_run_id)` — before batching into upsert groups. This enforces deterministic row-level lock acquisition order across concurrent recorder instances; removing or reordering the sort causes deadlocks. Events that collide on either `id` or natural key are coalesced via union-find to a single canonical ID — the input `TaskRun.id` and `state.state_details.task_run_id` are mutated in-place to that canonical value. Any refactor that re-batches or re-merges must re-sort by conflict key. The function retries once internally on `IntegrityError` to handle TOCTOU races between concurrent recorders, then re-raises on a second failure — callers must catch `IntegrityError` or re-queue the batch.
71
+ - **`record_bulk_task_run_events` batches must be sorted by conflict key before upserting.** In `services/task_run_recorder.py`, task runs are sorted by conflict key — natural key `(flow_run_id, task_key, dynamic_key)` when available, otherwise `("id", task_run_id)` — before batching into upsert groups. This enforces deterministic row-level lock acquisition order across concurrent recorder instances; removing or reordering the sort causes deadlocks. Events that collide on either `id` or natural key are coalesced via union-find to a single canonical ID — the input `TaskRun.id` and `state.state_details.task_run_id` are mutated in-place to that canonical value. Any refactor that re-batches or re-merges must re-sort by conflict key. The function retries once internally on `IntegrityError` to handle TOCTOU races between concurrent recorders, then re-raises on a second failure — callers must catch `IntegrityError` or re-queue the batch. Events whose `flow_run_id` no longer exists are dropped with a warning before the upsert, since one foreign-key violation would otherwise fail the whole batch (#23663).
72
72
 
73
73
  - **`_segment_task_runs_for_upsert` must keep emitting contiguous blocks of its input.** That property, not the batch key, is what preserves the lock ordering above, so a new condition may only *close* a segment earlier — never reorder rows. Each existing condition guards a failure that is silent on at least one dialect; see its docstring and `_fillable_columns` before relaxing one. Absent keys are `NULL`-filled and restored with `coalesce(excluded.col, task_run.col)`, applied to exactly the columns that were filled — a payload asking to write a real `NULL` keeps a plain `excluded.col`, and the batch splits rather than let one statement mean both. This is also why `flow_run_id` must stay out of `_fillable_columns`: coalescing it would break detach.
74
74
 
75
75
  - **`docket.add()` in monitor loops must pass a per-entity `key=` to prevent duplicate enqueues.** Without it, repeated iterations over the same pending entity enqueue duplicate tasks — causing duplicate state transitions. Format: `"<service-name>:<entity-id>"`, e.g., `"mark-flow-run-late:{run.id}"` in `services/late_runs.py`.
76
+ Keyed `add()` can suppress later enqueues while earlier work remains known to Docket, including stranded work awaiting redelivery after a Redis disruption. Use `replace()` only when superseding the pending schedule and arguments is safe (see `schedule_readiness_update` in `api/workers.py`). Choose keys by logical work: independent updates that must both run need distinct keys, while updates intended to supersede one another share a key. Replacement does not synchronously cancel already-running work; `redelivery_timeout` controls reclamation eligibility, not key expiration.
76
77
 
77
78
  - **`TaskRunRecorder` and `EventPersister` share a buffered-consumer shape; keep their failure handling in sync.** Both (`services/task_run_recorder.py`, `events/services/event_persister.py`) queue messages and flush from a never-awaited `flush_periodically` task, so any exception escaping that loop silently stops flushing for the life of the service (#22441, #23308). Database drivers can raise `CancelledError` during outages, so the loop exits on cancellation only after the shutdown path sets its `stopping` flag. Mirror retry/drop/cancellation fixes in both.
78
79
 
@@ -20,7 +20,7 @@ from prefect.server.api.validation import (
20
20
  validate_job_variables_for_deployment,
21
21
  validate_job_variables_for_deployment_flow_run,
22
22
  )
23
- from prefect.server.api.workers import WorkerLookups
23
+ from prefect.server.api.workers import WorkerLookups, schedule_readiness_update
24
24
  from prefect.server.database import PrefectDBInterface, provide_database_interface
25
25
  from prefect.server.exceptions import MissingVariableError, ObjectNotFoundError
26
26
  from prefect.server.models.deployments import mark_deployments_ready
@@ -656,10 +656,16 @@ async def get_scheduled_flow_runs_for_deployments(
656
656
  for orm_flow_run in orm_flow_runs
657
657
  ]
658
658
 
659
+ becoming_ready = await models.deployments.has_not_ready_deployments(
660
+ session=session, deployment_ids=deployment_ids
661
+ )
662
+
659
663
  sorted_deployment_ids = ",".join(str(d) for d in sorted(deployment_ids))
660
- await docket.add(
664
+ await schedule_readiness_update(
665
+ docket,
661
666
  mark_deployments_ready,
662
667
  key=f"mark_deployments_ready:deployments:{sorted_deployment_ids}",
668
+ becoming_ready=becoming_ready,
663
669
  )(
664
670
  deployment_ids=deployment_ids,
665
671
  )
@@ -11,6 +11,7 @@ from urllib.parse import quote
11
11
  from uuid import UUID
12
12
 
13
13
  import orjson
14
+ import pydantic_core
14
15
  import sqlalchemy as sa
15
16
  from docket import Depends as DocketDepends
16
17
  from docket import Docket, Retry
@@ -69,6 +70,21 @@ logger: "logging.Logger" = get_logger("server.api")
69
70
  router: PrefectRouter = PrefectRouter(prefix="/flow_runs", tags=["Flow Runs"])
70
71
 
71
72
 
73
+ def _json_response(content: Any) -> Response:
74
+ """
75
+ Serialize already JSON-compatible `content` into a JSON response.
76
+
77
+ orjson is much faster than the FastAPI encoder, but it rejects integers
78
+ outside of the 64-bit range. Flow run parameters are arbitrary user data, so
79
+ fall back to pydantic-core, which supports arbitrarily large integers.
80
+ """
81
+ try:
82
+ body = orjson.dumps(content)
83
+ except TypeError:
84
+ body = pydantic_core.to_json(content)
85
+ return Response(content=body, media_type="application/json")
86
+
87
+
72
88
  def _get_request_docket(request: Request) -> Docket | None:
73
89
  return getattr(request.app.state, "docket", None)
74
90
 
@@ -621,10 +637,7 @@ async def read_flow_runs(
621
637
  ).model_dump(mode="json")
622
638
  for fr in db_flow_runs
623
639
  ]
624
- return Response(
625
- content=orjson.dumps(encoded),
626
- media_type="application/json",
627
- )
640
+ return _json_response(encoded)
628
641
 
629
642
 
630
643
  @router.delete("/{id:uuid}", status_code=status.HTTP_204_NO_CONTENT)
@@ -1047,10 +1060,7 @@ async def paginate_flow_runs(
1047
1060
  page=page,
1048
1061
  ).model_dump(mode="json")
1049
1062
 
1050
- return Response(
1051
- content=orjson.dumps(response),
1052
- media_type="application/json",
1053
- )
1063
+ return _json_response(response)
1054
1064
 
1055
1065
 
1056
1066
  FLOW_RUN_LOGS_DOWNLOAD_PAGE_LIMIT = 1000
@@ -11,7 +11,9 @@ import contextlib
11
11
  import gc
12
12
  import hmac
13
13
  import importlib.metadata
14
+ import json
14
15
  import logging
16
+ import math
15
17
  import mimetypes
16
18
  import os
17
19
  import random
@@ -292,16 +294,34 @@ async def validation_exception_handler(
292
294
  """Provide a detailed message for request validation errors."""
293
295
  return JSONResponse(
294
296
  status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
295
- content=jsonable_encoder(
296
- {
297
- "exception_message": "Invalid request received.",
298
- "exception_detail": exc.errors(),
299
- "request_body": exc.body,
300
- }
297
+ content=_json_safe(
298
+ jsonable_encoder(
299
+ {
300
+ "exception_message": "Invalid request received.",
301
+ "exception_detail": exc.errors(),
302
+ "request_body": exc.body,
303
+ }
304
+ )
301
305
  ),
302
306
  )
303
307
 
304
308
 
309
+ def _json_safe(value: Any) -> Any:
310
+ """
311
+ Replace values that cannot be rendered as strict JSON, such as `NaN` or strings
312
+ containing unpaired surrogates, so that invalid input can be echoed back.
313
+ """
314
+ if isinstance(value, float) and not math.isfinite(value):
315
+ return json.dumps(value)
316
+ if isinstance(value, str):
317
+ return value.encode("utf-8", "backslashreplace").decode("utf-8")
318
+ if isinstance(value, dict):
319
+ return {_json_safe(k): _json_safe(v) for k, v in value.items()}
320
+ if isinstance(value, list):
321
+ return [_json_safe(v) for v in value]
322
+ return value
323
+
324
+
305
325
  async def integrity_exception_handler(request: Request, exc: Exception) -> JSONResponse:
306
326
  """Capture database integrity errors."""
307
327
  logger.error("Encountered exception in request:", exc_info=True)
@@ -317,7 +337,20 @@ async def integrity_exception_handler(request: Request, exc: Exception) -> JSONR
317
337
  )
318
338
 
319
339
 
340
+ def is_invalid_data_exception(exc: Exception) -> bool:
341
+ """
342
+ Whether the database rejected a value as invalid (SQLSTATE class 22, "data
343
+ exception"), e.g. a NUL character or `NaN` in a PostgreSQL JSON value.
344
+ """
345
+ orig = exc.orig if isinstance(exc, sqlalchemy.exc.DBAPIError) else exc
346
+ sqlstate = getattr(orig, "sqlstate", None)
347
+ return isinstance(sqlstate, str) and sqlstate.startswith("22")
348
+
349
+
320
350
  def is_client_retryable_exception(exc: Exception) -> bool:
351
+ if is_invalid_data_exception(exc):
352
+ return False
353
+
321
354
  if isinstance(exc, sqlalchemy.exc.OperationalError) and isinstance(
322
355
  exc.orig, sqlite3.OperationalError
323
356
  ):
@@ -399,8 +432,29 @@ async def custom_internal_exception_handler(
399
432
  """
400
433
  Log a detailed exception for internal server errors before returning.
401
434
 
402
- Send 503 for errors clients can retry on.
435
+ Send 422 for values the database rejected and 503 for errors clients can retry on.
403
436
  """
437
+ if is_invalid_data_exception(exc):
438
+ logger.warning("Database rejected a value in request:", exc_info=True)
439
+ return JSONResponse(
440
+ content={
441
+ "exception_message": "Invalid request received.",
442
+ "exception_detail": [
443
+ {
444
+ "type": "value_error",
445
+ "loc": ["body"],
446
+ "msg": (
447
+ "The database rejected a value in the request. This "
448
+ "usually means a string contains a NUL character or a "
449
+ "JSON value contains NaN or Infinity. See server logs "
450
+ "for details."
451
+ ),
452
+ }
453
+ ],
454
+ },
455
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
456
+ )
457
+
404
458
  if is_client_retryable_exception(exc):
405
459
  if PREFECT_API_LOG_RETRYABLE_ERRORS.value():
406
460
  logger.error("Encountered retryable exception in request:", exc_info=True)
@@ -18,6 +18,7 @@ from sqlalchemy.exc import IntegrityError
18
18
  import prefect.server.api.dependencies as dependencies
19
19
  import prefect.server.models as models
20
20
  import prefect.server.schemas as schemas
21
+ from prefect.server.api.workers import schedule_readiness_update
21
22
  from prefect.server.database import (
22
23
  PrefectDBInterface,
23
24
  provide_database_interface,
@@ -189,19 +190,32 @@ async def read_work_queue_runs(
189
190
  if x_prefect_ui:
190
191
  return flow_runs
191
192
 
192
- await docket.add(
193
+ work_queue_becoming_ready = work_queue.status == WorkQueueStatus.NOT_READY
194
+ if work_queue_becoming_ready:
195
+ deployments_becoming_ready = True
196
+ else:
197
+ async with db.session_context() as session:
198
+ deployments_becoming_ready = (
199
+ await models.deployments.has_not_ready_deployments(
200
+ session=session, work_queue_ids=[work_queue_id]
201
+ )
202
+ )
203
+
204
+ await schedule_readiness_update(
205
+ docket,
193
206
  mark_work_queues_ready,
194
207
  key=f"mark_work_queues_ready:{work_queue_id}",
208
+ becoming_ready=work_queue_becoming_ready,
195
209
  )(
196
210
  polled_work_queue_ids=[work_queue_id],
197
- ready_work_queue_ids=(
198
- [work_queue_id] if work_queue.status == WorkQueueStatus.NOT_READY else []
199
- ),
211
+ ready_work_queue_ids=[work_queue_id] if work_queue_becoming_ready else [],
200
212
  )
201
213
 
202
- await docket.add(
214
+ await schedule_readiness_update(
215
+ docket,
203
216
  mark_deployments_ready,
204
217
  key=f"mark_deployments_ready:work_queue:{work_queue_id}",
218
+ becoming_ready=deployments_becoming_ready,
205
219
  )(
206
220
  work_queue_ids=[work_queue_id],
207
221
  )