From e1b961b88e4f3256fa0b40d1ea4fdf330e8c1c30 Mon Sep 17 00:00:00 2001 From: Aqr-K <1210498076@qq.com> Date: Sun, 13 Sep 2026 00:14:56 -0400 Subject: [PATCH] =?UTF-8?q?fix(log):=20=E5=9B=9E=E8=B0=83=E6=8D=A2?= =?UTF-8?q?=E5=AE=9E=E4=BE=8B=E9=87=8D=E7=BB=91=E6=97=B6=E4=BB=8E=E5=8E=9F?= =?UTF-8?q?=E5=A7=8B=E5=9B=9E=E8=B0=83=E9=87=8D=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 防止包装链随重载次数无限增长的幂等守卫只判断「是否已被包装」,没判断「是不是 为同一个实例包装的」。已为实例 A 包装的回调再为实例 B 包装时,外层先绑定 B, 调用旧包装器后内层又绑回 A,原始回调仍在 A 的上下文中执行,B 的日志按 A 的 覆盖等级过滤,实例日志设置互相隔离的合同被破坏。插件的 `get_api`/`get_service` 返回同一份缓存声明、被多个分身依次注册即可触发。 改为在包装标记里一并记住最内层的原始回调,换实例重绑时剥回原始回调重新包装, 同实例重复包装仍返回原对象。标记值用私有 NamedTuple 承载并以 `isinstance` 校验, `Mock` 之类会为任意属性名凭空造值的回调才不会让重绑取到与包装无关的垃圾。 --- app/runtime/log.py | 41 ++++++++++++++++++++------- tests/test_plugin_instance_logging.py | 41 +++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 10 deletions(-) diff --git a/app/runtime/log.py b/app/runtime/log.py index 21c86bd17..f94ecc6ed 100644 --- a/app/runtime/log.py +++ b/app/runtime/log.py @@ -19,7 +19,7 @@ from datetime import datetime, timezone from logging.handlers import RotatingFileHandler from pathlib import Path from types import FrameType -from typing import Any, Callable, Dict, Iterator, Optional, Protocol, Self, Tuple +from typing import Any, Callable, Dict, Iterator, NamedTuple, Optional, Protocol, Self, Tuple import click from pydantic import BaseModel, ConfigDict @@ -273,7 +273,19 @@ def bind_plugin_instance(instance_id: str) -> Iterator[None]: _current_plugin_instance.reset(token) -# 标记包装函数已绑定的实例,用于判定是否已经包过,避免重复包装叠成长链 +class _InstanceBinding(NamedTuple): + """包装函数身上的绑定标记:已绑定的实例,以及被包在最内层的原始回调。 + + 用私有类型而非裸值承载,是为了能用 `isinstance` 认出这确实是本模块包的: + 插件回调可能是 `Mock` 之类会为任意属性名凭空造值的对象,按属性名取值会拿到 + 与包装无关的垃圾。 + """ + + instance_id: str + origin: Callable[..., Any] + + +# 包装函数携带绑定标记的属性名 _PLUGIN_BINDING_MARK = "_plugin_instance_binding" @@ -291,30 +303,39 @@ def wrap_for_plugin_instance( 对同一实例重复包装直接返回原对象:插件的 `get_api`/`get_service` 可能 每次都返回同一份缓存好的声明,每次刷新注册再包一层会让包装链随重载次数 无限增长。 + + 换成另一个实例重绑时,包的是内层的原始回调而不是上一个包装器:绑定发生在 + 包装函数体内,旧包装器嵌在新绑定里只会在新绑定之后再把上下文改回旧实例, + 原始回调仍按旧实例的等级过滤。共享同一份缓存声明的多个分身依次注册即可触发。 :param func: 插件提供的原始回调,通常是插件实例的绑定方法 :param instance_id: 实例 ID :return: 包装后的可调用对象 """ - if getattr(func, _PLUGIN_BINDING_MARK, None) == instance_id: + binding = getattr(func, _PLUGIN_BINDING_MARK, None) + if not isinstance(binding, _InstanceBinding): + origin = func + elif binding.instance_id == instance_id: return func + else: + origin = binding.origin - if inspect.iscoroutinefunction(func): - @functools.wraps(func) + if inspect.iscoroutinefunction(origin): + @functools.wraps(origin) async def _async_wrapped(*args: Any, **kwargs: Any) -> Any: """在绑定实例上下文内等待原始协程回调。""" with bind_plugin_instance(instance_id): - return await func(*args, **kwargs) + return await origin(*args, **kwargs) - setattr(_async_wrapped, _PLUGIN_BINDING_MARK, instance_id) + setattr(_async_wrapped, _PLUGIN_BINDING_MARK, _InstanceBinding(instance_id, origin)) return _async_wrapped - @functools.wraps(func) + @functools.wraps(origin) def _sync_wrapped(*args: Any, **kwargs: Any) -> Any: """在绑定实例上下文内调用原始同步回调。""" with bind_plugin_instance(instance_id): - return func(*args, **kwargs) + return origin(*args, **kwargs) - setattr(_sync_wrapped, _PLUGIN_BINDING_MARK, instance_id) + setattr(_sync_wrapped, _PLUGIN_BINDING_MARK, _InstanceBinding(instance_id, origin)) return _sync_wrapped diff --git a/tests/test_plugin_instance_logging.py b/tests/test_plugin_instance_logging.py index af84616e9..76a66c26f 100644 --- a/tests/test_plugin_instance_logging.py +++ b/tests/test_plugin_instance_logging.py @@ -230,6 +230,47 @@ def test_wrap_for_plugin_instance_is_idempotent_for_the_same_instance(): assert wrap_for_plugin_instance(wrapped, "OtherInstance") is not wrapped +def test_rebinding_a_wrapped_callable_to_another_instance_switches_the_context(): + """同一个回调先为 A 包装再为 B 包装,执行时上下文必须是 B。 + + 插件的 `get_api`/`get_service` 可能每次都返回同一份缓存好的声明,多个分身 + 依次注册就会把同一个回调对象接连包装;拿旧包装器当内层的话,内层会在外层 + 绑定之后再把上下文改回 A,B 的日志就按 A 的覆盖等级过滤。 + """ + seen: list[str | None] = [] + + def _callback() -> None: + seen.append(current_plugin_instance_id()) + + for_a = wrap_for_plugin_instance(_callback, "InstanceA") + for_b = wrap_for_plugin_instance(for_a, "InstanceB") + for_b() + + assert seen == ["InstanceB"] + # 重绑包的是内层原始回调,包装链不随重绑次数变长 + assert for_b.__wrapped__ is _callback + assert wrap_for_plugin_instance(for_b, "InstanceB") is for_b + # 已经交出去的 A 包装器不受重绑影响,仍按 A 绑定 + for_a() + assert seen == ["InstanceB", "InstanceA"] + + +def test_rebinding_a_wrapped_coroutine_to_another_instance_switches_the_context(): + """异步回调重绑到另一个实例后,等待期间的上下文必须是新实例。""" + seen: list[str | None] = [] + + async def _callback() -> None: + seen.append(current_plugin_instance_id()) + + for_a = wrap_for_plugin_instance(_callback, "InstanceA") + for_b = wrap_for_plugin_instance(for_a, "InstanceB") + assert inspect.iscoroutinefunction(for_b) + asyncio.run(for_b()) + + assert seen == ["InstanceB"] + assert for_b.__wrapped__ is _callback + + def test_bound_instance_with_lower_override_emits_debug_log(fake_writer): """绑定实例设了更宽松的覆盖时,全局等级挡不住的 DEBUG 日志应放行。""" set_plugin_instance_log_level("DemoPluginWork", "DEBUG")