test_is_stuck.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. import logging
  2. from unittest.mock import Mock, patch
  3. import pytest
  4. from pytest import TempPathFactory
  5. from openhands.controller.agent_controller import AgentController
  6. from openhands.controller.state.state import State
  7. from openhands.controller.stuck import StuckDetector
  8. from openhands.events.action import CmdRunAction, FileReadAction, MessageAction
  9. from openhands.events.action.commands import IPythonRunCellAction
  10. from openhands.events.observation import (
  11. CmdOutputObservation,
  12. FileReadObservation,
  13. )
  14. from openhands.events.observation.commands import IPythonRunCellObservation
  15. from openhands.events.observation.empty import NullObservation
  16. from openhands.events.observation.error import ErrorObservation
  17. from openhands.events.stream import EventSource, EventStream
  18. from openhands.storage import get_file_store
  19. def collect_events(stream):
  20. return [event for event in stream.get_events()]
  21. logging.basicConfig(level=logging.DEBUG)
  22. jupyter_line_1 = '\n[Jupyter current working directory:'
  23. jupyter_line_2 = '\n[Jupyter Python interpreter:'
  24. code_snippet = """
  25. edit_file_by_replace(
  26. 'book_store.py',
  27. to_replace=\"""def total(basket):
  28. if not basket:
  29. return 0
  30. """
  31. @pytest.fixture
  32. def temp_dir(tmp_path_factory: TempPathFactory) -> str:
  33. return str(tmp_path_factory.mktemp('test_is_stuck'))
  34. @pytest.fixture
  35. def event_stream(temp_dir):
  36. file_store = get_file_store('local', temp_dir)
  37. event_stream = EventStream('asdf', file_store)
  38. yield event_stream
  39. # clear after each test
  40. event_stream.clear()
  41. class TestStuckDetector:
  42. @pytest.fixture
  43. def stuck_detector(self):
  44. state = State(inputs={}, max_iterations=50)
  45. state.history = [] # Initialize history as an empty list
  46. return StuckDetector(state)
  47. def _impl_syntax_error_events(
  48. self,
  49. state: State,
  50. error_message: str,
  51. random_line: bool,
  52. incidents: int = 4,
  53. ):
  54. for i in range(incidents):
  55. ipython_action = IPythonRunCellAction(code=code_snippet)
  56. state.history.append(ipython_action)
  57. extra_number = (i + 1) * 10 if random_line else '42'
  58. extra_line = '\n' * (i + 1) if random_line else ''
  59. ipython_observation = IPythonRunCellObservation(
  60. content=f' Cell In[1], line {extra_number}\n'
  61. 'to_replace="""def largest(min_factor, max_factor):\n ^\n'
  62. f'{error_message}{extra_line}' + jupyter_line_1 + jupyter_line_2,
  63. code=code_snippet,
  64. )
  65. # ipython_observation._cause = ipython_action._id
  66. state.history.append(ipython_observation)
  67. def _impl_unterminated_string_error_events(
  68. self, state: State, random_line: bool, incidents: int = 4
  69. ):
  70. for i in range(incidents):
  71. ipython_action = IPythonRunCellAction(code=code_snippet)
  72. state.history.append(ipython_action)
  73. line_number = (i + 1) * 10 if random_line else '1'
  74. ipython_observation = IPythonRunCellObservation(
  75. content=f'print(" Cell In[1], line {line_number}\nhello\n ^\nSyntaxError: unterminated string literal (detected at line {line_number})'
  76. + jupyter_line_1
  77. + jupyter_line_2,
  78. code=code_snippet,
  79. )
  80. # ipython_observation._cause = ipython_action._
  81. state.history.append(ipython_observation)
  82. def test_history_too_short(self, stuck_detector: StuckDetector):
  83. state = stuck_detector.state
  84. message_action = MessageAction(content='Hello', wait_for_response=False)
  85. message_action._source = EventSource.USER
  86. observation = NullObservation(content='')
  87. # observation._cause = message_action.id
  88. state.history.append(message_action)
  89. state.history.append(observation)
  90. cmd_action = CmdRunAction(command='ls')
  91. state.history.append(cmd_action)
  92. cmd_observation = CmdOutputObservation(
  93. command_id=1, command='ls', content='file1.txt\nfile2.txt'
  94. )
  95. # cmd_observation._cause = cmd_action._id
  96. state.history.append(cmd_observation)
  97. assert stuck_detector.is_stuck() is False
  98. def test_is_stuck_repeating_action_observation(self, stuck_detector: StuckDetector):
  99. state = stuck_detector.state
  100. message_action = MessageAction(content='Done', wait_for_response=False)
  101. message_action._source = EventSource.USER
  102. hello_action = MessageAction(content='Hello', wait_for_response=False)
  103. hello_observation = NullObservation('')
  104. # 2 events
  105. state.history.append(hello_action)
  106. state.history.append(hello_observation)
  107. cmd_action_1 = CmdRunAction(command='ls')
  108. cmd_action_1._id = 1
  109. state.history.append(cmd_action_1)
  110. cmd_observation_1 = CmdOutputObservation(content='', command='ls', command_id=1)
  111. cmd_observation_1._cause = cmd_action_1._id
  112. state.history.append(cmd_observation_1)
  113. # 4 events
  114. cmd_action_2 = CmdRunAction(command='ls')
  115. cmd_action_2._id = 2
  116. state.history.append(cmd_action_2)
  117. cmd_observation_2 = CmdOutputObservation(content='', command='ls', command_id=2)
  118. cmd_observation_2._cause = cmd_action_2._id
  119. state.history.append(cmd_observation_2)
  120. # 6 events
  121. # random user message just because we can
  122. message_null_observation = NullObservation(content='')
  123. state.history.append(message_action)
  124. state.history.append(message_null_observation)
  125. # 8 events
  126. assert stuck_detector.is_stuck() is False
  127. assert stuck_detector.state.almost_stuck == 2
  128. cmd_action_3 = CmdRunAction(command='ls')
  129. cmd_action_3._id = 3
  130. state.history.append(cmd_action_3)
  131. cmd_observation_3 = CmdOutputObservation(content='', command='ls', command_id=3)
  132. cmd_observation_3._cause = cmd_action_3._id
  133. state.history.append(cmd_observation_3)
  134. # 10 events
  135. assert len(state.history) == 10
  136. assert (
  137. len(state.history) == 10
  138. ) # Adjusted since history is a list and the controller is not running
  139. # FIXME are we still testing this without this test?
  140. # assert (
  141. # len(
  142. # get_pairs_from_events(state.history)
  143. # )
  144. # == 5
  145. # )
  146. assert stuck_detector.is_stuck() is False
  147. assert stuck_detector.state.almost_stuck == 1
  148. cmd_action_4 = CmdRunAction(command='ls')
  149. cmd_action_4._id = 4
  150. state.history.append(cmd_action_4)
  151. cmd_observation_4 = CmdOutputObservation(content='', command='ls', command_id=4)
  152. cmd_observation_4._cause = cmd_action_4._id
  153. state.history.append(cmd_observation_4)
  154. # 12 events
  155. assert len(state.history) == 12
  156. # assert (
  157. # len(
  158. # get_pairs_from_events(state.history)
  159. # )
  160. # == 6
  161. # )
  162. with patch('logging.Logger.warning') as mock_warning:
  163. assert stuck_detector.is_stuck() is True
  164. assert stuck_detector.state.almost_stuck == 0
  165. mock_warning.assert_called_once_with('Action, Observation loop detected')
  166. def test_is_stuck_repeating_action_error(self, stuck_detector: StuckDetector):
  167. state = stuck_detector.state
  168. # (action, error_observation), not necessarily the same error
  169. message_action = MessageAction(content='Done', wait_for_response=False)
  170. message_action._source = EventSource.USER
  171. hello_action = MessageAction(content='Hello', wait_for_response=False)
  172. hello_observation = NullObservation(content='')
  173. state.history.append(hello_action)
  174. # hello_observation._cause = hello_action._id
  175. state.history.append(hello_observation)
  176. # 2 events
  177. cmd_action_1 = CmdRunAction(command='invalid_command')
  178. state.history.append(cmd_action_1)
  179. error_observation_1 = ErrorObservation(content='Command not found')
  180. # error_observation_1._cause = cmd_action_1._id
  181. state.history.append(error_observation_1)
  182. # 4 events
  183. cmd_action_2 = CmdRunAction(command='invalid_command')
  184. state.history.append(cmd_action_2)
  185. error_observation_2 = ErrorObservation(
  186. content='Command still not found or another error'
  187. )
  188. # error_observation_2._cause = cmd_action_2._id
  189. state.history.append(error_observation_2)
  190. # 6 events
  191. message_null_observation = NullObservation(content='')
  192. state.history.append(message_action)
  193. state.history.append(message_null_observation)
  194. # 8 events
  195. cmd_action_3 = CmdRunAction(command='invalid_command')
  196. state.history.append(cmd_action_3)
  197. error_observation_3 = ErrorObservation(content='Different error')
  198. # error_observation_3._cause = cmd_action_3._id
  199. state.history.append(error_observation_3)
  200. # 10 events
  201. cmd_action_4 = CmdRunAction(command='invalid_command')
  202. state.history.append(cmd_action_4)
  203. error_observation_4 = ErrorObservation(content='Command not found')
  204. # error_observation_4._cause = cmd_action_4._id
  205. state.history.append(error_observation_4)
  206. # 12 events
  207. with patch('logging.Logger.warning') as mock_warning:
  208. assert stuck_detector.is_stuck() is True
  209. mock_warning.assert_called_once_with(
  210. 'Action, ErrorObservation loop detected'
  211. )
  212. def test_is_stuck_invalid_syntax_error(self, stuck_detector: StuckDetector):
  213. state = stuck_detector.state
  214. self._impl_syntax_error_events(
  215. state,
  216. error_message='SyntaxError: invalid syntax. Perhaps you forgot a comma?',
  217. random_line=False,
  218. )
  219. with patch('logging.Logger.warning'):
  220. assert stuck_detector.is_stuck() is True
  221. def test_is_not_stuck_invalid_syntax_error_random_lines(
  222. self, stuck_detector: StuckDetector
  223. ):
  224. state = stuck_detector.state
  225. self._impl_syntax_error_events(
  226. state,
  227. error_message='SyntaxError: invalid syntax. Perhaps you forgot a comma?',
  228. random_line=True,
  229. )
  230. with patch('logging.Logger.warning'):
  231. assert stuck_detector.is_stuck() is False
  232. def test_is_not_stuck_invalid_syntax_error_only_three_incidents(
  233. self, stuck_detector: StuckDetector
  234. ):
  235. state = stuck_detector.state
  236. self._impl_syntax_error_events(
  237. state,
  238. error_message='SyntaxError: invalid syntax. Perhaps you forgot a comma?',
  239. random_line=True,
  240. incidents=3,
  241. )
  242. with patch('logging.Logger.warning'):
  243. assert stuck_detector.is_stuck() is False
  244. def test_is_stuck_incomplete_input_error(self, stuck_detector: StuckDetector):
  245. state = stuck_detector.state
  246. self._impl_syntax_error_events(
  247. state,
  248. error_message='SyntaxError: incomplete input',
  249. random_line=False,
  250. )
  251. with patch('logging.Logger.warning'):
  252. assert stuck_detector.is_stuck() is True
  253. def test_is_not_stuck_incomplete_input_error(self, stuck_detector: StuckDetector):
  254. state = stuck_detector.state
  255. self._impl_syntax_error_events(
  256. state,
  257. error_message='SyntaxError: incomplete input',
  258. random_line=True,
  259. )
  260. with patch('logging.Logger.warning'):
  261. assert stuck_detector.is_stuck() is False
  262. def test_is_not_stuck_ipython_unterminated_string_error_random_lines(
  263. self, stuck_detector: StuckDetector
  264. ):
  265. state = stuck_detector.state
  266. self._impl_unterminated_string_error_events(state, random_line=True)
  267. with patch('logging.Logger.warning'):
  268. assert stuck_detector.is_stuck() is False
  269. def test_is_not_stuck_ipython_unterminated_string_error_only_three_incidents(
  270. self, stuck_detector: StuckDetector
  271. ):
  272. state = stuck_detector.state
  273. self._impl_unterminated_string_error_events(
  274. state, random_line=False, incidents=3
  275. )
  276. with patch('logging.Logger.warning'):
  277. assert stuck_detector.is_stuck() is False
  278. def test_is_stuck_ipython_unterminated_string_error(
  279. self, stuck_detector: StuckDetector
  280. ):
  281. state = stuck_detector.state
  282. self._impl_unterminated_string_error_events(state, random_line=False)
  283. with patch('logging.Logger.warning'):
  284. assert stuck_detector.is_stuck() is True
  285. def test_is_not_stuck_ipython_syntax_error_not_at_end(
  286. self, stuck_detector: StuckDetector
  287. ):
  288. state = stuck_detector.state
  289. # this test is to make sure we don't get false positives
  290. # since the "at line x" is changing in between!
  291. ipython_action_1 = IPythonRunCellAction(code='print("hello')
  292. state.history.append(ipython_action_1)
  293. ipython_observation_1 = IPythonRunCellObservation(
  294. content='print("hello\n ^\nSyntaxError: unterminated string literal (detected at line 1)\nThis is some additional output',
  295. code='print("hello',
  296. )
  297. # ipython_observation_1._cause = ipython_action_1._id
  298. state.history.append(ipython_observation_1)
  299. ipython_action_2 = IPythonRunCellAction(code='print("hello')
  300. state.history.append(ipython_action_2)
  301. ipython_observation_2 = IPythonRunCellObservation(
  302. content='print("hello\n ^\nSyntaxError: unterminated string literal (detected at line 1)\nToo much output here on and on',
  303. code='print("hello',
  304. )
  305. # ipython_observation_2._cause = ipython_action_2._id
  306. state.history.append(ipython_observation_2)
  307. ipython_action_3 = IPythonRunCellAction(code='print("hello')
  308. state.history.append(ipython_action_3)
  309. ipython_observation_3 = IPythonRunCellObservation(
  310. content='print("hello\n ^\nSyntaxError: unterminated string literal (detected at line 3)\nEnough',
  311. code='print("hello',
  312. )
  313. # ipython_observation_3._cause = ipython_action_3._id
  314. state.history.append(ipython_observation_3)
  315. ipython_action_4 = IPythonRunCellAction(code='print("hello')
  316. state.history.append(ipython_action_4)
  317. ipython_observation_4 = IPythonRunCellObservation(
  318. content='print("hello\n ^\nSyntaxError: unterminated string literal (detected at line 2)\nLast line of output',
  319. code='print("hello',
  320. )
  321. # ipython_observation_4._cause = ipython_action_4._id
  322. state.history.append(ipython_observation_4)
  323. with patch('logging.Logger.warning') as mock_warning:
  324. assert stuck_detector.is_stuck() is False
  325. mock_warning.assert_not_called()
  326. def test_is_stuck_repeating_action_observation_pattern(
  327. self, stuck_detector: StuckDetector
  328. ):
  329. state = stuck_detector.state
  330. message_action = MessageAction(content='Come on', wait_for_response=False)
  331. message_action._source = EventSource.USER
  332. state.history.append(message_action)
  333. message_observation = NullObservation(content='')
  334. state.history.append(message_observation)
  335. cmd_action_1 = CmdRunAction(command='ls')
  336. state.history.append(cmd_action_1)
  337. cmd_observation_1 = CmdOutputObservation(
  338. command_id=1, command='ls', content='file1.txt\nfile2.txt'
  339. )
  340. # cmd_observation_1._cause = cmd_action_1._id
  341. state.history.append(cmd_observation_1)
  342. read_action_1 = FileReadAction(path='file1.txt')
  343. state.history.append(read_action_1)
  344. read_observation_1 = FileReadObservation(
  345. content='File content', path='file1.txt'
  346. )
  347. # read_observation_1._cause = read_action_1._id
  348. state.history.append(read_observation_1)
  349. cmd_action_2 = CmdRunAction(command='ls')
  350. state.history.append(cmd_action_2)
  351. cmd_observation_2 = CmdOutputObservation(
  352. command_id=2, command='ls', content='file1.txt\nfile2.txt'
  353. )
  354. # cmd_observation_2._cause = cmd_action_2._id
  355. state.history.append(cmd_observation_2)
  356. read_action_2 = FileReadAction(path='file1.txt')
  357. state.history.append(read_action_2)
  358. read_observation_2 = FileReadObservation(
  359. content='File content', path='file1.txt'
  360. )
  361. # read_observation_2._cause = read_action_2._id
  362. state.history.append(read_observation_2)
  363. message_action = MessageAction(content='Come on', wait_for_response=False)
  364. message_action._source = EventSource.USER
  365. state.history.append(message_action)
  366. message_null_observation = NullObservation(content='')
  367. state.history.append(message_null_observation)
  368. cmd_action_3 = CmdRunAction(command='ls')
  369. state.history.append(cmd_action_3)
  370. cmd_observation_3 = CmdOutputObservation(
  371. command_id=3, command='ls', content='file1.txt\nfile2.txt'
  372. )
  373. # cmd_observation_3._cause = cmd_action_3._id
  374. state.history.append(cmd_observation_3)
  375. read_action_3 = FileReadAction(path='file1.txt')
  376. state.history.append(read_action_3)
  377. read_observation_3 = FileReadObservation(
  378. content='File content', path='file1.txt'
  379. )
  380. # read_observation_3._cause = read_action_3._id
  381. state.history.append(read_observation_3)
  382. with patch('logging.Logger.warning') as mock_warning:
  383. assert stuck_detector.is_stuck() is True
  384. mock_warning.assert_called_once_with('Action, Observation pattern detected')
  385. def test_is_stuck_not_stuck(self, stuck_detector: StuckDetector):
  386. state = stuck_detector.state
  387. message_action = MessageAction(content='Done', wait_for_response=False)
  388. message_action._source = EventSource.USER
  389. hello_action = MessageAction(content='Hello', wait_for_response=False)
  390. state.history.append(hello_action)
  391. hello_observation = NullObservation(content='')
  392. # hello_observation._cause = hello_action._id
  393. state.history.append(hello_observation)
  394. cmd_action_1 = CmdRunAction(command='ls')
  395. state.history.append(cmd_action_1)
  396. cmd_observation_1 = CmdOutputObservation(
  397. command_id=cmd_action_1.id, command='ls', content='file1.txt\nfile2.txt'
  398. )
  399. # cmd_observation_1._cause = cmd_action_1._id
  400. state.history.append(cmd_observation_1)
  401. read_action_1 = FileReadAction(path='file1.txt')
  402. state.history.append(read_action_1)
  403. read_observation_1 = FileReadObservation(
  404. content='File content', path='file1.txt'
  405. )
  406. # read_observation_1._cause = read_action_1._id
  407. state.history.append(read_observation_1)
  408. cmd_action_2 = CmdRunAction(command='pwd')
  409. state.history.append(cmd_action_2)
  410. cmd_observation_2 = CmdOutputObservation(
  411. command_id=2, command='pwd', content='/home/user'
  412. )
  413. # cmd_observation_2._cause = cmd_action_2._id
  414. state.history.append(cmd_observation_2)
  415. read_action_2 = FileReadAction(path='file2.txt')
  416. state.history.append(read_action_2)
  417. read_observation_2 = FileReadObservation(
  418. content='Another file content', path='file2.txt'
  419. )
  420. # read_observation_2._cause = read_action_2._id
  421. state.history.append(read_observation_2)
  422. message_null_observation = NullObservation(content='')
  423. state.history.append(message_action)
  424. state.history.append(message_null_observation)
  425. cmd_action_3 = CmdRunAction(command='pwd')
  426. state.history.append(cmd_action_3)
  427. cmd_observation_3 = CmdOutputObservation(
  428. command_id=cmd_action_3.id, command='pwd', content='/home/user'
  429. )
  430. # cmd_observation_3._cause = cmd_action_3._id
  431. state.history.append(cmd_observation_3)
  432. read_action_3 = FileReadAction(path='file2.txt')
  433. state.history.append(read_action_3)
  434. read_observation_3 = FileReadObservation(
  435. content='Another file content', path='file2.txt'
  436. )
  437. # read_observation_3._cause = read_action_3._id
  438. state.history.append(read_observation_3)
  439. assert stuck_detector.is_stuck() is False
  440. def test_is_stuck_monologue(self, stuck_detector):
  441. state = stuck_detector.state
  442. # Add events to the history list directly
  443. message_action_1 = MessageAction(content='Hi there!')
  444. message_action_1._source = EventSource.USER
  445. state.history.append(message_action_1)
  446. message_action_2 = MessageAction(content='Hi there!')
  447. message_action_2._source = EventSource.AGENT
  448. state.history.append(message_action_2)
  449. message_action_3 = MessageAction(content='How are you?')
  450. message_action_3._source = EventSource.USER
  451. state.history.append(message_action_3)
  452. cmd_kill_action = CmdRunAction(
  453. command='echo 42', thought="I'm not stuck, he's stuck"
  454. )
  455. state.history.append(cmd_kill_action)
  456. message_action_4 = MessageAction(content="I'm doing well, thanks for asking.")
  457. message_action_4._source = EventSource.AGENT
  458. state.history.append(message_action_4)
  459. message_action_5 = MessageAction(content="I'm doing well, thanks for asking.")
  460. message_action_5._source = EventSource.AGENT
  461. state.history.append(message_action_5)
  462. message_action_6 = MessageAction(content="I'm doing well, thanks for asking.")
  463. message_action_6._source = EventSource.AGENT
  464. state.history.append(message_action_6)
  465. assert stuck_detector.is_stuck()
  466. # Add an observation event between the repeated message actions
  467. cmd_output_observation = CmdOutputObservation(
  468. content='OK, I was stuck, but no more.',
  469. command_id=42,
  470. command='storybook',
  471. exit_code=0,
  472. )
  473. # cmd_output_observation._cause = cmd_kill_action._id
  474. state.history.append(cmd_output_observation)
  475. message_action_7 = MessageAction(content="I'm doing well, thanks for asking.")
  476. message_action_7._source = EventSource.AGENT
  477. state.history.append(message_action_7)
  478. message_action_8 = MessageAction(content="I'm doing well, thanks for asking.")
  479. message_action_8._source = EventSource.AGENT
  480. state.history.append(message_action_8)
  481. with patch('logging.Logger.warning'):
  482. assert not stuck_detector.is_stuck()
  483. class TestAgentController:
  484. @pytest.fixture
  485. def controller(self):
  486. controller = Mock(spec=AgentController)
  487. controller._is_stuck = AgentController._is_stuck.__get__(
  488. controller, AgentController
  489. )
  490. controller.delegate = None
  491. controller.state = Mock()
  492. return controller
  493. def test_is_stuck_delegate_stuck(self, controller: AgentController):
  494. controller.delegate = Mock()
  495. controller.delegate._is_stuck.return_value = True
  496. assert controller._is_stuck() is True