Peach: Local-first video metadata scraper and media manager.
fix(diagnostics): 将标准库连接清理断连保留为本机证据
longmeidao9fb5dbc93d30
diff --git a/docs/DIAGNOSTICS_AUDIT.md b/docs/DIAGNOSTICS_AUDIT.mdindex ed2a0fbf9..f45ee347a 100644--- a/docs/DIAGNOSTICS_AUDIT.md+++ b/docs/DIAGNOSTICS_AUDIT.md@@ -43,6 +43,8 @@回归验收使用临时数据根和 SDK 内存接收端。本机已配置独立的 `peach-errors` 与 `peach-library-research` 接收项目,合成错误 `PEACH-ERRORS-1` 已在 Sentry 核对代码位置;没有发送真实馆藏。发布工作流的两个公开 DSN 仓库变量已配置并回读核对,构建包从变量取得接收地址;配置变量不触发发布。技术诊断选择见 [ADR-0110](adr/0110-recommended-diagnostics-choice.md)。安装辅助进程只在本机取证,不初始化远程客户端或发送事件;应用进程按用户选择发送。+`asyncio` 连接清理只在同时满足以下条件时保留为本机诊断:`ConnectionResetError` 的 `winerror` 为 `10054`,回调为标准库 `_ProactorBasePipeTransport._call_connection_lost`,调用栈只含该回调与 `asyncio.events._run`,且没有关联异常。该分类不发送至 Sentry;其他错误码、回调、业务栈与关联异常继续按技术故障规则处理。本机记录保留异常与标准库帧,并补充回调、协议类、可识别的服务端类别和 TLS 标志;这些上下文字段不进入远程载荷,不访问连接地址、请求内容或对象文本。默认事件循环处理器仍执行,底层连接清理行为沿用 Python 标准库。+### 馆藏与口味群体研究「馆藏与口味研究」是独立默认关闭的选项。首次设置说明入口;设置页先列出字段,再生成可滚动查看的完整本机 JSON 预览。用户还必须主动勾选「我已查看字段与预览,同意每周自动上传馆藏与口味明细用于 Peach 群体研究」,才可开启。服务端要求当前进程生成、10 分钟内有效的一次性预览凭据和当前字段版本;单独提交开关或打开错误诊断均不构成同意。关闭不要求预览或重新同意。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 8897c61c0..5ab75e4d3 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -150,6 +150,8 @@ Peach 播放器皮肤直接装饰 Video.js 10 的 light DOM:右侧控制组用可选远程诊断复用官方 [sentry-sdk 2.72.0](https://github.com/getsentry/sentry-python/tree/2.72.0)(MIT,维护中,支持 Python 3.14);固定版源码通过 `opensrc path pypi:sentry-sdk` 核对。SDK 负责后台 HTTP、TLS、Sentry 信封和服务端限流;Peach 负责本机选择、技术字段投影、同类错误去重与每机每日上限。版本统计与错误诊断共用默认勾选的开关,关闭时不构造 SDK;SDK 全局自动集成、追踪、回放、日志、会话与指标采集均关闭。`HttpTransport._send_envelope` 的窄覆盖在真正发送前复查本机选择版本并移除本机传输元数据;它是固定版本的内部接口,升级必须通过真实 SDK 信封回归。无真实外发的内存接收端检查最终字节、停用后队列失效与断网不影响本机取证。新增依赖仅 `sentry-sdk`,复用已声明的 urllib3 / certifi;体积以发行构建为准。未采用自写 Sentry 协议或 Workers 收集后台,避免另行维护传输、去重和查看界面。没有真实 ledger 写入。+Windows 连接清理诊断复用 CPython 3.14.7 的 `asyncio` 回调与异常栈(PSF 许可,无新增依赖)。只将纯标准库 `_call_connection_lost` 回调中的 `WinError 10054` 分类为本机连接清理证据,保留其他网络故障。核对本机 `proactor_events.py` 源码与重启前后日志;33 次回环实验未复现原始竞争时序,不据此认定客户端来源。合成异常通过真实 `asyncio.Handle` 分派验证筛选与默认处理器,协议类别只写本机日志。没有修改或复制传输实现、全局替换事件循环,或引入另一套日志 SDK。+馆藏与口味群体研究复用 `LedgerDatabase.read_connection`、`taste_preferences.preference_profile`、`error_reporting.redact` 与同一固定版 Sentry 的内存附件 API;偏好权重与身份口径不另写一份。研究使用独立项目、独立同意文件和字段版本;默认关闭,预览只在用户点击时读取,后台读取要求有效同意与接收端。没有复制浏览器资料、原始历史或媒体,没有真实 ledger 写入。SDK 本机安装目录含缓存约 3.1 MB,Windows 构建复制 MIT 许可证元数据;压缩后的发行增量未单独测量。`src/peach/diagnostics.py` 统一生成 CLI 与本机 API 报告;复用 `settings_file`、`health` 的只读迁移校验、`FFmpegResolver`、访问策略和挂载快照。数据库用 SQLite `mode=ro`;写入与端口检查用标准库短暂探针,不新增运行依赖。diff --git a/src/peach/error_reporting.py b/src/peach/error_reporting.pyindex bf38908a1..2cd0be782 100644--- a/src/peach/error_reporting.py+++ b/src/peach/error_reporting.py@@ -251,6 +251,52 @@ def cli_main() -> int:return 1+def _code_name(value) -> str:+ name = f"{getattr(value, '__module__', '')}.{getattr(value, '__qualname__', '')}"+ return name if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_.]{0,180}", name) else ""+++def _asyncio_fields(context) -> dict:+ """仅保留代码类别,不访问连接地址、实例文本或请求内容。"""+ callback = getattr(context.get("handle"), "_callback", None)+ transport = context.get("transport") or getattr(callback, "__self__", None)+ protocol = context.get("protocol") or getattr(transport, "_protocol", None)+ fields = {}+ if name := _code_name(callback):+ fields["asyncio_callback"] = name+ tls = _code_name(type(protocol)) == "asyncio.sslproto.SSLProtocol"+ if tls:+ protocol = getattr(protocol, "_app_protocol", None)+ if protocol is not None and (name := _code_name(type(protocol))):+ fields["asyncio_protocol"] = name+ if name.startswith("uvicorn.protocols.http."):+ fields["asyncio_connection_role"] = "http-server"+ if tls:+ fields["asyncio_tls"] = True+ return fields+++def is_asyncio_connection_cleanup(error, fields) -> bool:+ """识别 Winsock 重置连接时、纯标准库清理回调中的异常。"""+ callback = "asyncio.proactor_events._ProactorBasePipeTransport._call_connection_lost"+ if (not isinstance(error, ConnectionResetError) or getattr(error, "winerror", None) != 10054+ or fields.get("asyncio_callback") != callback+ or error.__cause__ is not None or error.__context__ is not None):+ return False+ frame = error.__traceback__+ last = None+ while frame is not None:+ last = (frame.tb_frame.f_globals.get("__name__"), frame.tb_frame.f_code.co_name)+ if last not in {("asyncio.events", "_run"), ("asyncio.proactor_events", "_call_connection_lost")}:+ return False+ frame = frame.tb_next+ return last == ("asyncio.proactor_events", "_call_connection_lost")++def asyncio_handler(loop, context) -> None:- event("unhandled-asyncio", context.get("exception"), message=context.get("message", ""))+ error = context.get("exception")+ fields = _asyncio_fields(context)+ if is_asyncio_connection_cleanup(error, fields):+ fields["classification"] = "connection-cleanup"+ event("unhandled-asyncio", error, message=context.get("message", ""), **fields)loop.default_exception_handler(context)diff --git a/src/peach/remote_reporting.py b/src/peach/remote_reporting.pyindex 5b370017a..2a8327650 100644--- a/src/peach/remote_reporting.py+++ b/src/peach/remote_reporting.py@@ -232,6 +232,10 @@ def _actionable(stage, error, fields):"""仅允许技术故障入口;预期领域状态和 SDK 自身日志留在本机。"""if str(fields.get("logger", "")).startswith(("sentry_sdk", "urllib3")):return False+ if stage == "unhandled-asyncio":+ from .error_reporting import is_asyncio_connection_cleanup+ if is_asyncio_connection_cleanup(error, fields):+ return Falsestages = {"browser", "http-request", "unhandled-main", "unhandled-thread", "unraisable","unhandled-asyncio", "cli", "packaged-cli", "desktop-entry", "tray-import","background-job", "library-preview", "frame-capture", "frame-tile", "media-probe",diff --git a/tests/test_error_reporting.py b/tests/test_error_reporting.pyindex 8b3f779ed..f2670af07 100644--- a/tests/test_error_reporting.py+++ b/tests/test_error_reporting.py@@ -1,4 +1,5 @@"""异常取证与分享报告只使用临时目录;进程级钩子在子进程里验证。"""+import asyncioimport ioimport jsonimport os@@ -393,6 +394,88 @@ class ErrorReportingTests(unittest.TestCase):self.assertEqual(self.records()[0]["stage"], "unhandled-asyncio")loop.default_exception_handler.assert_called_once()+ def asyncio_callback(self, error, *, module='asyncio.proactor_events',+ name='_call_connection_lost', business=False):+ namespace = {'__name__': module, 'failure': error}+ if business:+ exec(compile('def fail():\n raise failure\n', 'peach/network_fixture.py', 'exec'), namespace)+ operation = 'fail()' if business else 'raise failure'+ exec(compile(f'class _ProactorBasePipeTransport:\n def {name}(self):\n {operation}\n',+ 'asyncio/proactor_events.py', 'exec'), namespace)+ transport = namespace['_ProactorBasePipeTransport']()+ protocol_type = type('H11Protocol', (), {'__module__': 'uvicorn.protocols.http.h11_impl'})+ ssl_type = type('SSLProtocol', (), {'__module__': 'asyncio.sslproto'})+ transport._protocol = ssl_type()+ transport._protocol._app_protocol = protocol_type()+ transport.private_url = 'https://private.example/?token=private-token'+ transport.private_path = 'D:/private/movie.mp4'+ loop = mock.Mock()+ loop.get_debug.return_value = False+ loop.call_exception_handler.side_effect = lambda context: error_reporting.asyncio_handler(loop, context)+ asyncio.Handle(getattr(transport, name), (), loop)._run()+ return loop++ def test_windows_asyncio_connection_cleanup_stays_local_with_safe_context(self):+ from peach import remote_reporting+ error = ConnectionResetError(10054, 'connection reset')+ error.winerror = 10054+ with mock.patch.object(remote_reporting, 'send') as send:+ loop = self.asyncio_callback(error)+ send.assert_not_called()+ record = self.records()[0]+ self.assertEqual(record['classification'], 'connection-cleanup')+ self.assertEqual(record['asyncio_callback'],+ 'asyncio.proactor_events._ProactorBasePipeTransport._call_connection_lost')+ self.assertEqual(record['asyncio_protocol'], 'uvicorn.protocols.http.h11_impl.H11Protocol')+ self.assertEqual(record['asyncio_connection_role'], 'http-server')+ self.assertTrue(record['asyncio_tls'])+ self.assertEqual(record['exception'][0]['winerror'], 10054)+ self.assertEqual(record['frames'][-1]['function'], '_call_connection_lost')+ for value in ('private.example', 'private-token', 'movie.mp4', 'private_url', 'private_path'):+ self.assertNotIn(value, json.dumps(record))+ loop.default_exception_handler.assert_called_once()++ def test_asyncio_connection_faults_require_the_exact_cleanup_signature(self):+ from peach import remote_reporting+ cases = [+ ({}, 10053, ConnectionResetError),+ ({}, 10054, RuntimeError),+ ({'name': '_read_ready'}, 10054, ConnectionResetError),+ ({'module': 'peach.network_fixture'}, 10054, ConnectionResetError),+ ({'business': True}, 10054, ConnectionResetError),+ ]+ for options, code, error_type in cases:+ with self.subTest(options=options, code=code, error_type=error_type):+ error = error_type(code, 'network failure')+ error.winerror = code+ with mock.patch.object(remote_reporting, 'send') as send:+ loop = self.asyncio_callback(error, **options)+ send.assert_called_once()+ self.assertNotIn('classification', self.records()[-1])+ loop.default_exception_handler.assert_called_once()++ def test_asyncio_cleanup_with_linked_failure_keeps_remote_evidence(self):+ from peach import remote_reporting+ for attribute in ('__cause__', '__context__'):+ with self.subTest(attribute=attribute):+ error = ConnectionResetError(10054, 'connection reset')+ error.winerror = 10054+ setattr(error, attribute, ValueError('linked failure'))+ with mock.patch.object(remote_reporting, 'send') as send:+ self.asyncio_callback(error)+ send.assert_called_once()+ self.assertNotIn('classification', self.records()[-1])+ self.assertNotIn('asyncio_protocol', json.dumps(send.call_args.args[1]))++ def test_connection_reset_in_business_stage_is_reported_without_asyncio_metadata(self):+ from peach import remote_reporting+ error = ConnectionResetError(10054, 'business network failure')+ error.winerror = 10054+ with mock.patch.object(remote_reporting, 'send') as send:+ error_reporting.event('background-job', error)+ send.assert_called_once()+ self.assertEqual(send.call_args.args[1]['tags']['winerror'], '10054')+def test_unraisable_errors_and_logging_exceptions_have_persistent_records(self):code = """import gc, logging, sys