Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-4136 [FIX] Report PG worker pods ready only after every consumer child has loaded (#2301)

Rahul Johnyf9dc6656187a
diff --git a/workers/pg_queue_consumer/supervisor.py b/workers/pg_queue_consumer/supervisor.py
index 62f39a683..247498308 100644
--- a/workers/pg_queue_consumer/supervisor.py
+++ b/workers/pg_queue_consumer/supervisor.py
@@ -23,6 +23,14 @@ internally (transient); a child that **crash-loops** (dies immediately N times i
a row, never reaching a real poll) forces the probe to 503 so k8s restarts the
pod rather than the supervisor masking a wedged fleet with fresh-looking re-forks.
+**Readiness** (UN-4136): the same port serves ``/ready``, which answers 200 only
+once EVERY child has finished its ``import worker`` bootstrap and built its
+consumer. ``/health`` cannot say this — the heartbeats are seeded fresh at
+construction so liveness does not trip during a slow import — which is why a pod
+used to go Ready ~20s after start while its N children were still importing, and
+the HPA counted that multi-core start-up burst as load. A k8s ``startupProbe`` on
+``/ready`` keeps the pod NotReady until the burst is over.
+
**Fork safety**: the initial fleet is forked while the parent is single-threaded.
Re-forks happen after the liveness daemon thread exists; the only other thread is
that probe (idle in ``select`` between requests, and CPython 3.12 re-inits the
@@ -152,6 +160,11 @@ class _Fleet:
now = time.time()
for i in range(concurrency):
self._heartbeats[i] = now
+ # Shared, fork-inherited "finished loading" flags (one per child), read by
+ # /ready. Same write discipline as the heartbeats: the owning child sets
+ # its slot once bootstrapped; the parent clears it in reap(), when no child
+ # owns the slot. Zero-initialised, so a fresh fleet starts not-ready.
+ self._loaded = multiprocessing.Array("b", concurrency, lock=False)
self._pids: dict[int, int] = {}
self._last_fork: dict[int, float] = {}
self._consecutive_crashes: dict[int, int] = {}
@@ -168,6 +181,13 @@ class _Fleet:
"""
return self._heartbeats
+ @property
+ def loaded(self): # noqa: ANN201
+ """The shared loaded-flag array (a ctypes array, passed to forked children,
+ which set their own slot once bootstrapped).
+ """
+ return self._loaded
+
def _validate(self, slot: int) -> None:
if not 0 <= slot < self._n:
raise IndexError(f"slot {slot} out of range [0, {self._n})")
@@ -184,9 +204,14 @@ class _Fleet:
self._restart_due.pop(slot, None)
def reap(self, slot: int) -> float:
- """Drop the slot's pid + last-fork together; return the child's uptime (s)."""
+ """Drop the slot's pid + last-fork together; return the child's uptime (s).
+
+ Also clears the slot's loaded flag: its replacement must finish its own
+ bootstrap before the fleet counts as loaded again.
+ """
forked_at = self._last_fork.pop(slot, time.monotonic())
self._pids.pop(slot, None)
+ self._loaded[slot] = 0
return time.monotonic() - forked_at
def schedule_restart(self, slot: int, uptime: float) -> int:
@@ -231,6 +256,14 @@ class _Fleet:
n >= _CRASH_LOOP_THRESHOLD for n in tuple(self._consecutive_crashes.values())
)
+ def loaded_count(self) -> int:
+ """Children that have finished their bootstrap (``import worker`` + build)."""
+ return sum(self._loaded)
+
+ def all_loaded(self) -> bool:
+ """Readiness verdict source: True once every slot's child has loaded."""
+ return self.loaded_count() == self._n
+
def oldest_age(self) -> float:
now = time.time()
return max((now - hb for hb in self._heartbeats), default=0.0)
@@ -244,14 +277,16 @@ class _Fleet:
return float("inf") if self.is_crash_looping() else self.oldest_age()
-def _run_child(slot: int, heartbeats) -> None: # noqa: ANN001 (ctypes array)
+def _run_child(slot: int, heartbeats, loaded) -> None: # noqa: ANN001 (ctypes arrays)
"""Build one consumer and run it forever, publishing its heartbeat.
The worker import (and any connections it opens) happens HERE, in the child —
never inherited across the fork — so each process owns its own connections.
A *guarded* daemon thread publishes the consumer's last-poll wall-time into
- ``heartbeats[slot]`` for the supervisor's fleet liveness.
+ ``heartbeats[slot]`` for the supervisor's fleet liveness, and ``loaded[slot]``
+ is set once the bootstrap is done, for the supervisor's ``/ready``.
"""
+ started = time.monotonic()
from pg_queue_consumer._bootstrap import select_source_worker_type
select_source_worker_type() # set WORKER_TYPE before importing worker
@@ -277,11 +312,17 @@ def _run_child(slot: int, heartbeats) -> None: # noqa: ANN001 (ctypes array)
time.sleep(_REPORT_INTERVAL_SECONDS)
threading.Thread(target=_publish_heartbeat, daemon=True, name=f"pg-hb-{slot}").start()
+ loaded[slot] = 1
+ logger.info(
+ "PG-queue consumer: child slot=%s loaded in %.1fs",
+ slot,
+ time.monotonic() - started,
+ )
# consumer.run() installs its own SIGTERM/SIGINT handlers → graceful stop.
consumer.run()
-def _child_after_fork(slot: int, heartbeats) -> None: # noqa: ANN001 (ctypes array)
+def _child_after_fork(slot: int, heartbeats, loaded) -> None: # noqa: ANN001 (ctypes arrays)
"""Child side of the fork: reset inherited state, run, hard-exit on failure.
Resets the supervisor's signal handlers to ``SIG_DFL`` *immediately* — until
@@ -294,7 +335,7 @@ def _child_after_fork(slot: int, heartbeats) -> None: # noqa: ANN001 (ctypes ar
signal.signal(signal.SIGTERM, signal.SIG_DFL)
signal.signal(signal.SIGINT, signal.SIG_DFL)
try:
- _run_child(slot, heartbeats)
+ _run_child(slot, heartbeats, loaded)
except Exception:
# A child that can't even start must not return into the supervisor loop
# (it would fork grandchildren). Log + hard exit. Exception (not
@@ -321,7 +362,7 @@ def _try_fork_child(fleet: _Fleet, slot: int) -> bool:
)
return False
if pid == 0: # child — never returns
- _child_after_fork(slot, fleet.heartbeats)
+ _child_after_fork(slot, fleet.heartbeats, fleet.loaded)
fleet.record_fork(slot, pid)
logger.info("PG-queue consumer: forked child slot=%s pid=%s", slot, pid)
return True
@@ -480,6 +521,9 @@ def _maybe_start_supervisor_health(fleet: _Fleet) -> LivenessServer | None:
(``check="pg_queue_fleet"``, age key ``oldest_child_seconds_since_poll``) since
the freshness source is the fleet's oldest child, not one poll loop.
+ ``/ready`` → 200 only once every child has loaded (:meth:`_Fleet.all_loaded`),
+ for the chart's opt-in ``startupProbe``.
+
A bind failure does not abort the consumer (it must keep draining the queue),
but ``EADDRINUSE`` usually signals a real config bug, so it's logged at error;
either way ``liveness_probe_bound: false`` is surfaced in the status payload so
@@ -502,6 +546,7 @@ def _maybe_start_supervisor_health(fleet: _Fleet) -> LivenessServer | None:
def _extra_status() -> dict[str, object]:
return {
"alive_children": fleet.alive_count(),
+ "loaded_children": fleet.loaded_count(),
"concurrency": fleet.concurrency,
"crash_looping": fleet.is_crash_looping(),
"liveness_probe_bound": True,
@@ -522,6 +567,7 @@ def _maybe_start_supervisor_health(fleet: _Fleet) -> LivenessServer | None:
age_key="oldest_child_seconds_since_poll",
extra_status_fn=_extra_status,
metrics_fn=metrics.render,
+ ready_fn=fleet.all_loaded,
thread_name="pg-supervisor-liveness",
log_label="pg-queue supervisor",
)
@@ -541,8 +587,8 @@ def _maybe_start_supervisor_health(fleet: _Fleet) -> LivenessServer | None:
)
return None
logger.info(
- "PG-queue consumer supervisor: fleet liveness on :%s/health (stale after "
- "%ss, %d children)",
+ "PG-queue consumer supervisor: fleet liveness on :%s/health, readiness on "
+ "/ready (stale after %ss, %d children)",
server.bound_port,
stale_after,
fleet.concurrency,
diff --git a/workers/queue_backend/pg_queue/README.md b/workers/queue_backend/pg_queue/README.md
index 8ae3f8fea..5b203bd5b 100644
--- a/workers/queue_backend/pg_queue/README.md
+++ b/workers/queue_backend/pg_queue/README.md
@@ -113,6 +113,14 @@ deadline**, then SIGKILLs stragglers. Must be ≤ the pod's
the supervisor reports the *oldest* child's staleness on `/health`. Frozen during a
long task, so a wedged child goes stale and trips the probe.
+**Readiness** — `/ready` on the same port answers 200 only once **every** child has
+finished its `import worker` bootstrap and built its consumer (503 `starting` until
+then; the JSON carries `loaded_children`). It is for a k8s `startupProbe`: the N
+children import in parallel for a minute or two at multiple cores, and a pod that is
+not yet Ready has that CPU ignored by the HPA instead of read as load. Single-process
+consumers (`CONCURRENCY = 1`) answer 200 as soon as the port is up, since they bind it
+only after loading. The reaper serves no `/ready` (404).
+
**Reaper** — a singleton (leader-elected) sweeper that recovers **stranded** work:
fast-fails a barrier whose `last_progress_at` stalled, cascades a terminal
execution to its files, and sweeps expired retention rows.
diff --git a/workers/queue_backend/pg_queue/consumer.py b/workers/queue_backend/pg_queue/consumer.py
index 9f0e27fb9..057c8d85e 100644
--- a/workers/queue_backend/pg_queue/consumer.py
+++ b/workers/queue_backend/pg_queue/consumer.py
@@ -1212,6 +1212,11 @@ class LivenessServer(_BaseLivenessServer):
consumer's heartbeat (``seconds_since_last_poll``). Same wire shape as before
(``/health`` → 200 fresh / 503 stale, ``check="pg_queue_poll"``), plus
``/metrics`` exporting that heartbeat as a scrapeable gauge.
+
+ ``/ready`` is always 200 here: it takes an already-built consumer, and
+ ``main()`` only starts it after ``import worker`` and the build, so a probe
+ that can reach it is talking to a loaded process. The same ``startupProbe``
+ therefore works for single-process and prefork pools alike.
"""
def __init__(
@@ -1227,6 +1232,7 @@ class LivenessServer(_BaseLivenessServer):
check_name="pg_queue_poll",
age_key="seconds_since_last_poll",
metrics_fn=metrics.render,
+ ready_fn=lambda: True,
thread_name="pg-consumer-liveness",
log_label="pg-queue consumer",
)
diff --git a/workers/queue_backend/pg_queue/liveness.py b/workers/queue_backend/pg_queue/liveness.py
index 07f41f6ce..c2bba7155 100644
--- a/workers/queue_backend/pg_queue/liveness.py
+++ b/workers/queue_backend/pg_queue/liveness.py
@@ -17,6 +17,12 @@ Serves ``/health`` (also ``/healthz``, ``/livez``) on ``0.0.0.0`` (a
container/k8s probe reaches it from outside the process) in a daemon thread.
Bind ``port=0`` to let the OS pick a free port (read back via :attr:`bound_port`)
— used in tests. Start once; :meth:`stop` returns it to the inert state.
+
+Optionally also serves ``/ready`` (also ``/readyz``): "has this process finished
+loading?", answered by a ``ready_fn`` callable. It is a separate question from
+liveness — a process can be alive while it is still importing — and exists for a
+k8s ``startupProbe`` (UN-4136): a pod that is not yet Ready has its start-up CPU
+ignored by the HPA, so the import burst cannot trigger a scale-out.
"""
from __future__ import annotations
@@ -46,9 +52,15 @@ class LivenessServer:
module stays free of the prometheus dependency; the metric definitions live
in :mod:`queue_backend.pg_queue.metrics`. A ``metrics_fn`` failure returns
500 on ``/metrics`` only — it can never affect the ``/health`` verdict.
+
+ ``ready_fn`` (optional) additionally serves ``/ready``: 200 once it returns
+ True, else 503. Without it ``/ready`` is a 404, so a probe pointed at a
+ process that has no readiness notion fails loudly instead of passing. A
+ ``ready_fn`` that raises answers 503 — never a false "ready".
"""
_PATHS = frozenset({"/health", "/healthz", "/livez"})
+ _READY_PATHS = frozenset({"/ready", "/readyz"})
_METRICS_PATH = "/metrics"
# Prometheus text exposition format (metrics.METRICS_CONTENT_TYPE — inlined
# so this module keeps zero imports from the metrics side).
@@ -64,6 +76,7 @@ class LivenessServer:
age_key: str,
extra_status_fn: Callable[[], dict[str, Any]] | None = None,
metrics_fn: Callable[[], bytes] | None = None,
+ ready_fn: Callable[[], bool] | None = None,
thread_name: str = "pg-queue-liveness",
log_label: str = "pg-queue",
) -> None:
@@ -79,6 +92,7 @@ class LivenessServer:
self._age_key = age_key
self._extra_status_fn = extra_status_fn
self._metrics_fn = metrics_fn
+ self._ready_fn = ready_fn
self._thread_name = thread_name
# Prefixes the (now-shared) log messages so they stay attributable to the
# source process after the consumer/reaper extraction (e.g. "pg-queue
@@ -99,9 +113,11 @@ class LivenessServer:
freshness_fn = self._freshness_fn
stale_after = self._stale_after
paths = self._PATHS
+ ready_paths = self._READY_PATHS
metrics_path = self._METRICS_PATH
metrics_content_type = self._METRICS_CONTENT_TYPE
metrics_fn = self._metrics_fn
+ ready_fn = self._ready_fn
check_name = self._check_name
age_key = self._age_key
extra_status_fn = self._extra_status_fn
@@ -114,6 +130,9 @@ class LivenessServer:
if metrics_fn is not None and path == metrics_path:
self._serve_metrics()
return
+ if ready_fn is not None and path in ready_paths:
+ self._serve_ready()
+ return
if path not in paths:
self.send_response(404)
self.end_headers()
@@ -123,26 +142,44 @@ class LivenessServer:
# fields are informational and never flip it.
age = freshness_fn()
stale = age > stale_after
- # Extra fields first, then overlay the core fields — so a caller's
- # extra_status_fn can NEVER clobber status/check/age_key/
- # stale_after_seconds (which a monitor reads): core always wins.
- payload: dict[str, Any] = {}
- if extra_status_fn is not None:
- payload.update(extra_status_fn())
- payload.update(
+ self._send_json(
+ 503 if stale else 200,
{
"status": "unhealthy" if stale else "healthy",
"check": check_name,
age_key: round(age, 3),
"stale_after_seconds": stale_after,
- }
+ },
+ )
+
+ def _serve_ready(self) -> None:
+ # A readiness check that raises must read as NOT ready: answering
+ # 200 would let the pod go Ready (and its start-up CPU count toward
+ # the HPA) on the strength of a bug.
+ try:
+ ready = bool(ready_fn()) # type: ignore[misc] # guarded by caller
+ except Exception:
+ logger.exception("%s: readiness check failed", log_label)
+ ready = False
+ self._send_json(
+ 200 if ready else 503,
+ {"status": "ready" if ready else "starting", "check": check_name},
)
+
+ def _send_json(self, code: int, core: dict[str, Any]) -> None:
+ # Extra fields first, then overlay the core fields — so a caller's
+ # extra_status_fn can NEVER clobber status/check/age_key/
+ # stale_after_seconds (which a monitor reads): core always wins.
+ payload: dict[str, Any] = {}
+ if extra_status_fn is not None:
+ payload.update(extra_status_fn())
+ payload.update(core)
body = json.dumps(payload).encode()
# Headers too, not just the body write: a client that hangs up
# before headers go out would otherwise raise into socketserver's
# handle_error, which prints an unattributed traceback to stderr.
try:
- self.send_response(503 if stale else 200)
+ self.send_response(code)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
@@ -160,7 +197,7 @@ class LivenessServer:
self.send_response(500)
self.end_headers()
return
- # Same hung-up-client guard as the /health path above.
+ # Same hung-up-client guard as _send_json above.
try:
self.send_response(200)
self.send_header("Content-Type", metrics_content_type)
diff --git a/workers/tests/test_pg_consumer_supervisor.py b/workers/tests/test_pg_consumer_supervisor.py
index aaee2ba44..e4d88f458 100644
--- a/workers/tests/test_pg_consumer_supervisor.py
+++ b/workers/tests/test_pg_consumer_supervisor.py
@@ -24,6 +24,7 @@ from pg_queue_consumer.supervisor import (
_join_children,
_reap_dead,
_restart_due_children,
+ _run_child,
_try_fork_child,
_wait_for_exit,
concurrency_from_env,
@@ -184,6 +185,34 @@ class TestFleet:
clock[0] += 100.0 # well past any backoff
assert f.due_restarts() == [0]
+ # --- readiness (UN-4136) ---------------------------------------------------
+
+ def test_fresh_fleet_is_not_loaded(self):
+ # Unlike the heartbeats (seeded fresh), nothing is loaded at construction:
+ # a pod must not go Ready before its children have imported.
+ f = _Fleet(3)
+ assert f.loaded_count() == 0
+ assert f.all_loaded() is False
+
+ def test_all_loaded_only_when_every_slot_has_loaded(self):
+ f = _Fleet(3)
+ f.loaded[0] = 1
+ f.loaded[2] = 1
+ assert f.loaded_count() == 2
+ assert f.all_loaded() is False # slot 1 still importing
+ f.loaded[1] = 1
+ assert f.all_loaded() is True
+
+ def test_reap_clears_the_slot_loaded_flag(self):
+ # A dead child's replacement must bootstrap again before the fleet counts
+ # as loaded; the stale flag must not carry over.
+ f = _Fleet(2)
+ f.loaded[0] = f.loaded[1] = 1
+ f.record_fork(1, 111)
+ f.reap(1)
+ assert list(f.loaded) == [1, 0]
+ assert f.all_loaded() is False
+
class TestReapDead:
def test_dead_child_reaped_and_rescheduled(self):
@@ -258,19 +287,32 @@ class TestTryForkChild:
assert _try_fork_child(f, 0) is True
assert f.alive_items() == [(0, 222)]
+ def test_child_is_handed_the_shared_heartbeat_and_loaded_arrays(self):
+ # The child writes its own slot in BOTH arrays; handing it a copy (or not
+ # handing over `loaded` at all) would leave /ready stuck at 503.
+ f = _Fleet(1)
+ with (
+ patch(f"{_MOD}.os.fork", return_value=0), # we are the child
+ patch(f"{_MOD}._child_after_fork", side_effect=SystemExit) as child,
+ ):
+ with pytest.raises(SystemExit):
+ _try_fork_child(f, 0)
+ child.assert_called_once_with(0, f.heartbeats, f.loaded)
+
class TestChildAfterFork:
def test_resets_signals_and_exits_zero_on_clean_run(self):
with (
patch(f"{_MOD}.signal.signal") as sig,
- patch(f"{_MOD}._run_child"),
+ patch(f"{_MOD}._run_child") as run,
patch(f"{_MOD}.os._exit", side_effect=SystemExit) as exit_,
):
- queue = MagicMock()
+ heartbeats, loaded = MagicMock(), MagicMock()
with pytest.raises(SystemExit):
- _child_after_fork(0, queue)
+ _child_after_fork(0, heartbeats, loaded)
# SIGTERM + SIGINT reset to default before running.
assert sig.call_count == 2
+ run.assert_called_once_with(0, heartbeats, loaded)
exit_.assert_called_once_with(0)
def test_hard_exits_one_when_run_raises(self):
@@ -279,12 +321,51 @@ class TestChildAfterFork:
patch(f"{_MOD}._run_child", side_effect=RuntimeError("boom")),
patch(f"{_MOD}.os._exit", side_effect=SystemExit) as exit_,
):
- queue = MagicMock()
with pytest.raises(SystemExit):
- _child_after_fork(0, queue)
+ _child_after_fork(0, MagicMock(), MagicMock())
exit_.assert_called_once_with(1)
+class TestRunChildLoaded:
+ """The child marks itself loaded only after the bootstrap, and before it
+ starts polling (UN-4136).
+ """
+
+ @staticmethod
+ def _run_slot_1(fleet: _Fleet, build) -> None: # noqa: ANN001
+ # No real `import worker` bootstrap and no real heartbeat thread.
+ with (
+ patch.dict("sys.modules", {"worker": MagicMock()}),
+ patch("pg_queue_consumer._bootstrap.select_source_worker_type"),
+ patch(
+ "queue_backend.pg_queue.consumer.build_consumer_from_env",
+ side_effect=build,
+ ),
+ patch(f"{_MOD}.threading.Thread"),
+ ):
+ _run_child(1, fleet.heartbeats, fleet.loaded)
+
+ def test_marks_its_slot_loaded_before_polling(self):
+ f = _Fleet(2)
+ seen: list[list[int]] = []
+ consumer = MagicMock()
+ # Snapshot the flags at the moment polling would begin.
+ consumer.run.side_effect = lambda: seen.append(list(f.loaded))
+ self._run_slot_1(f, lambda: consumer)
+ assert seen == [[0, 1]] # own slot only, and set before run()
+
+ def test_not_marked_loaded_when_the_build_fails(self):
+ # A child that cannot finish its bootstrap must never count as loaded.
+ f = _Fleet(2)
+
+ def _boom(): # noqa: ANN202
+ raise RuntimeError("cannot build")
+
+ with pytest.raises(RuntimeError, match="cannot build"):
+ self._run_slot_1(f, _boom)
+ assert list(f.loaded) == [0, 0]
+
+
class TestWaitForExit:
def test_true_when_child_exits(self):
with patch(f"{_MOD}.os.waitpid", return_value=(111, 0)):
@@ -385,3 +466,43 @@ class TestSupervisorHealth:
):
# Must not propagate — the consumer keeps draining without a probe.
assert sup._maybe_start_supervisor_health(_Fleet(1)) is None
+
+ def test_ready_is_503_until_every_child_loads_while_health_stays_200(
+ self, monkeypatch
+ ):
+ # UN-4136: the whole point. /health is fresh from construction (liveness
+ # must not trip during the import), so only /ready can hold the pod
+ # NotReady while the children import.
+ import json
+ import urllib.error
+ import urllib.request
+
+ monkeypatch.setenv("WORKER_PG_QUEUE_CONSUMER_HEALTH_PORT", "0") # OS picks
+ fleet = _Fleet(2)
+ server = sup._maybe_start_supervisor_health(fleet)
+ assert server is not None
+ base = f"http://127.0.0.1:{server.bound_port}"
+
+ def _ready() -> tuple[int, dict]:
+ try:
+ with urllib.request.urlopen(f"{base}/ready", timeout=5) as resp:
+ return resp.status, json.loads(resp.read())
+ except urllib.error.HTTPError as exc:
+ return exc.code, json.loads(exc.read())
+
+ try:
+ with urllib.request.urlopen(f"{base}/health", timeout=5) as resp:
+ assert resp.status == 200 # alive, but...
+
+ code, body = _ready()
+ assert (code, body["status"], body["loaded_children"]) == (503, "starting", 0)
+
+ fleet.loaded[0] = 1
+ code, body = _ready()
+ assert (code, body["loaded_children"]) == (503, 1) # one still importing
+
+ fleet.loaded[1] = 1
+ code, body = _ready()
+ assert (code, body["status"], body["loaded_children"]) == (200, "ready", 2)
+ finally:
+ server.stop()
diff --git a/workers/tests/test_pg_queue_consumer.py b/workers/tests/test_pg_queue_consumer.py
index 3e5d836dc..f4105cc1e 100644
--- a/workers/tests/test_pg_queue_consumer.py
+++ b/workers/tests/test_pg_queue_consumer.py
@@ -738,6 +738,82 @@ class TestPollHeartbeat:
finally:
server.stop()
+ def test_single_process_ready_is_200_once_serving(self):
+ # UN-4136: the single-process server only starts after `import worker` and
+ # the consumer build, so reaching /ready means loaded. The chart's
+ # startupProbe hits /ready on every PG consumer, CONCURRENCY=1 included.
+ import json
+ import urllib.request
+
+ from queue_backend.pg_queue.consumer import LivenessServer
+
+ consumer = PgQueueConsumer(["q"], client=MagicMock())
+ server = LivenessServer(consumer, port=0, stale_after=60)
+ server.start()
+ try:
+ base = f"http://127.0.0.1:{server.bound_port}"
+ for path in ("/ready", "/readyz", "/ready?probe=startup"):
+ with urllib.request.urlopen(f"{base}{path}", timeout=5) as resp:
+ assert resp.status == 200, path
+ assert json.loads(resp.read())["status"] == "ready", path
+ finally:
+ server.stop()
+
+ def test_ready_is_404_without_a_ready_fn(self):
+ # A process with no readiness notion (e.g. the reaper) must NOT answer
+ # /ready with a pass — a startupProbe mistakenly pointed at it has to fail.
+ import urllib.error
+ import urllib.request
+
+ from queue_backend.pg_queue.liveness import LivenessServer as Base
+
+ server = Base(
+ freshness_fn=lambda: 0.0,
+ stale_after=60,
+ port=0,
+ check_name="t",
+ age_key="age",
+ )
+ server.start()
+ try:
+ with pytest.raises(urllib.error.HTTPError) as ei:
+ urllib.request.urlopen(
+ f"http://127.0.0.1:{server.bound_port}/ready", timeout=5
+ )
+ assert ei.value.code == 404
+ finally:
+ server.stop()
+
+ def test_ready_fn_that_raises_answers_503_and_leaves_health_alone(self):
+ import json
+ import urllib.error
+ import urllib.request
+
+ from queue_backend.pg_queue.liveness import LivenessServer as Base
+
+ def _broken() -> bool:
+ raise RuntimeError("boom")
+
+ server = Base(
+ freshness_fn=lambda: 0.0,
+ stale_after=60,
+ port=0,
+ check_name="t",
+ age_key="age",
+ ready_fn=_broken,
+ )
+ server.start()
+ try:
+ base = f"http://127.0.0.1:{server.bound_port}"
+ with pytest.raises(urllib.error.HTTPError) as ei:
+ urllib.request.urlopen(f"{base}/ready", timeout=5)
+ assert ei.value.code == 503
+ assert json.loads(ei.value.read())["status"] == "starting"
+ with urllib.request.urlopen(f"{base}/health", timeout=5) as resp:
+ assert resp.status == 200 # readiness never flips liveness
+ finally:
+ server.stop()
+
def test_double_start_is_rejected(self):
from queue_backend.pg_queue.consumer import LivenessServer