Skip to content

Commit b861756

Browse files
fix: drain_grace_seconds bounds a serve() that is still running after stop (#91)
A scoped entrypoint (consumer, daemon, one-shot) finishes its in-flight unit inside serve(), and the Host awaited every serve() with no deadline. That work ran outside any budget, DrainTimeoutError never fired, and readiness stayed true until the slowest serve() returned. Once stop is set the Host now withdraws readiness and gives every serve() still running drain_grace_seconds + 5 s to return, the same allowance as a drain() step. A serve() still running after that is cancelled, its kind is logged, and a DrainTimeoutError goes through the existing timeouts path. Closes #88
1 parent c780180 commit b861756

12 files changed

Lines changed: 230 additions & 37 deletions

File tree

‎docs/agents.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ configure observability
7979
→ bind() each entrypoint, in order
8080
→ health.ready = True → post_start hooks
8181
→ serve() all concurrently, until stop
82-
→ health.ready = False
82+
→ health.ready = False (as soon as stop is set)
83+
→ every serve() returns, within drain_grace_seconds + 5 (else cancelled)
8384
→ drain(grace) in reverse bind order
8485
→ stop() in reverse bind order
8586
→ pre_shutdown hooks (app scope still open)
@@ -387,8 +388,9 @@ Each `*Plugin` takes exactly the same arguments as its entrypoint and exposes `.
387388
shutdown step is logged and skipped so the others still get their turn.
388389
5. **Warmup's budget is a fixed 60 seconds and is not an `AppSpec` field.** Only
389390
`drain_delay_seconds` (0.0), `drain_grace_seconds` (30.0) and `cleanup_timeout_seconds`
390-
(10.0) are configurable. The delay is spent once, before the first drain; the drain step
391-
is allowed `drain_grace_seconds + 5`; every post-drain step gets `cleanup_timeout_seconds`.
391+
(10.0) are configurable. The delay is spent once, before the first drain; once `stop` is
392+
set, every `serve()` still running is allowed `drain_grace_seconds + 5` to return (then it
393+
is cancelled), and so is each drain step; every post-drain step gets `cleanup_timeout_seconds`.
392394
`terminationGracePeriodSeconds` must exceed the sum of all three. An overrun raises
393395
`DrainTimeoutError` / `CleanupTimeoutError` out of `run()` — but only when nothing else is
394396
already propagating.
@@ -588,7 +590,7 @@ Every runtime error derives from `ServiceWrightError`:
588590
| `ServiceWrightError` | base class for everything the runtime raises |
589591
| `WarmupError` | a warmer failed (or the engine's own timeout elapsed) with failure raising enabled |
590592
| `WarmupTimeoutError` | warmup did not finish inside its 60-second budget (also a `TimeoutError`) |
591-
| `DrainTimeoutError` | an entrypoint's `drain` outlived `drain_grace_seconds + 5` (also a `TimeoutError`) |
593+
| `DrainTimeoutError` | an entrypoint's `serve()` (after `stop`) or `drain` outlived `drain_grace_seconds + 5` (also a `TimeoutError`) |
592594
| `CleanupTimeoutError` | a `stop()`, hook or observability flush outlived `cleanup_timeout_seconds` (also a `TimeoutError`) |
593595
| `RedisWarmupError`, `PostgresWarmupError`, `KafkaProducerWarmupError` | the matching built-in warmer failed; all subclass `WarmupError` |
594596

‎docs/blueprints/batch-job.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,10 @@ async def backfill(scope: UnitScopeProtocol) -> None:
147147
cursor = await use_case.save_checkpoint(batch.last_id)
148148
```
149149

150-
On `SIGTERM` the Host cancels `serve()` at the next await point, and the last saved checkpoint
151-
means the retry resumes instead of restarting. Give the Job a
152-
`terminationGracePeriodSeconds` large enough for one batch to finish.
150+
On `SIGTERM` the function gets `drain_grace_seconds` (plus 5 seconds) to finish; after that the
151+
Host cancels `serve()` at the next await point, and the last saved checkpoint means the retry
152+
resumes instead of restarting. Size `drain_grace_seconds` for one batch, and the Job's
153+
`terminationGracePeriodSeconds` above it.
153154

154155
## `Job` + `CronJob`, or a scheduler entrypoint?
155156

‎docs/blueprints/worker.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,11 @@ if __name__ == "__main__":
200200
main()
201201
```
202202

203-
Shutdown, in order: readiness goes false, then the consumer drains and commits, then the outbox
204-
loop returns, then the scheduler pauses and waits for its running job — all within
205-
`drain_grace_seconds` — and the connection pool closes last.
203+
Shutdown, in order: readiness goes false as soon as `SIGTERM` arrives; the consumer finishes the
204+
message it is handling and the outbox loop finishes its batch, both inside `serve()`; then the
205+
consumer drains and commits, and the scheduler pauses and waits for its running job. Each of those
206+
steps gets `drain_grace_seconds`, and a `serve()` that outlives it is cancelled. The connection
207+
pool closes last.
206208

207209
## 5. Health and metrics without an HTTP port
208210

‎docs/concepts/entrypoints.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ That is the whole contract. The Host never branches on what kind of entrypoint i
2222
| Method | Called | Contract |
2323
| --- | --- | --- |
2424
| `bind(ctx)` | once, before readiness | Allocate, subscribe, register. **Accept nothing yet.** Raise if the resource is unavailable — the Host aborts startup instead of reporting ready. |
25-
| `serve(stop=...)` | once, in a `TaskGroup` | Run until `stop` is set, then return **while still accepting**. Raise to report a fatal failure. |
25+
| `serve(stop=...)` | once, in a `TaskGroup` | Run until `stop` is set, then return **while still accepting**. A unit already in flight may finish first, within `drain_grace_seconds`; after that the Host cancels it. Raise to report a fatal failure. |
2626
| `drain(grace)` | on shutdown, reverse order | Stop intake. Let in-flight work finish within `grace` seconds. |
2727
| `stop()` | after drain, reverse order | Hard stop. Release everything. Must be safe to call after `drain`. |
2828

@@ -31,8 +31,8 @@ stateDiagram-v2
3131
[*] --> Bound: bind(ctx) — allocate, accept nothing
3232
Bound --> Serving: serve(stop) — the Host flips readiness on
3333
Serving --> Serving: stop is not set
34-
Serving --> Accepting: stop is set, serve() returns
35-
Accepting --> Draining: readiness off, then drain(grace)
34+
Serving --> Accepting: stop is set, readiness off, serve() returns
35+
Accepting --> Draining: drain(grace)
3636
Draining --> Stopped: stop()
3737
Stopped --> [*]
3838
```

‎docs/concepts/lifecycle.md‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -57,19 +57,28 @@ is what actually closes the listener.
5757
If the HTTP entrypoint shut uvicorn down inside `serve()` instead, the readiness endpoint would
5858
die before the load balancer noticed, and the drain window would be meaningless.
5959

60+
A scoped entrypoint — a consumer, a daemon, a one-shot job — may be in the middle of a unit of
61+
work when `stop` arrives, and that unit finishes inside `serve()`. The Host withdraws readiness
62+
as soon as `stop` is set and gives every `serve()` still running `drain_grace_seconds` (plus 5
63+
seconds) to return. One that is still running then is cancelled at its next await point, which
64+
unwinds its unit scope, and reported as a `DrainTimeoutError`.
65+
6066
## Shutdown
6167

62-
1. **`health.ready = False` first.** Load balancers stop routing before you stop accepting.
63-
2. **`drain_delay_seconds` pass** with every entrypoint still accepting. Readiness going red
68+
1. **`health.ready = False` first**, the moment `stop` is set. Load balancers stop routing before
69+
you stop accepting.
70+
2. **Every `serve()` returns**, within `drain_grace_seconds` + 5s; a unit of work that was in
71+
flight finishes here.
72+
3. **`drain_delay_seconds` pass** with every entrypoint still accepting. Readiness going red
6473
reaches the routing layer asynchronously; this is the window in which it catches up. The
6574
default is `0.0`, and the wait is skipped when the service never reached Ready.
66-
3. **`drain(grace)`** on every bound entrypoint, in **reverse** bind order. Intake stops;
75+
4. **`drain(grace)`** on every bound entrypoint, in **reverse** bind order. Intake stops;
6776
in-flight work finishes inside the window.
68-
4. **`stop()`** on every bound entrypoint, in reverse order. Hard stop, time-boxed.
69-
5. **`pre_shutdown` hooks** — the application scope is still alive here. Flush the outbox, emit
77+
5. **`stop()`** on every bound entrypoint, in reverse order. Hard stop, time-boxed.
78+
6. **`pre_shutdown` hooks** — the application scope is still alive here. Flush the outbox, emit
7079
final events.
71-
6. **The application scope closes.** Your DI finalizers close pools and clients.
72-
7. **Observability flushes** (spans, Sentry events, the metrics server thread), then
80+
7. **The application scope closes.** Your DI finalizers close pools and clients.
81+
8. **Observability flushes** (spans, Sentry events, the metrics server thread), then
7382
**`post_shutdown` hooks** run.
7483

7584
Only entrypoints that were actually bound are drained and stopped, and a step that fails is
@@ -83,14 +92,15 @@ spec = AppSpec(
8392
service_name="orders",
8493
create_container=build_container,
8594
drain_delay_seconds=5.0, # once, unready but still accepting
86-
drain_grace_seconds=30.0, # per entrypoint, for in-flight work
95+
drain_grace_seconds=30.0, # per entrypoint and step, for in-flight work
8796
cleanup_timeout_seconds=10.0, # per post-drain step
8897
)
8998
```
9099

91100
| Step | Budget | On overrun |
92101
| --- | --- | --- |
93102
| Warmup (whole phase) | 60s, fixed | `WarmupTimeoutError`, startup aborts |
103+
| `serve()` returning after `stop` | `drain_grace_seconds` + 5s | cancelled, `DrainTimeoutError` |
94104
| `drain(grace)` | `drain_grace_seconds` + 5s | `DrainTimeoutError` |
95105
| `stop()` | `cleanup_timeout_seconds` | `CleanupTimeoutError` |
96106
| `pre_shutdown` hooks | `cleanup_timeout_seconds` | `CleanupTimeoutError` |
@@ -100,6 +110,11 @@ spec = AppSpec(
100110
The extra 5 seconds on the drain step exist so an entrypoint that honours its own grace window
101111
exactly is not killed a millisecond too early.
102112

113+
The window is per step, and the steps run one after another: first the `serve()` tails (all at
114+
once), then each `drain()` in turn. A worker whose consumer is mid-batch spends its window in the
115+
first; an HTTP server with slow requests spends its window in the second. If one process holds
116+
both and both can be busy for the whole window, budget `drain_grace_seconds` for each.
117+
103118
`drain_delay_seconds` is not a budget but a fixed wait, spent once between readiness going red and
104119
the first `drain()`, and only when the service had reached Ready. It costs the full amount on every
105120
graceful stop, so keep it at the propagation lag and no longer.
@@ -112,7 +127,8 @@ in the first place.
112127

113128
Keep `terminationGracePeriodSeconds` larger than
114129
`drain_delay_seconds + drain_grace_seconds + cleanup_timeout_seconds`, otherwise the kubelet
115-
sends `SIGKILL` in the middle of your drain. See [Kubernetes](../operations/kubernetes.md).
130+
sends `SIGKILL` in the middle of your drain. Add another `drain_grace_seconds` for each
131+
entrypoint that can be busy for its whole window at the same time as another. See [Kubernetes](../operations/kubernetes.md).
116132

117133
## Event loop
118134

@@ -242,8 +258,8 @@ sequenceDiagram
242258
H->>E: serve(stop=...)
243259
Note over H,E: ... serving ...
244260
H->>H: SIGTERM → stop.set()
245-
E-->>H: serve() returns (still accepting)
246261
H->>H: health.ready = False
262+
E-->>H: serve() returns (still accepting)
247263
Note over H,E: drain_delay_seconds — still accepting
248264
H->>E: drain(grace)
249265
H->>E: stop()

‎docs/guides/custom-entrypoint.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,8 @@ async def test__consumer__message_arrives__handled_in_its_own_scope() -> None:
183183
- [ ] Extends `ScopedEntrypoint` (you open the scope) or `ServerEntrypoint` (the framework does).
184184
- [ ] `bind` calls `super().bind(ctx)` and raises on unavailable resources.
185185
- [ ] `bind` allocates but accepts nothing.
186-
- [ ] `serve` returns promptly when `stop` is set, and returns **while still accepting**.
186+
- [ ] `serve` returns promptly when `stop` is set, and returns **while still accepting**. The
187+
unit in flight gets `drain_grace_seconds` to finish; past that the Host cancels `serve`.
187188
- [ ] `serve` raises only for failures that should stop the process.
188189
- [ ] `drain` stops intake and honours `grace`.
189190
- [ ] `stop` is idempotent and safe after a partial `bind`.

‎docs/operations/kubernetes.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,10 @@ spec:
100100
terminationGracePeriodSeconds: 60 # 5 + 30 + 10 + slack
101101
```
102102

103+
`drain_grace_seconds` is a window per shutdown step: a consumer finishing its batch inside
104+
`serve()` uses one, an HTTP server finishing its requests in `drain()` uses another. If a pod runs
105+
both and both can be busy for the whole window, add `drain_grace_seconds` once more.
106+
103107
!!! tip "Set `drain_delay_seconds` to your propagation lag"
104108

105109
The usual `preStop: sleep 5` hack exists to keep a pod serving while endpoint removal

‎docs/operations/runbooks.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,10 +255,13 @@ Exit code `137` means `SIGKILL` arrived. Raise the grace period, or lower the bu
255255
### `DrainTimeoutError` in the logs
256256

257257
An entrypoint did not finish draining within `drain_grace_seconds + 5s`. The log line names the
258-
`kind`, so you know which one.
258+
`kind`, so you know which one, and the `phase`: `serve` means its `serve()` was still running a
259+
unit of work and was cancelled, `drain` means `drain()` itself overran.
259260

260261
- HTTP: a request is running longer than the window. Bound your handlers, or raise the window.
261262
- Scheduler: a job is running long. It is logged with `job_id` and `run_id`.
263+
- Consumer, daemon or one-shot (`phase=serve`): the unit in flight when `SIGTERM` arrived took
264+
longer than the window. Make the unit smaller, check `stop` between units, or raise the window.
262265
- Custom entrypoint: your `drain()` is not returning — check the in-flight polling loop.
263266

264267
The error is raised out of `run()` only if nothing else is already propagating, so it never masks

‎servicewright/core/aio/host.py‎

Lines changed: 63 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import asyncio
66
import contextlib
77
import logging
8-
from typing import TYPE_CHECKING, TypeVar
8+
from typing import TYPE_CHECKING, Any, TypeVar
99

1010
from ..constants import DEFAULT_DRAIN_TIMEOUT_BUFFER_SECONDS
1111
from ..exceptions import CleanupTimeoutError, DrainTimeoutError, ServiceWrightError
@@ -48,6 +48,7 @@ def __init__(self, spec: AppSpec[TSettings, TContainer]) -> None:
4848
self.spec = spec
4949
self._entrypoints: list[Entrypoint] = []
5050
self._bound: list[Entrypoint] = []
51+
self._was_ready = False
5152

5253
def add_entrypoint(self, entrypoint: Entrypoint) -> None:
5354
"""Append an entrypoint (typically from a plugin's ``on_register``)."""
@@ -87,6 +88,7 @@ async def run(
8788
"""
8889
self._entrypoints = list(entrypoints)
8990
self._bound = []
91+
self._was_ready = False
9092
for plugin in plugins:
9193
plugin.on_register(self.spec, self)
9294

@@ -150,9 +152,9 @@ async def _run_with_app_scope(
150152
timeouts: list[ServiceWrightError] = []
151153
try:
152154
if await self._startup(service_ctx, self._entrypoints, stop):
153-
await self._serve(self._entrypoints, stop)
155+
timeouts = await self._serve(self._entrypoints, stop)
154156
finally:
155-
timeouts = await self._shutdown_in_scope(service_ctx)
157+
timeouts += await self._shutdown_in_scope(service_ctx)
156158

157159
if timeouts:
158160
raise timeouts[0]
@@ -237,11 +239,16 @@ async def _collect_and_warmup(
237239
extra={"service": self.spec.service_name},
238240
)
239241

240-
async def _serve(self, entrypoints: Sequence[Entrypoint], stop: asyncio.Event) -> None:
241-
"""Serve every entrypoint until ``stop``; re-raise an essential failure."""
242+
async def _serve(self, entrypoints: Sequence[Entrypoint], stop: asyncio.Event) -> list[ServiceWrightError]:
243+
"""Serve every entrypoint until ``stop``; re-raise an essential failure.
244+
245+
Returns:
246+
One :class:`DrainTimeoutError` per ``serve()`` that had to be
247+
cancelled because it outran the drain budget after ``stop``.
248+
"""
242249
if not entrypoints:
243250
await stop.wait()
244-
return
251+
return []
245252

246253
async def runner(entrypoint: Entrypoint) -> None:
247254
try:
@@ -265,10 +272,11 @@ async def runner(entrypoint: Entrypoint) -> None:
265272
stop.set()
266273

267274
failure: BaseException | None = None
275+
timeouts: list[ServiceWrightError] = []
268276
try:
269277
async with asyncio.TaskGroup() as group:
270-
for entrypoint in entrypoints:
271-
group.create_task(runner(entrypoint))
278+
tasks = {group.create_task(runner(entrypoint)): entrypoint for entrypoint in entrypoints}
279+
timeouts = await self._bound_serve_tail(tasks, stop)
272280
except* Exception as eg:
273281
logger.exception(
274282
"Serve loop aborted by entrypoint failure",
@@ -281,22 +289,66 @@ async def runner(entrypoint: Entrypoint) -> None:
281289
# may not exit 0, or every exit-code-based supervisor reads it as success.
282290
if failure is not None:
283291
raise failure
292+
return timeouts
293+
294+
async def _bound_serve_tail(
295+
self,
296+
tasks: dict[asyncio.Task[None], Entrypoint],
297+
stop: asyncio.Event,
298+
) -> list[ServiceWrightError]:
299+
"""Wait for ``stop``, then give the ``serve()`` calls still running the drain budget.
300+
301+
A scoped entrypoint finishes its in-flight unit inside ``serve()``, so
302+
this is where ``drain_grace_seconds`` has to hold for it. Readiness is
303+
withdrawn as soon as ``stop`` is set: nothing has stopped accepting yet,
304+
and nothing should be routed to a process that is shutting down.
305+
"""
306+
stopping = asyncio.ensure_future(stop.wait())
307+
serving = asyncio.gather(*tasks, return_exceptions=True)
308+
waiters: set[asyncio.Future[Any]] = {stopping, serving}
309+
try:
310+
await asyncio.wait(waiters, return_when=asyncio.FIRST_COMPLETED)
311+
finally:
312+
stopping.cancel()
313+
if not stop.is_set():
314+
return [] # Every serve() returned on its own.
315+
316+
self._withdraw_readiness()
317+
budget = self.spec.drain_grace_seconds + DEFAULT_DRAIN_TIMEOUT_BUFFER_SECONDS
318+
_, overrun = await asyncio.wait(tasks, timeout=budget)
319+
timeouts: list[ServiceWrightError] = []
320+
for task in overrun:
321+
task.cancel()
322+
kind = tasks[task].kind
323+
timeout_error = DrainTimeoutError(f"serve did not return within {budget}s of stop")
324+
logger.warning(
325+
"Shutdown step timed out",
326+
extra={"service": self.spec.service_name, "phase": "serve", "kind": kind, "budget": budget},
327+
exc_info=timeout_error,
328+
)
329+
timeouts.append(timeout_error)
330+
return timeouts
331+
332+
def _withdraw_readiness(self) -> None:
333+
"""Flip readiness off, remembering whether the service had been routed to."""
334+
if self.spec.health.ready:
335+
self.spec.health.ready = False
336+
self._was_ready = True
284337

285338
async def _shutdown_in_scope(
286339
self,
287340
service_ctx: ServiceContext[TSettings, TContainer],
288341
) -> list[ServiceWrightError]:
289342
"""Withdraw readiness, drain, stop and run pre-shutdown hooks; return any budget overruns."""
290343
# Stop routing first (k8s/LB) before we stop accepting work...
291-
was_ready = self.spec.health.ready
292-
self.spec.health.ready = False
344+
self._withdraw_readiness()
293345

294346
# ...and keep accepting while the routing layer catches up: readiness
295347
# going red reaches the load balancer asynchronously, and nothing closes
296348
# a listener until the first drain() below. A service that never reached
297349
# Ready was never routed to, so it has nothing to wait for.
298350
delay = self.spec.drain_delay_seconds
299-
if was_ready and delay > 0:
351+
if self._was_ready and delay > 0:
300352
logger.info(
301353
"Readiness withdrawn; holding intake open before drain",
302354
extra={"service": self.spec.service_name, "delay": delay},

‎servicewright/core/contracts/entrypoint.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ async def serve(self, *, stop: asyncio.Event) -> None:
4141
:meth:`stop`. Closing listeners here instead would make ``drain(grace)``
4242
inert and would take the readiness endpoint down before the router knows.
4343
44+
Work already in progress when ``stop`` is set may finish first, within
45+
``drain_grace_seconds`` (plus 5 s): the Host cancels a ``serve()`` that
46+
has not returned by then and reports a ``DrainTimeoutError``.
47+
4448
Raise to report a fatal serve-time failure.
4549
"""
4650
...

0 commit comments

Comments
 (0)