Skip to content

Commit 61f39ed

Browse files
fix(agent): bound transient command output replay by deadline (#46785)
Co-authored-by: 盐粒 Yanli <mail@yanli.one>
1 parent d9622af commit 61f39ed

3 files changed

Lines changed: 233 additions & 7 deletions

File tree

‎dify-agent/docs/dify-agent/concepts/runtime-resources/index.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ The Shell module consumes `RuntimeLease.commands` and `RuntimeLease.layout`. It
4545
tracks only request-local shell job ids and offsets.
4646
Closing a run clears that job state; it does not retire the Binding.
4747

48+
Transient commands share one timeout budget across execution and paginated
49+
output replay. A replay that exhausts the budget returns incomplete output with
50+
reason `timeout`; a still-running job is interrupted before its final cleanup.
51+
4852
## State ownership
4953

5054
Dify API is the lifecycle ledger. It stores three resource records:

‎dify-agent/src/dify_agent/runtime/command_runner.py‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import asyncio
56
import logging
67
import time
78
from typing import Literal
@@ -57,16 +58,25 @@ async def execute_complete_with_commands(
5758
if captured_bytes >= max_output_bytes and (result.truncated or not result.done):
5859
incomplete_reason = "output_limit"
5960
break
60-
if result.truncated:
61-
result = await commands.read_output(result.job_id, offset=result.offset)
62-
continue
63-
if result.done:
61+
if not result.truncated and result.done:
6462
break
6563
remaining_time = _remaining_time(deadline)
6664
if remaining_time <= 0.0:
6765
incomplete_reason = "timeout"
6866
break
69-
result = await commands.wait(result.job_id, offset=result.offset, timeout=remaining_time)
67+
if result.truncated:
68+
# Output replay has no provider timeout argument.
69+
read_timeout = asyncio.timeout(remaining_time)
70+
try:
71+
async with read_timeout:
72+
result = await commands.read_output(result.job_id, offset=result.offset)
73+
except TimeoutError:
74+
if not read_timeout.expired():
75+
raise
76+
incomplete_reason = "timeout"
77+
break
78+
else:
79+
result = await commands.wait(result.job_id, offset=result.offset, timeout=remaining_time)
7080

7181
final_status = result.status
7282
final_done = result.done

‎dify-agent/tests/local/dify_agent/runtime/test_command_runner.py‎

Lines changed: 214 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22

33
import asyncio
44
from contextlib import suppress
5-
from dataclasses import dataclass, field
5+
from dataclasses import dataclass, field, replace
66

77
import pytest
88

9-
from dify_agent.adapters.shell.protocols import ShellCommandResult, ShellExecutionMode
9+
from dify_agent.adapters.shell.protocols import ShellCommandResult, ShellCommandStatus, ShellExecutionMode
10+
from dify_agent.runtime import command_runner
1011
from dify_agent.runtime.command_runner import execute_complete_with_commands
1112

1213

@@ -91,3 +92,214 @@ async def test_cancellation_deletes_job_returned_before_blocking_wait() -> None:
9192
await asyncio.wait_for(task, timeout=1)
9293

9394
assert commands.deletes == [("job-1", True)]
95+
96+
97+
@dataclass(slots=True)
98+
class _Clock:
99+
now: float = 0.0
100+
101+
def monotonic(self) -> float:
102+
return self.now
103+
104+
105+
@pytest.fixture
106+
def clock(monkeypatch: pytest.MonkeyPatch) -> _Clock:
107+
clock = _Clock()
108+
monkeypatch.setattr(command_runner, "time", clock)
109+
return clock
110+
111+
112+
_FIRST_PAGE = ShellCommandResult("job-1", "running", False, None, "first", 5, True)
113+
_FINAL_PAGE = ShellCommandResult("job-1", "exited", True, 0, "-last", 10, False)
114+
115+
116+
@dataclass(slots=True)
117+
class _PagedCommands:
118+
clock: _Clock
119+
run_result: ShellCommandResult = _FIRST_PAGE
120+
run_elapsed: float = 0.0
121+
replay_elapsed: float = 0.0
122+
# A None entry keeps the read pending until cancellation.
123+
read_results: list[ShellCommandResult | TimeoutError | None] = field(default_factory=list)
124+
read_started: asyncio.Event = field(default_factory=asyncio.Event)
125+
read_offsets: list[int] = field(default_factory=list)
126+
cleanup_calls: list[tuple[str, str] | tuple[str, str, bool]] = field(default_factory=list)
127+
read_cancelled: bool = False
128+
129+
async def run(
130+
self,
131+
script: str,
132+
*,
133+
cwd: str | None = None,
134+
env: dict[str, str] | None = None,
135+
timeout: float,
136+
mode: ShellExecutionMode = "pty",
137+
) -> ShellCommandResult:
138+
self.clock.now += self.run_elapsed
139+
return self.run_result
140+
141+
async def wait(self, job_id: str, *, offset: int, timeout: float) -> ShellCommandResult:
142+
raise AssertionError("unexpected wait")
143+
144+
async def read_output(self, job_id: str, *, offset: int) -> ShellCommandResult:
145+
assert job_id == self.run_result.job_id
146+
assert self.read_results, "unexpected read_output"
147+
self.read_offsets.append(offset)
148+
page = self.read_results.pop(0)
149+
if isinstance(page, TimeoutError):
150+
raise page
151+
if page is not None:
152+
self.clock.now += self.replay_elapsed
153+
return page
154+
self.read_started.set()
155+
try:
156+
await asyncio.Event().wait()
157+
except asyncio.CancelledError:
158+
self.read_cancelled = True
159+
raise
160+
raise AssertionError("read_output must remain blocked until cancellation")
161+
162+
async def input(self, job_id: str, text: str, *, offset: int, timeout: float) -> ShellCommandResult:
163+
raise AssertionError("unexpected input")
164+
165+
async def interrupt(self, job_id: str, *, grace_seconds: float) -> ShellCommandStatus:
166+
self.cleanup_calls.append(("interrupt", job_id))
167+
return ShellCommandStatus(job_id, "interrupted", True, 130, 10)
168+
169+
async def tail(self, job_id: str) -> ShellCommandResult:
170+
raise AssertionError("unexpected tail")
171+
172+
async def delete(self, job_id: str, *, force: bool = False, grace_seconds: float | None = None) -> None:
173+
assert grace_seconds is None
174+
self.cleanup_calls.append(("delete", job_id, force))
175+
176+
177+
@pytest.mark.anyio
178+
@pytest.mark.parametrize("done", [False, True], ids=["running", "terminal"])
179+
async def test_expired_deadline_does_not_start_output_replay(clock: _Clock, done: bool) -> None:
180+
timeout = 10.0
181+
run_result = replace(_FIRST_PAGE, status="exited", done=True, exit_code=7) if done else _FIRST_PAGE
182+
commands = _PagedCommands(clock, run_result=run_result, run_elapsed=timeout)
183+
184+
result = await execute_complete_with_commands(
185+
commands, "long-running", cwd="/workspace", env=None, timeout=timeout, max_output_bytes=4096, mode="stdio"
186+
)
187+
188+
assert result.incomplete_reason == "timeout"
189+
assert not result.output_complete
190+
assert result.output == "first"
191+
assert commands.read_offsets == []
192+
assert result.done
193+
if done:
194+
assert (result.status, result.exit_code) == ("exited", 7)
195+
assert commands.cleanup_calls == [("delete", "job-1", True)]
196+
else:
197+
assert (result.status, result.exit_code) == ("interrupted", 130)
198+
assert commands.cleanup_calls == [("interrupt", "job-1"), ("delete", "job-1", True)]
199+
200+
201+
@pytest.mark.anyio
202+
async def test_output_replay_is_bounded_by_remaining_timeout(clock: _Clock) -> None:
203+
timeout = 10.0
204+
commands = _PagedCommands(
205+
clock,
206+
run_elapsed=4.0,
207+
replay_elapsed=5.98,
208+
read_results=[ShellCommandResult("job-1", "running", False, None, "-more", 10, True), None],
209+
)
210+
result = await asyncio.wait_for(
211+
execute_complete_with_commands(
212+
commands, "long-running", cwd="/workspace", env=None, timeout=timeout, max_output_bytes=4096, mode="stdio"
213+
),
214+
timeout=1,
215+
)
216+
217+
assert result.incomplete_reason == "timeout"
218+
assert result.output == "first-more"
219+
assert not result.output_complete
220+
assert commands.read_offsets == [5, 10]
221+
assert commands.read_cancelled
222+
assert commands.cleanup_calls == [("interrupt", "job-1"), ("delete", "job-1", True)]
223+
224+
225+
@pytest.mark.anyio
226+
async def test_read_output_timeout_error_propagates_before_deadline(clock: _Clock) -> None:
227+
error = TimeoutError("provider read timed out")
228+
commands = _PagedCommands(clock, read_results=[error])
229+
230+
with pytest.raises(TimeoutError) as exc_info:
231+
await execute_complete_with_commands(
232+
commands, "long-running", cwd="/workspace", env=None, timeout=10.0, max_output_bytes=4096, mode="stdio"
233+
)
234+
235+
assert exc_info.value is error
236+
assert commands.read_offsets == [5]
237+
assert commands.cleanup_calls == [("delete", "job-1", True)]
238+
239+
240+
@pytest.mark.anyio
241+
async def test_output_limit_takes_precedence_over_expired_deadline(clock: _Clock) -> None:
242+
timeout = 10.0
243+
commands = _PagedCommands(clock, run_elapsed=timeout)
244+
245+
result = await execute_complete_with_commands(
246+
commands, "long-running", cwd="/workspace", env=None, timeout=timeout, max_output_bytes=5, mode="stdio"
247+
)
248+
249+
assert result.incomplete_reason == "output_limit"
250+
assert not result.output_complete
251+
assert result.output == "first"
252+
assert commands.read_offsets == []
253+
254+
255+
@pytest.mark.anyio
256+
async def test_final_replay_page_takes_precedence_over_expired_deadline(clock: _Clock) -> None:
257+
timeout = 10.0
258+
commands = _PagedCommands(clock, replay_elapsed=timeout, read_results=[_FINAL_PAGE])
259+
260+
result = await execute_complete_with_commands(
261+
commands, "long-running", cwd="/workspace", env=None, timeout=timeout, max_output_bytes=4096, mode="stdio"
262+
)
263+
264+
assert result.output == "first-last"
265+
assert result.output_complete
266+
assert result.incomplete_reason is None
267+
assert commands.read_offsets == [5]
268+
assert commands.cleanup_calls == [("delete", "job-1", True)]
269+
270+
271+
@pytest.mark.anyio
272+
async def test_output_replay_within_budget_preserves_complete_output(clock: _Clock) -> None:
273+
commands = _PagedCommands(clock, read_results=[_FINAL_PAGE])
274+
result = await execute_complete_with_commands(
275+
commands, "long-running", cwd="/workspace", env=None, timeout=60.0, max_output_bytes=4096, mode="stdio"
276+
)
277+
278+
assert result.output == "first-last"
279+
assert result.output_complete
280+
assert result.incomplete_reason is None
281+
assert commands.read_offsets == [5]
282+
assert commands.cleanup_calls == [("delete", "job-1", True)]
283+
284+
285+
@pytest.mark.anyio
286+
async def test_caller_cancellation_during_output_replay_still_propagates(clock: _Clock) -> None:
287+
commands = _PagedCommands(clock, read_results=[None])
288+
task = asyncio.create_task(
289+
execute_complete_with_commands(
290+
commands, "long-running", cwd="/workspace", env=None, timeout=60.0, max_output_bytes=4096, mode="stdio"
291+
)
292+
)
293+
try:
294+
await asyncio.wait_for(commands.read_started.wait(), timeout=1)
295+
task.cancel()
296+
with pytest.raises(asyncio.CancelledError):
297+
await asyncio.wait_for(task, timeout=1)
298+
finally:
299+
if not task.done():
300+
task.cancel()
301+
with suppress(asyncio.CancelledError):
302+
await asyncio.wait_for(task, timeout=1)
303+
304+
assert commands.read_cancelled
305+
assert commands.cleanup_calls == [("delete", "job-1", True)]

0 commit comments

Comments
 (0)