跳转至

调度

调度模型与背压策略。worker:mode 选择执行模型,worker:runPolicy 设置池的背压。

zoo_framework.core.waiter.base_waiter.BaseWaiter

The base waiter (scheduler).

属性:

名称 类型 描述
worker_mode

the effective scheduling model name

pool_enable

whether a resource pool is in use (derived from the model name)

model SchedulerModel

the assembled scheduling model

core

the dispatch core

源代码位于: zoo_framework/core/waiter/base_waiter.py
class BaseWaiter:
    """The base waiter (scheduler).

    Attributes:
        worker_mode: the effective scheduling model name
        pool_enable: whether a resource pool is in use (derived from the model
            name)
        model: the assembled scheduling model
        core: the dispatch core
    """

    def __init__(
        self,
        model_name: str | None = None,
        pool_size: int | None = None,
        backpressure_policy: str | None = None,
    ):
        """Assemble the scheduler.

        Args:
            model_name: the scheduling model name (a ``worker:mode`` value);
                None means derived from config
            pool_size: the pool size; None takes ``worker:pool:size``
            backpressure_policy: the policy for undersized pools; None is
                derived from ``worker:runPolicy``

        Raises:
            NotImplementedError: the model name is not an implemented mode
            ValueError: the run policy is not recognized
        """
        from zoo_framework.params import WorkerParams

        configured_mode, self.pool_enable = self.get_worker_mode(WorkerParams.WORKER_POOL_ENABLE)
        self.worker_mode = self.validate_worker_mode(model_name) if model_name else configured_mode

        size = WorkerParams.WORKER_POOL_SIZE if pool_size is None else pool_size
        policy = (
            backpressure_policy
            if backpressure_policy is not None
            else self._resolve_backpressure_policy(WorkerParams.WORKER_RUN_POLICY)
        )
        # An explicitly passed policy is validated as well: in thread mode this
        # parameter is meaningless to the model, but silently ignoring a wrong
        # value would quietly forfeit the configured intent - MUST NOT be
        # silently ignored
        self._validate_backpressure_policy(policy)

        self.model: SchedulerModel = self._build_model(self.worker_mode, size, policy)

        # Model-agnostic bookkeeping and correctness logic is owned entirely by
        # the core (single owner)
        self.core = WorkerDispatchCore(default_run_timeout=WorkerParams.WORKER_RUN_TIMEOUT)

        self.register_handler()

    # ------------------------------------------------------------------ assembly

    @staticmethod
    def _build_model(model_name: str, pool_size: int, backpressure_policy: str) -> SchedulerModel:
        """Assemble the concrete model by its name."""
        if model_name == WaiterConstant.WORKER_MODE_THREAD_POOL:
            return ThreadPoolModel(pool_size=pool_size, backpressure_policy=backpressure_policy)
        return ThreadPerTaskModel()

    @staticmethod
    def _resolve_backpressure_policy(policy: str) -> str:
        """Map legacy ``worker:runPolicy`` values onto backpressure policies.

        Raises:
            ValueError: the value is not recognized - MUST NOT silently fall
                back to some default policy
        """
        mapped = LEGACY_POLICY_TO_BACKPRESSURE.get(policy)
        if mapped is None:
            raise ValueError(
                f"unknown run policy {policy!r}; expected one of {list(LEGACY_POLICY_TO_BACKPRESSURE)}"
            )
        return mapped

    @staticmethod
    def _validate_backpressure_policy(policy: str) -> None:
        """Validate a backpressure policy value.

        Shares the same set of legal values as the config path; unknown values
        MUST be rejected explicitly with the legal alternatives listed and MUST
        NOT be silently ignored - even if the current model (e.g. the
        thread-per-task model) does not use the parameter.

        Raises:
            ValueError: the value is not recognized
        """
        allowed = sorted(set(LEGACY_POLICY_TO_BACKPRESSURE.values()))
        if policy not in allowed:
            raise ValueError(f"unknown backpressure policy {policy!r}; expected one of {allowed}")

    # ------------------------------------------------------------------ state view
    # The scheduling list and the in-flight table are owned by the core; only
    # **read-only** views are exposed here so the state is not stored twice.
    # To change the scheduling list use call_workers / add_worker - a direct
    # assignment would bypass the model's start and make submit refuse the
    # dispatch under its "submit before start" contract.

    @property
    def workers(self):
        return self.core.workers

    @property
    def worker_props(self):
        return self.core.worker_props

    @property
    def _broken(self):
        return self.core.broken

    # ------------------------------------------------------------------ 模式选择

    @staticmethod
    def validate_worker_mode(mode: str) -> str:
        """Check whether the dispatch mode is implemented.

        Unimplemented modes MUST be rejected explicitly and MUST NOT silently
        execute as some other mode.

        Args:
            mode: the dispatch mode name

        Returns:
            The validated mode name

        Raises:
            NotImplementedError: the mode is not implemented
        """
        if mode not in WaiterConstant.IMPLEMENTED_WORKER_MODES:
            raise NotImplementedError(
                f"dispatch mode {mode!r} is not implemented; implemented modes are "
                f"{list(WaiterConstant.IMPLEMENTED_WORKER_MODES)}"
            )
        return mode

    def get_worker_mode(self, pool_enable: bool) -> tuple[str, bool]:
        """Get the Worker's mode.

        An explicitly configured ``worker:mode`` takes precedence; when unset it
        is derived from ``worker:pool:enable``. Unimplemented modes are
        rejected explicitly.

        Args:
            pool_enable: the pool switch

        Returns:
            (mode name, whether a pool is used)
        """
        from zoo_framework.params import WorkerParams

        mode = WorkerParams.WORKER_MODE
        if not mode:
            mode = (
                WaiterConstant.WORKER_MODE_THREAD_POOL
                if pool_enable
                else WaiterConstant.WORKER_MODE_THREAD
            )
        self.validate_worker_mode(mode)
        return mode, mode == WaiterConstant.WORKER_MODE_THREAD_POOL

    def register_handler(self):
        """Register the handler.

        Binds the result reactor to the unified result topic.
        ``bind_topic_reactor`` is idempotent, so constructing the scheduler
        repeatedly does not pile up duplicate reactors under the topic.
        """
        EventReactorManager().bind_topic_reactor(
            WaiterConstant.WORKER_RESULT_TOPIC, WaiterResultReactor()
        )

    # ------------------------------------------------------------------ muster & registration

    def call_workers(self, worker_list: list):
        """Muster the workers and start the model container honoring the backpressure policy.

        Args:
            worker_list: the Workers participating in scheduling
        """
        self.core.set_workers(worker_list)
        # The backpressure policy must take effect before the pool is built: the
        # expand policy widens the size, and widening after the build is void
        self.model.prepare_workers(self.core.workers)
        self.model.start(self.core)

    def add_worker(self, worker: BaseWorker) -> None:
        """Admit a Worker newly registered at runtime into scheduling.

        The scheduling list is owned by the scheduler; being listed in a
        registry alone is not enough for the Worker to be dispatched.

        Runtime admission goes through the **same capacity admission** as the
        startup muster (``call_workers`` -> ``model.prepare_workers``): the
        prospective scheduling list is handed to the model first, so the
        backpressure policy governs runtime registration too (issue #233). A
        rejected Worker - the ``reject`` policy with an over-capacity count -
        MUST raise and MUST NOT be silently added to the scheduling list.

        Args:
            worker: the Worker to add to scheduling

        Raises:
            ValueError: the backpressure policy rejects the prospective worker set
        """
        # 与 call_workers 同一套容量准入:先把**候选**调度列表交给模型裁决;被拒
        # (reject 策略下超容量)时抛错,调度列表保持不变,MUST NOT 静默纳入。
        candidate = list(self.core.workers)
        if worker not in candidate:
            candidate.append(worker)
        self.model.prepare_workers(candidate)
        self.core.add_worker(worker)

    def __del__(self):
        # No cleanup that may raise during teardown: an exception out of __del__
        # would only be printed to stderr
        with contextlib.suppress(Exception):
            self.shutdown(wait=False)

    # ------------------------------------------------------------------ scheduling round

    def execute_service(self):
        """Execute one service round.

        Only Workers declared looping and not circuit-broken remain in the
        scheduling list after this round.
        """
        if self.core.stopped:
            return

        for worker in list(self.core.workers):
            # Ignore malformed scheduling entries directly; MUST NOT raise an
            # attribute error on them
            if worker is None:
                continue

            # Timeout evaluation precedes the in-flight check: a Worker judged
            # timed out is circuit-broken this round
            self.core.reap_timeout(worker)

            if self.core.is_broken(worker):
                continue

            # The in-flight check precedes period scheduling: period scheduling
            # has side effects (advancing the sequence); calling it on a Worker
            # still executing would consume this trigger without dispatching
            if self.core.is_inflight(worker):
                continue

            # Period scheduling: a periodic Worker not yet due is skipped this
            # round but stays in the scheduling list
            if not self.core.is_due(worker):
                continue

            self._dispatch_worker(worker)

        self.core.workers = self.core.retain_looping(self.core.workers)

    def _dispatch_worker(self, worker):
        """Dispatch the worker.

        Registration MUST precede dispatch, or an instantly finishing task
        would complete its deregistration before the registration lands.

        Args:
            worker: the Worker to dispatch
        """
        handle = self.core.begin(worker, self.core.resolve_run_timeout(worker))
        if handle is None:
            return

        try:
            self.model.submit(self.core, worker)
        except Exception as e:
            # A dispatch failure must not interrupt the whole round; clear the
            # registration so the next round can retry
            self.core.abort(worker)
            LogUtils.error(f"Worker {worker.name} failed to dispatch: {e}", self.__class__.__name__)

    # ------------------------------------------------------------------ shutdown

    def shutdown(self, wait: bool = True, timeout: float | None = None) -> None:
        """Shutdown: stop dispatching and let the model reclaim the container.

        MUST be repeatable.

        Args:
            wait: whether to wait for in-flight tasks to finish
            timeout: the waiting bound in seconds; None means unbounded
        """
        if not self.core.mark_stopped():
            return

        LogUtils.info("waiter shutting down", self.__class__.__name__)

        self.model.teardown(self.core, wait=wait, timeout=timeout)
        self.core.clear()

validate_worker_mode staticmethod

validate_worker_mode(mode: str) -> str

Check whether the dispatch mode is implemented.

Unimplemented modes MUST be rejected explicitly and MUST NOT silently execute as some other mode.

参数:

名称 类型 描述 默认
mode str

the dispatch mode name

必需

返回:

类型 描述
str

The validated mode name

引发:

类型 描述
NotImplementedError

the mode is not implemented

源代码位于: zoo_framework/core/waiter/base_waiter.py
@staticmethod
def validate_worker_mode(mode: str) -> str:
    """Check whether the dispatch mode is implemented.

    Unimplemented modes MUST be rejected explicitly and MUST NOT silently
    execute as some other mode.

    Args:
        mode: the dispatch mode name

    Returns:
        The validated mode name

    Raises:
        NotImplementedError: the mode is not implemented
    """
    if mode not in WaiterConstant.IMPLEMENTED_WORKER_MODES:
        raise NotImplementedError(
            f"dispatch mode {mode!r} is not implemented; implemented modes are "
            f"{list(WaiterConstant.IMPLEMENTED_WORKER_MODES)}"
        )
    return mode

get_worker_mode

get_worker_mode(pool_enable: bool) -> tuple[str, bool]

Get the Worker's mode.

An explicitly configured worker:mode takes precedence; when unset it is derived from worker:pool:enable. Unimplemented modes are rejected explicitly.

参数:

名称 类型 描述 默认
pool_enable bool

the pool switch

必需

返回:

类型 描述
tuple[str, bool]

(mode name, whether a pool is used)

源代码位于: zoo_framework/core/waiter/base_waiter.py
def get_worker_mode(self, pool_enable: bool) -> tuple[str, bool]:
    """Get the Worker's mode.

    An explicitly configured ``worker:mode`` takes precedence; when unset it
    is derived from ``worker:pool:enable``. Unimplemented modes are
    rejected explicitly.

    Args:
        pool_enable: the pool switch

    Returns:
        (mode name, whether a pool is used)
    """
    from zoo_framework.params import WorkerParams

    mode = WorkerParams.WORKER_MODE
    if not mode:
        mode = (
            WaiterConstant.WORKER_MODE_THREAD_POOL
            if pool_enable
            else WaiterConstant.WORKER_MODE_THREAD
        )
    self.validate_worker_mode(mode)
    return mode, mode == WaiterConstant.WORKER_MODE_THREAD_POOL

register_handler

register_handler()

Register the handler.

Binds the result reactor to the unified result topic. bind_topic_reactor is idempotent, so constructing the scheduler repeatedly does not pile up duplicate reactors under the topic.

源代码位于: zoo_framework/core/waiter/base_waiter.py
def register_handler(self):
    """Register the handler.

    Binds the result reactor to the unified result topic.
    ``bind_topic_reactor`` is idempotent, so constructing the scheduler
    repeatedly does not pile up duplicate reactors under the topic.
    """
    EventReactorManager().bind_topic_reactor(
        WaiterConstant.WORKER_RESULT_TOPIC, WaiterResultReactor()
    )

call_workers

call_workers(worker_list: list)

Muster the workers and start the model container honoring the backpressure policy.

参数:

名称 类型 描述 默认
worker_list list

the Workers participating in scheduling

必需
源代码位于: zoo_framework/core/waiter/base_waiter.py
def call_workers(self, worker_list: list):
    """Muster the workers and start the model container honoring the backpressure policy.

    Args:
        worker_list: the Workers participating in scheduling
    """
    self.core.set_workers(worker_list)
    # The backpressure policy must take effect before the pool is built: the
    # expand policy widens the size, and widening after the build is void
    self.model.prepare_workers(self.core.workers)
    self.model.start(self.core)

add_worker

add_worker(worker: BaseWorker) -> None

Admit a Worker newly registered at runtime into scheduling.

The scheduling list is owned by the scheduler; being listed in a registry alone is not enough for the Worker to be dispatched.

Runtime admission goes through the same capacity admission as the startup muster (call_workers -> model.prepare_workers): the prospective scheduling list is handed to the model first, so the backpressure policy governs runtime registration too (issue #233). A rejected Worker - the reject policy with an over-capacity count - MUST raise and MUST NOT be silently added to the scheduling list.

参数:

名称 类型 描述 默认
worker BaseWorker

the Worker to add to scheduling

必需

引发:

类型 描述
ValueError

the backpressure policy rejects the prospective worker set

源代码位于: zoo_framework/core/waiter/base_waiter.py
def add_worker(self, worker: BaseWorker) -> None:
    """Admit a Worker newly registered at runtime into scheduling.

    The scheduling list is owned by the scheduler; being listed in a
    registry alone is not enough for the Worker to be dispatched.

    Runtime admission goes through the **same capacity admission** as the
    startup muster (``call_workers`` -> ``model.prepare_workers``): the
    prospective scheduling list is handed to the model first, so the
    backpressure policy governs runtime registration too (issue #233). A
    rejected Worker - the ``reject`` policy with an over-capacity count -
    MUST raise and MUST NOT be silently added to the scheduling list.

    Args:
        worker: the Worker to add to scheduling

    Raises:
        ValueError: the backpressure policy rejects the prospective worker set
    """
    # 与 call_workers 同一套容量准入:先把**候选**调度列表交给模型裁决;被拒
    # (reject 策略下超容量)时抛错,调度列表保持不变,MUST NOT 静默纳入。
    candidate = list(self.core.workers)
    if worker not in candidate:
        candidate.append(worker)
    self.model.prepare_workers(candidate)
    self.core.add_worker(worker)

execute_service

execute_service()

Execute one service round.

Only Workers declared looping and not circuit-broken remain in the scheduling list after this round.

源代码位于: zoo_framework/core/waiter/base_waiter.py
def execute_service(self):
    """Execute one service round.

    Only Workers declared looping and not circuit-broken remain in the
    scheduling list after this round.
    """
    if self.core.stopped:
        return

    for worker in list(self.core.workers):
        # Ignore malformed scheduling entries directly; MUST NOT raise an
        # attribute error on them
        if worker is None:
            continue

        # Timeout evaluation precedes the in-flight check: a Worker judged
        # timed out is circuit-broken this round
        self.core.reap_timeout(worker)

        if self.core.is_broken(worker):
            continue

        # The in-flight check precedes period scheduling: period scheduling
        # has side effects (advancing the sequence); calling it on a Worker
        # still executing would consume this trigger without dispatching
        if self.core.is_inflight(worker):
            continue

        # Period scheduling: a periodic Worker not yet due is skipped this
        # round but stays in the scheduling list
        if not self.core.is_due(worker):
            continue

        self._dispatch_worker(worker)

    self.core.workers = self.core.retain_looping(self.core.workers)

shutdown

shutdown(wait: bool = True, timeout: float | None = None) -> None

Shutdown: stop dispatching and let the model reclaim the container.

MUST be repeatable.

参数:

名称 类型 描述 默认
wait bool

whether to wait for in-flight tasks to finish

True
timeout float | None

the waiting bound in seconds; None means unbounded

None
源代码位于: zoo_framework/core/waiter/base_waiter.py
def shutdown(self, wait: bool = True, timeout: float | None = None) -> None:
    """Shutdown: stop dispatching and let the model reclaim the container.

    MUST be repeatable.

    Args:
        wait: whether to wait for in-flight tasks to finish
        timeout: the waiting bound in seconds; None means unbounded
    """
    if not self.core.mark_stopped():
        return

    LogUtils.info("waiter shutting down", self.__class__.__name__)

    self.model.teardown(self.core, wait=wait, timeout=timeout)
    self.core.clear()

调度模型

zoo_framework.core.waiter.scheduler_model

Scheduling models: declare contracts and own the concurrency primitive and round shape.

The six contract items MUST be programmatically queryable (describe()):

  1. concurrency primitive concurrency_primitive
  2. supported time semantics supported_time_semantics
  3. backpressure policy backpressure_policy
  4. stop semantics stop_semantics
  5. supported Worker kinds supported_worker_kinds
  6. observable metrics observable_metrics

"Supported time semantics" declares which time semantics this model can schedule, and MUST NOT be read as pinning the whole process to one semantics: period and phase are declared per Worker, and one model MUST be able to schedule periodic-driven and event-driven Workers at the same time (a device scenario with periodic control loops coexisting with event-driven alarm handlers is exactly that). Period scheduling itself is independent of the concurrency primitive; it is owned by :class:~zoo_framework.core.waiter.dispatch_core.WorkerDispatchCore.

A model is only responsible for "how to send Workers out and how to reclaim the concurrency container". Any model-agnostic correctness logic - the single settlement path, timeout observation and circuit-breaking, shutdown reclamation, runtime registration, period scheduling - MUST NOT be re-implemented at this layer.

SchedulerModel

Bases: ABC

Scheduling model base class.

属性:

名称 类型 描述
concurrency_primitive str

one of the concurrency primitive values

supported_time_semantics tuple

the time semantics this model can schedule

backpressure_policy str

one of the backpressure policy values

stop_semantics str

one of the stop semantics values

supported_worker_kinds tuple

the supported Worker kinds

observable_metrics tuple

the runtime metric names this model can expose

源代码位于: zoo_framework/core/waiter/scheduler_model.py
class SchedulerModel(ABC):
    """Scheduling model base class.

    Attributes:
        concurrency_primitive: one of the concurrency primitive values
        supported_time_semantics: the time semantics this model can schedule
        backpressure_policy: one of the backpressure policy values
        stop_semantics: one of the stop semantics values
        supported_worker_kinds: the supported Worker kinds
        observable_metrics: the runtime metric names this model can expose
    """

    concurrency_primitive: str = ""
    supported_time_semantics: tuple = ()
    backpressure_policy: str = ""
    stop_semantics: str = ""
    supported_worker_kinds: tuple = ()
    observable_metrics: tuple = (
        METRIC_INFLIGHT,
        METRIC_COMPLETED,
        METRIC_TIMEOUTS,
        METRIC_JITTER,
    )

    def describe(self) -> dict:
        """The programmatic query entry for the six contract items.

        Per **instance**: items like the backpressure policy may vary with
        instance arguments (``ThreadPoolModel``); a classmethod would read the
        class-level empty values and hide the instance's real declaration.

        Returns:
            A dict with the six declarations; any empty item means the model
            did not declare it correctly
        """
        return {
            "concurrency_primitive": self.concurrency_primitive,
            "supported_time_semantics": list(self.supported_time_semantics),
            "backpressure_policy": self.backpressure_policy,
            "stop_semantics": self.stop_semantics,
            "supported_worker_kinds": list(self.supported_worker_kinds),
            "observable_metrics": list(self.observable_metrics),
        }

    @abstractmethod
    def start(self, core) -> None:
        """Start the model (create the container) and mark it started.

        Each model MUST implement this itself: ``submit`` requires a started
        model, and both models should treat "submit before start" the same way
        (refuse, not silently fail).
        """

    @abstractmethod
    def submit(self, core, worker) -> None:
        """Dispatch the Worker.

        Implementations MUST call ``core.settle`` on completion so settlement
        goes through the single path.
        """

    @abstractmethod
    def prepare_workers(self, workers) -> int:
        """Process the Worker list according to the backpressure policy **before** creating the container.

        MUST be called before container creation: ``expand`` semantics require
        the widened size to be in effect when the pool is built.

        Returns:
            The capacity this model actually uses (0 when it has no container
            concept)
        """

    @abstractmethod
    def teardown(self, core, wait: bool = True, timeout: float | None = None) -> None:
        """Reclaim the container and mark the model not started. MUST be repeatable."""

describe

describe() -> dict

The programmatic query entry for the six contract items.

Per instance: items like the backpressure policy may vary with instance arguments (ThreadPoolModel); a classmethod would read the class-level empty values and hide the instance's real declaration.

返回:

类型 描述
dict

A dict with the six declarations; any empty item means the model

dict

did not declare it correctly

源代码位于: zoo_framework/core/waiter/scheduler_model.py
def describe(self) -> dict:
    """The programmatic query entry for the six contract items.

    Per **instance**: items like the backpressure policy may vary with
    instance arguments (``ThreadPoolModel``); a classmethod would read the
    class-level empty values and hide the instance's real declaration.

    Returns:
        A dict with the six declarations; any empty item means the model
        did not declare it correctly
    """
    return {
        "concurrency_primitive": self.concurrency_primitive,
        "supported_time_semantics": list(self.supported_time_semantics),
        "backpressure_policy": self.backpressure_policy,
        "stop_semantics": self.stop_semantics,
        "supported_worker_kinds": list(self.supported_worker_kinds),
        "observable_metrics": list(self.observable_metrics),
    }

start abstractmethod

start(core) -> None

Start the model (create the container) and mark it started.

Each model MUST implement this itself: submit requires a started model, and both models should treat "submit before start" the same way (refuse, not silently fail).

源代码位于: zoo_framework/core/waiter/scheduler_model.py
@abstractmethod
def start(self, core) -> None:
    """Start the model (create the container) and mark it started.

    Each model MUST implement this itself: ``submit`` requires a started
    model, and both models should treat "submit before start" the same way
    (refuse, not silently fail).
    """

submit abstractmethod

submit(core, worker) -> None

Dispatch the Worker.

Implementations MUST call core.settle on completion so settlement goes through the single path.

源代码位于: zoo_framework/core/waiter/scheduler_model.py
@abstractmethod
def submit(self, core, worker) -> None:
    """Dispatch the Worker.

    Implementations MUST call ``core.settle`` on completion so settlement
    goes through the single path.
    """

prepare_workers abstractmethod

prepare_workers(workers) -> int

Process the Worker list according to the backpressure policy before creating the container.

MUST be called before container creation: expand semantics require the widened size to be in effect when the pool is built.

返回:

类型 描述
int

The capacity this model actually uses (0 when it has no container

int

concept)

源代码位于: zoo_framework/core/waiter/scheduler_model.py
@abstractmethod
def prepare_workers(self, workers) -> int:
    """Process the Worker list according to the backpressure policy **before** creating the container.

    MUST be called before container creation: ``expand`` semantics require
    the widened size to be in effect when the pool is built.

    Returns:
        The capacity this model actually uses (0 when it has no container
        concept)
    """

teardown abstractmethod

teardown(core, wait: bool = True, timeout: float | None = None) -> None

Reclaim the container and mark the model not started. MUST be repeatable.

源代码位于: zoo_framework/core/waiter/scheduler_model.py
@abstractmethod
def teardown(self, core, wait: bool = True, timeout: float | None = None) -> None:
    """Reclaim the container and mark the model not started. MUST be repeatable."""

ThreadPerTaskModel

Bases: SchedulerModel

One thread per task: no backpressure, dispatch never blocks the scheduling round.

Corresponds to the existing worker:mode=thread. Dispatched task threads are daemon threads; at shutdown in-flight tasks are abandoned rather than awaited (CPython cannot safely interrupt a running thread).

源代码位于: zoo_framework/core/waiter/scheduler_model.py
class ThreadPerTaskModel(SchedulerModel):
    """One thread per task: no backpressure, dispatch never blocks the scheduling round.

    Corresponds to the existing ``worker:mode=thread``. Dispatched task threads
    are daemon threads; at shutdown in-flight tasks are **abandoned** rather
    than awaited (CPython cannot safely interrupt a running thread).
    """

    concurrency_primitive = CONCURRENCY_THREAD_PER_TASK
    supported_time_semantics = (TIME_SEMANTICS_EVENT_DRIVEN, TIME_SEMANTICS_PERIODIC)
    backpressure_policy = BACKPRESSURE_UNBOUNDED
    stop_semantics = STOP_ABANDON_INFLIGHT
    supported_worker_kinds = (WORKER_KIND_SYNC,)

    def __init__(self):
        self._started = False

    def start(self, core) -> None:
        """No thread-pool container to build; mark started so ``submit``'s precondition can be checked."""
        self._started = True

    def teardown(self, core, wait: bool = True, timeout: float | None = None) -> None:
        """Dispatched daemon threads are abandoned per the stop semantics; no container to reclaim; mark not started."""
        self._started = False

    def prepare_workers(self, workers) -> int:
        """This model starts an independent thread per dispatch with **no capacity concept**, so no limits apply and 0 is returned.

        The backpressure policy is ``unbounded``: never refuses because of the
        worker count and never queues.
        """
        return 0

    def submit(self, core, worker) -> None:
        if not self._started:
            raise RuntimeError("model not started (start() has not been called)")

        # Carry the dispatcher's context explicitly: a new thread does not inherit
        # the caller's ContextVars; without carry_context the run identity would
        # be silently lost inside the worker thread
        thread = threading.Thread(
            target=carry_context(core.run_and_settle),
            args=(worker,),
            name=f"zoo-{worker.name}",
            daemon=True,
        )
        core.attach_container(worker, thread)
        thread.start()

start

start(core) -> None

No thread-pool container to build; mark started so submit's precondition can be checked.

源代码位于: zoo_framework/core/waiter/scheduler_model.py
def start(self, core) -> None:
    """No thread-pool container to build; mark started so ``submit``'s precondition can be checked."""
    self._started = True

teardown

teardown(core, wait: bool = True, timeout: float | None = None) -> None

Dispatched daemon threads are abandoned per the stop semantics; no container to reclaim; mark not started.

源代码位于: zoo_framework/core/waiter/scheduler_model.py
def teardown(self, core, wait: bool = True, timeout: float | None = None) -> None:
    """Dispatched daemon threads are abandoned per the stop semantics; no container to reclaim; mark not started."""
    self._started = False

prepare_workers

prepare_workers(workers) -> int

This model starts an independent thread per dispatch with no capacity concept, so no limits apply and 0 is returned.

The backpressure policy is unbounded: never refuses because of the worker count and never queues.

源代码位于: zoo_framework/core/waiter/scheduler_model.py
def prepare_workers(self, workers) -> int:
    """This model starts an independent thread per dispatch with **no capacity concept**, so no limits apply and 0 is returned.

    The backpressure policy is ``unbounded``: never refuses because of the
    worker count and never queues.
    """
    return 0

ThreadPoolModel

Bases: SchedulerModel

Thread pool: bounded concurrency, handling undersized pools via backpressure_policy.

Corresponds to the existing worker:mode=thread_pool. The three backpressure policies absorb the only difference among the former SimpleWaiter / StableWaiter / SafeWaiter: expand / queue / reject.

Container implementation (change replace-pool-dispatch-queue / #47 P2): fixed worker threads + a queue.Queue task queue, replacing the old concurrent.futures.ThreadPoolExecutor - measurements showed Future bookkeeping dominates the dispatch cost (submit().result() 31.9 us vs 1.86 us via the queue directly, bench/DECISION.md section 4). The six contract items and the three backpressure semantics are unchanged item by item: bound = thread count, queue = unbounded FIFO, stop-cancel-queued = discard not-yet-started tasks.

源代码位于: zoo_framework/core/waiter/scheduler_model.py
class ThreadPoolModel(SchedulerModel):
    """Thread pool: bounded concurrency, handling undersized pools via ``backpressure_policy``.

    Corresponds to the existing ``worker:mode=thread_pool``. The three
    backpressure policies absorb the **only** difference among the former
    ``SimpleWaiter`` / ``StableWaiter`` / ``SafeWaiter``: expand / queue /
    reject.

    Container implementation (change replace-pool-dispatch-queue / #47 P2):
    fixed worker threads + a ``queue.Queue`` task queue, replacing the old
    ``concurrent.futures.ThreadPoolExecutor`` - measurements showed Future
    bookkeeping dominates the dispatch cost (submit().result() 31.9 us vs
    1.86 us via the queue directly, bench/DECISION.md section 4). The six
    contract items and the three backpressure semantics are unchanged item by
    item: bound = thread count, queue = unbounded FIFO, stop-cancel-queued =
    discard not-yet-started tasks.
    """

    concurrency_primitive = CONCURRENCY_THREAD_POOL
    supported_time_semantics = (TIME_SEMANTICS_EVENT_DRIVEN, TIME_SEMANTICS_PERIODIC)
    stop_semantics = STOP_CANCEL_QUEUED
    supported_worker_kinds = (WORKER_KIND_SYNC,)

    def __init__(self, pool_size: int, backpressure_policy: str = BACKPRESSURE_EXPAND):
        """Initialize the thread pool model.

        Args:
            pool_size: the pool size
            backpressure_policy: the policy for undersized pools (queue /
                expand / reject)

        Raises:
            ValueError: the backpressure policy is not one of the legal values
        """
        if backpressure_policy not in (
            BACKPRESSURE_QUEUE,
            BACKPRESSURE_EXPAND,
            BACKPRESSURE_REJECT,
        ):
            raise ValueError(
                f"unsupported backpressure policy {backpressure_policy!r}; expected "
                f"{[BACKPRESSURE_QUEUE, BACKPRESSURE_EXPAND, BACKPRESSURE_REJECT]}"
            )
        self.pool_size = pool_size
        self.backpressure_policy = backpressure_policy
        # The actually effective pool size (the expand policy widens it but does
        # **not** modify pool_size itself - the caller's configured intent MUST
        # stay readable)
        self.effective_pool_size = pool_size
        # Task queue + fixed worker threads (the "cancel queued" of
        # stop_semantics=stop_dispatch_cancel_queued is implemented by teardown
        # discarding not-yet-started tasks; clearing the in-flight table is the
        # core's shutdown responsibility)
        self._tasks: queue.Queue | None = None
        self._threads: list[threading.Thread] = []

    def prepare_workers(self, workers: list[BaseWorker | None]) -> int:
        """Handle "worker count exceeds the pool size" according to the backpressure policy.

        Called **before** the pool is created at startup - ``expand`` semantics
        require the widened size to be in effect when the pool is built. It is
        also the admission entry for **runtime** registration (``BaseWaiter.add_worker``,
        issue #233): when the pool is already running, the widened size MUST be
        applied to the live container as well, or ``expand`` would only bump a
        number that has no effect (a silent no-op).

        Args:
            workers: the Worker list about to participate in scheduling

        Returns:
            The pool size this model actually uses

        Raises:
            ValueError: the policy is reject and the worker count exceeds the
                pool size
        """
        count = len([worker for worker in workers if worker is not None])
        if count <= self.effective_pool_size:
            return self.effective_pool_size

        if self.backpressure_policy == BACKPRESSURE_REJECT:
            raise ValueError(
                f"worker count {count} exceeds the pool size {self.pool_size};"
                "increase worker:pool:size, or switch the undersized-pool policy to expand / queue"
            )
        if self.backpressure_policy == BACKPRESSURE_EXPAND:
            self.effective_pool_size = count + 1
            # 运行期注册时容器可能已在运行:把放宽后的容量真正应用到活的池,
            # 否则数字变了却没有效果(静默 no-op)。启动期(_tasks 为 None)由
            # 随后的 start 建池,无需在此建。
            if self._tasks is not None:
                self._ensure_threads(self.effective_pool_size)
        # queue: the size stays; the excess queues inside the pool
        return self.effective_pool_size

    def start(self, core) -> None:
        """Build the queue and worker threads at the **current** effective size (sized by prepare_workers before start).

        Idempotent: when the container already exists, the thread count is
        reconciled up to the effective size (the runtime ``expand`` path widens
        it via ``prepare_workers``) - threads are never removed here, shrinking
        is ``teardown``'s job.
        """
        if self._tasks is None:
            if self.effective_pool_size <= 0:
                # Aligned with the old ThreadPoolExecutor(max_workers<=0) error
                # behavior: an illegal size is refused on the spot; MUST NOT silently
                # build a zero-thread pool so that submit never finds a "started"
                # container
                raise ValueError(
                    f"pool size must be positive, got {self.effective_pool_size} (config key worker:pool:size)"
                )
            self._tasks = queue.Queue()
        self._ensure_threads(self.effective_pool_size)

    def _ensure_threads(self, target: int) -> None:
        """Grow the worker-thread count up to ``target`` (``_tasks`` must exist).

        New threads take indices from the current length, so names stay
        ``zoo-worker-<n>``. Threads are only ever **added** here: shrinking is
        ``teardown``'s responsibility (it discards queued tasks and reclaims
        every thread).
        """
        tasks = self._tasks
        if tasks is None:
            return
        while len(self._threads) < target:
            thread = threading.Thread(
                target=self._worker_loop,
                args=(tasks,),
                name=f"zoo-worker-{len(self._threads)}",
                daemon=True,
            )
            self._threads.append(thread)
            thread.start()

    @staticmethod
    def _worker_loop(tasks: queue.Queue) -> None:
        """Worker-thread main loop: fetch a task, execute it, observe escaped exceptions in place.

        The execution unit (``core.run_and_settle``) already catches Worker
        exceptions and goes through the single settlement; anything escaping
        this layer is a dispatch-path defect, MUST leave a trace and the thread
        MUST keep serving. None is the shutdown sentinel.
        """
        while True:
            item = tasks.get()
            if item is None:
                return
            run_and_settle, worker = item
            try:
                run_and_settle(worker)
            except Exception as error:  # an escape is a defect; log, do not re-raise, keep serving
                LogUtils.error(
                    f"scheduler execution unit raised (not a Worker's own exception): {error}",
                    ThreadPoolModel.__name__,
                )

    def submit(self, core, worker) -> None:
        if self._tasks is None or not self._threads:
            raise RuntimeError("model not started (start() has not been called)")
        # Worker threads do not inherit the caller's context; like the thread
        # mode, carry it explicitly at the dispatch site
        run_and_settle = carry_context(core.run_and_settle)
        self._tasks.put((run_and_settle, worker))
        core.attach_container(worker, run_and_settle)

    def teardown(self, core, wait: bool = True, timeout: float | None = None) -> None:
        """Shutdown: discard queued not-yet-started tasks (``stop_dispatch_cancel_queued``), then stop the threads.

        Started tasks cannot be interrupted (a CPython limitation, the same as
        the old ThreadPoolExecutor implementation); the in-flight table and the
        scheduling list are cleared by ``core.clear()`` (called from
        BaseWaiter.shutdown).
        """
        tasks, threads = self._tasks, self._threads
        self._tasks, self._threads = None, []
        if tasks is None and not threads:
            return
        if tasks is not None:
            # Discard queued items before putting the sentinels, or a sentinel
            # would be treated as a normal item and dropped, leaving the thread
            # blocked on get() forever
            self._discard_queued(tasks)
            for _ in threads:
                tasks.put(None)
        if wait:
            self._join_threads(threads, timeout)

    @staticmethod
    def _discard_queued(tasks: queue.Queue) -> None:
        """Drain the not-yet-started tasks; their in-flight registrations are settled by core.clear, the same shape as future cancellation."""
        while True:
            try:
                tasks.get_nowait()
            except queue.Empty:
                return

    @staticmethod
    def _join_threads(threads: list[threading.Thread], timeout: float | None) -> None:
        """Wait for the worker threads to exit within the given bound.

        Uses the monotonic-clock **total budget** semantics: ``timeout`` is a
        shared waiting bound for all the threads and MUST NOT be treated as a
        per-thread bound (that would make the wait grow with the thread count).
        """
        deadline = None if timeout is None else time.monotonic() + timeout
        for thread in threads:
            remaining = None if deadline is None else deadline - time.monotonic()
            if remaining is not None and remaining <= 0:
                return
            thread.join(remaining)

prepare_workers

prepare_workers(workers: list[BaseWorker | None]) -> int

Handle "worker count exceeds the pool size" according to the backpressure policy.

Called before the pool is created at startup - expand semantics require the widened size to be in effect when the pool is built. It is also the admission entry for runtime registration (BaseWaiter.add_worker, issue #233): when the pool is already running, the widened size MUST be applied to the live container as well, or expand would only bump a number that has no effect (a silent no-op).

参数:

名称 类型 描述 默认
workers list[BaseWorker | None]

the Worker list about to participate in scheduling

必需

返回:

类型 描述
int

The pool size this model actually uses

引发:

类型 描述
ValueError

the policy is reject and the worker count exceeds the pool size

源代码位于: zoo_framework/core/waiter/scheduler_model.py
def prepare_workers(self, workers: list[BaseWorker | None]) -> int:
    """Handle "worker count exceeds the pool size" according to the backpressure policy.

    Called **before** the pool is created at startup - ``expand`` semantics
    require the widened size to be in effect when the pool is built. It is
    also the admission entry for **runtime** registration (``BaseWaiter.add_worker``,
    issue #233): when the pool is already running, the widened size MUST be
    applied to the live container as well, or ``expand`` would only bump a
    number that has no effect (a silent no-op).

    Args:
        workers: the Worker list about to participate in scheduling

    Returns:
        The pool size this model actually uses

    Raises:
        ValueError: the policy is reject and the worker count exceeds the
            pool size
    """
    count = len([worker for worker in workers if worker is not None])
    if count <= self.effective_pool_size:
        return self.effective_pool_size

    if self.backpressure_policy == BACKPRESSURE_REJECT:
        raise ValueError(
            f"worker count {count} exceeds the pool size {self.pool_size};"
            "increase worker:pool:size, or switch the undersized-pool policy to expand / queue"
        )
    if self.backpressure_policy == BACKPRESSURE_EXPAND:
        self.effective_pool_size = count + 1
        # 运行期注册时容器可能已在运行:把放宽后的容量真正应用到活的池,
        # 否则数字变了却没有效果(静默 no-op)。启动期(_tasks 为 None)由
        # 随后的 start 建池,无需在此建。
        if self._tasks is not None:
            self._ensure_threads(self.effective_pool_size)
    # queue: the size stays; the excess queues inside the pool
    return self.effective_pool_size

start

start(core) -> None

Build the queue and worker threads at the current effective size (sized by prepare_workers before start).

Idempotent: when the container already exists, the thread count is reconciled up to the effective size (the runtime expand path widens it via prepare_workers) - threads are never removed here, shrinking is teardown's job.

源代码位于: zoo_framework/core/waiter/scheduler_model.py
def start(self, core) -> None:
    """Build the queue and worker threads at the **current** effective size (sized by prepare_workers before start).

    Idempotent: when the container already exists, the thread count is
    reconciled up to the effective size (the runtime ``expand`` path widens
    it via ``prepare_workers``) - threads are never removed here, shrinking
    is ``teardown``'s job.
    """
    if self._tasks is None:
        if self.effective_pool_size <= 0:
            # Aligned with the old ThreadPoolExecutor(max_workers<=0) error
            # behavior: an illegal size is refused on the spot; MUST NOT silently
            # build a zero-thread pool so that submit never finds a "started"
            # container
            raise ValueError(
                f"pool size must be positive, got {self.effective_pool_size} (config key worker:pool:size)"
            )
        self._tasks = queue.Queue()
    self._ensure_threads(self.effective_pool_size)

teardown

teardown(core, wait: bool = True, timeout: float | None = None) -> None

Shutdown: discard queued not-yet-started tasks (stop_dispatch_cancel_queued), then stop the threads.

Started tasks cannot be interrupted (a CPython limitation, the same as the old ThreadPoolExecutor implementation); the in-flight table and the scheduling list are cleared by core.clear() (called from BaseWaiter.shutdown).

源代码位于: zoo_framework/core/waiter/scheduler_model.py
def teardown(self, core, wait: bool = True, timeout: float | None = None) -> None:
    """Shutdown: discard queued not-yet-started tasks (``stop_dispatch_cancel_queued``), then stop the threads.

    Started tasks cannot be interrupted (a CPython limitation, the same as
    the old ThreadPoolExecutor implementation); the in-flight table and the
    scheduling list are cleared by ``core.clear()`` (called from
    BaseWaiter.shutdown).
    """
    tasks, threads = self._tasks, self._threads
    self._tasks, self._threads = None, []
    if tasks is None and not threads:
        return
    if tasks is not None:
        # Discard queued items before putting the sentinels, or a sentinel
        # would be treated as a normal item and dropped, leaving the thread
        # blocked on get() forever
        self._discard_queued(tasks)
        for _ in threads:
            tasks.put(None)
    if wait:
        self._join_threads(threads, timeout)

派发与结算

zoo_framework.core.waiter.dispatch_core

Dispatch core: model-agnostic bookkeeping and correctness logic.

Five kinds of logic MUST be owned by this core; new scheduling models MUST NOT re-implement them:

  1. Single settlement path (settle) - clears the in-flight record and reports the result on success. All concurrency primitives share this one path, so results are delivered under any of them.
  2. Timeout observation and circuit-breaking (reap_timeout) - record only, mark unhealthy, stop dispatching. CPython cannot safely interrupt a running thread, so the system MUST NOT claim it terminated one.
  3. Shutdown resource reclamation (the shutdown path) - stop dispatching, clear the in-flight table; reclaiming the concurrency container (e.g. a thread pool) is provided by the model via teardown.
  4. Runtime registration (add_worker) - the scheduling list is owned by this core; being listed in a registry alone is not enough for a Worker to be dispatched.
  5. Period scheduling (is_due / jitter / skipped_count) - period and phase are per-Worker declarations, independent of the concurrency primitive; if each model implemented its own, the absolute sequence, skip semantics and jitter sampling would be implemented multiple times and inevitably diverge.

Holds a second model-agnostic concurrency contract: the in-flight table and the broken set are guarded by a single threading.RLock (both are accessed concurrently by the dispatch thread and completion callbacks), plus runtime metric counters.

Time base: every interval quantity in this module MUST use time.monotonic() and MUST NOT mix in wall-clock time.

WorkerDispatchCore

Dispatch core.

属性:

名称 类型 描述
workers list

the list of Workers participating in scheduling

worker_props dict

the in-flight table, worker name ->

broken set

the set of circuit-broken (timed-out) worker names

stopped

the shutdown flag

default_run_timeout

the global default timeout; <= 0 disables timeout evaluation

源代码位于: zoo_framework/core/waiter/dispatch_core.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
class WorkerDispatchCore:
    """Dispatch core.

    Attributes:
        workers: the list of Workers participating in scheduling
        worker_props: the in-flight table, worker name ->
            {worker, run_time, run_timeout, deadline, container}
        broken: the set of circuit-broken (timed-out) worker names
        stopped: the shutdown flag
        default_run_timeout: the global default timeout; ``<= 0`` disables
            timeout evaluation
    """

    def __init__(self, default_run_timeout=None):
        self.workers: list = []
        self.worker_props: dict = {}
        # 在飞表与熔断集合会被派发线程与完成回调并发访问
        self._lock = threading.RLock()
        self.broken: set = set()
        self.stopped = False
        self.default_run_timeout = default_run_timeout

        # 运行期指标(模型经 metrics() 暴露,MUST NOT 只在停机时可得)
        self._completed = 0
        self._timeouts = 0

        # 周期排期状态(每个 Worker 独立)
        self._period_base: float | None = None
        self._ticks: dict[str, int] = {}
        self._next_at: dict[str, float] = {}
        self._skipped: dict[str, int] = {}
        # 抖动只保留摘要(最近 / 上界 / 样本数),避免长跑 Worker 无限积累样本
        self._jitter: dict[str, dict] = {}

        # 策略解析缓存(#47 P1):worker 名 -> 属性键 -> 已解析值。此前每轮每个
        # Worker 都重走"自报→覆盖→默认"三段并现拼参数字符串键(实测 9.4 µs/任务,
        # 占提交侧 33%);解析结果在 Worker 存续期内是静态的(配置无运行期重载),
        # 失效入口只有 set_workers / add_worker(同名) / clear 三处。
        self._policy_cache: dict[tuple[str, str], object] = {}

    # ---------------------------------------------------------------- 调度列表

    def set_workers(self, worker_list) -> None:
        """Set the list of Workers participating in scheduling."""
        with self._lock:
            self.workers = list(worker_list)
            # 调度列表整体替换:旧列表的策略条目全部作废
            self._policy_cache.clear()

    def add_worker(self, worker) -> None:
        """Admit a Worker newly registered at runtime into scheduling.

        The scheduling list is owned by this core; being listed in a registry
        alone is not enough for the Worker to be dispatched.

        This method only appends to the scheduling list and implements **no**
        capacity admission. The backpressure policy MUST be applied by the
        scheduler (``BaseWaiter.add_worker`` passes the prospective list through
        ``model.prepare_workers``) **before** this is called, otherwise a
        runtime-registered Worker would bypass the policy (issue #233).
        """
        if worker is None:
            return
        with self._lock:
            # 同名重注册(如 Master.register_worker 覆盖旧实例)时旧解析作废;
            # 新名字无需动作——缓存惰性填充。
            self._invalidate_policy(worker.name)
            if worker not in self.workers:
                self.workers.append(worker)

    def retain_looping(self, workers) -> list:
        """Filter the Workers that stay in the scheduling list after this round.

        All three conditions must hold: non-empty, **not circuit-broken**, and
        declared looping. Broken Workers MUST be removed from the list, or they
        would be re-evaluated every round (and "broken means stop dispatching"
        would lose its meaning). One-shot Workers do not take part in the next
        round - "exactly once" here is a **scheduling-bookkeeping** semantic
        (the same task is never dispatched twice concurrently), not a delivery
        attempt semantic: delivery is at-least-once and a failed event callback
        is retried by EventReactor (consumers needing exactly-once bring their
        own idempotency; the framework does not build in idempotency keys).
        """
        with self._lock:
            return [
                worker
                for worker in workers
                if worker is not None and worker.name not in self.broken and worker.is_loop
            ]

    # ---------------------------------------------------------------- 状态查询

    def is_inflight(self, worker) -> bool:
        with self._lock:
            return worker.name in self.worker_props

    def is_broken(self, worker) -> bool:
        with self._lock:
            return worker.name in self.broken

    # ---------------------------------------------------------------- 周期排期

    def _policy(self, worker, key: str, compute):
        """Cache one resolution keyed by (worker name, property) (#47 P1).

        The hit test is sentinel identity: None / 0 / False / "" in the cache
        are all **valid results** and MUST NOT be re-resolved as misses or
        fallen through to defaults. The caller may already hold
        ``self._lock`` (the RLock is reentrant); this method reads/writes under
        the lock uniformly.
        """
        cache_key = (worker.name, key)
        with self._lock:
            cached = self._policy_cache.get(cache_key, _POLICY_MISS)
            if cached is not _POLICY_MISS:
                return cached
            value = compute(worker)
            self._policy_cache[cache_key] = value
            return value

    def _invalidate_policy(self, worker_name: str) -> None:
        """Invalidate all policy entries for one worker name (the caller holds the lock)."""
        stale = [k for k in self._policy_cache if k[0] == worker_name]
        for k in stale:
            del self._policy_cache[k]

    def resolve_period(self, worker: BaseWorker) -> float | None:
        """Resolve the Worker's period: self-report -> per-name override -> global default.

        The result is cached per worker name (#47 P1) while the three-stage
        semantics are preserved item by item: falsy self-reported/override
        values (0 / False / "") still fall through to the next stage per the
        existing rules, and the cache MUST NOT change that.

        Returns:
            The period in seconds; None when undeclared (callers then treat the
            Worker as event-driven)
        """
        period: float | None = self._policy(worker, "period", self._compute_period)
        return period

    @staticmethod
    def _compute_period(worker):
        from zoo_framework.core.params_factory import ParamsFactory
        from zoo_framework.params import WorkerParams

        period = getattr(worker, "period", None)
        if period:
            return period

        override = ParamsFactory().get_params(
            f"{WorkerParams.WORKER_OVERRIDE_PREFIX}:{worker.name}:period",
            default_value=None,
        )
        if override:
            return override

        return WorkerParams.WORKER_PERIOD or None

    def resolve_phase(self, worker: BaseWorker) -> float:
        """Resolve the Worker's phase offset: self-report -> per-name override -> global default.

        The result is cached per worker name (#47 P1). Phase is the classic
        falsy case: an explicit ``phase: 0`` in config is a valid value, so the
        cache check MUST be sentinel comparison rather than truthiness.

        Returns:
            The phase offset in seconds; 0.0 when undeclared
        """
        phase: float = self._policy(worker, "phase", self._compute_phase)
        return phase

    @staticmethod
    def _compute_phase(worker):
        from zoo_framework.core.params_factory import ParamsFactory
        from zoo_framework.params import WorkerParams

        phase = getattr(worker, "phase", None)
        if phase:
            return phase

        override = ParamsFactory().get_params(
            f"{WorkerParams.WORKER_OVERRIDE_PREFIX}:{worker.name}:phase",
            default_value=None,
        )
        if override is not None:
            return override

        return WorkerParams.WORKER_PHASE or 0.0

    def is_due(self, worker: BaseWorker, now: float | None = None) -> bool:
        """Whether the Worker is due at this moment.

        Periodic scheduling computes trigger times from a **monotonic-clock
        absolute sequence** (base + phase + n x period); it MUST NOT schedule as
        "last execution finish time + period", which drifts cumulatively each
        round.

        When one round of execution spans several theoretical trigger times,
        the missed rounds are **skipped** and the next trigger is the next
        future time on the sequence; catch-up runs MUST NOT happen (catch-up
        self-amplifies under sustained overload).

        The **scheduling base** is the moment of the Worker's **first due
        check** (the framework has no process-level scheduling epoch), so the
        first trigger lands at "first-check time + phase" and later theoretical
        times are "base + phase + n x period".

        Args:
            worker: the target Worker
            now: the current monotonic time; None takes ``time.monotonic()``
                (handy for test injection)

        Returns:
            Whether due; always True for Workers without a declared period
            (event-driven semantics)
        """
        period = self.resolve_period(worker)
        if not period or period <= 0:
            return True

        now = time.monotonic() if now is None else now

        with self._lock:
            if self._period_base is None:
                self._period_base = now
            key = worker.name
            phase = self.resolve_phase(worker)
            anchor = self._period_base + phase

            if key not in self._next_at:
                # 首次排期:基准 + 相位
                self._ticks[key] = 0
                self._next_at[key] = anchor

            if now < self._next_at[key]:
                return False

            # 到点:记录抖动(实际 - 理论),再把序列推进到第一个**未来**时刻
            self._record_jitter(key, expected=self._next_at[key], actual=now)

            index = int((now - anchor) // period) + 1
            self._skipped[key] = self._skipped.get(key, 0) + max(0, index - (self._ticks[key] + 1))
            self._ticks[key] = index
            self._next_at[key] = anchor + index * period
            return True

    def _record_jitter(self, key: str, expected: float, actual: float) -> None:
        """Record a trigger's jitter summary (last / upper bound / sample count)."""
        jitter = actual - expected
        summary = self._jitter.get(key)
        if summary is None:
            self._jitter[key] = {"last": jitter, "upper_bound": jitter, "samples": 1}
            return
        summary["last"] = jitter
        # 上界只升不降:后续更小的抖动 MUST NOT 把它拉低
        summary["upper_bound"] = max(summary["upper_bound"], jitter)
        summary["samples"] += 1

    def skipped_count(self, worker) -> int:
        """The Worker's cumulative count of skipped rounds."""
        with self._lock:
            return self._skipped.get(worker.name, 0)

    def jitter(self, worker) -> dict:
        """The Worker's trigger jitter summary.

        Workers without a declared period return the explicit "not applicable"
        marker and MUST NOT return 0.
        """
        with self._lock:
            summary = self._jitter.get(worker.name)

        if summary is None:
            return {
                "applicable": False,
                "jitter": JITTER_NOT_APPLICABLE,
                "reason": "no period declared; no periodic triggers, jitter not applicable",
            }
        return {"applicable": True, **summary}

    # ---------------------------------------------------------------- 派发登记

    def begin(
        self, worker: BaseWorker, timeout: float | None, deadline: float | None = None
    ) -> dict | None:
        """Register a Worker that is about to be dispatched.

        **Registration MUST precede dispatch**: if the task were submitted
        before the registration, an instantly finishing task would deregister
        itself before the registration lands, leaving an in-flight record that
        is never cleared, and the Worker would never be dispatched again.

        Args:
            worker: the target Worker
            timeout: the relative timeout in seconds
            deadline: an absolute deadline (monotonic-clock base); when given
                it takes precedence over ``timeout``

        Returns:
            The registration entry; None if already in flight (the caller MUST
            NOT dispatch)
        """
        handle = {
            "worker": worker,
            "run_time": time.monotonic(),
            "run_timeout": timeout,
            "deadline": deadline,
            "container": None,
            # 运行标识在**登记时**捕获并随登记项一起保存:结算可能发生在别的工作线程,
            # 那里的上下文未必是派发时的上下文,故以显式字段为真相来源
            "identity": current_identity(),
        }
        with self._lock:
            if worker.name in self.worker_props:
                return None
            self.worker_props[worker.name] = handle
        return handle

    def attach_container(self, worker, container) -> None:
        """Attach the container (thread or Future) carrying this Worker to its registration."""
        with self._lock:
            handle = self.worker_props.get(worker.name)
            if handle is not None:
                handle["container"] = container

    def abort(self, worker) -> None:
        """Roll back the registration: clear the entry on dispatch failure so the next round can retry."""
        with self._lock:
            self.worker_props.pop(worker.name, None)

    # ---------------------------------------------------------------- 结算收口

    def settle(
        self, worker: BaseWorker, result: Any = None, error: BaseException | None = None
    ) -> None:
        """The single completion settlement: deregister in-flight state and report the result on success.

        Deregistration MUST happen regardless of success; an exception raised by
        the reporting step itself MUST NOT affect deregistration.

        The run identity stamped on the result comes from the **registration
        entry** (not the current context) - settlement may happen on a worker
        thread whose context differs from dispatch time; the identity in the
        registration entry is the source of truth.

        Args:
            worker: the Worker that finished executing
            result: the execution result; None on failure
            error: the exception raised during execution; None on success
        """
        with self._lock:
            handle = self.worker_props.pop(worker.name, None)
            self._completed += 1

        identity: RunIdentity | None = handle.get("identity") if handle else None
        if identity is None:
            # 登记项已被熔断清理时退回当前上下文,不编造值
            identity = current_identity()

        if result is not None and identity is not None and hasattr(result, "run_id"):
            result.run_id = identity.run_id
            result.session_id = identity.session_id

        if error is not None:
            LogUtils.error(
                f"Worker {worker.name} execution failed: {error}", self.__class__.__name__
            )
            return

        if result is None:
            return

        try:
            EventReactorManager().dispatch(result.topic, result)
        except Exception as e:
            LogUtils.error(
                f"Worker {worker.name} result reporting failed: {e}", self.__class__.__name__
            )

    def run_and_settle(self, worker: BaseWorker) -> None:
        """Execute once on a worker thread and settle.

        This is the model- and primitive-independent execution unit: the
        dispatching side MUST wrap it with ``carry_context(core.run_and_settle)``
        before submitting, or the worker thread will not inherit the caller's
        context and the run identity will be silently lost at dispatch time.

        Args:
            worker: the Worker to execute
        """
        try:
            result = self.run_worker(worker)
        except Exception as e:
            self.settle(worker, error=e)
        else:
            self.settle(worker, result=result)

    # ---------------------------------------------------------------- 超时熔断

    def resolve_run_timeout(self, worker: BaseWorker) -> float | None:
        """Resolve the Worker's run timeout: self-report -> per-name override -> global default.

        The result is cached per worker name (#47 P1); the global default comes
        from ``default_run_timeout``, which does not change after construction
        (changing it would require invalidating the cache in step; there is
        currently no such runtime entry point).

        Returns:
            The timeout in seconds; None when undeclared
        """
        timeout: float | None = self._policy(worker, "run_timeout", self._compute_run_timeout)
        return timeout

    def _compute_run_timeout(self, worker):
        from zoo_framework.core.params_factory import ParamsFactory
        from zoo_framework.params import WorkerParams

        timeout = worker.run_timeout
        if timeout:
            return timeout

        override = ParamsFactory().get_params(
            f"{WorkerParams.WORKER_OVERRIDE_PREFIX}:{worker.name}:runTimeout",
            default_value=None,
        )
        if override:
            return override

        return self.default_run_timeout or None

    def reap_timeout(self, worker) -> bool:
        """Timeout evaluation and circuit-breaking.

        Observation and circuit-breaking only: record, mark unhealthy, stop
        dispatching. The system MUST NOT claim it terminated a still-running
        Worker - CPython cannot safely interrupt a running thread.

        One of the two deadline sources applies: the **absolute deadline** given
        at registration takes precedence; otherwise the relative timeout is
        used.

        Returns:
            Whether this evaluation found the Worker timed out
        """
        with self._lock:
            handle = self.worker_props.get(worker.name)
            if handle is None:
                return False

            now = time.monotonic()
            deadline = handle.get("deadline")
            if deadline is not None:
                if now < deadline:
                    return False
                elapsed = now - handle.get("run_time", now)
                reason = f"dispatch deadline exceeded (deadline {deadline:.3f}, now {now:.3f})"
            else:
                timeout = handle.get("run_timeout")
                if not timeout or timeout <= 0:
                    return False
                elapsed = now - handle.get("run_time", 0)
                if elapsed < timeout:
                    return False
                reason = f"execution exceeded {timeout}s (actual {elapsed:.3f}s)"

            self.broken.add(worker.name)
            self.worker_props.pop(worker.name, None)
            self._timeouts += 1

        LogUtils.error(
            f"Worker {worker.name} {reason}, marked unhealthy and dispatch stopped;"
            "the system does not force-terminate still-running workers",
            self.__class__.__name__,
        )
        return True

    # ---------------------------------------------------------------- 执行入口

    @staticmethod
    def run_worker(worker: Any) -> WorkerResult | None:
        """Execute one Worker.

        Returns:
            WorkerResult; None when the worker is not a valid BaseWorker
        """
        if not isinstance(worker, BaseWorker):
            return None

        return worker.run()

    # ---------------------------------------------------------------- 停机

    def mark_stopped(self) -> bool:
        """Set the stopped flag.

        Returns:
            Whether this call is the first shutdown (repeated calls return
            False)
        """
        with self._lock:
            already_stopped = self.stopped
            self.stopped = True
        return not already_stopped

    def clear(self) -> None:
        """Clear the scheduling list, the in-flight table and the period-scheduling state.

        Period scheduling is reset as well: after a shutdown a fresh start
        should establish a new base rather than reuse the old sequence.
        """
        with self._lock:
            self.workers = []
            self.worker_props.clear()
            self._policy_cache.clear()
            self._period_base = None
            self._ticks.clear()
            self._next_at.clear()
            self._skipped.clear()
            self._jitter.clear()

    # ---------------------------------------------------------------- 指标

    def metrics(self) -> dict:
        """Runtime metrics: in-flight count, cumulative completions, timeout circuit-breaks.

        MUST be queryable at runtime, MUST NOT be available only at shutdown.
        Jitter is **per-Worker** observation, queried via ``jitter(worker)``, so
        it is not aggregated here.
        """
        with self._lock:
            return {
                "inflight": len(self.worker_props),
                "completed": self._completed,
                "timeouts": self._timeouts,
            }

set_workers

set_workers(worker_list) -> None

Set the list of Workers participating in scheduling.

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def set_workers(self, worker_list) -> None:
    """Set the list of Workers participating in scheduling."""
    with self._lock:
        self.workers = list(worker_list)
        # 调度列表整体替换:旧列表的策略条目全部作废
        self._policy_cache.clear()

add_worker

add_worker(worker) -> None

Admit a Worker newly registered at runtime into scheduling.

The scheduling list is owned by this core; being listed in a registry alone is not enough for the Worker to be dispatched.

This method only appends to the scheduling list and implements no capacity admission. The backpressure policy MUST be applied by the scheduler (BaseWaiter.add_worker passes the prospective list through model.prepare_workers) before this is called, otherwise a runtime-registered Worker would bypass the policy (issue #233).

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def add_worker(self, worker) -> None:
    """Admit a Worker newly registered at runtime into scheduling.

    The scheduling list is owned by this core; being listed in a registry
    alone is not enough for the Worker to be dispatched.

    This method only appends to the scheduling list and implements **no**
    capacity admission. The backpressure policy MUST be applied by the
    scheduler (``BaseWaiter.add_worker`` passes the prospective list through
    ``model.prepare_workers``) **before** this is called, otherwise a
    runtime-registered Worker would bypass the policy (issue #233).
    """
    if worker is None:
        return
    with self._lock:
        # 同名重注册(如 Master.register_worker 覆盖旧实例)时旧解析作废;
        # 新名字无需动作——缓存惰性填充。
        self._invalidate_policy(worker.name)
        if worker not in self.workers:
            self.workers.append(worker)

retain_looping

retain_looping(workers) -> list

Filter the Workers that stay in the scheduling list after this round.

All three conditions must hold: non-empty, not circuit-broken, and declared looping. Broken Workers MUST be removed from the list, or they would be re-evaluated every round (and "broken means stop dispatching" would lose its meaning). One-shot Workers do not take part in the next round - "exactly once" here is a scheduling-bookkeeping semantic (the same task is never dispatched twice concurrently), not a delivery attempt semantic: delivery is at-least-once and a failed event callback is retried by EventReactor (consumers needing exactly-once bring their own idempotency; the framework does not build in idempotency keys).

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def retain_looping(self, workers) -> list:
    """Filter the Workers that stay in the scheduling list after this round.

    All three conditions must hold: non-empty, **not circuit-broken**, and
    declared looping. Broken Workers MUST be removed from the list, or they
    would be re-evaluated every round (and "broken means stop dispatching"
    would lose its meaning). One-shot Workers do not take part in the next
    round - "exactly once" here is a **scheduling-bookkeeping** semantic
    (the same task is never dispatched twice concurrently), not a delivery
    attempt semantic: delivery is at-least-once and a failed event callback
    is retried by EventReactor (consumers needing exactly-once bring their
    own idempotency; the framework does not build in idempotency keys).
    """
    with self._lock:
        return [
            worker
            for worker in workers
            if worker is not None and worker.name not in self.broken and worker.is_loop
        ]

resolve_period

resolve_period(worker: BaseWorker) -> float | None

Resolve the Worker's period: self-report -> per-name override -> global default.

The result is cached per worker name (#47 P1) while the three-stage semantics are preserved item by item: falsy self-reported/override values (0 / False / "") still fall through to the next stage per the existing rules, and the cache MUST NOT change that.

返回:

类型 描述
float | None

The period in seconds; None when undeclared (callers then treat the

float | None

Worker as event-driven)

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def resolve_period(self, worker: BaseWorker) -> float | None:
    """Resolve the Worker's period: self-report -> per-name override -> global default.

    The result is cached per worker name (#47 P1) while the three-stage
    semantics are preserved item by item: falsy self-reported/override
    values (0 / False / "") still fall through to the next stage per the
    existing rules, and the cache MUST NOT change that.

    Returns:
        The period in seconds; None when undeclared (callers then treat the
        Worker as event-driven)
    """
    period: float | None = self._policy(worker, "period", self._compute_period)
    return period

resolve_phase

resolve_phase(worker: BaseWorker) -> float

Resolve the Worker's phase offset: self-report -> per-name override -> global default.

The result is cached per worker name (#47 P1). Phase is the classic falsy case: an explicit phase: 0 in config is a valid value, so the cache check MUST be sentinel comparison rather than truthiness.

返回:

类型 描述
float

The phase offset in seconds; 0.0 when undeclared

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def resolve_phase(self, worker: BaseWorker) -> float:
    """Resolve the Worker's phase offset: self-report -> per-name override -> global default.

    The result is cached per worker name (#47 P1). Phase is the classic
    falsy case: an explicit ``phase: 0`` in config is a valid value, so the
    cache check MUST be sentinel comparison rather than truthiness.

    Returns:
        The phase offset in seconds; 0.0 when undeclared
    """
    phase: float = self._policy(worker, "phase", self._compute_phase)
    return phase

is_due

is_due(worker: BaseWorker, now: float | None = None) -> bool

Whether the Worker is due at this moment.

Periodic scheduling computes trigger times from a monotonic-clock absolute sequence (base + phase + n x period); it MUST NOT schedule as "last execution finish time + period", which drifts cumulatively each round.

When one round of execution spans several theoretical trigger times, the missed rounds are skipped and the next trigger is the next future time on the sequence; catch-up runs MUST NOT happen (catch-up self-amplifies under sustained overload).

The scheduling base is the moment of the Worker's first due check (the framework has no process-level scheduling epoch), so the first trigger lands at "first-check time + phase" and later theoretical times are "base + phase + n x period".

参数:

名称 类型 描述 默认
worker BaseWorker

the target Worker

必需
now float | None

the current monotonic time; None takes time.monotonic() (handy for test injection)

None

返回:

类型 描述
bool

Whether due; always True for Workers without a declared period

bool

(event-driven semantics)

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def is_due(self, worker: BaseWorker, now: float | None = None) -> bool:
    """Whether the Worker is due at this moment.

    Periodic scheduling computes trigger times from a **monotonic-clock
    absolute sequence** (base + phase + n x period); it MUST NOT schedule as
    "last execution finish time + period", which drifts cumulatively each
    round.

    When one round of execution spans several theoretical trigger times,
    the missed rounds are **skipped** and the next trigger is the next
    future time on the sequence; catch-up runs MUST NOT happen (catch-up
    self-amplifies under sustained overload).

    The **scheduling base** is the moment of the Worker's **first due
    check** (the framework has no process-level scheduling epoch), so the
    first trigger lands at "first-check time + phase" and later theoretical
    times are "base + phase + n x period".

    Args:
        worker: the target Worker
        now: the current monotonic time; None takes ``time.monotonic()``
            (handy for test injection)

    Returns:
        Whether due; always True for Workers without a declared period
        (event-driven semantics)
    """
    period = self.resolve_period(worker)
    if not period or period <= 0:
        return True

    now = time.monotonic() if now is None else now

    with self._lock:
        if self._period_base is None:
            self._period_base = now
        key = worker.name
        phase = self.resolve_phase(worker)
        anchor = self._period_base + phase

        if key not in self._next_at:
            # 首次排期:基准 + 相位
            self._ticks[key] = 0
            self._next_at[key] = anchor

        if now < self._next_at[key]:
            return False

        # 到点:记录抖动(实际 - 理论),再把序列推进到第一个**未来**时刻
        self._record_jitter(key, expected=self._next_at[key], actual=now)

        index = int((now - anchor) // period) + 1
        self._skipped[key] = self._skipped.get(key, 0) + max(0, index - (self._ticks[key] + 1))
        self._ticks[key] = index
        self._next_at[key] = anchor + index * period
        return True

skipped_count

skipped_count(worker) -> int

The Worker's cumulative count of skipped rounds.

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def skipped_count(self, worker) -> int:
    """The Worker's cumulative count of skipped rounds."""
    with self._lock:
        return self._skipped.get(worker.name, 0)

jitter

jitter(worker) -> dict

The Worker's trigger jitter summary.

Workers without a declared period return the explicit "not applicable" marker and MUST NOT return 0.

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def jitter(self, worker) -> dict:
    """The Worker's trigger jitter summary.

    Workers without a declared period return the explicit "not applicable"
    marker and MUST NOT return 0.
    """
    with self._lock:
        summary = self._jitter.get(worker.name)

    if summary is None:
        return {
            "applicable": False,
            "jitter": JITTER_NOT_APPLICABLE,
            "reason": "no period declared; no periodic triggers, jitter not applicable",
        }
    return {"applicable": True, **summary}

begin

begin(worker: BaseWorker, timeout: float | None, deadline: float | None = None) -> dict | None

Register a Worker that is about to be dispatched.

Registration MUST precede dispatch: if the task were submitted before the registration, an instantly finishing task would deregister itself before the registration lands, leaving an in-flight record that is never cleared, and the Worker would never be dispatched again.

参数:

名称 类型 描述 默认
worker BaseWorker

the target Worker

必需
timeout float | None

the relative timeout in seconds

必需
deadline float | None

an absolute deadline (monotonic-clock base); when given it takes precedence over timeout

None

返回:

类型 描述
dict | None

The registration entry; None if already in flight (the caller MUST

dict | None

NOT dispatch)

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def begin(
    self, worker: BaseWorker, timeout: float | None, deadline: float | None = None
) -> dict | None:
    """Register a Worker that is about to be dispatched.

    **Registration MUST precede dispatch**: if the task were submitted
    before the registration, an instantly finishing task would deregister
    itself before the registration lands, leaving an in-flight record that
    is never cleared, and the Worker would never be dispatched again.

    Args:
        worker: the target Worker
        timeout: the relative timeout in seconds
        deadline: an absolute deadline (monotonic-clock base); when given
            it takes precedence over ``timeout``

    Returns:
        The registration entry; None if already in flight (the caller MUST
        NOT dispatch)
    """
    handle = {
        "worker": worker,
        "run_time": time.monotonic(),
        "run_timeout": timeout,
        "deadline": deadline,
        "container": None,
        # 运行标识在**登记时**捕获并随登记项一起保存:结算可能发生在别的工作线程,
        # 那里的上下文未必是派发时的上下文,故以显式字段为真相来源
        "identity": current_identity(),
    }
    with self._lock:
        if worker.name in self.worker_props:
            return None
        self.worker_props[worker.name] = handle
    return handle

attach_container

attach_container(worker, container) -> None

Attach the container (thread or Future) carrying this Worker to its registration.

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def attach_container(self, worker, container) -> None:
    """Attach the container (thread or Future) carrying this Worker to its registration."""
    with self._lock:
        handle = self.worker_props.get(worker.name)
        if handle is not None:
            handle["container"] = container

abort

abort(worker) -> None

Roll back the registration: clear the entry on dispatch failure so the next round can retry.

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def abort(self, worker) -> None:
    """Roll back the registration: clear the entry on dispatch failure so the next round can retry."""
    with self._lock:
        self.worker_props.pop(worker.name, None)

settle

settle(worker: BaseWorker, result: Any = None, error: BaseException | None = None) -> None

The single completion settlement: deregister in-flight state and report the result on success.

Deregistration MUST happen regardless of success; an exception raised by the reporting step itself MUST NOT affect deregistration.

The run identity stamped on the result comes from the registration entry (not the current context) - settlement may happen on a worker thread whose context differs from dispatch time; the identity in the registration entry is the source of truth.

参数:

名称 类型 描述 默认
worker BaseWorker

the Worker that finished executing

必需
result Any

the execution result; None on failure

None
error BaseException | None

the exception raised during execution; None on success

None
源代码位于: zoo_framework/core/waiter/dispatch_core.py
def settle(
    self, worker: BaseWorker, result: Any = None, error: BaseException | None = None
) -> None:
    """The single completion settlement: deregister in-flight state and report the result on success.

    Deregistration MUST happen regardless of success; an exception raised by
    the reporting step itself MUST NOT affect deregistration.

    The run identity stamped on the result comes from the **registration
    entry** (not the current context) - settlement may happen on a worker
    thread whose context differs from dispatch time; the identity in the
    registration entry is the source of truth.

    Args:
        worker: the Worker that finished executing
        result: the execution result; None on failure
        error: the exception raised during execution; None on success
    """
    with self._lock:
        handle = self.worker_props.pop(worker.name, None)
        self._completed += 1

    identity: RunIdentity | None = handle.get("identity") if handle else None
    if identity is None:
        # 登记项已被熔断清理时退回当前上下文,不编造值
        identity = current_identity()

    if result is not None and identity is not None and hasattr(result, "run_id"):
        result.run_id = identity.run_id
        result.session_id = identity.session_id

    if error is not None:
        LogUtils.error(
            f"Worker {worker.name} execution failed: {error}", self.__class__.__name__
        )
        return

    if result is None:
        return

    try:
        EventReactorManager().dispatch(result.topic, result)
    except Exception as e:
        LogUtils.error(
            f"Worker {worker.name} result reporting failed: {e}", self.__class__.__name__
        )

run_and_settle

run_and_settle(worker: BaseWorker) -> None

Execute once on a worker thread and settle.

This is the model- and primitive-independent execution unit: the dispatching side MUST wrap it with carry_context(core.run_and_settle) before submitting, or the worker thread will not inherit the caller's context and the run identity will be silently lost at dispatch time.

参数:

名称 类型 描述 默认
worker BaseWorker

the Worker to execute

必需
源代码位于: zoo_framework/core/waiter/dispatch_core.py
def run_and_settle(self, worker: BaseWorker) -> None:
    """Execute once on a worker thread and settle.

    This is the model- and primitive-independent execution unit: the
    dispatching side MUST wrap it with ``carry_context(core.run_and_settle)``
    before submitting, or the worker thread will not inherit the caller's
    context and the run identity will be silently lost at dispatch time.

    Args:
        worker: the Worker to execute
    """
    try:
        result = self.run_worker(worker)
    except Exception as e:
        self.settle(worker, error=e)
    else:
        self.settle(worker, result=result)

resolve_run_timeout

resolve_run_timeout(worker: BaseWorker) -> float | None

Resolve the Worker's run timeout: self-report -> per-name override -> global default.

The result is cached per worker name (#47 P1); the global default comes from default_run_timeout, which does not change after construction (changing it would require invalidating the cache in step; there is currently no such runtime entry point).

返回:

类型 描述
float | None

The timeout in seconds; None when undeclared

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def resolve_run_timeout(self, worker: BaseWorker) -> float | None:
    """Resolve the Worker's run timeout: self-report -> per-name override -> global default.

    The result is cached per worker name (#47 P1); the global default comes
    from ``default_run_timeout``, which does not change after construction
    (changing it would require invalidating the cache in step; there is
    currently no such runtime entry point).

    Returns:
        The timeout in seconds; None when undeclared
    """
    timeout: float | None = self._policy(worker, "run_timeout", self._compute_run_timeout)
    return timeout

reap_timeout

reap_timeout(worker) -> bool

Timeout evaluation and circuit-breaking.

Observation and circuit-breaking only: record, mark unhealthy, stop dispatching. The system MUST NOT claim it terminated a still-running Worker - CPython cannot safely interrupt a running thread.

One of the two deadline sources applies: the absolute deadline given at registration takes precedence; otherwise the relative timeout is used.

返回:

类型 描述
bool

Whether this evaluation found the Worker timed out

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def reap_timeout(self, worker) -> bool:
    """Timeout evaluation and circuit-breaking.

    Observation and circuit-breaking only: record, mark unhealthy, stop
    dispatching. The system MUST NOT claim it terminated a still-running
    Worker - CPython cannot safely interrupt a running thread.

    One of the two deadline sources applies: the **absolute deadline** given
    at registration takes precedence; otherwise the relative timeout is
    used.

    Returns:
        Whether this evaluation found the Worker timed out
    """
    with self._lock:
        handle = self.worker_props.get(worker.name)
        if handle is None:
            return False

        now = time.monotonic()
        deadline = handle.get("deadline")
        if deadline is not None:
            if now < deadline:
                return False
            elapsed = now - handle.get("run_time", now)
            reason = f"dispatch deadline exceeded (deadline {deadline:.3f}, now {now:.3f})"
        else:
            timeout = handle.get("run_timeout")
            if not timeout or timeout <= 0:
                return False
            elapsed = now - handle.get("run_time", 0)
            if elapsed < timeout:
                return False
            reason = f"execution exceeded {timeout}s (actual {elapsed:.3f}s)"

        self.broken.add(worker.name)
        self.worker_props.pop(worker.name, None)
        self._timeouts += 1

    LogUtils.error(
        f"Worker {worker.name} {reason}, marked unhealthy and dispatch stopped;"
        "the system does not force-terminate still-running workers",
        self.__class__.__name__,
    )
    return True

run_worker staticmethod

run_worker(worker: Any) -> WorkerResult | None

Execute one Worker.

返回:

类型 描述
WorkerResult | None

WorkerResult; None when the worker is not a valid BaseWorker

源代码位于: zoo_framework/core/waiter/dispatch_core.py
@staticmethod
def run_worker(worker: Any) -> WorkerResult | None:
    """Execute one Worker.

    Returns:
        WorkerResult; None when the worker is not a valid BaseWorker
    """
    if not isinstance(worker, BaseWorker):
        return None

    return worker.run()

mark_stopped

mark_stopped() -> bool

Set the stopped flag.

返回:

类型 描述
bool

Whether this call is the first shutdown (repeated calls return

bool

False)

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def mark_stopped(self) -> bool:
    """Set the stopped flag.

    Returns:
        Whether this call is the first shutdown (repeated calls return
        False)
    """
    with self._lock:
        already_stopped = self.stopped
        self.stopped = True
    return not already_stopped

clear

clear() -> None

Clear the scheduling list, the in-flight table and the period-scheduling state.

Period scheduling is reset as well: after a shutdown a fresh start should establish a new base rather than reuse the old sequence.

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def clear(self) -> None:
    """Clear the scheduling list, the in-flight table and the period-scheduling state.

    Period scheduling is reset as well: after a shutdown a fresh start
    should establish a new base rather than reuse the old sequence.
    """
    with self._lock:
        self.workers = []
        self.worker_props.clear()
        self._policy_cache.clear()
        self._period_base = None
        self._ticks.clear()
        self._next_at.clear()
        self._skipped.clear()
        self._jitter.clear()

metrics

metrics() -> dict

Runtime metrics: in-flight count, cumulative completions, timeout circuit-breaks.

MUST be queryable at runtime, MUST NOT be available only at shutdown. Jitter is per-Worker observation, queried via jitter(worker), so it is not aggregated here.

源代码位于: zoo_framework/core/waiter/dispatch_core.py
def metrics(self) -> dict:
    """Runtime metrics: in-flight count, cumulative completions, timeout circuit-breaks.

    MUST be queryable at runtime, MUST NOT be available only at shutdown.
    Jitter is **per-Worker** observation, queried via ``jitter(worker)``, so
    it is not aggregated here.
    """
    with self._lock:
        return {
            "inflight": len(self.worker_props),
            "completed": self._completed,
            "timeouts": self._timeouts,
        }

常量

zoo_framework.constant.worker_constant.WorkerConstant

Worker run mode and run policy constants.

Implemented: RUN_MODE_THREAD and three run policies. RUN_MODE_PROCESS / RUN_MODE_COROUTINE and their abbreviations are unimplemented placeholders - process mode requires pickleable Workers; coroutine mode has no scheduling entry yet. Unimplemented constants MUST NOT be silently treated as other modes.

源代码位于: zoo_framework/constant/worker_constant.py
class WorkerConstant:
    """Worker run mode and run policy constants.

    Implemented: ``RUN_MODE_THREAD`` and three run policies.
    ``RUN_MODE_PROCESS`` / ``RUN_MODE_COROUTINE`` and their abbreviations
    are **unimplemented placeholders** - process mode requires pickleable
    Workers; coroutine mode has no scheduling entry yet.
    Unimplemented constants MUST NOT be silently treated as other modes.
    """

    # Run modes
    RUN_MODE_THREAD = "thread"
    RUN_MODE_PROCESS = "process"  # unimplemented (placeholder)
    RUN_MODE_COROUTINE = "coroutine"  # unimplemented (placeholder)

    # Run modes (abbreviations)
    RUN_MODE_THREAD_ABBREVIATE = "T"
    RUN_MODE_PROCESS_ABBREVIATE = "P"  # unimplemented (placeholder)
    RUN_MODE_COROUTINE_ABBREVIATE = "C"  # unimplemented (placeholder)

    # The implemented run modes set, for validation
    IMPLEMENTED_RUN_MODES = (RUN_MODE_THREAD,)

    # Policies when the pool size is insufficient (consumed by
    # ThreadPoolModel as a back-pressure policy):
    #   simple -> scale up; stable -> queue; safe -> reject
    # History: the three were once three scheduler classes
    # (SimpleWaiter / StableWaiter / SafeWaiter); their differences were
    # only in pool-size semantics, unrelated to concurrency primitives or
    # time semantics, so they were demoted to model parameters.
    RUN_POLICY_SAFE = "safe"
    RUN_POLICY_SIMPLE = "simple"
    RUN_POLICY_STABLE = "stable"

    # The implemented run policies set, for validation
    IMPLEMENTED_RUN_POLICIES = (RUN_POLICY_SIMPLE, RUN_POLICY_STABLE, RUN_POLICY_SAFE)

zoo_framework.constant.waiter_constant.WaiterConstant

Scheduler constants.

Implemented worker modes: WORKER_MODE_THREAD and WORKER_MODE_THREAD_POOL. Unimplemented modes (placeholders): WORKER_MODE_PROCESS and WORKER_MODE_PROCESS_POOL - process modes require pickleable Workers and cross-process communication, no implementation provided yet. A request for an unimplemented mode MUST be rejected explicitly and MUST NOT silently run as another mode.

源代码位于: zoo_framework/constant/waiter_constant.py
class WaiterConstant:
    """Scheduler constants.

    Implemented worker modes: ``WORKER_MODE_THREAD`` and
    ``WORKER_MODE_THREAD_POOL``.
    Unimplemented modes (placeholders): ``WORKER_MODE_PROCESS`` and
    ``WORKER_MODE_PROCESS_POOL`` - process modes require pickleable Workers
    and cross-process communication, no implementation provided yet.
    A request for an unimplemented mode MUST be rejected explicitly and
    MUST NOT silently run as another mode.
    """

    # Implemented worker modes
    WORKER_MODE_THREAD = "thread"
    WORKER_MODE_THREAD_POOL = "thread_pool"

    # Unimplemented (placeholders): let callers state intent; explicitly
    # rejected at present
    WORKER_MODE_PROCESS = "process"
    WORKER_MODE_PROCESS_POOL = "process_pool"

    # The implemented modes set, for validation
    IMPLEMENTED_WORKER_MODES = (WORKER_MODE_THREAD, WORKER_MODE_THREAD_POOL)

    # The Worker result topic.
    # All Workers' results are delivered to this unified topic; receivers
    # filter by WorkerResult.worker_name, instead of each Worker deriving
    # its own topic from its class name.
    WORKER_RESULT_TOPIC = "waiter"