跳转至

Worker

任务单元。继承 BaseWorker 并实现 _execute()。

from zoo_framework.workers import BaseWorker

Worker 必须以「类」注册。 WorkerRegistry 用 issubclass 校验,传入函数或实例会得到 TypeError: issubclass() arg 1 must be a class。

zoo_framework.workers.base_worker.BaseWorker

Worker base class.

Configuration is carried uniformly by the _props dict; is_loop / run_timeout / delay_time are exposed as properties - reading them MUST NOT require call syntax, and subclasses MUST NOT shadow them with instance attributes.

源代码位于: zoo_framework/workers/base_worker.py
class BaseWorker:
    """Worker base class.

    Configuration is carried uniformly by the ``_props`` dict; ``is_loop`` /
    ``run_timeout`` / ``delay_time`` are exposed as properties - reading them
    MUST NOT require call syntax, and subclasses MUST NOT shadow them with
    instance attributes.
    """

    def __init__(self, props: dict):
        self._props = props
        self.state: dict = {}
        # 注解为 Callable | None 而非让它被推断成 None:`__del__` 里那处真值判定正是
        # "它可能被赋成可调用对象"的证据。**但现状是全仓库没有任何地方给它赋值**,
        # 故那条销毁路径目前恒不执行——这是独立于类型的问题,已记为发现,见任务表 3.1。
        self._destroy_func: Callable | None = None
        self._on_create()
        self.num = 1

    def __del__(self):
        if self._destroy_func:
            self._destroy_func()

    @property
    def is_loop(self) -> bool:
        """Whether to keep this Worker across scheduling rounds and re-execute it.

        ``_props`` is the single source of truth; treated as non-looping when
        undeclared.
        """
        return bool(self._props.get("is_loop", False))

    @property
    def run_timeout(self):
        """Timeout in seconds for one execution; None when undeclared."""
        return self._props.get("run_timeout")

    @property
    def period(self):
        """Execution period in seconds.

        None when undeclared, meaning **event-driven** (every scheduling round
        counts as due). The period is declared per Worker and MUST NOT be
        pinned uniformly by the process or the scheduling model.
        """
        return self._props.get("period")

    @property
    def phase(self):
        """Period phase offset in seconds; 0.0 when undeclared.

        The offset of the first trigger relative to the schedule baseline, used
        to stagger the trigger moments of multiple periodic Workers.
        """
        return self._props.get("phase", 0.0)

    @property
    def delay_time(self) -> float:
        """Seconds to wait after each execution; treated as no wait when undeclared."""
        return self._props.get("delay_time") or 0

    @property
    def registry_name(self) -> str:
        """The suffix-free identity: configured name, or class name when undeclared.

        ``name`` is this identity plus the instance ordinal. A receiver
        filtering results by "which Worker" MUST match on this identity, since
        the ordinal is not known when the filter is declared (issue #229).
        """
        if self._props.get("name"):
            return str(self._props.get("name"))
        return str(self.__class__.__name__)

    @property
    def name(self):
        """Instance-unique name: the registry name plus the instance ordinal."""
        return f"{self.registry_name}_{self.num}"

    def _destroy_result(self, result):
        pass

    def _execute(self):
        pass

    def _on_create(self):
        pass

    def _wait(self, seconds: float) -> None:
        """Delayed wait.

        ``sleep_func`` in ``props`` can replace the wait implementation, so
        scheduling-related test cases need no real waiting.
        """
        sleep_func = self._props.get("sleep_func") or time.sleep
        sleep_func(seconds)

    def run(self) -> WorkerResult:
        """Execute once.

        A failure is **reported, not left implicit** (issue #228): the result
        topic is how consumers observe that a Worker finished, so an execution
        body raising MUST still produce one result carrying the failure. The
        returned result is marked as a failure (``error`` set, ``success``
        false, content None) so consumers can tell "failed" apart from "still
        running"; the failure MUST NOT be delivered in the shape of a
        successful empty result. The error is logged and ``_on_error`` /
        ``_on_done`` still run, exactly as before.

        Returns:
            WorkerResult: The result of this execution. On failure the content
                is None and ``error`` carries the reason.
        """
        result: Any = {}
        error: Exception | None = None
        try:
            # 每轮进入/退出是框架自己的心跳,默认级别下不输出(log.level=debug 可见)
            LogUtils.debug(f"{self.name} Worker is Start", self.__class__.__name__)
            result = self._execute()
            self._destroy_result(result)
            LogUtils.debug(f"{self.name} Worker is Stop", self.__class__.__name__)
        except Exception as e:
            error = e
            self._on_error()
            LogUtils.error(str(e), self.__class__.__name__)
        finally:
            self._on_done()

        if error is not None:
            # 失败也产生一条结果(#228):消费者靠结果主题判断"跑完没有",
            # 只写日志的失败会被当成"仍在执行"(Worker 已不在调度表里,却永远
            # 等不到结果)。失败结果携带 error 标记,MUST NOT 冒充成功空结果。
            # 不写 _destroy_result:失败没有产出可销毁的结果。
            return WorkerResult(
                WaiterConstant.WORKER_RESULT_TOPIC,
                None,
                self.__class__.__name__,
                worker_name=self.name,
                registry_name=self.registry_name,
                error=f"{type(error).__name__}: {error}",
            )

        if self.delay_time:
            self._wait(self.delay_time)

        return WorkerResult(
            WaiterConstant.WORKER_RESULT_TOPIC,
            result,
            self.__class__.__name__,
            worker_name=self.name,
            registry_name=self.registry_name,
        )

    def _on_error(self):
        pass

    def _on_done(self):
        pass

is_loop property

is_loop: bool

Whether to keep this Worker across scheduling rounds and re-execute it.

_props is the single source of truth; treated as non-looping when undeclared.

run_timeout property

run_timeout

Timeout in seconds for one execution; None when undeclared.

period property

period

Execution period in seconds.

None when undeclared, meaning event-driven (every scheduling round counts as due). The period is declared per Worker and MUST NOT be pinned uniformly by the process or the scheduling model.

phase property

phase

Period phase offset in seconds; 0.0 when undeclared.

The offset of the first trigger relative to the schedule baseline, used to stagger the trigger moments of multiple periodic Workers.

delay_time property

delay_time: float

Seconds to wait after each execution; treated as no wait when undeclared.

registry_name property

registry_name: str

The suffix-free identity: configured name, or class name when undeclared.

name is this identity plus the instance ordinal. A receiver filtering results by "which Worker" MUST match on this identity, since the ordinal is not known when the filter is declared (issue #229).

name property

name

Instance-unique name: the registry name plus the instance ordinal.

run

run() -> WorkerResult

Execute once.

A failure is reported, not left implicit (issue #228): the result topic is how consumers observe that a Worker finished, so an execution body raising MUST still produce one result carrying the failure. The returned result is marked as a failure (error set, success false, content None) so consumers can tell "failed" apart from "still running"; the failure MUST NOT be delivered in the shape of a successful empty result. The error is logged and _on_error / _on_done still run, exactly as before.

返回:

名称 类型 描述
WorkerResult WorkerResult

The result of this execution. On failure the content is None and error carries the reason.

源代码位于: zoo_framework/workers/base_worker.py
def run(self) -> WorkerResult:
    """Execute once.

    A failure is **reported, not left implicit** (issue #228): the result
    topic is how consumers observe that a Worker finished, so an execution
    body raising MUST still produce one result carrying the failure. The
    returned result is marked as a failure (``error`` set, ``success``
    false, content None) so consumers can tell "failed" apart from "still
    running"; the failure MUST NOT be delivered in the shape of a
    successful empty result. The error is logged and ``_on_error`` /
    ``_on_done`` still run, exactly as before.

    Returns:
        WorkerResult: The result of this execution. On failure the content
            is None and ``error`` carries the reason.
    """
    result: Any = {}
    error: Exception | None = None
    try:
        # 每轮进入/退出是框架自己的心跳,默认级别下不输出(log.level=debug 可见)
        LogUtils.debug(f"{self.name} Worker is Start", self.__class__.__name__)
        result = self._execute()
        self._destroy_result(result)
        LogUtils.debug(f"{self.name} Worker is Stop", self.__class__.__name__)
    except Exception as e:
        error = e
        self._on_error()
        LogUtils.error(str(e), self.__class__.__name__)
    finally:
        self._on_done()

    if error is not None:
        # 失败也产生一条结果(#228):消费者靠结果主题判断"跑完没有",
        # 只写日志的失败会被当成"仍在执行"(Worker 已不在调度表里,却永远
        # 等不到结果)。失败结果携带 error 标记,MUST NOT 冒充成功空结果。
        # 不写 _destroy_result:失败没有产出可销毁的结果。
        return WorkerResult(
            WaiterConstant.WORKER_RESULT_TOPIC,
            None,
            self.__class__.__name__,
            worker_name=self.name,
            registry_name=self.registry_name,
            error=f"{type(error).__name__}: {error}",
        )

    if self.delay_time:
        self._wait(self.delay_time)

    return WorkerResult(
        WaiterConstant.WORKER_RESULT_TOPIC,
        result,
        self.__class__.__name__,
        worker_name=self.name,
        registry_name=self.registry_name,
    )

内建 Worker

zoo_framework.workers.event_worker.EventWorker

Bases: BaseWorker

Event Worker.

The key constraint of the consume loop: every event taken from the queue MUST have a settled destination - delivered, requeued, or moved to dead-letter. Silent dropping was historically this class's main source of event loss.

Join-timeout semantics (issue #232): the wait for a round's dispatch results is bounded by the maximum effective timeout across that round's reactors. A reactor's effective timeout is two-level: its own declared event_timout (a positive value = legitimately slow) takes precedence over the global event:timeout; undeclared reactors follow the global default, so the merged behavior equals the pre-change one. Only a future still unfinished after its own effective timeout elapses is reported as unfinished - a declared-slow reactor no longer triggers the warning every round.

Ordering (issue #230): a channel's FIFO is a delivery guarantee, not an execution-order guarantee. This consumer pops events in queue order and submits each one to the shared reactor executor, so calls to the same reactor overlap and finish in whatever order they actually complete - the completion order MUST NOT be assumed to follow the enqueue order, and consumers that need ordered handling MUST serialize on their own side (an explicit lock or queue). Enabling event:dispatchBatchingEnabled batches the same (channel, reactor) events of one round into a single executor task, which does execute them sequentially in dequeue order; it is a process-wide switch, not a per-topic declaration.

Note: this class MUST NOT be decorated with any class-replacing decorator (the historical @cage did exactly that and was deleted). WorkerRegistry.register_class validates the contract with issubclass; swapping the class for a function would make it raise TypeError: issubclass() arg 1 must be a class. The singleton and the instance cache are owned by WorkerRegistry._worker_instances, with no second mechanism needed - so this class also does not take @process_scoped: that would move the "one instance per Worker" ownership away from WorkerRegistry.

源代码位于: zoo_framework/workers/event_worker.py
class EventWorker(BaseWorker):
    """Event Worker.

    The key constraint of the consume loop: every event taken from the
    queue MUST have a settled destination - delivered, requeued, or moved to
    dead-letter. Silent dropping was historically this class's main source of
    event loss.

    Join-timeout semantics (issue #232): the wait for a round's dispatch
    results is bounded by the **maximum effective timeout** across that
    round's reactors. A reactor's effective timeout is two-level: its own
    declared `event_timout` (a positive value = legitimately slow) takes
    precedence over the global `event:timeout`; undeclared reactors follow
    the global default, so the merged behavior equals the pre-change one.
    Only a future still unfinished after its own effective timeout elapses
    is reported as unfinished - a declared-slow reactor no longer triggers
    the warning every round.

    Ordering (issue #230): a channel's FIFO is a **delivery** guarantee, not
    an execution-order guarantee. This consumer pops events in queue order and
    submits each one to the shared reactor executor, so calls to the same
    reactor overlap and finish in whatever order they actually complete -
    the completion order MUST NOT be assumed to follow the enqueue order, and
    consumers that need ordered handling MUST serialize on their own side (an
    explicit lock or queue). Enabling `event:dispatchBatchingEnabled` batches
    the same (channel, reactor) events of one round into a single executor
    task, which does execute them sequentially in dequeue order; it is a
    process-wide switch, not a per-topic declaration.

    Note: this class MUST NOT be decorated with any class-replacing decorator
    (the historical `@cage` did exactly that and was deleted).
    `WorkerRegistry.register_class` validates the contract with `issubclass`;
    swapping the class for a function would make it raise
    `TypeError: issubclass() arg 1 must be a class`. The singleton and the
    instance cache are owned by `WorkerRegistry._worker_instances`, with no
    second mechanism needed - so this class also does not take
    `@process_scoped`: that would move the "one instance per Worker"
    ownership away from `WorkerRegistry`.
    """

    @staticmethod
    def _effective_timeout(reactor) -> float:
        """Resolve a reactor's effective join timeout (two levels).

        The reactor's self-declared timeout wins when positive; otherwise the
        global `event:timeout` applies. Same shape as the worker side's
        `resolve_run_timeout` (self-report -> global default), without a
        config-override layer - the declaration entry point already exists
        (`@event(timeout=...)`), a second one would only add a second source
        of truth.

        Args:
            reactor: the reactor whose effective timeout is being resolved

        Returns:
            The effective timeout in seconds (always positive)
        """
        from zoo_framework.params import EventParams

        declared = getattr(reactor, "event_timout", None)
        if declared is not None and declared > 0:
            return float(declared)
        return float(EventParams.EVENT_JOIN_TIMEOUT)

    def __init__(self):
        # EventParams is imported lazily and must precede the props assembly:
        # the tempo participates in BaseWorker.__init__.
        # Resolution happens at first import; freezing into the defaults
        # would occur if it were earlier than the config load (see #51) -
        # this class is constructed by WorkerRegistry at runtime, so the
        # order holds.
        from zoo_framework.params import EventParams

        # is_loop is exposed by BaseWorker as a property with _props as the
        # sole source of truth; here it MUST NOT be shadowed by an instance
        # attribute (the property has no setter, assignment raises
        # AttributeError directly).
        BaseWorker.__init__(
            self,
            {
                "is_loop": True,
                "delay_time": EventParams.EVENT_DELAY_TIME,
                "name": "EventWorker",
            },
        )

        # Event channel manager
        self.eventChannelManager: EventChannelManager = EventChannelManager()

        # Reactor dispatch executor: built once per instance
        # (align-execution-primitives D1). Replaces the historical
        # gevent.spawn/joinall: greenlet primitives are unavailable on
        # free-threaded builds, and a single dispatch measured 38.1 us, far
        # above a thread submit.
        self._executor = ThreadPoolExecutor(
            max_workers=EventParams.EVENT_EXECUTOR_WORKERS,
            thread_name_prefix="zoo-event-reactor",
        )
        # The destroy path is invoked via BaseWorker.__del__; wait=False
        # matches the greenlet era: no forced kill and no unbounded wait for
        # in-flight reactors.
        self._destroy_func = partial(self._executor.shutdown, wait=False, cancel_futures=True)

    def _execute(self):
        from zoo_framework.params import EventParams

        # 推模型(add-event-push-model):若无事件,挂起等待生产者 notify——
        # 被唤醒或兜底超时后进入下方正常排空,消费主体完全复用。
        # 关闭时 _push_wait 是零开销空操作,行为与合入前逐字节一致。
        # 注意 MUST NOT 在挂起后做「全空则跳过排空」的守卫:notify/超时与
        # 生产者入队之间没有原子性,守卫求值瞬间恰好入队的事件会被饿到
        # 下一拍——空排空只花 µs,而竞态丢的可是真事件。
        if EventParams.PUSH_MODEL_ENABLED:
            self._push_wait(EventParams.PUSH_FALLBACK_TIMEOUT)

        if EventParams.DISPATCH_BATCHING_ENABLED:
            self._execute_batched()
            return

        channel_names = self.eventChannelManager.get_all_channel_name()
        # 定位条目 (future, reactor_name, topic, effective_timeout):上报时还原
        # 是谁在慢/谁抛了异常;生效超时在提交现场解析
        dispatched: list[tuple[Future, str, str, float]] = []
        # TODO: get all event channels except failed ones
        for channel_name in channel_names:
            # get_channel creates-and-returns in place on a miss, so it will **never** return None;
            # the old `if channel is None: continue` was therefore dead code (proven by type checking) and was removed.
            channel: EventChannel = self.eventChannelManager.get_channel(channel_name)
            # Get all the event channels
            # This round only consumes events already queued at round start: requeued events wait for the next round,
            # otherwise the retry quota is exhausted within one consume loop and retrying is void.
            pending = channel.size()
            while pending > 0:
                pending -= 1
                event_node: EventNode | None = channel.pop_value()
                # A race window exists between size() and pop_value(): a concurrent producer may take elements in between.
                # An empty pop means no events this round; the loop must end - any method call on None raises.
                if event_node is None:
                    break
                # Decide whether the event is expired
                if event_node.is_expire():
                    event_node.expire_callback()
                    continue
                # Get the event reactors
                try:
                    reactors = self.eventChannelManager.get_channel_reactors(event_node)
                except Exception as e:
                    # The event was already popped; the exception path also needs a settled destination
                    channel.push_dead_letter(event_node, reason=f"failed to look up reactors: {e}")
                    continue
                # If empty here, check the node's retry quota; with quota left it must go back to the queue.
                # `not reactors` covers both None and []: get_channel_reactors returns
                # `list[EventReactor] | None`, where None means "no matching reactor", same as an
                # empty list. (This used to be written len(reactors) == 0, with a None-triggered
                # TypeError caught by the except above - exceptions as control flow, misreporting
                # "no match" as "failed to look up reactors".)
                if not reactors:
                    self._requeue_or_dead_letter(channel, event_node, reason="no matching reactor")
                    continue
                for reactor in reactors:
                    # Run the event reactor: EventReactor's public entry is execute(topic, content).
                    # 提交即并发执行(#230):同一反应器的多次调用会重叠,完成顺序由各次
                    # 实际结束时刻决定——FIFO 只保证出队/投递顺序,不保证完成顺序。
                    f = self._executor.submit(reactor.execute, event_node.topic, event_node.content)
                    dispatched.append(
                        (
                            f,
                            reactor.reactor_name,
                            event_node.topic,
                            self._effective_timeout(reactor),
                        )
                    )

        if len(dispatched) > 0:
            # A bounded wait for this round's dispatch results; the bound is the
            # maximum effective timeout across the round's reactors so every
            # reactor's declared bound is honoured (issue #232).
            wait_timeout = max(t for *_, t in dispatched)
            wait([f for f, *_ in dispatched], timeout=wait_timeout)
            self._report_unfinished(dispatched, wait_timeout)

    def _push_wait(self, timeout: float) -> None:
        """推模型挂起:在所有通道的 Condition 上等待有事件(design D3).

        依次对每个通道 wait_ready:任一通道被唤醒即返回(消费主体下一行立即
        排空);每通道各自的兜底超时防止生产者侧异常导致的永久滞留。
        通道无 Condition(推模型关闭)时 wait_ready 立即返回,零开销。
        """
        for name in self.eventChannelManager.get_all_channel_name():
            channel = self.eventChannelManager.get_channel(name)
            if channel.wait_ready(timeout) and channel.size() > 0:
                return

    def _execute_batched(self):
        """批量投递的消费排空(optimize-event-dispatch-batching D1/D2).

        与逐事件路径相同的排空骨架(批量扫描/去向语义/重试),仅投递段不同:
        同 (channel, reactor) 的待投递事件聚合为一批,以单个 callable 一次提交
        ——执行器簿记按批计而非按事件计(本变更 4.1 同一运行内实测:逐事件提交
        5.8µs/事件 → 批上限 64 时摊到 0.17µs/事件;读数与口径见变更目录的
        booking_measurement.json)。
        批内仍逐事件调用 execute(topic, content),语义不变;批内异常捕获后
        打包为 BatchReactorError 上抛到 future,由批级上报携带事件定位信息。

        批大小上限(design D2):**限量的是取,不是裁**——本轮从每个通道最多
        取出 `event:batchMaxSize` 个事件,超出的留在队列里按原顺序等下一轮。
        每个批相应不超过该上限,大批独占执行器线程的形态被此上限兜住。
        """
        from zoo_framework.params import EventParams

        channel_names = self.eventChannelManager.get_all_channel_name()
        # 定位条目 (future, reactor_name, topics):批量路径以批内事件集合为定位
        dispatched: list[tuple[Future, str, set[str], float]] = []
        batch_limit = EventParams.BATCH_MAX_SIZE
        for channel_name in channel_names:
            channel: EventChannel = self.eventChannelManager.get_channel(channel_name)
            pending = channel.size()
            # 聚合表:id(reactor) -> (reactor, [(topic, content, node), ...])
            batches: dict[int, tuple] = {}
            # 本轮从本通道取出的事件数(含过期/死信/回队者)——批上限的计量单位。
            # 计数放在 `pending -= 1` 之前(design D2 的"限量扫描"):到上限就不再
            # pop,剩余事件**原样留在队列**里(不裁批、不丢失、不死信、不改顺序)。
            taken = 0
            while pending > 0 and taken < batch_limit:
                pending -= 1
                taken += 1
                event_node = channel.pop_value()
                if event_node is None:
                    break
                if event_node.is_expire():
                    event_node.expire_callback()
                    continue
                try:
                    reactors = self.eventChannelManager.get_channel_reactors(event_node)
                except Exception as e:
                    channel.push_dead_letter(event_node, reason=f"查询响应器失败: {e}")
                    continue
                if not reactors:
                    self._requeue_or_dead_letter(channel, event_node, reason="没有匹配的响应器")
                    continue
                for reactor in reactors:
                    key = id(reactor)
                    entry = batches.get(key)
                    if entry is None:
                        entry = batches[key] = (reactor, [])
                    entry[1].append((event_node.topic, event_node.content, event_node))
            # 每批一次 submit:一个 callable 消费整批
            for reactor, items in batches.values():
                f = self._executor.submit(self._run_batch, reactor, items)
                topics = {topic for topic, _, _ in items}
                # 批生效超时在提交现场解析:同批必同 reactor(聚合键 = id(reactor)),
                # 解析值即该 reactor 的准确生效值
                dispatched.append(
                    (f, reactor.reactor_name, topics, self._effective_timeout(reactor))
                )

        if len(dispatched) > 0:
            # 与逐事件路径同一语义:等待时长取本轮生效超时的最大值(issue #232)
            wait_timeout = max(t for *_, t in dispatched)
            wait([f for f, _, _, _ in dispatched], timeout=wait_timeout)
            self._report_unfinished_batched(dispatched, wait_timeout)

    @staticmethod
    def _run_batch(reactor, items) -> None:
        """执行一批(同 reactor 的多个事件):逐事件 execute,异常聚合上抛.

        批内单事件异常不中断批内剩余事件(与既有逐事件提交语义一致——
        executor future 中 reactor 的异常本来就静默到 exception());
        已处理游标随 BatchReactorError 上抛,供批级上报定位到事件。
        """
        failures = []
        for index, (topic, content, node) in enumerate(items):
            try:
                reactor.execute(topic, content)
            except Exception as e:
                failures.append((index, node, e))
        if failures:
            raise BatchReactorError(items, failures)

    @staticmethod
    def _report_unfinished_batched(
        dispatched: list[tuple[Future, str, set[str], float]], wait_timeout: float
    ) -> None:
        """批级可观测(optimize-event-dispatch-batching D3 + fix-reactor-timeout 定位).

        未完成批上报(channel/reactor/批内主题集合尽力给出——future 未完成时
        其 callable 已不可再读,故以批为单位计数);已结束批携带的
        BatchReactorError 展开为带 reactor 名、批内索引与事件 topic 的定位上报。
        未完成判定与逐事件路径同一语义:等满 max(生效超时) 后仍未结束才上报
        (issue #232——声明了合法慢的响应器不触发告警)。

        Args:
            dispatched: (future, reactor_name, topics, effective_timeout) 条目
            wait_timeout: 本轮等待实际使用的上限
        """
        unfinished = [(name, sorted(topics)) for f, name, topics, _ in dispatched if not f.done()]
        if unfinished:
            summary = "; ".join(f"reactor={name} topics={topics}" for name, topics in unfinished)
            LogUtils.warning(
                f"{len(unfinished)} 个响应器批在 join 超时({wait_timeout}s)后仍未结束,"
                f"其结果未被回收: {summary}",
                "EventWorker",
            )

        for f, reactor_name, _topics, _effective in dispatched:
            if not f.done():
                continue
            exc = f.exception()
            if exc is None:
                continue
            if isinstance(exc, BatchReactorError):
                for index, node, cause in exc.failures:
                    LogUtils.warning(
                        f"批内事件处理抛出异常 reactor={reactor_name} index={index} "
                        f"topic={getattr(node, 'topic', None)}: {cause!r}",
                        "EventWorker",
                    )
            else:
                LogUtils.warning(
                    f"事件批执行抛出异常且结果未被回收 reactor={reactor_name} "
                    f"topics={sorted(_topics)}: {exc!r}",
                    "EventWorker",
                )

    @staticmethod
    def _requeue_or_dead_letter(channel, event_node, reason: str = "") -> None:
        """The settled destination when an event cannot be delivered.

        With retry quota left, decrement it and requeue; otherwise move to
        dead-letter - both paths are observable, no silent dropping.

        Args:
            channel: the channel the event belongs to
            event_node: the event that could not be delivered
            reason: the reason it could not be delivered
        """
        remaining = event_node.get_retry_times()
        if remaining > 0:
            event_node.set_retry_times(remaining - 1)
            channel.push_event(event_node)
            return

        channel.push_dead_letter(event_node, reason=reason)

    @staticmethod
    def _report_unfinished(
        dispatched: list[tuple[Future, str, str, float]], wait_timeout: float
    ) -> None:
        """Report reactors still running past the join timeout, and exceptions carried by finished reactors.

        The results of ones unfinished at timeout are not collected and MUST
        be observable, not silently vanish with the timeout; exceptions
        carried by finished ones MUST NOT be swallowed (in the greenlet era
        they vanished silently).

        Both reports carry locating info (reactor name + topic) - issue #232:
        a bare count is indistinguishable between a legitimately slow reactor
        and a real deadlock. A reactor is reported only after its own
        effective timeout has elapsed, which the caller guarantees by waiting
        the max effective timeout of the round.

        Args:
            dispatched: (future, reactor_name, topic, effective_timeout) entries
                dispatched this round
            wait_timeout: the bound actually used for this round's wait
        """
        unfinished = [(name, topic) for f, name, topic, _t in dispatched if not f.done()]
        if unfinished:
            summary = "; ".join(f"reactor={name} topic={topic}" for name, topic in unfinished)
            LogUtils.warning(
                f"{len(unfinished)} reactors were still running after the join timeout "
                f"({wait_timeout}s); their results were not collected: {summary}",
                "EventWorker",
            )

        for f, reactor_name, topic, _t in dispatched:
            if not f.done():
                continue
            # After done(), exception() does not block; None when no exception was raised.
            exc = f.exception()
            if exc is not None:
                LogUtils.warning(
                    f"reactor={reactor_name} topic={topic} raised and its result "
                    f"was not collected: {exc!r}",
                    "EventWorker",
                )

zoo_framework.workers.state_machine_work.StateMachineWorker

Bases: BaseWorker

State machine Worker - manages state machine persistence.

Features: - automatically loads and saves the state machine - thread-safe state machine access - file checksums and backups

源代码位于: zoo_framework/workers/state_machine_work.py
class StateMachineWorker(BaseWorker):
    """State machine Worker - manages state machine persistence.

    Features:
    - automatically loads and saves the state machine
    - thread-safe state machine access
    - file checksums and backups
    """

    # Class-level lock, protecting file access
    _file_lock = threading.RLock()

    # Instance-level lock, protecting state machine operations
    _instance_lock = threading.Lock()

    def __init__(self):
        # Tempo parameterization (change configurable-run-delay / #73): the
        # same family as EventWorker; the lazy import must precede the props
        # assembly, and this class is constructed by WorkerRegistry at
        # runtime, so the order holds.
        from zoo_framework.params import StateMachineParams

        # is_loop is exposed by BaseWorker as a property with _props as the
        # sole source of truth; here it MUST NOT be shadowed by an instance
        # attribute (the property has no setter, assignment raises
        # AttributeError directly).
        BaseWorker.__init__(
            self,
            {
                "is_loop": True,
                "delay_time": StateMachineParams.STATE_MACHINE_DELAY_TIME,
                "name": "StateMachineWorker",
            },
        )
        # Whether already loaded
        self._loaded = False

    def _destroy(self, result):
        """Save the state on destroy."""
        self._save_state_machines()

    def _execute(self):
        """Run the state machine persistence task."""
        # Use the thread lock to protect state machine operations
        with self._instance_lock:
            state_machine_manager = StateMachineManager()

            # Check whether the state machine is loaded
            if not self._loaded:
                self._load_state_machines(state_machine_manager)
                self._loaded = True
            else:
                # Save the state periodically
                self._save_state_machines(state_machine_manager)

    def _load_state_machines(self, state_machine_manager):
        """Load the state machine (thread-safe).

        Args:
            state_machine_manager: the state machine manager instance
        """
        from zoo_framework.params import StateMachineParams

        # Use the file lock to protect file reading
        with self._file_lock:
            if state_machine_manager.have_loaded():
                return

            if FileUtils.file_exists(StateMachineParams.PICKLE_PATH):
                try:
                    with open(StateMachineParams.PICKLE_PATH, "rb") as f:
                        # Validate the file integrity
                        file_content = f.read()
                        if not file_content:
                            LogUtils.warning("State machine file is empty, creating new")
                            state_machine_manager.load_state_machines()
                            return

                        # Seek back to the file start
                        f.seek(0)
                        unpickler = pickle.Unpickler(f)  # nosec B301 — 见文件头 import pickle 处的说明
                        state_machines = unpickler.load()

                        LogUtils.info(f"✅ State machines loaded: {len(state_machines)} states")
                        state_machine_manager.load_state_machines(state_machines)

                except (pickle.UnpicklingError, EOFError) as e:
                    LogUtils.error(f"❌ Failed to load state machines, file may be corrupted: {e}")
                    # Try restoring from a backup
                    self._load_from_backup(state_machine_manager)
                except Exception as e:
                    LogUtils.error(f"❌ Unexpected error loading state machines: {e}")
                    state_machine_manager.load_state_machines()
            else:
                LogUtils.info("📝 No state machine file found, creating new")
                state_machine_manager.load_state_machines()

    def _save_state_machines(self, state_machine_manager=None):
        """Save the state machine (thread-safe).

        Args:
            state_machine_manager: the state machine manager instance;
                auto-acquired when None
        """
        from zoo_framework.params import StateMachineParams

        if state_machine_manager is None:
            state_machine_manager = StateMachineManager()

        # Use the file lock to protect file writing
        with self._file_lock:
            try:
                # Create a backup first
                self._create_backup(StateMachineParams.PICKLE_PATH)

                # Write the temp file
                temp_path = StateMachineParams.PICKLE_PATH + ".tmp"
                state_machines = state_machine_manager.get_state_machines()

                # Deep-copy to avoid concurrent modification
                copy_value = copy.deepcopy(state_machines)

                with open(temp_path, "wb") as f:
                    pickle.dump(copy_value, f, protocol=pickle.HIGHEST_PROTOCOL)

                # Replace the file atomically
                import os

                if os.path.exists(StateMachineParams.PICKLE_PATH):
                    os.replace(temp_path, StateMachineParams.PICKLE_PATH)
                else:
                    os.rename(temp_path, StateMachineParams.PICKLE_PATH)

                LogUtils.debug("💾 State machines saved successfully")

            except Exception as e:
                LogUtils.error(f"❌ Failed to save state machines: {e}")
                # Try restoring the backup
                self._restore_backup(StateMachineParams.PICKLE_PATH)

    def _create_backup(self, file_path: str):
        """Create a file backup.

        Args:
            file_path: the original file path
        """
        import os
        import shutil
        from datetime import datetime

        if not os.path.exists(file_path):
            return

        backup_dir = os.path.join(os.path.dirname(file_path), "backups")
        os.makedirs(backup_dir, exist_ok=True)

        # Timestamps to microsecond precision: with second-level precision,
        # several backups within one second would overwrite each other. The
        # fixed-width microsecond suffix also makes lexicographic order
        # equal time order - taking the latest backup relies on that.
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
        backup_path = os.path.join(backup_dir, f"state_machine_{timestamp}.pkl")

        try:
            shutil.copy2(file_path, backup_path)
            LogUtils.debug(f"📦 Backup created: {backup_path}")

            # Clean up old backups (keep the last 5)
            self._cleanup_old_backups(backup_dir, keep=5)
        except Exception as e:
            LogUtils.warning(f"⚠️ Failed to create backup: {e}")

    def _load_from_backup(self, state_machine_manager):
        """Restore the state machine from a backup.

        Args:
            state_machine_manager: the state machine manager instance
        """
        import glob
        import os

        from zoo_framework.params import StateMachineParams

        backup_dir = os.path.join(os.path.dirname(StateMachineParams.PICKLE_PATH), "backups")

        if not os.path.exists(backup_dir):
            LogUtils.warning("⚠️ No backup directory found, creating new state machines")
            state_machine_manager.load_state_machines()
            return

        # Find the latest backup
        backup_files = glob.glob(os.path.join(backup_dir, "state_machine_*.pkl"))
        if not backup_files:
            LogUtils.warning("⚠️ No backup files found, creating new state machines")
            state_machine_manager.load_state_machines()
            return

        # Sort by time
        backup_files.sort(reverse=True)
        latest_backup = backup_files[0]

        try:
            with open(latest_backup, "rb") as f:
                state_machines = pickle.load(f)  # nosec B301 — 见文件头 import pickle 处的说明
                LogUtils.info(f"✅ State machines restored from backup: {latest_backup}")
                state_machine_manager.load_state_machines(state_machines)
        except Exception as e:
            LogUtils.error(f"❌ Failed to restore from backup: {e}")
            state_machine_manager.load_state_machines()

    def _restore_backup(self, file_path: str):
        """Restore a backup file.

        Args:
            file_path: the original file path
        """
        import glob
        import os
        import shutil

        backup_dir = os.path.join(os.path.dirname(file_path), "backups")
        if not os.path.exists(backup_dir):
            return

        backup_files = glob.glob(os.path.join(backup_dir, "state_machine_*.pkl"))
        if not backup_files:
            return

        backup_files.sort(reverse=True)
        latest_backup = backup_files[0]

        try:
            shutil.copy2(latest_backup, file_path)
            LogUtils.info(f"✅ File restored from backup: {latest_backup}")
        except Exception as e:
            LogUtils.error(f"❌ Failed to restore backup: {e}")

    def _cleanup_old_backups(self, backup_dir: str, keep: int = 5):
        """Clean up old backup files.

        Args:
            backup_dir: the backup directory
            keep: how many backups to keep
        """
        import glob
        import os

        backup_files = glob.glob(os.path.join(backup_dir, "state_machine_*.pkl"))

        if len(backup_files) <= keep:
            return

        # Sort by time and delete the old ones
        backup_files.sort(reverse=True)
        for old_file in backup_files[keep:]:
            try:
                os.remove(old_file)
                LogUtils.debug(f"🗑️ Old backup removed: {old_file}")
            except Exception as e:
                LogUtils.warning(f"⚠️ Failed to remove old backup: {e}")

协程 Worker

zoo_framework.workers.async_worker.AsyncWorker

Bases: BaseWorker

Async Worker base class.

Features: - native coroutine support - automatic event loop management - both synchronous and asynchronous execution modes

The abstract constraint is enforced by ABCMeta: a subclass that does not implement async_execute cannot be instantiated.

源代码位于: zoo_framework/workers/async_worker.py
class AsyncWorker(BaseWorker, metaclass=ABCMeta):
    """Async Worker base class.

    Features:
    - native coroutine support
    - automatic event loop management
    - both synchronous and asynchronous execution modes

    The abstract constraint is enforced by ``ABCMeta``: a subclass that does
    not implement ``async_execute`` cannot be instantiated.
    """

    def __init__(self, name: str | None = None):
        # Keep `name` as the public signature but convert it into the props dict
        # for BaseWorker - BaseWorker carries config in the _props dict, and
        # passing a bare string would crash the name / is_loop property access.
        super().__init__({"is_loop": False, "delay_time": 1, "name": name})
        self._loop: asyncio.AbstractEventLoop | None = None
        self._async_type = AsyncWorkerType.COROUTINE
        self._max_concurrent = 10  # max concurrency
        self._semaphore: asyncio.Semaphore | None = None

    async def async_init(self) -> None:
        """Async initialization.

        Subclasses may override this to initialize async resources.
        """
        LogUtils.info(f"✅ AsyncWorker '{self.name}' initialized")

    async def async_destroy(self, timeout: float | None = None) -> None:
        """Async teardown.

        Subclasses may override this to clean up async resources.

        Args:
            timeout: the timeout
        """
        LogUtils.info(f"🛑 AsyncWorker '{self.name}' destroyed")

    @abstractmethod
    async def async_execute(self, *args: Any, **kwargs: Any) -> Any:
        """The async execution method (subclasses MUST implement).

        Args:
            *args: positional arguments
            **kwargs: keyword arguments

        Returns:
            The execution result
        """
        raise NotImplementedError("Subclasses must implement async_execute")

    def _execute(self):
        """The only entry point on the scheduling path.

        The scheduling thread is an ordinary thread with no running event loop,
        so the coroutine is driven directly here. The return value flows into
        ``WorkerResult`` through ``BaseWorker.run()``.

        Returns:
            The business return value of the async execution body
        """
        return asyncio.run(self._execute_async())

    def execute(self, *args: Any, **kwargs: Any) -> Any:
        """The synchronous execution entry point.

        MUST be called from a thread with no running event loop. Calling it
        inside an event loop and returning a Task that nobody awaits would
        silently skip the coroutine, so this refuses explicitly and states the
        alternative.

        Args:
            *args: positional arguments
            **kwargs: keyword arguments

        Returns:
            The execution result

        Raises:
            RuntimeError: called inside a running event loop
        """
        try:
            asyncio.get_running_loop()
        except RuntimeError:
            return asyncio.run(self._execute_async(*args, **kwargs))

        raise RuntimeError(
            "execute() cannot be called inside a running event loop - it "
            "cannot synchronously wait on a coroutine's result, and returning "
            "an un-awaited Task would let the coroutine silently never run. "
            "Please directly await worker.async_execute(...) inside a coroutine."
        )

    def _get_semaphore(self) -> asyncio.Semaphore:
        """Get the concurrency semaphore for the current event loop.

        ``asyncio.Semaphore`` binds to the event loop it was created on, and
        reusing it across loops fails; so it is rebuilt lazily per loop instead
        of being created once at construction or initialization.

        Returns:
            The semaphore under the current loop
        """
        loop = asyncio.get_running_loop()
        if self._semaphore is None or self._loop is not loop:
            self._semaphore = asyncio.Semaphore(self._max_concurrent)
            self._loop = loop
        return self._semaphore

    async def _execute_async(self, *args: Any, **kwargs: Any) -> Any:
        """Internal async execution."""
        # Duration is an interval quantity and MUST use the monotonic clock -
        # wall-clock jumps would produce negative or wildly wrong durations
        start_time = time.monotonic()

        try:
            # Limit concurrency with the semaphore
            async with self._get_semaphore():
                result = await self.async_execute(*args, **kwargs)

            duration = time.monotonic() - start_time
            LogUtils.info(f"✅ AsyncWorker '{self.name}' executed in {duration:.3f}s")

            return result

        except Exception as e:
            duration = time.monotonic() - start_time
            LogUtils.error(f"❌ AsyncWorker '{self.name}' failed after {duration:.3f}s: {e}")
            raise

    def run_in_background(self, *args: Any, **kwargs: Any) -> _BackgroundTask:
        """Run in the background.

        The worker thread is a daemon: unfinished background tasks MUST NOT
        prevent interpreter exit.

        Args:
            *args: positional arguments
            **kwargs: keyword arguments

        Returns:
            _BackgroundTask: the background task, observable via done() /
                result()
        """
        result_container: dict = {}

        def run_async():
            try:
                result_container["result"] = asyncio.run(self._execute_async(*args, **kwargs))
            except BaseException as e:  # kept for result() to re-raise
                result_container["exception"] = e

        thread = threading.Thread(target=run_async, daemon=True, name=f"zoo-async-{self.name}")
        thread.start()

        return _BackgroundTask(thread, result_container)

async_init async

async_init() -> None

Async initialization.

Subclasses may override this to initialize async resources.

源代码位于: zoo_framework/workers/async_worker.py
async def async_init(self) -> None:
    """Async initialization.

    Subclasses may override this to initialize async resources.
    """
    LogUtils.info(f"✅ AsyncWorker '{self.name}' initialized")

async_destroy async

async_destroy(timeout: float | None = None) -> None

Async teardown.

Subclasses may override this to clean up async resources.

参数:

名称 类型 描述 默认
timeout float | None

the timeout

None
源代码位于: zoo_framework/workers/async_worker.py
async def async_destroy(self, timeout: float | None = None) -> None:
    """Async teardown.

    Subclasses may override this to clean up async resources.

    Args:
        timeout: the timeout
    """
    LogUtils.info(f"🛑 AsyncWorker '{self.name}' destroyed")

async_execute abstractmethod async

async_execute(*args: Any, **kwargs: Any) -> Any

The async execution method (subclasses MUST implement).

参数:

名称 类型 描述 默认
*args Any

positional arguments

()
**kwargs Any

keyword arguments

{}

返回:

类型 描述
Any

The execution result

源代码位于: zoo_framework/workers/async_worker.py
@abstractmethod
async def async_execute(self, *args: Any, **kwargs: Any) -> Any:
    """The async execution method (subclasses MUST implement).

    Args:
        *args: positional arguments
        **kwargs: keyword arguments

    Returns:
        The execution result
    """
    raise NotImplementedError("Subclasses must implement async_execute")

execute

execute(*args: Any, **kwargs: Any) -> Any

The synchronous execution entry point.

MUST be called from a thread with no running event loop. Calling it inside an event loop and returning a Task that nobody awaits would silently skip the coroutine, so this refuses explicitly and states the alternative.

参数:

名称 类型 描述 默认
*args Any

positional arguments

()
**kwargs Any

keyword arguments

{}

返回:

类型 描述
Any

The execution result

引发:

类型 描述
RuntimeError

called inside a running event loop

源代码位于: zoo_framework/workers/async_worker.py
def execute(self, *args: Any, **kwargs: Any) -> Any:
    """The synchronous execution entry point.

    MUST be called from a thread with no running event loop. Calling it
    inside an event loop and returning a Task that nobody awaits would
    silently skip the coroutine, so this refuses explicitly and states the
    alternative.

    Args:
        *args: positional arguments
        **kwargs: keyword arguments

    Returns:
        The execution result

    Raises:
        RuntimeError: called inside a running event loop
    """
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        return asyncio.run(self._execute_async(*args, **kwargs))

    raise RuntimeError(
        "execute() cannot be called inside a running event loop - it "
        "cannot synchronously wait on a coroutine's result, and returning "
        "an un-awaited Task would let the coroutine silently never run. "
        "Please directly await worker.async_execute(...) inside a coroutine."
    )

run_in_background

run_in_background(*args: Any, **kwargs: Any) -> _BackgroundTask

Run in the background.

The worker thread is a daemon: unfinished background tasks MUST NOT prevent interpreter exit.

参数:

名称 类型 描述 默认
*args Any

positional arguments

()
**kwargs Any

keyword arguments

{}

返回:

名称 类型 描述
_BackgroundTask _BackgroundTask

the background task, observable via done() / result()

源代码位于: zoo_framework/workers/async_worker.py
def run_in_background(self, *args: Any, **kwargs: Any) -> _BackgroundTask:
    """Run in the background.

    The worker thread is a daemon: unfinished background tasks MUST NOT
    prevent interpreter exit.

    Args:
        *args: positional arguments
        **kwargs: keyword arguments

    Returns:
        _BackgroundTask: the background task, observable via done() /
            result()
    """
    result_container: dict = {}

    def run_async():
        try:
            result_container["result"] = asyncio.run(self._execute_async(*args, **kwargs))
        except BaseException as e:  # kept for result() to re-raise
            result_container["exception"] = e

    thread = threading.Thread(target=run_async, daemon=True, name=f"zoo-async-{self.name}")
    thread.start()

    return _BackgroundTask(thread, result_container)

原生执行 Worker

zoo_framework.workers.dual_arm_worker.DualArmWorker

Bases: BaseWorker

以在线自学的路由决策在「原生/Python」双臂间选择执行体.

属性:

名称 类型 描述
native_task_name

子类 props 声明的原生任务名;None 表示纯 python 臂 (恒定 python,不参与决策也不取锁)

子类 MUST 实现 :meth:_execute_python(python 臂执行体);声明了原生臂的, 再提供 :meth:_prepare_native_input(到达 NativeAdapter.execute 的 bytes 载荷;默认取 props["input"])。

关闭语义(spec「关闭时零影响」):adaptive:enabled=false(默认)时按 纯 python 臂执行,不进入 bandit 分支、不取锁。

显式拒绝语义(spec「原生臂不可用时显式拒绝」):声明了原生臂但 native:enabled=false 或扩展缺失/握手失败 → 构造期显式报错,MUST NOT 有人一次静默的 python 臂执行。

源代码位于: zoo_framework/workers/dual_arm_worker.py
class DualArmWorker(BaseWorker):
    """以在线自学的路由决策在「原生/Python」双臂间选择执行体.

    Attributes:
        native_task_name: 子类 props 声明的原生任务名;None 表示纯 python 臂
            (恒定 python,不参与决策也不取锁)

    子类 MUST 实现 :meth:`_execute_python`(python 臂执行体);声明了原生臂的,
    再提供 :meth:`_prepare_native_input`(到达 ``NativeAdapter.execute`` 的
    bytes 载荷;默认取 ``props["input"]``)。

    关闭语义(spec「关闭时零影响」):``adaptive:enabled=false``(默认)时按
    纯 python 臂执行,不进入 bandit 分支、不取锁。

    显式拒绝语义(spec「原生臂不可用时显式拒绝」):声明了原生臂但
    ``native:enabled=false`` 或扩展缺失/握手失败 → 构造期显式报错,MUST NOT
    有人一次静默的 python 臂执行。
    """

    def __init__(self, props: dict, policy: BanditPolicy | None = None):
        """Args:
            props: Worker 属性字典(含可选 ``native_task_name``)
            policy: 注入的决策器(测试用);None 取进程级单例

        Raises:
            NotImplementedError: 子类未实现 ``_execute_python``
            RuntimeError: 声明了原生臂但原生执行未启用
            NativeInvalidInput: 原生扩展缺失 / 握手失败(复用 adapter 错误族)
        """
        super().__init__(props)
        # 「子类未覆写 _execute_python」判据:与基类自带定义做**函数身份比较**——
        # 在实例上 getattr 是绑定方法(`is not` 函数本体恒真,探测会失效),
        # 且要比较必须在 type(self) 上取,继承未覆写时与基类函数同一对象。
        if type(self)._execute_python is DualArmWorker._execute_python:
            raise NotImplementedError(
                f"{type(self).__name__} MUST 实现 _execute_python()——"
                "DualArmWorker 声明的 python 臂执行体由子类提供,不能猜"
            )

        self.native_task_name = (
            str(props[_NATIVE_TASK_KEY]) if props.get(_NATIVE_TASK_KEY) else None
        )
        self.policy = policy if policy is not None else get_bandit_policy()

        if self.native_task_name is not None:
            # 构造期显式拒绝(design D3):两层都拦在构造期,才有「无一次静默
            # python 臂执行」的时点承诺。
            # 开关层:native:enabled 是框架侧开关,adapter.ensure_ready 只管扩展
            # 层(未安装/版本不匹配/能力不支持),不读这个键——开发期曾指望它统一
            # 拒绝,是计划里的一个错误,正确职责切分如上。
            from zoo_framework.core.params_factory import ParamsFactory
            from zoo_framework.params import NativeParams

            if not ParamsFactory().get_params(
                "native:enabled", default_value=NativeParams.NATIVE_ENABLED
            ):
                raise RuntimeError(
                    f"{type(self).__name__} 声明了原生臂 {self.native_task_name!r},"
                    "但 native:enabled=false——原生任务执行未启用。请启用开关或去掉"
                    "原生臂声明;不许静默回退 python 臂"
                )
            # 扩展层:复用 NativeAdapter 的握手与「不静默回退」语义——ensure_ready
            # 会把「未安装」「版本不匹配」「能力不支持」挡在执行前。
            from zoo_framework.native import get_native_adapter

            get_native_adapter().ensure_ready()

    # ---------------------------------------------------------------- 执行

    def _execute_python(self):
        """Python 臂执行体——**子类 MUST 实现**,语义与原生臂等价."""
        raise NotImplementedError

    def _prepare_native_input(self) -> bytes:
        """原生臂输入载荷;默认取 ``props["input"]``(MUST 为 bytes).

        Raises:
            NativeInvalidInput: 输入不是 bytes(adapter 边界转换时报)
        """
        payload = self._props.get("input", b"")
        return payload if isinstance(payload, bytes) else b""

    def _execute(self):
        """决策 → 计时执行对应臂 → 记录实测时长.

        Returns:
            所走臂执行体的返回值(进 WorkerResult.content)

        Raises:
            Exception: 执行体自身的异常照 BaseWorker 契约向上传播(决策层
                异常除外——那按 fail-open 落 python 臂)
        """
        # 关闭判定在决策之前:AdaptiveParams 属 params 包,必须 lazy import
        # (禁止模块级 import——会绕过配置读取时序并造成循环导入,见文件头)。
        from zoo_framework.params import AdaptiveParams

        if not AdaptiveParams.ADAPTIVE_ENABLED or self.native_task_name is None:
            # 关闭(默认)或无双臂:纯 python,零分支零锁(spec「关闭零影响」)
            return self._execute_timed(ARM_PYTHON)

        class_name = type(self).__name__
        try:
            arm = self.policy.decide(class_name)
        except Exception:
            arm = ARM_PYTHON

        if arm == ARM_NATIVE:
            return self._execute_timed(ARM_NATIVE, class_name)
        return self._execute_timed(ARM_PYTHON, class_name)

    def _execute_timed(self, arm: str, class_name: str | None = None):
        """执行指定臂 + 实测计时 + (启用时)把时长记入对应臂.

        Raises:
            Exception: 执行体异常原样向上传播;记录发生在 finally——执行失败
                也记一次实测时长(失败路径的时长同样是该臂的真实成本样本)
        """
        if arm == ARM_NATIVE:
            from zoo_framework.native import get_native_adapter

            adapter = get_native_adapter()
            start = time.perf_counter()
            try:
                payload = self._prepare_native_input()
                contract = adapter.contract(self.native_task_name)  # type: ignore[arg-type]
                raw = adapter.execute(self.native_task_name, payload)  # type: ignore[arg-type]
                return adapter.convert_output(raw, contract)
            finally:
                if class_name is not None:
                    self.policy.record(class_name, ARM_NATIVE, time.perf_counter() - start)
        start = time.perf_counter()
        try:
            return self._execute_python()
        finally:
            if class_name is not None:
                self.policy.record(class_name, ARM_PYTHON, time.perf_counter() - start)

zoo_framework.native.worker.NativeTaskWorker

Bases: BaseWorker

以既有 Worker 形态执行一个原生任务.

属性:

名称 类型 描述
task_name

要执行的原生任务名(MUST 已在扩展侧注册)

adapter

注入的原生适配器;缺省为进程级单例

props 里除 BaseWorker 的既有键外,本类读取:

  • task_name(必需;缺省时报错而不是猜)

结果语义:_execute() 返回转换后的 Python 值,跑进 BaseWorker.run() 统一包成 :class:~zoo_framework.workers.WorkerResult(含 worker 名), 运行标识(run_id / session_id)由结算点盖章——本类不碰身份字段。

源代码位于: zoo_framework/native/worker.py
class NativeTaskWorker(BaseWorker):
    """以既有 Worker 形态执行一个原生任务.

    Attributes:
        task_name: 要执行的原生任务名(MUST 已在扩展侧注册)
        adapter: 注入的原生适配器;缺省为进程级单例

    ``props`` 里除 BaseWorker 的既有键外,本类读取:

    - ``task_name``(必需;缺省时报错而不是猜)

    结果语义:``_execute()`` 返回转换后的 Python 值,跑进 ``BaseWorker.run()``
    统一包成 :class:`~zoo_framework.workers.WorkerResult`(含 worker 名),
    运行标识(run_id / session_id)由结算点盖章——本类不碰身份字段。
    """

    def __init__(self, props: dict, adapter=None):
        """Args:
            props: Worker 属性字典(含 ``task_name``)
            adapter: 可选注入的原生适配器;None 取模块级单例

        Raises:
            ValueError: props 未声明 ``task_name``
        """
        super().__init__(props)
        task_name = props.get("task_name")
        if not task_name:
            raise ValueError(
                "NativeTaskWorker 需要显式 task_name(原生任务按显式名称注册,"
                "不能把任意 callable 当作原生任务)"
            )
        self.task_name = str(task_name)
        self.adapter = adapter if adapter is not None else get_native_adapter()

    def _execute(self):
        """委托执行契约:边界转换输入 → 扩展执行(体内释放 GIL)→ 转换输出.

        Returns:
            转换后的输出值(进 WorkerResult.content)

        Raises:
            NativeInvalidInput: 契约读取失败 / 输入格式或尺寸不满足
            NativeTaskFailed / NativePanic: 扩展侧受控错误或 panic
        """
        contract = self.adapter.contract(self.task_name)
        payload = self.adapter.prepare_input(self._props.get("input"), contract)
        raw_output = self.adapter.execute(self.task_name, payload)
        return self.adapter.convert_output(raw_output, contract)

Worker 相关值对象

zoo_framework.workers.worker_props.WorkerProps

源代码位于: zoo_framework/workers/worker_props.py
1
2
3
4
5
class WorkerProps:
    def __init__(self, name, is_loop=True, delay_time=1):
        self.is_loop = is_loop
        self.delay_time = delay_time
        self.name = name

zoo_framework.workers.worker_result.WorkerResult

The Worker execution result.

All results are delivered to WaiterConstant.WORKER_RESULT_TOPIC; worker_name identifies the Worker that produced the result, letting receivers filter by Worker. cls_name keeps the Worker's class name, letting receivers tell apart different instances of the same class.

A failed execution also produces a result here (issue #228): the result topic is how consumers observe that a Worker finished, so a Worker whose execution body raised MUST still leave exactly one observable result carrying error. Receivers distinguish "failed" from "still running" by error / success; a failure MUST NOT be delivered in the shape of a successful empty result.

worker_name carries the instance ordinal (ok -> ok_1), while registry_name is the suffix-free identity (the configured name, or the class name when undeclared). Receivers filtering by Worker SHOULD match on registry_name: the ordinal is not known in advance, so a filter built from the registration name would never match worker_name (issue #229).

run_id / session_id are explicit run-identity fields: receivers can filter results by run or by session from them, and MUST NOT rely on implicit context (results may be produced in a worker thread, and worker threads do not inherit the caller's context variables). The values are stamped by the dispatch side at settlement.

参数:

名称 类型 描述 默认
topic str

the delivery topic; empty falls into the unified result topic

必需
content Any

the return value of the Worker's execution body

必需
cls_name str

the class name of the Worker that produced the result

必需
worker_name str | None

the instance name (with ordinal) of the Worker that produced the result

None
run_id str | None

the identity of the run that produced the result

None
session_id str | None

the identity of the session the result belongs to

None
error str | None

the failure reason; None when the execution succeeded. A non-None value marks this result as a failure, and the content is then None (no execution output was produced)

None
registry_name str | None

the suffix-free identity of the Worker that produced the result (configured name, or class name when undeclared)

None
源代码位于: zoo_framework/workers/worker_result.py
class WorkerResult:
    """The Worker execution result.

    All results are delivered to ``WaiterConstant.WORKER_RESULT_TOPIC``;
    ``worker_name`` identifies the Worker that produced the result, letting
    receivers filter by Worker. ``cls_name`` keeps the Worker's class name,
    letting receivers tell apart different instances of the same class.

    A **failed** execution also produces a result here (issue #228): the
    result topic is how consumers observe that a Worker finished, so a Worker
    whose execution body raised MUST still leave exactly one observable result
    carrying ``error``. Receivers distinguish "failed" from "still running" by
    ``error`` / ``success``; a failure MUST NOT be delivered in the shape of a
    successful empty result.

    ``worker_name`` carries the instance ordinal (``ok`` -> ``ok_1``), while
    ``registry_name`` is the **suffix-free** identity (the configured name, or
    the class name when undeclared). Receivers filtering by Worker SHOULD
    match on ``registry_name``: the ordinal is not known in advance, so a
    filter built from the registration name would never match ``worker_name``
    (issue #229).

    ``run_id`` / ``session_id`` are **explicit** run-identity fields:
    receivers can filter results by run or by session from them, and MUST
    NOT rely on implicit context (results may be produced in a worker thread,
    and worker threads do not inherit the caller's context variables). The
    values are stamped by the dispatch side at settlement.

    Args:
        topic: the delivery topic; empty falls into the unified result topic
        content: the return value of the Worker's execution body
        cls_name: the class name of the Worker that produced the result
        worker_name: the instance name (with ordinal) of the Worker that
            produced the result
        run_id: the identity of the run that produced the result
        session_id: the identity of the session the result belongs to
        error: the failure reason; None when the execution succeeded. A
            non-None value marks this result as a failure, and the content is
            then None (no execution output was produced)
        registry_name: the suffix-free identity of the Worker that produced
            the result (configured name, or class name when undeclared)
    """

    def __init__(
        self,
        topic: str,
        content: Any,
        cls_name: str,
        worker_name: str | None = None,
        run_id: str | None = None,
        session_id: str | None = None,
        error: str | None = None,
        registry_name: str | None = None,
    ) -> None:
        self.topic = topic or WaiterConstant.WORKER_RESULT_TOPIC
        self.content = content
        self.cls_name = cls_name
        self.worker_name = worker_name
        self.run_id = run_id
        self.session_id = session_id
        self.error = error
        self.registry_name = registry_name

    @property
    def success(self) -> bool:
        """Whether the execution succeeded.

        The single failure discriminator: None ``error`` means success. A
        failed execution MUST NOT be presented as a successful empty result,
        so receivers MUST check this (or ``error``) rather than the content.
        """
        return self.error is None

    def __repr__(self) -> str:
        return (
            f"WorkerResult(topic={self.topic}, cls_name={self.cls_name}, "
            f"worker_name={self.worker_name}, run_id={self.run_id}, "
            f"error={self.error})"
        )

success property

success: bool

Whether the execution succeeded.

The single failure discriminator: None error means success. A failed execution MUST NOT be presented as a successful empty result, so receivers MUST check this (or error) rather than the content.

zoo_framework.workers.worker_register.WorkerRegister

The worker registrar.

源代码位于: zoo_framework/workers/worker_register.py
class WorkerRegister:
    """The worker registrar."""

    def __init__(self) -> None:
        self._worker_register: ThreadSafeDict[str, Any] = ThreadSafeDict()

    def register(self, key: str, value: Any) -> None:
        """Register a worker."""
        self._worker_register[key] = value

    def get_worker(self, key: str) -> Any | None:
        """Get a worker."""
        return self._worker_register.get(key)

    def get_all_worker(self) -> list:
        """Get all workers."""
        return list(self._worker_register.values())

    def unregister(self, key: str) -> None:
        """Unregister a worker."""
        self._worker_register.pop(key)

register

register(key: str, value: Any) -> None

Register a worker.

源代码位于: zoo_framework/workers/worker_register.py
def register(self, key: str, value: Any) -> None:
    """Register a worker."""
    self._worker_register[key] = value

get_worker

get_worker(key: str) -> Any | None

Get a worker.

源代码位于: zoo_framework/workers/worker_register.py
def get_worker(self, key: str) -> Any | None:
    """Get a worker."""
    return self._worker_register.get(key)

get_all_worker

get_all_worker() -> list

Get all workers.

源代码位于: zoo_framework/workers/worker_register.py
def get_all_worker(self) -> list:
    """Get all workers."""
    return list(self._worker_register.values())

unregister

unregister(key: str) -> None

Unregister a worker.

源代码位于: zoo_framework/workers/worker_register.py
def unregister(self, key: str) -> None:
    """Unregister a worker."""
    self._worker_register.pop(key)