Skip to content

Commit ae335ce

Browse files
rustyconoverclaude
andcommitted
client: stop the stderr enrichment racing its own drainer
`_client_error_with_stderr` read `_stderr_buffer` the moment an error was raised, but that buffer is filled by a daemon thread otherwise joined only in `stop()`. Lose the race and the error carries no stderr at all -- so the traceback the enrichment exists to surface is precisely the one most likely to go missing, and a worker that died on startup reports a bare "Tried reading schema message, was null or length 0". Not theoretical: delaying the drainer by 50ms loses the output entirely, and a machine saturated by `pytest -n auto` delays a daemon thread by far more, which is how this reached CI as an intermittent failure of test_error_includes_stderr_on_worker_failure. Wait for the drainers, but only once every worker process has exited -- then the pipes are at EOF and the threads are microseconds from returning. A live worker holds its pipe open and its drainer never returns at all, so waiting there would stall every ordinary error (a bind rejection from a perfectly healthy worker) for nothing. Measured: 0.0000s on that path with a deliberately never-ending drainer. Both halves are pinned by tests that force the timing rather than hoping for it -- one delays the drainer 250ms and asserts the stderr still lands, the other asserts enrichment returns while the drainer is provably still blocked. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent fcf1d1b commit ae335ce

2 files changed

Lines changed: 96 additions & 0 deletions

File tree

‎tests/client/test_worker_debug.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
import os
88
import sys
9+
import time
10+
from typing import Any
911
from unittest.mock import patch
1012

1113
import pyarrow as pa
@@ -82,6 +84,65 @@ def test_error_includes_stderr_on_worker_failure(self) -> None:
8284
assert "Worker stderr" in error_msg
8385
assert "Error: function not found" in error_msg
8486

87+
def test_stderr_survives_a_late_drainer(self, monkeypatch: pytest.MonkeyPatch) -> None:
88+
"""Enrichment must not race the drainer thread that fills its buffer.
89+
90+
``_stderr_buffer`` is filled by a daemon thread otherwise joined only in
91+
``stop()``, so before the fix an error raised the instant a worker died
92+
could be built from an empty buffer — losing exactly the traceback the
93+
enrichment exists to surface. Delaying the drainer reproduces under a
94+
scheduler what a loaded machine produces on its own; 50ms was enough to
95+
lose the output entirely.
96+
"""
97+
real_drain = Client._drain_stderr
98+
99+
def late_drain(self: Client, stderr: Any) -> None:
100+
time.sleep(0.25)
101+
real_drain(self, stderr)
102+
103+
monkeypatch.setattr(Client, "_drain_stderr", late_drain)
104+
105+
client = Client(_stderr_worker("Error: function not found"), pool=None)
106+
with pytest.raises(ClientError) as exc_info:
107+
client.start()
108+
list(client.table_function(function_name="nonexistent", schema_name="main", arguments=Arguments()))
109+
client.stop()
110+
111+
assert "Error: function not found" in str(exc_info.value)
112+
113+
def test_a_live_worker_does_not_stall_the_error_path(self, monkeypatch: pytest.MonkeyPatch) -> None:
114+
"""Only a *dead* worker's drainer is waited on.
115+
116+
A running worker holds its stderr pipe open, so its drainer never
117+
returns; waiting on that would stall every ordinary error — a bind
118+
rejection from a perfectly healthy worker — until the timeout.
119+
"""
120+
elapsed: list[float] = []
121+
real_enrich = Client._client_error_with_stderr
122+
123+
def timed_enrich(self: Client, error: ClientError) -> ClientError:
124+
started = time.monotonic()
125+
try:
126+
return real_enrich(self, error)
127+
finally:
128+
elapsed.append(time.monotonic() - started)
129+
130+
monkeypatch.setattr(Client, "_client_error_with_stderr", timed_enrich)
131+
132+
with Client("vgi-fixture-worker", pool=None) as client:
133+
with pytest.raises(ClientError):
134+
list(client.table_function(function_name="no_such_function", schema_name="main", arguments=Arguments()))
135+
assert client._primary is not None # noqa: SLF001 - a started client always has one
136+
proc = client._primary.proc # noqa: SLF001 - the point is that it is still running
137+
assert proc is not None
138+
assert proc.poll() is None, "probe is only meaningful while the worker is alive"
139+
assert client._stderr_threads[0].is_alive(), "the drainer should still be blocked on the open pipe" # noqa: SLF001
140+
141+
assert elapsed, "the error should have gone through stderr enrichment"
142+
assert max(elapsed) < Client.STDERR_DRAIN_TIMEOUT / 4, (
143+
f"enrichment waited {max(elapsed):.3f}s on a worker that is still running"
144+
)
145+
85146
def test_error_no_stderr_section_when_passthrough(self) -> None:
86147
"""Error messages should NOT include 'Worker stderr:' when passthrough is enabled."""
87148
worker_script = _stderr_worker("Debug info")

‎vgi/client/client.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,8 @@ class Client(CatalogClientMixin, AggregateClientMixin):
247247
PROCESS_WAIT_TIMEOUT: Seconds to wait for a worker process to exit during
248248
shutdown before killing it. A hang guard — teardown never blocks past
249249
this, and never raises ``TimeoutExpired`` at the caller.
250+
STDERR_DRAIN_TIMEOUT: Seconds to wait for a dead worker's stderr to finish
251+
draining before an error message is built from it.
250252
"""
251253

252254
THREAD_JOIN_TIMEOUT: float = 5.0
@@ -257,6 +259,10 @@ class Client(CatalogClientMixin, AggregateClientMixin):
257259
# far enough above normal shutdown that only a genuinely wedged process
258260
# reaches it.
259261
PROCESS_WAIT_TIMEOUT: float = 30.0
262+
# Bound on waiting for a dead worker's stderr to be drained before an error
263+
# message is built from it. Reached only if a drainer wedges on an
264+
# already-EOF pipe, so it trades a stalled error path for a truncated one.
265+
STDERR_DRAIN_TIMEOUT: float = 2.0
260266

261267
@staticmethod
262268
def _combine_batches(batches: list[pa.RecordBatch]) -> pa.RecordBatch | None:
@@ -593,6 +599,34 @@ def get_worker_stderr(self) -> str:
593599
with self._stderr_lock:
594600
return b"".join(self._stderr_buffer).decode("utf-8", errors="replace")
595601

602+
def _await_stderr_drain(self) -> None:
603+
"""Let the drainers finish when the workers they read are already gone.
604+
605+
``_stderr_buffer`` is filled by daemon threads that are otherwise only
606+
joined in ``stop()``, so an error raised the instant a worker dies can be
607+
enriched *before* that worker's dying words have been read — the traceback
608+
the enrichment exists to surface is exactly the one most likely to be
609+
missing. It is a genuine race, not a theoretical one: delaying the drainer
610+
by 50ms is enough to lose the output entirely, and a loaded machine
611+
delays a daemon thread by far more than that.
612+
613+
Only wait once every worker process has exited, which is when the pipes
614+
are at EOF and the drainers are microseconds from returning. A worker
615+
that is still running holds its pipe open and its drainer will not return
616+
at all, so waiting there would stall every ordinary error — a bind
617+
rejection from a perfectly healthy worker — for no benefit.
618+
"""
619+
if not self._stderr_threads:
620+
return
621+
workers = [w for w in [self._primary, *self._additional_workers] if w is not None]
622+
procs = [w.proc for w in workers if w.proc is not None]
623+
# Only the direct-subprocess path owns a ``proc`` and starts a drainer,
624+
# so "no procs" means the threads belong to workers already torn down.
625+
if not procs or any(proc.poll() is None for proc in procs):
626+
return
627+
for stderr_thread in self._stderr_threads:
628+
stderr_thread.join(timeout=self.STDERR_DRAIN_TIMEOUT)
629+
596630
def _client_error_with_stderr(self, error: ClientError) -> ClientError:
597631
"""Enrich a [`ClientError`][] with captured worker stderr, if available.
598632
@@ -604,6 +638,7 @@ def _client_error_with_stderr(self, error: ClientError) -> ClientError:
604638
"""
605639
if self.passthrough_stderr:
606640
return error
641+
self._await_stderr_drain()
607642
stderr = self.get_worker_stderr()
608643
if not stderr.strip():
609644
return error

0 commit comments

Comments
 (0)