Skip to content

Commit 63593f6

Browse files
ShivaniSharma14chrisguidryclaude
authored
Fix watch subscription timeout handling (#584)
`##` Summary Fixes #509, where `docket watch` may exit with code `0` while the task is still running. ## Problem The timeout handling in `iterate_with_timeout()` used `asyncio.wait_for()` to await the next item from the subscription iterator. When the timeout expired, `wait_for()` cancelled the pending read. This could terminate the async subscription iterator, causing the watch command to stop waiting before the task reached a terminal state. ## Changes - Keep the pending iterator read alive across polling timeouts. - Yield `None` when a timeout occurs, allowing the caller to continue its polling behavior. - Cancel any remaining pending read and close the iterator during cleanup. - Add a regression test verifying that the iterator continues and returns its result after a timeout. ### Testing `python -m pytest -q -n0 --no-cov --confcutdir=python/tests/cli python/tests/cli/test_iterate_with_timeout.py` — 7 passed. The broader CLI test run encountered fixture setup errors, so the full CLI suite has not been verified successfully. Closes #509 --------- Co-authored-by: Chris Guidry <chris@theguidrys.us> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 87bfec3 commit 63593f6

2 files changed

Lines changed: 88 additions & 9 deletions

File tree

‎python/src/docket/cli/_support.py‎

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,28 +24,51 @@ async def iterate_with_timeout(
2424
"""Iterate over an async iterator with timeout, ensuring proper cleanup.
2525
2626
Wraps an async iterator to add timeout support and guaranteed cleanup.
27-
On timeout, yields None to allow the caller to handle polling fallback.
27+
On timeout, yields None without cancelling the pending read.
2828
2929
Args:
30-
iterator: An async generator (must have __anext__ and aclose methods)
31-
timeout: Timeout in seconds for each iteration
30+
iterator: An async iterator with __anext__ and aclose methods.
31+
timeout: Timeout in seconds for each iteration.
3232
3333
Yields:
34-
Items from the iterator, or None if timeout expires
34+
Items from the iterator, or None if the timeout expires.
3535
"""
3636
import asyncio
3737

38+
pending: asyncio.Task[dict[str, Any]] | None = None
39+
3840
try:
3941
while True:
40-
try:
41-
yield await asyncio.wait_for(iterator.__anext__(), timeout=timeout)
42-
except asyncio.TimeoutError:
43-
# Yield None to signal timeout, allowing caller to handle polling
42+
if pending is None:
43+
pending = asyncio.create_task(iterator.__anext__())
44+
45+
done, _ = await asyncio.wait({pending}, timeout=timeout)
46+
47+
if not done:
4448
yield None
49+
continue
50+
51+
task = pending
52+
pending = None
53+
54+
try:
55+
item = task.result()
4556
except StopAsyncIteration:
4657
break
58+
59+
yield item
4760
finally:
48-
await iterator.aclose()
61+
try:
62+
if pending is not None:
63+
if not pending.done():
64+
pending.cancel()
65+
66+
try:
67+
await pending
68+
except (asyncio.CancelledError, StopAsyncIteration):
69+
pass
70+
finally:
71+
await iterator.aclose()
4972

5073

5174
class LogLevel(str, enum.Enum):

‎python/tests/cli/test_iterate_with_timeout.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,59 @@ async def aclose(self) -> None:
9999
pass # pragma: no cover - exception always raised before this
100100

101101
assert close_called, "aclose() should be called even on exception"
102+
103+
104+
async def test_iterate_with_timeout_preserves_iterator_after_timeout():
105+
"""A timeout must not cancel the pending read from the iterator."""
106+
107+
release = asyncio.Event()
108+
109+
async def delayed_iterator():
110+
await release.wait()
111+
yield {"value": "completed"}
112+
113+
wrapped = iterate_with_timeout(delayed_iterator(), timeout=0.05)
114+
115+
assert await wrapped.__anext__() is None
116+
117+
release.set()
118+
119+
assert await wrapped.__anext__() == {"value": "completed"}
120+
await wrapped.aclose()
121+
122+
123+
async def test_iterate_with_timeout_closes_iterator_when_pending_read_fails():
124+
"""Close the iterator even if the pending read raises an exception."""
125+
126+
class FailingIterator:
127+
def __init__(self):
128+
self.fail_read = asyncio.Event()
129+
self.read_finished = asyncio.Event()
130+
self.close_called = False
131+
132+
def __aiter__(self): # pragma: no cover
133+
return self
134+
135+
async def __anext__(self):
136+
await self.fail_read.wait()
137+
try:
138+
raise RuntimeError("read failed")
139+
finally:
140+
self.read_finished.set()
141+
142+
async def aclose(self):
143+
self.close_called = True
144+
145+
iterator = FailingIterator()
146+
wrapped = iterate_with_timeout(iterator, timeout=0.01)
147+
148+
assert await wrapped.__anext__() is None
149+
150+
iterator.fail_read.set()
151+
await iterator.read_finished.wait()
152+
await asyncio.sleep(0)
153+
154+
with pytest.raises(RuntimeError, match="read failed"):
155+
await wrapped.aclose()
156+
157+
assert iterator.close_called

0 commit comments

Comments
 (0)