|
2 | 2 |
|
3 | 3 | import asyncio |
4 | 4 | from contextlib import suppress |
5 | | -from dataclasses import dataclass, field |
| 5 | +from dataclasses import dataclass, field, replace |
6 | 6 |
|
7 | 7 | import pytest |
8 | 8 |
|
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 |
10 | 11 | from dify_agent.runtime.command_runner import execute_complete_with_commands |
11 | 12 |
|
12 | 13 |
|
@@ -91,3 +92,214 @@ async def test_cancellation_deletes_job_returned_before_blocking_wait() -> None: |
91 | 92 | await asyncio.wait_for(task, timeout=1) |
92 | 93 |
|
93 | 94 | 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