probe-dual-channel-contracts.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """离线复现当前双渠道风险;通过表示成功复现现状,不代表业务验收通过。"""
  2. from __future__ import annotations
  3. from dataclasses import dataclass
  4. import ast
  5. import importlib.util
  6. import json
  7. import os
  8. from pathlib import Path
  9. import tempfile
  10. import time
  11. from unittest.mock import patch
  12. ROOT = Path(__file__).resolve().parents[1]
  13. RUNTIME = ROOT / 'cloud/onboarding/runtime'
  14. def load(name: str, path: Path, package: bool = False):
  15. import sys
  16. spec = importlib.util.spec_from_file_location(
  17. name, path, submodule_search_locations=[str(path.parent)] if package else None)
  18. module = importlib.util.module_from_spec(spec)
  19. sys.modules[name] = module
  20. spec.loader.exec_module(module)
  21. return module
  22. def main():
  23. results = []
  24. def record(name, kind, observed, evidence):
  25. results.append({'name': name, 'kind': kind, 'observed': observed, 'evidence': evidence})
  26. installer = load('dual_probe_install', ROOT / 'cloud/onboarding/install.py')
  27. original = {'platforms': {'wecom': {'enabled': True, 'extra': {'bot_id': 'fixture-bot'}},
  28. 'matrix': {'enabled': False}}, 'plugins': {'enabled': ['existing']}}
  29. merged = installer.merge_config(original, {'plugins': ['bridge'], 'hooks': {}})
  30. assert merged['platforms']['wecom'] == original['platforms']['wecom']
  31. assert original['plugins']['enabled'] == ['existing']
  32. record('installer_preserves_wecom', 'working_contract', True, 'merge_config增量保留企微且不修改原对象')
  33. assert merged['platforms']['matrix']['enabled'] is False
  34. record('installer_preserves_explicit_matrix_disabled', 'configuration_gate', True,
  35. '已有matrix.enabled=false时仅追加typing_indicator;实际生效仍取决于安装版config_env优先级')
  36. inject = load('dual_probe_inject', RUNTIME / 'plugins/plugin-deliverable-inject/__init__.py', True)
  37. inject._load_state = lambda sid: {}
  38. inject._current_turn_id = lambda sid: 'fixture-turn'
  39. reference = 'https://work.weixin.qq.com/api/doc/90000/90136/91770'
  40. with patch.dict(os.environ, {'PLUGIN_DELIVERABLE_INJECT_DISABLE': '0', 'PLUGIN_FMODE_STRIP_MEDIA_DISABLE': '0'}):
  41. for platform in ('matrix', 'wecom'):
  42. text = '参考官方文档:' + reference
  43. transformed = inject._on_transform_llm_output(text, 'fixture-session', 'fixture-turn', platform=platform)
  44. assert reference not in transformed
  45. record(platform + '_ordinary_reference_url_removed', 'reproduced_defect', transformed,
  46. '无成果台账时普通参考链接被全局白名单删除,platform kwargs被忽略')
  47. media = inject._on_transform_llm_output('交付图片\nMEDIA:https://s3.fmode.cn/fixture/picture.png',
  48. 'fixture-session', 'fixture-turn', platform=platform)
  49. assert 'MEDIA:' not in media and 'https://' not in media
  50. record(platform + '_remote_media_anchor_removed', 'reproduced_behavior', media,
  51. '无本轮pushed时远程MEDIA锚点与URL均被剥除;需实际adapter确认终端后果')
  52. local = inject._on_transform_llm_output('交付文件\nMEDIA:/opt/data/work/output.pdf',
  53. 'fixture-session', 'fixture-turn', platform=platform)
  54. assert local is None or 'MEDIA:/opt/data/work/output.pdf' in local
  55. record(platform + '_local_media_anchor_preserved', 'working_contract', True,
  56. '本地MEDIA标记仍保留,不能把所有附件问题归因于全量剥除')
  57. outbound = load('dual_probe_outbound', RUNTIME / 'plugins/plugin-matrix-outbound-s3/__init__.py')
  58. with tempfile.TemporaryDirectory(prefix='fmode-dual-contract-') as tmp:
  59. directory = Path(tmp)
  60. a, b = directory / 'session-a/report.pdf', directory / 'session-b/report.pdf'
  61. a.parent.mkdir()
  62. b.parent.mkdir()
  63. a.write_bytes(b'AAAA')
  64. b.write_bytes(b'BBBB')
  65. now = time.time()
  66. for name, file, url, timestamp in [('a', a, 'https://s3.fmode.cn/fixture/a.pdf', now - 2),
  67. ('b', b, 'https://s3.fmode.cn/fixture/b.pdf', now - 1)]:
  68. (directory / (name + '.json')).write_text(json.dumps({'pushed': [
  69. {'path': str(file), 'url': url, 'ts': timestamp, 'turn_id': 'turn-' + name}]}))
  70. outbound._STATE_DIR = str(directory)
  71. outbound._INDEX_CACHE = {'sig': None, 'map': {}}
  72. actual = outbound._preuploaded_lookup(str(a), 4, wait=False)
  73. assert actual == 'https://s3.fmode.cn/fixture/b.pdf'
  74. record('same_name_same_size_cross_session_url', 'reproduced_defect', actual,
  75. '请求session-a/report.pdf却选中较新的session-b同名同大小文件;没有session/turn/hash约束')
  76. merge = load('dual_probe_media_merge', RUNTIME / 'plugins/plugin-media-text-merge/__init__.py')
  77. merge._log = lambda message: None
  78. merge._arm_timer = lambda chat_id, gateway: None
  79. @dataclass
  80. class Source:
  81. platform: str
  82. chat_id: str
  83. thread_id: str
  84. chat_type: str = 'dm'
  85. @dataclass
  86. class Event:
  87. source: Source
  88. text: str
  89. media_urls: list
  90. media_types: list
  91. with patch.dict(os.environ, {'MEDIA_TEXT_MERGE_SECONDS': '2.5'}):
  92. for label, second_platform in [('matrix_cross_thread', 'matrix'), ('same_chat_id_cross_platform', 'wecom')]:
  93. merge._PENDING.clear()
  94. first = Event(Source('matrix', 'same-chat', 'thread-a'), 'A', ['https://s3.fmode.cn/fixture/a.png'], ['image/png'])
  95. second = Event(Source(second_platform, 'same-chat', 'thread-b'), 'B', [], [])
  96. assert merge._on_pre_gateway_dispatch(first)['action'] == 'skip'
  97. assert merge._on_pre_gateway_dispatch(second)['action'] == 'skip'
  98. combined = merge._merged_event(merge._PENDING['same-chat'])
  99. assert combined.source.thread_id == 'thread-a' and 'B' in combined.text
  100. record(label + '_buffer_collision', 'reproduced_defect',
  101. {'keptPlatform': combined.source.platform, 'keptThread': combined.source.thread_id, 'mergedText': combined.text},
  102. '缓冲键只有chat_id;同房间不同thread会合并,跨平台相同chat_id也会合并')
  103. merge._PENDING.clear()
  104. hook_file = RUNTIME / 'scripts/fmode-deliverable-hook.py'
  105. hook_tree = ast.parse(hook_file.read_text(encoding='utf-8'))
  106. import re
  107. pure = {'os': os, 're': re, 'log': lambda message: None}
  108. names = {'_scrub_fake_urls', '_scrub_local_paths'}
  109. functions = [n for n in hook_tree.body if isinstance(n, ast.FunctionDef) and n.name in names]
  110. assert len(functions) == 2
  111. exec(compile(ast.Module(body=functions, type_ignores=[]), str(hook_file), 'exec'), pure)
  112. cleaned = pure['_scrub_fake_urls']('参考文档:https://work.weixin.qq.com/fixture', set())
  113. assert 'https://' not in cleaned
  114. record('shell_hook_reference_url_removed', 'reproduced_defect', cleaned,
  115. 'shell输出钩子纯函数也删除普通URL;完整调度是否采纳其输出仍须验证部署版hook返回语义')
  116. cleaned = pure['_scrub_local_paths']('交付文件\nMEDIA:/opt/data/work/output.pdf')
  117. assert 'MEDIA:' not in cleaned
  118. record('shell_hook_local_media_anchor_removed', 'reproduced_defect', cleaned,
  119. 'shell清洗函数删除本地MEDIA行;Python注入插件保留标记不代表整条链路保留')
  120. transform = next(n for n in hook_tree.body if isinstance(n, ast.FunctionDef) and n.name == 'handle_transform_llm_output')
  121. dedup = next(n for n in transform.body if isinstance(n, ast.If) and isinstance(n.test, ast.Name) and n.test.id == 'todo')
  122. with tempfile.TemporaryDirectory(prefix='fmode-dual-preupload-') as tmp:
  123. a, b = Path(tmp) / 'a/report.pdf', Path(tmp) / 'b/report.pdf'
  124. a.parent.mkdir()
  125. b.parent.mkdir()
  126. a.write_bytes(b'AAAA')
  127. b.write_bytes(b'BBBB')
  128. os.utime(a, (100, 100))
  129. os.utime(b, (200, 200))
  130. namespace = {'os': os, 'log': lambda message: None,
  131. 'todo': [{'path': str(a), 'turn_id': 'same-turn'}, {'path': str(b), 'turn_id': 'same-turn'}]}
  132. exec(compile(ast.Module(body=[dedup], type_ignores=[]), str(hook_file), 'exec'), namespace)
  133. assert len(namespace['todo']) == 1 and namespace['todo'][0]['path'] == str(b)
  134. record('preupload_same_turn_different_content_dropped', 'reproduced_defect',
  135. {'inputFiles': 2, 'retainedFiles': len(namespace['todo'])},
  136. '直接执行上传前现有AST去重分支:同轮不同目录/同名同大小但内容不同,只保留较新文件')
  137. reporter_file = RUNTIME / 'plugins/plugin-active-reporter/__init__.py'
  138. tree = ast.parse(reporter_file.read_text(encoding='utf-8'))
  139. function = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == '_fmode_channel_snapshot')
  140. namespace = {}
  141. exec(compile(ast.Module(body=[function], type_ignores=[]), str(reporter_file), 'exec'), namespace)
  142. with tempfile.TemporaryDirectory(prefix='fmode-dual-reporter-') as tmp:
  143. (Path(tmp) / 'gateway_state.json').write_text(json.dumps({'platforms': {
  144. 'matrix': {'state': 'connected'}, 'wecom': {'state': 'connected'}}}))
  145. with patch.dict(os.environ, {'HERMES_HOME': tmp, 'MATRIX_USER_ID': '@fixture:invalid'}):
  146. snapshot = namespace['_fmode_channel_snapshot']()
  147. assert snapshot['matrix'] is True and 'wecom' not in snapshot
  148. record('reporter_omits_connected_wecom', 'reproduced_defect', snapshot,
  149. '输入双渠道connected,输出只有matrix/matrixConfig;本地云函数agent.set(field,value)整字段赋值,线上部署版本待比对')
  150. result = {'scope': 'local_offline_existing_source_only', 'meaning': '通过表示复现断言成立,不代表修复或线上验收',
  151. 'networkRequests': 0, 'productionChanges': 0, 'observations': results}
  152. output = ROOT / 'test-results/dual-channel-20261201/local-contract-probe.json'
  153. output.parent.mkdir(parents=True, exist_ok=True)
  154. output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
  155. print(json.dumps({'observations': len(results), 'evidence': str(output.relative_to(ROOT)),
  156. 'defectsReproduced': sum(x['kind'] == 'reproduced_defect' for x in results)}, ensure_ascii=False))
  157. if __name__ == '__main__':
  158. main()