test_onboarding_delivery_scope.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """No-network regressions: inputs and old failed queues never become new outputs."""
  2. import contextlib
  3. import copy
  4. import hashlib
  5. import importlib.util
  6. import io
  7. import json
  8. import os
  9. from pathlib import Path
  10. import sys
  11. import tempfile
  12. import time
  13. import unittest
  14. from unittest.mock import patch
  15. ROOT = Path(__file__).resolve().parents[2]
  16. RUNTIME = ROOT / 'cloud/onboarding/runtime'
  17. def load(name, file, package=False):
  18. spec = importlib.util.spec_from_file_location(name, file, submodule_search_locations=[str(file.parent)] if package else None)
  19. module = importlib.util.module_from_spec(spec)
  20. if package:
  21. sys.modules[name] = module
  22. spec.loader.exec_module(module)
  23. return module
  24. class DeliveryScopeTests(unittest.TestCase):
  25. def setUp(self):
  26. self.m = load('delivery_scope_hook', RUNTIME / 'scripts/fmode-deliverable-hook.py')
  27. self.m.log = lambda text: None
  28. self.now = time.time()
  29. def test_user_input_directory_is_denied_before_marked_extension(self):
  30. # Normalize using the runtime's OS rather than constructing actual /opt/data files.
  31. path = os.path.abspath('/opt/data/work/uploads/original/report.md')
  32. self.m.STATE_DIR_DENY = (os.path.abspath('/opt/data/work/uploads').replace('\\', '/') + '/',)
  33. with patch.object(self.m.os.path, 'abspath', side_effect=lambda p: str(p).replace('\\', '/')):
  34. self.assertFalse(self.m.classify(path.replace('\\', '/'), 123)[0])
  35. def test_old_tagged_and_untagged_queue_cannot_be_reclaimed_by_new_turn(self):
  36. self.assertFalse(self.m._queued_in_round({'turn_id': 'old', 'ts': self.now}, 'new'))
  37. self.assertFalse(self.m._queued_in_round({'ts': self.now - 60}, 'new'))
  38. self.assertFalse(self.m._queued_in_round({'ts': self.now}, 'new'))
  39. self.assertFalse(self.m._queued_in_round({'ts': self.now}, ''))
  40. self.assertTrue(self.m._queued_in_round({'turn_id': 'new', 'ts': self.now}, 'new'))
  41. def test_plain_text_new_turn_preserves_failed_queue_without_uploading(self):
  42. state = {'queued': [{'path': '/kept/report.md', 'turn_id': 'old', 'ts': self.now - 30}], 'pushed': []}
  43. original = copy.deepcopy(state)
  44. self.m.load_round = lambda sid: {'turn_id': 'new', 'start_ts': self.now}
  45. self.m.load_state = lambda sid: state
  46. self.m._denied = lambda path: None
  47. self.m.upload_and_register = lambda *args: self.fail('old failed queue must not cause network upload')
  48. self.m.save_state = lambda *args: self.fail('old failed queue must remain unchanged')
  49. out = io.StringIO()
  50. with patch.object(self.m.os.path, 'isfile', return_value=True), contextlib.redirect_stdout(out):
  51. self.m.handle_transform_llm_output({'session_id': 'fixture', 'response_text': 'ONLY_NEW_REPLY'})
  52. self.assertEqual(json.loads(out.getvalue())['response_text'], 'ONLY_NEW_REPLY')
  53. self.assertEqual(state, original)
  54. def test_direct_tool_candidate_records_current_turn(self):
  55. state = {'queued': [{'path': '/kept/report.md', 'turn_id': 'old', 'ts': self.now - 60}], 'pushed': []}
  56. self.m.load_round = lambda sid: {'turn_id': 'current', 'start_ts': self.now}
  57. self.m.load_state = lambda sid: state
  58. self.m._spawn_process_notice = lambda *args: None
  59. self.m.sweep_new_files = lambda *args: []
  60. self.m.paths_from_tool = lambda *args: ['/kept/report.md']
  61. self.m.classify = lambda *args: (True, 'fixture')
  62. self.m.save_state = lambda *args: None
  63. with patch.object(self.m.os.path, 'isfile', return_value=True), patch.object(self.m.os.path, 'getsize', return_value=12):
  64. self.m.handle_post_tool_call({'session_id': 'fixture', 'tool_name': 'write_file', 'tool_input': {}})
  65. self.assertEqual(state['queued'][0]['turn_id'], 'old')
  66. self.assertEqual(state['queued'][1]['turn_id'], 'current')
  67. def test_same_turn_failed_output_can_still_retry(self):
  68. old_failed = {'path': '/kept/report.md', 'turn_id': 'old', 'ts': self.now - 60}
  69. state = {'queued': [old_failed, {'path': '/kept/report.md', 'turn_id': 'current', 'ts': self.now}],
  70. 'pushed': [{'path': '/kept/report.md', 'turn_id': 'older-success', 'url': 'https://s3.fmode.cn/deliverables/old.md'}]}
  71. self.m.load_round = lambda sid: {'turn_id': 'current', 'start_ts': self.now}
  72. self.m.load_state = lambda sid: state
  73. self.m._denied = lambda path: None
  74. self.m.save_state = lambda *args: None
  75. self.m.LEDGER = Path(tempfile.gettempdir()) / 'nonexistent-delivery-scope-dir' / 'ledger.jsonl'
  76. calls = []
  77. def upload(items, *args):
  78. calls.append(items)
  79. return [{'path': '/kept/report.md', 'ok': True, 'url': 'https://s3.fmode.cn/deliverables/result.md', 'hub': {'ok': True}}]
  80. self.m.upload_and_register = upload
  81. # Suppress optional ledger output; no test artifacts escape the fixture.
  82. with tempfile.TemporaryDirectory() as directory:
  83. self.m.LEDGER = Path(directory) / 'ledger.jsonl'
  84. with patch.object(self.m.os.path, 'isfile', return_value=True), contextlib.redirect_stdout(io.StringIO()):
  85. self.m.handle_transform_llm_output({'session_id': 'fixture', 'response_text': 'done'})
  86. self.assertEqual(len(calls), 1)
  87. self.assertEqual(state['pushed'][-1]['turn_id'], 'current')
  88. self.assertEqual(state['queued'], [old_failed])
  89. def test_already_pushed_current_round_does_not_clear_old_failed_queue(self):
  90. old_failed = {'path': '/kept/old-failure.md', 'turn_id': 'old'}
  91. state = {'queued': [old_failed, {'path': '/kept/done.md', 'turn_id': 'now'}],
  92. 'pushed': [{'path': '/kept/done.md', 'url': 'https://s3.fmode.cn/deliverables/done.md', 'turn_id': 'now'}]}
  93. self.m.load_round = lambda sid: {'turn_id': 'now'}
  94. self.m.load_state = lambda sid: state
  95. self.m.save_state = lambda *args: None
  96. self.m._denied = lambda path: None
  97. self.m.upload_and_register = lambda *args: self.fail('current completed output cannot upload again')
  98. self.m._pushed_current_paths = lambda *args: {'/kept/done.md'}
  99. with patch.object(self.m.os.path, 'isfile', return_value=True), contextlib.redirect_stdout(io.StringIO()):
  100. self.m.handle_transform_llm_output({'session_id': 'fixture', 'response_text': 'done'})
  101. self.assertEqual(state['queued'], [old_failed])
  102. def test_current_round_path_skip_requires_verified_unchanged_bytes(self):
  103. with tempfile.TemporaryDirectory() as directory:
  104. file = Path(directory) / 'report.md'
  105. file.write_bytes(b'first version')
  106. state = {'pushed': [{'path': str(file), 'turn_id': 'now', 'url': 'https://s3.fmode.cn/deliverables/report.md', 'sha256': hashlib.sha256(file.read_bytes()).hexdigest()}]}
  107. self.assertEqual(self.m._pushed_current_paths(state, 'now'), {str(file)})
  108. file.write_bytes(b'new version')
  109. self.assertEqual(self.m._pushed_current_paths(state, 'now'), set())
  110. self.assertEqual(self.m._pushed_current_paths(state, 'different-turn'), set())
  111. def test_poisoned_current_pushed_input_url_cannot_suppress_real_output(self):
  112. with tempfile.TemporaryDirectory() as directory:
  113. file = Path(directory) / 'report.md'
  114. file.write_bytes(b'actual result')
  115. bad_url = 'https://s3.fmode.cn/user/owner/chat/report.md'
  116. good_url = 'https://s3.fmode.cn/deliverables/report.md'
  117. state = {'queued': [{'path': str(file), 'turn_id': 'now'}], 'pushed': [
  118. {'path': str(file), 'turn_id': 'now', 'url': bad_url, 'sha256': hashlib.sha256(file.read_bytes()).hexdigest()}]}
  119. self.m.load_round = lambda sid: {'turn_id': 'now'}
  120. self.m.load_state = lambda sid: state
  121. self.m.save_state = lambda *args: None
  122. self.m.LEDGER = Path(directory) / 'ledger.jsonl'
  123. calls = []
  124. def upload(items, *args):
  125. calls.append(items)
  126. return [{'path': str(file), 'ok': True, 'url': good_url, 'hub': {'ok': True}, 'sha256': hashlib.sha256(file.read_bytes()).hexdigest()}]
  127. self.m.upload_and_register = upload
  128. out = io.StringIO()
  129. with contextlib.redirect_stdout(out):
  130. self.m.handle_transform_llm_output({'session_id': 'fixture', 'response_text': 'done ' + bad_url})
  131. text = json.loads(out.getvalue())['response_text']
  132. self.assertEqual(len(calls), 1)
  133. self.assertIn(good_url, text)
  134. self.assertNotIn(bad_url, text)
  135. def test_user_upload_urls_never_qualify_for_output_reuse(self):
  136. self.assertTrue(self.m._user_upload_url('https://s3.fmode.cn/user/owner/chat/202611/input.md'))
  137. self.assertTrue(self.m._user_upload_url('https://file-cloud.fmode.cn/user/owner/chat/input.md'))
  138. self.assertFalse(self.m._user_upload_url('https://s3.fmode.cn/deliverables/agent/result.md'))
  139. self.assertFalse(self.m._user_upload_url('https://s3.fmode.cn/user/owner/avatar/picture.png'))
  140. class InjectionScopeTests(unittest.TestCase):
  141. def setUp(self):
  142. self.m = load('delivery_scope_plugin', RUNTIME / 'plugins/plugin-deliverable-inject/__init__.py', True)
  143. self.addCleanup(lambda: [sys.modules.pop(name, None) for name in list(sys.modules)
  144. if name == 'delivery_scope_plugin' or name.startswith('delivery_scope_plugin.')])
  145. def test_old_bad_pushed_inputs_are_not_injected_even_when_turn_matches(self):
  146. state = {'pushed': [
  147. {'path': '/opt/data/work/uploads/input.md', 'url': 'https://s3.fmode.cn/shared.md', 'turn_id': 'now'},
  148. {'path': '/opt/data/work/report.md', 'url': 'https://s3.fmode.cn/user/owner/chat/202611/report.md', 'turn_id': 'now'},
  149. {'path': '/opt/data/work/deliverables/report.md', 'url': 'https://s3.fmode.cn/deliverables/result.md', 'turn_id': 'now'},
  150. ]}
  151. self.assertEqual(self.m._collect_urls(state, 'now'), ['https://s3.fmode.cn/deliverables/result.md'])
  152. self.assertEqual(self.m._collect_pushed_paths(state, 'now'), ['/opt/data/work/deliverables/report.md'])
  153. self.assertIsNone(self.m._find_pushed_url('input.md', state['pushed'], 'now'))
  154. def test_plain_reply_does_not_gain_links_from_legacy_poisoned_state(self):
  155. self.m._load_state = lambda sid: {'pushed': [{'path': '/opt/data/work/uploads/input.txt', 'url': 'https://s3.fmode.cn/user/owner/chat/input.txt', 'turn_id': 'current'}]}
  156. result = self.m._on_transform_llm_output(response_text='ONLY_CURRENT_REPLY', session_id='fixture', turn_id='current')
  157. self.assertIn(result, (None, 'ONLY_CURRENT_REPLY'))
  158. def test_legacy_output_without_turn_tag_cannot_leak_into_new_reply(self):
  159. record = {'path': '/opt/data/work/deliverables/old.md', 'url': 'https://s3.fmode.cn/deliverables/old.md', 'ts': time.time()}
  160. self.assertEqual(self.m._collect_urls({'pushed': [record]}, 'new'), [])
  161. if __name__ == '__main__':
  162. unittest.main()