Core Module#

The core module provides the fundamental building blocks:

  • Analyzer: Base class for result analysis components

  • EventBus: Communication system between optimization components

  • StrategyBase: Base class for optimization strategies

  • Heuristic: Base class for point generation algorithms

  • Module: Base class for all Panobbgo components

Core#

This is the core part. It contains the essential components and base-classes for the modules:

  • Results: Database of all results, with some rudimentary queries and statistics.

  • EventBus: This is the backbone for communicating between the strategy, the heuristics and the analyzers.

  • “abstract” base-classes for the modules

  • and most importantly, the StrategyBase which holds everything together and subclasses in strategies implement the actual strategies.

digraph inheritancec2aaa6a2f7 { bgcolor=transparent; rankdir=LR; size="8.0, 12.0"; "panobbgo.core.Analyzer" [URL="#panobbgo.core.Analyzer",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Abstract parent class for all types of analyzers."]; "panobbgo.core.Module" -> "panobbgo.core.Analyzer" [arrowsize=0.5,style="setlinewidth(0.5)"]; "panobbgo.core.Event" [URL="#panobbgo.core.Event",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="This class holds the data for one single :class:`~.EventBus` event."]; "panobbgo.core.EventBus" [URL="#panobbgo.core.EventBus",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Publish/subscribe bus connecting the strategy, its analyzers and its"]; "panobbgo.core.Heuristic" [URL="#panobbgo.core.Heuristic",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="This is the \"abstract\" parent class for all types of point generating classes,"]; "panobbgo.core.Module" -> "panobbgo.core.Heuristic" [arrowsize=0.5,style="setlinewidth(0.5)"]; "panobbgo.core.HeuristicSubprocess" [URL="#panobbgo.core.HeuristicSubprocess",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="This Heuristic is a subclass of :class:`.Heuristic`, which is additionally starting"]; "panobbgo.core.Heuristic" -> "panobbgo.core.HeuristicSubprocess" [arrowsize=0.5,style="setlinewidth(0.5)"]; "panobbgo.core.Module" [URL="#panobbgo.core.Module",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="\"Abstract\" parent class for various panobbgo modules, e.g."]; "panobbgo.core.PipeBridgeHeuristic" [URL="#panobbgo.core.PipeBridgeHeuristic",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="A sequential solver in a subprocess, **pulled** from the caller's thread."]; "panobbgo.core.Heuristic" -> "panobbgo.core.PipeBridgeHeuristic" [arrowsize=0.5,style="setlinewidth(0.5)"]; "panobbgo.core.Results" [URL="#panobbgo.core.Results",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="A very simple database of results with a notification for new results."]; "panobbgo.core.StopHeuristic" [URL="#panobbgo.core.StopHeuristic",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Indicates the heuristic has finished and should be ignored/removed."]; "panobbgo.core.StrategyBase" [URL="#panobbgo.core.StrategyBase",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="This abstract BaseStrategy is the parent class of all Strategies."]; }
panobbgo.core.ASYNC_POLICIES: Tuple[str, ...] = ('pull', 'legacy')#

the asynchronous main loop’s policy (see StrategyBase._free_workers()).

Type:

evaluation.async_policy values

class panobbgo.core.Analyzer(strategy: StrategyBase, name: str | None = None)[source]#

Bases: Module

Abstract parent class for all types of analyzers.

Parameters:

@type strategy: StrategyBase

class panobbgo.core.Event(**kwargs: Any)[source]#

Bases: object

This class holds the data for one single EventBus event.

terminate: bool#
class panobbgo.core.EventBus(config: Any)[source]#

Bases: object

Publish/subscribe bus connecting the strategy, its analyzers and its heuristics. E.g. the “new best point” information is sent to every subscribing heuristic.

Delivery is serial and ordered: one dispatcher thread pops events from a single FIFO and calls the subscribers’ on_<key> handlers one after the other, in subscription order. Events published by a handler are appended to the same FIFO. Consequently

  • a module never has two handlers running at the same time, so module state needs no locking;

  • the sequence of handler invocations is a pure function of the sequence of publish calls — the property the seeded, reproducible runs rely on (see wait_idle());

  • handlers must return promptly. A module reacts to events; it never sleeps, polls or waits for other events inside a handler.

property inflight: int#

Events queued plus the one currently being dispatched.

A non-zero value means a handler is about to run (or is running), i.e. a heuristic may still refill its queue without any new evaluation. StrategyBase._alive() needs exactly this: the difference between “every queue is empty” and “nothing can ever produce again”.

is_subscribed(target: Any) → bool[source]#

True iff target still listens to at least one key.

property keys: List[str]#

List of all keys where you can send an Event to.

publish(key: str, event: Event | None = None, terminate: bool = False, **kwargs: Any) → None[source]#

Publishes a new Event to all subscribers, who listen to the given key. It is either possible to send an existing event or to create an event object on the fly with the given **kwargs. Every subscriber gets its own Event instance.

Args:

  • event: if set, this given Event’s payload is sent (and not a new one created).

  • terminate: if True, the subscription of key ends after this event

    (use it for on_start and similar one-shot lifecycle events).

  • **kwargs: any additional keyword arguments are stored inside the Event

    if event is None.

register(target: Any) → None[source]#

Registers a given target for this EventBus instance: every on_<key> method it has becomes a subscription to key.

Parameters:

target (Module)

shutdown(timeout: float = 2.0) → None[source]#

Deliver what is still queued (bounded by timeout), then stop the dispatcher thread and drop all subscriptions.

subscribe(key: str, target: Any) → None[source]#

Called by register().

Note

counterpart is unsubscribe().

unsubscribe(key: str | None, target: Any) → None[source]#

Args:

  • if key is None, the target is removed from all keys.

wait_idle(timeout: float | None = None) → bool[source]#

Block until every published event has been handled.

Handlers may publish further events (new_results → new_best → on_new_best …); the whole cascade counts. Returns True when the bus is idle, False on timeout. The synchronous evaluation mode calls this before every draw so each main-loop pass sees the fully updated state of all analyzers and heuristics.

class panobbgo.core.Heuristic(strategy: StrategyBase, name: str | None = None, cap: int | None = None)[source]#

Bases: Module

This is the “abstract” parent class for all types of point generating classes, which we call collectively “Heuristics”.

Such a heuristic is capable of the following:

  1. They can be parameterized by passing in optional arguments in the constructor. This should be reflected in the name!

  2. The EventBus spawns a thread for each on_* method and calls them when a corresponding Event occurs.

  3. Of course, they are capable of storing their state in the instance. This is also the way of how information is shared between those threads.

  4. The main purpose of a heuristic is to emit new search points by calling either emit() or returning a list of points. The datatype must be numpy.ndarray of floats.

  5. Additionally, the can get hold of other heuristics or anayzers via the strategy instance.

  6. The EventBus inside this strategy instance allows them to publish their own events, too. This can be used to signal related heuristics something or to queue up tasks for itself.

Parameters:

@type strategy: StrategyBase

WARM_START_MODES: Tuple[str, ...] = ('archive', 'archive_diverse', 'archive_leaf')#

Selector names archive_seed() understands. None (the default of every warm_start= constructor argument) means “cold start”, i.e. do not call archive_seed() at all.

property active: bool#

This is queried by the strategy to determine, if it should still consider it. This is the case, iff there is still something in its output queue or if there is a chance that there will be something in the future (it still listens to at least one event).

archive_seed(k: int, *, mode: str | None = None, box: Any = None) → List[Result][source]#

Up to k good points from the shared archive, best first.

The query layer of planning/DESIGN_warm_start_2026-09-10.md §2: a heuristic that wants to start from points it did not pay for asks here instead of reaching into another module’s state. Three selectors, all of them unfiltered by who:

  • "archive" (default) — the k best results;

  • "archive_diverse" — k well-separated good results;

  • "archive_leaf" — the best point of each of the k best Splitter leaves, i.e. k different basins.

Source is the opt-in Archive analyzer when the strategy has one; otherwise the Splitter’s root box, which holds every result in Result form, sorted by penalty value. With neither analyzer — or with nothing evaluated yet — the answer is [], which every caller has to read as “use the cold path”.

Never raises: a missing analyzer, an unstarted one or a broken constraint handler all degrade to [].

property can_produce: bool#

True iff produce() would hand out a point right now.

The same question as has_points for a reactive heuristic, and the correct one for an on_demand one, whose queue is empty by construction between round trips. This is the predicate schedulers gate on and the one StrategyBase._alive() sums over.

cap: int#
clear_output() → None[source]#
emit(points: ndarray | List[ndarray] | Point | List[Point] | List[Any]) → None[source]#

This is used to send out new search points for evaluation. Args:

  • points: Either a numpy.ndarray of float64 or preferrably a list of them.

Raises TypeError for anything that is not an ndarray — a wrong return type is a bug in the heuristic, not something to skip quietly.

ensure_output_capacity(n: int) → None[source]#

Grow the output queue so that at least n additional points fit.

Heuristics that emit points in batches whose size can exceed the configured queue capacity (e.g. CMA-ES after IPOP restarts double λ) must call this before emitting, otherwise put_nowait silently drops the overflow and the heuristic deadlocks waiting for results that will never arrive.

fill_queue(draw: Callable[[], ndarray]) → None[source]#

Top the output queue up to cap with points from draw.

The refill contract of every reactive heuristic: fill on start (or whatever event defines its search region) and top up on each result batch, so the strategy always finds points without the heuristic having to poll.

get_points(limit: int | None = None) → List[Point][source]#

Drain the output queue until limit points are removed or it is empty.

property has_points: bool#

True iff this heuristic can hand out a point right now.

Selection strategies use this to skip heuristics that would return an empty list, so the probability mass they would have received is not wasted.

new_who(rng: Generator | None = None) → str[source]#

A who tag carrying a unique request id: "<name>:<hex>".

Heuristics that must match a result back to the trial that produced it (the DE family, PSO) tag each point this way. The id is drawn from the module’s own generator, so it is part of the reproducible stream.

on_demand: bool = False#

True iff this heuristic produces points on demand, on the caller’s thread, rather than reactively topping its queue up from event handlers. The solver bridges (LBFGSB, COBYQA) set it: a sequential SciPy optimizer cannot queue a point ahead, because its next iterate is a function of f at the current one. A scheduler must call produce() — never get_points() — or such an arm is starved by any competitor that keeps a stocked queue (planning/DESIGN_pump_and_stall_2026-09-11.md §1).

performance: float#
produce(limit: int | None = None, timeout: float | None = None) → List[Point][source]#

The scheduler’s point-acquisition call.

For a reactive heuristic this is exactly get_points() — the queue is whatever its event handlers put there. An on_demand heuristic overrides it and produces the next point synchronously, on the calling thread.

timeout is a deadlock backstop for the on-demand case, never a scheduling parameter: a healthy producer answers immediately, so the value cannot influence which points a run evaluates — only whether the run reports a wedged worker.

required_analyzers() → Tuple[str, ...][source]#

Also the Splitter when this heuristic warm-starts.

archive_seed() reads Splitter leaves for "archive_leaf" and falls back to the Splitter root without an Archive; a warm_start_box is a Splitter box. Every heuristic with a warm start stores its mode in self.warm_start.

warm_start_now() → bool[source]#

Re-seed this heuristic from the shared archive, right now.

Called by a scheduler that just handed this heuristic a fresh block of evaluations (see StrategyBlockBandit), by direct method call — the event bus only broadcasts. Returns True iff a seed was actually used. The default is False: a heuristic that does not opt in is left exactly as it was.

class panobbgo.core.HeuristicSubprocess(strategy: StrategyBase, name: str | None = None, cap: int | None = None)[source]#

Bases: Heuristic

This Heuristic is a subclass of Heuristic, which is additionally starting a subprocess, which communicates with the main thread via a pipe in a blocking communication scheme.

Parameters:

@type strategy: StrategyBase

static subprocess(pipe: Any) → None[source]#

overwrite this pipe.recv() & pipe.send() loop and compute something in between.

class panobbgo.core.Module(strategy: StrategyBase, name: str | None = None)[source]#

Bases: object

“Abstract” parent class for various panobbgo modules, e.g. Heuristic and Analyzer.

Parameters:

@type strategy: StrategyBase

budget_progress() → float | None[source]#

Fraction of the evaluation budget used, len(strategy.results) / max_eval in [0, 1].

None when the budget is unknown (no max_eval, zero, negative or non-numeric), so a schedule can fall back to its constant setting instead of guessing a horizon.

check_dependencies(analyzers: List[Analyzer], heuristics: List[Heuristic]) → bool[source]#

This method is called by the core initialization to assess, if the dependencies for the given module are met.

By default, it returns true. Return false if there is a problem.

The arguments are the list of pre-initialized analyzers and heuristics.

derive_rng(seed: int | None) → Generator[source]#

Generator for a sub-component: seed if given, else this module’s own.

Heuristics that expose a seed argument use this so an explicit seed pins that component while None keeps it inside the strategy’s reproducible stream.

derive_seed(seed: int | None) → int[source]#

Integer seed for a component that needs one (e.g. scipy.stats.qmc).

property eventbus: EventBus#
max_eval_or(default: int) → int[source]#

The evaluation budget as an int, or default when it is unknown.

property name: str#

The module’s name.

Note

It should be unique, which is important for parameterized heuristics or analyzers!

property problem: Problem#
required_analyzers() → Tuple[str, ...][source]#

Analyzer names this instance needs; defaults to requires_analyzers.

Override when the need depends on constructor arguments.

requires_analyzers: Tuple[str, ...] = ()#

Names of the analyzers this module reads (strategy.analyzer(name)) or whose events it subscribes to, e.g. ("Splitter",). StrategyBase.initialize() installs a default analyzer that is only needed on demand (the Splitter) exactly when some module declares it here; see required_analyzers().

property results: Any#
rng: Generator#

Per-module random generator, keyed by the master seed and this module’s name (see StrategyBase.spawn_rng()): adding, removing or reordering other modules does not change it. Modules must draw randomness from here, never from the global np.random state.

spawn_thread(target: Callable[[], None], name: str | None = None) → Thread[source]#

Run target on a daemon thread owned by this module.

The event bus delivers handlers serially, so anything that blocks — a pipe pump bridging a subprocess solver, say — must not run inside a handler. Threads registered here are joined by __stop__().

property strategy: StrategyBase#
class panobbgo.core.PipeBridgeHeuristic(strategy: StrategyBase, name: str | None = None, cap: int | None = None)[source]#

Bases: Heuristic

A sequential solver in a subprocess, pulled from the caller’s thread.

SciPy’s local optimizers (fmin_l_bfgs_b, minimize(method="COBYQA")) are synchronous: they call f(x) and block for the return value, and they cannot be suspended mid-step to yield an evaluation request. So the solver runs in its own subprocess and each f(x) is a round trip over a pipe. The protocol is strictly one outstanding evaluation:

worker: f(x) -> pipe.send(x), blocks on recv
parent: produce()  -> recv(x), emit -> the strategy evaluates it
parent: on_new_results -> stores the penalty value
parent: produce()  -> sends the value, recv's the next x

Every pipe operation happens on the thread that calls produce(), i.e. the strategy’s main loop. Until 2026-09 a daemon “pump” thread did the recv/emit half and the event-bus thread did the send half. That had three consequences, all removed here:

  1. the arm’s output queue was empty whenever the scheduler looked, so any competitor with a stocked queue starved it completely — under StrategyRoundRobin such an arm contributed 0 points beside Random;

  2. Heuristic.active and StrategyBase._can_still_produce() answered “yes” from the pump thread’s liveness, which never ended, so they were constants;

  3. emissions were timing-dependent, which excluded these heuristics from the reproducible sync_evaluation mode.

Now a bridge arm’s contribution is a pure function of the seed: the point it hands out depends only on the values it was given and its worker’s seed. See planning/DESIGN_pump_and_stall_2026-09-11.md §1.

Subclasses provide the subprocess and the pipes (p1 = parent end of the request pipe, out1 = parent end of the status pipe), and may intercept control messages by overriding _bridge_control().

Restarts follow the same rule. An on_restart handler runs on the event-bus thread, so it only records the request (_request_restart()); the next produce() replaces the worker (_bridge_respawn()) on the main loop’s thread. Respawning from the bus thread used to rebind p1 under a produce that was mid-recv. A worker that finished (converged, hit max_starts) is only _bridge_done, not stopped: a later restart revives it.

Only the value of the point we are currently waiting on is handed to the worker: on_new_results() matches the result’s x against it. A point emitted by a replaced worker (or an aborted descent) may still be in flight, and its value must not answer the new worker’s first f(x).

Parameters:

@type strategy: StrategyBase

property active: bool#

A finished worker drops out of the rotation until a restart revives it.

bridge_timeout: float = 60.0#

Deadlock backstop for produce(), in seconds. Not a scheduling parameter: a live worker is waited for however long it needs, and this can only expire when the worker is wedged — an error, logged as one. It therefore never influences which points a run evaluates.

property can_produce: bool#

True iff produce() would hand out a point right now.

The same question as has_points for a reactive heuristic, and the correct one for an on_demand one, whose queue is empty by construction between round trips. This is the predicate schedulers gate on and the one StrategyBase._alive() sums over.

on_demand: bool = True#

True iff this heuristic produces points on demand, on the caller’s thread, rather than reactively topping its queue up from event handlers. The solver bridges (LBFGSB, COBYQA) set it: a sequential SciPy optimizer cannot queue a point ahead, because its next iterate is a function of f at the current one. A scheduler must call produce() — never get_points() — or such an arm is starved by any competitor that keeps a stocked queue (planning/DESIGN_pump_and_stall_2026-09-11.md §1).

on_failed_evaluations(points: List[Point]) → None[source]#

Answer our outstanding point with inf when its evaluation failed.

Without an answer the worker waits for a value that never comes: can_produce stays False and the arm is dead for the rest of the run, silently. inf is what pipe_objective() makes of any non-finite value. Same thread and locking rules as on_new_results().

on_new_results(results: List[Result]) → None[source]#

Store the penalty value of our point; never touch the pipe here.

This runs on the event-bus dispatcher thread, which EventBus delivers serially — so it must return promptly and must not do I/O. produce() sends the value on, from the main thread.

out1: Any = None#
p1: Any = None#

Parent end of the request pipe (x in, f(x) out) and of the worker’s status pipe. Created by the subclass when it spawns.

produce(limit: int | None = None, timeout: float | None = None) → List[Point][source]#

The scheduler’s point-acquisition call.

For a reactive heuristic this is exactly get_points() — the queue is whatever its event handlers put there. An on_demand heuristic overrides it and produces the next point synchronously, on the calling thread.

timeout is a deadlock backstop for the on-demand case, never a scheduling parameter: a healthy producer answers immediately, so the value cannot influence which points a run evaluates — only whether the run reports a wedged worker.

class panobbgo.core.Results(strategy: StrategyBase)[source]#

Bases: object

A very simple database of results with a notification for new results. The new results are fed directly by the StrategyBase, outside of the EventBus.

Note

Later on, maybe this will be a cool actual database which allows to persistently store past evaluations for a given problem. This would allow resuming and further a-posteriory analysis. In the meantime, this is a pandas DataFrame.

add_results(new_results: List[Result], save_to_storage: bool = True) → None[source]#

Add one single or a list of new @Result objects. Then, publish a new_result event.

backend: Any#
close() → None[source]#

Close the storage backend if it exists.

eventbus: EventBus#
get_history(n: int | None = None) → Dict[str, Any][source]#

Retrieve the last n results as numpy arrays.

Parameters:

n (int, optional) – Number of recent results to retrieve. If None, returns all.

Returns:

Dictionary with keys ‘x’, ‘fx’, ‘cv’, ‘cv_vec’, ‘who’, ‘error’.

Values are numpy arrays (or list/array of objects for ‘who’).

Return type:

dict

info() → None[source]#
load_from_storage() → int[source]#

Load results from storage backend and populate the database.

problem: Problem#
property results: DataFrame | None#
strategy: StrategyBase#
exception panobbgo.core.StopHeuristic(msg: str = 'stopped')[source]#

Bases: Exception

Indicates the heuristic has finished and should be ignored/removed.

Args:

  • msg: a custom message, will be visible in the log. (default: “stopped”)

class panobbgo.core.StrategyBase(problem, parse_args=False, testing_mode=False, **kwargs)[source]#

Bases: object

This abstract BaseStrategy is the parent class of all Strategies.

Use it this way:

  1. Subclass it, write your optional initializer, afterwards call the initializer of this class (it will start its the main loop).

  2. Overwrite the execute(), which returns a list of new search points (by requesting them from the heuristics via the get_points() method) and might also emit Events.

This execute method will be called repeatedly as long as there are less than the given maximum number of search points evaluated.

@type problem: panobbgo.lib.Problem @param problem: @param parse_args: @param testing_mode: @param kwargs: Additional configuration parameters (e.g. max_eval, max_evaluations)

PROBLEM_KEY = 'problem'#
add(Heur, **kwargs)[source]#
add_analyzer(a)[source]#

Add an analyzer to the strategy.

Parameters:

a (Analyzer) – The analyzer instance to add

add_heuristic(h)[source]#

Add a heuristic to the strategy.

Parameters:

h (Heuristic) – The heuristic instance to add

add_pass_observer(fn: Callable[[StrategyBase], None]) → None[source]#

Call fn(strategy) after every pass of the main loop, and once when it ends.

For instruments that record the run without changing it (panobbgo.features.FeatureLogger): fn must only read — the archive, the heuristics’ state — and must not draw from any shared random stream. Under sync_evaluation it runs after the pass’s handlers have all returned, so what it reads is a deterministic function of the seed.

analyzer(who)[source]#
property analyzers#
property avg_time_per_task: float#

average walltime per finished task, NaN before the first one.

O(1): a running count and sum, since the main loop reads it every pass.

Type:

return float

property best#
budget_progress() → float | None[source]#

len(self.results) / max_eval in [0, 1], None if the budget is unknown (Module.budget_progress()).

cap_request(n: int) → int[source]#

n limited by request_cap (unchanged without a cap).

check_dependencies()[source]#

This method is called in self.start() (and only there) for checking all the dependencies of all modules.

property evaluators#

Compatibility property for legacy code that references evaluators. Returns a mock object with attributes needed by strategies.

execute()[source]#

Overwrite this method when you extend this base strategy.

property failure_model: Any#

The strategy’s FailureModel, or None without one.

Heuristics with failure-aware handling query it (p_fail / in_poison); the first installed instance counts.

heuristic(who)[source]#

Look up a heuristic by its who tag.

Some heuristics (e.g. CMAES, DifferentialEvolution) embed extra context in the who field (e.g. "CMAES:g3:i0"). We first try the full string, then fall back to the prefix before the first :.

property heuristics#
info()[source]#
init_module(module)[source]#

StrategyBase calls this method.

Parameters:

module (Module)

initialize()[source]#

Initialize the strategy components (heuristics, analyzers) without running the optimization loop. Useful for manual control or custom runners (e.g. benchmarks).

max_eval_or(default: int) → int[source]#

The evaluation budget as an int, or default when it is unknown (Module.max_eval_or()).

n_admit_trimmed#

Candidates the pull-when-free safety net (_admit_free()) had to hand back; stays 0 unless a strategy ignores its cap.

n_timed_out#

Evaluations that hit evaluation.timeout and were booked as a NaN result (_timed_out_result()).

property name#
on_converged(reason, stats)[source]#

Called when the Convergence analyzer detects convergence.

preload_results(results: List[Result]) → None[source]#

Book results before the first pass, as a resume from storage books its results.

For a run that continues from points evaluated elsewhere — the shared probe of a counterfactual branch (panobbgo.selector_data), a design evaluated before the optimizer was chosen. Call it before start(). initialize() adds them right after the storage backend’s results: they are in the store, and the new_results event for them is published, before the start event, so every module sees them before it emits its first point (an arm with an archive warm start, warm_start="archive", fits its start to them). Like restored results they count as dispatched: a run with max_eval = B and k preloaded results evaluates B - k new points. Nothing is evaluated here, and a run without a preload is unchanged.

With a storage backend the preload is saved like any booked result, deliberately: it is part of the run’s archive, and a resumed run must see it (and must not re-evaluate its budget share). So a resumed run gets it from storage — preloading it again there would book it twice, and initialize() refuses that (ValueError). The results are booked as given (the same objects); a caller that reuses them across runs passes copies.

Raises RuntimeError after initialize() (the preload would never be booked) and TypeError for anything but Result.

record_walltime(seconds: float) → None[source]#

Book the walltime of one finished task (for avg_time_per_task).

request_cap: int | None = None#

How many points execute() may hand back in the current pass, or None for no limit. Set by the main loop before each execute call where the evaluation mode knows it — the free workers, within the budget, under the pull-when-free policies (the virtual clock’s "async", the real loop’s evaluation.async_policy = "pull") — and honoured by the strategies (cap_request(), collect_pulls()), so a strategy only does its bookkeeping (pull counts, discounts, block lengths) for points that are dispatched.

request_stop()[source]#

Ask the main loop to end after the current pass.

Thread-safe (a single flag write): a harness enforcing a wall-clock timeout calls it from another thread, then joins the runner thread. In-flight evaluations of an asynchronous run are abandoned.

requires_analyzers: Tuple[str, ...] = ()#

Analyzer names the strategy itself reads (see Module.requires_analyzers).

rng: Generator#

Strategy-level generator (Thompson sampling, phase draws, …): its own keyed stream of seed, independent of the module streams spawn_rng() hands out, so neither shifts the other.

seed: int#
spawn_rng(key: str = '') → Generator[source]#

Return the next generator for key derived from the master seed.

The stream of the n-th call with a given key is SeedSequence(seed, spawn_key=(crc32(key), n)) — a function of seed, key and n only. Module passes its name, so a module’s randomness does not change when an unrelated module is added, removed or reordered, and two instances of one class (same name) still get distinct streams. It never draws from rng, the strategy-level stream.

start()[source]#
property time_cpu#

effective cpu time in seconds

property time_start_str#
property time_wall#

wall time in seconds

validate_setup()[source]#

Validate that the framework is properly set up before starting optimization.

This method checks for common configuration errors and missing components that would cause the optimization to fail or behave unexpectedly.

Raises:

ValueError – If the setup is invalid with descriptive error messages.

panobbgo.core.budget_progress_of(max_eval: Any, n_results: Callable[[], int]) → float | None[source]#

n_results() / max_eval clipped to [0, 1]; None when the budget is unknown.

n_results is a callable so a strategy stand-in without results degrades to None instead of raising.

panobbgo.core.keyed_rng(seed: int, spawn_key: Tuple[int, ...]) → Generator[source]#

A generator derived from the master seed and a stable spawn_key.

SeedSequence(seed, spawn_key=...) streams are independent for distinct keys and depend on nothing else — not on how many other streams were drawn before, nor in which order.

panobbgo.core.known_budget(max_eval: Any) → float | None[source]#

max_eval as a positive finite float, or None when the budget is unknown.

Unknown means missing, non-numeric, non-finite, zero or negative. The one parser behind Module.budget_progress() / Module.max_eval_or() and their StrategyBase twins.

panobbgo.core.max_eval_or_default(max_eval: Any, default: int) → int[source]#

int(max_eval) when the budget is known (see known_budget()), else default.

panobbgo.core.pipe_objective(pipe: Any) → Callable[[ndarray], float][source]#

Worker side of a PipeBridgeHeuristic: f(x) as a pipe round trip.

Sends x (as a float array), blocks for the value and maps None or a non-finite value to inf. A closed pipe raises SystemExit so the worker shuts down cleanly when the parent terminates it.

panobbgo.core.rng_stream_key(name: str, occurrence: int) → Tuple[int, int][source]#

The SeedSequence spawn_key of the occurrence-th module called name.

panobbgo.core.safe_send(output: Any, payload: Any) → None[source]#

Worker side: send payload over the status pipe, ignoring a parent that already went away.

panobbgo.core.terminate_process(proc: Any, timeout: float = 1.0) → None[source]#

Terminate a worker process if it is alive; kill it if it ignores that.

Local Evaluation Pool#

Backend of evaluation_method = "threaded" and "processes".

Local evaluation pool#

The backend of evaluation_method = "threaded" (LocalPool) and "processes" (ProcessPool): evaluations are submitted by task id and harvested without blocking by LocalPool.poll(), which reports every task exactly once, as a result or as a failure.

What it guarantees beyond a bare executor:

  • A timed-out task is reported with Outcome.timed_out; the strategy books it as a NaN result (Result.timed_out), not a failure. evaluation.timeout is a limit on one call.

  • The timeout counts running time only. The clock of a task starts when a worker picks it up (a thread records it; a worker process reports it over its pipe), so time spent queued behind other evaluations never times a task out.

  • Processes: only the timed-out call dies. ProcessPool runs its own worker processes, one task at a time each, and kills exactly the worker whose call ran past the limit; a fresh worker replaces it. Every other in-flight evaluation keeps running undisturbed.

  • Threads: a timed-out evaluation is abandoned — a thread cannot be killed, so the call runs to completion in the background and its result is discarded. So that it cannot hold a worker slot forever, the executor is retired (shutdown(wait=False)) and the tasks that had not started yet move to a fresh ThreadPoolExecutor. ThreadPoolExecutor threads are not daemon threads: an abandoned evaluation that never returns keeps the interpreter from exiting. Abandoned threads are counted and warned about. Use "processes" (or dask) for objectives that can hang.

  • Processes: a crashing evaluation does not end the run. A worker that dies (os._exit, a segfault, the OOM killer, a signal) while evaluating fails exactly its own task — attribution is exact, because a worker runs one task at a time. A task whose worker died before the call started (still loading the problem) is re-queued, not failed.

  • Processes: workers that cannot load the problem are an error. If MAX_IDLE_BREAKS workers in a row die before any evaluation started (the problem does not unpickle in a fresh interpreter — a class defined in __main__ or a notebook, a __setstate__ that raises), respawning cannot help: WorkerInitError is raised.

  • Closing is bounded and leaves nothing running (close()): queued tasks are cancelled, running ones get until the deadline, then worker processes are killed.

Processes mode evaluates copies of the problem: each worker unpickles its own, so state the problem object accumulates while evaluating (counters, traces, caches, loggers) lives in the workers and is not seen by the caller’s object.

class panobbgo.local_pool.LocalPool(problem: Any, n_workers: int, processes: bool = False, logger: Any = None)[source]#

Threads evaluating problem (see the module docstring).

LocalPool(..., processes=True) returns a ProcessPool.

Not thread-safe: one thread (the strategy’s main loop) submits, polls and closes.

property abandoned: int#

Timed-out evaluation threads that are still running.

ages(now: float | None = None) → Tuple[int, float | None, float | None][source]#

(outstanding, oldest running age, oldest queued age) in seconds (None: none such).

close(deadline: float) → int[source]#

Cancel queued tasks, give running ones until deadline, then stop the workers.

Returns the number of evaluations still running at the deadline (abandoned: a thread cannot be killed).

events#

the caller’s liveness check reads it.

Type:

Starts and finishes seen

poll(timeout: float | None = None) → List[Outcome][source]#

Harvest finished, failed and timed-out tasks without blocking.

timeout is the per-evaluation limit in seconds of running time (None: no limit).

running() → int[source]#

Tasks that a worker has picked up and that have not been harvested.

submit(task_id: str, point: Any) → None[source]#

Queue one evaluation.

wait(deadline: float | None = None, poll_interval: float = 0.001) → None[source]#

Block until a task can be harvested (or deadline).

waiting() → bool[source]#

True while an outstanding task is legitimately being waited for.

A task is running (a worker picked it up and it has not been harvested), or it is queued on a pool whose workers can still pick it up. How long a task runs is limited only by evaluation.timeout; the caller’s deadlock backstop reads this so that it never cuts a running evaluation.

class panobbgo.local_pool.Outcome(task_id: str, ok: bool, result: Any = None, error: str = '', started: float | None = None, finished: float = <factory>, point: Any = None, timed_out: bool = False)[source]#

What became of one task: ok with its result, or failed with an error message.

point is the evaluated point, so a failure can be reported to the module that asked for it (the failed_evaluations event). timed_out marks a failure by evaluation.timeout: the caller books it as a NaN result rather than a failure.

class panobbgo.local_pool.ProcessPool(problem: Any, n_workers: int, processes: bool = False, logger: Any = None)[source]#

Spawned worker processes evaluating problem, each one task at a time.

The pool owns its workers (no ProcessPoolExecutor), so a timed-out call is killed by killing exactly its worker, and a crash is attributed exactly to the task that worker was running. Workers are spawned on demand, up to n_workers, and replaced when they die.

close(deadline: float) → int[source]#

Cancel queued tasks, give running ones until deadline, then kill the workers.

Returns the number of evaluations still running at the deadline.

poll(timeout: float | None = None) → List[Outcome][source]#

Harvest finished, failed and timed-out tasks without blocking.

timeout is the per-evaluation limit in seconds of running time (None: no limit); a call past it is killed with its worker, and only that call.

submit(task_id: str, point: Any) → None[source]#

Queue one evaluation.

wait(deadline: float | None = None, poll_interval: float = 0.001) → None[source]#

Block until a worker reports something or dies (or deadline).

waiting() → bool[source]#

Outstanding tasks are always waited for: the pool spawns the workers it needs.

Dask Evaluation Backend#

Optional distributed-evaluation backend (evaluation_method = "dask"), imported lazily so the core carries no Dask dependency. Install the dask extra to use it.

Dask-based distributed evaluation backend#

Everything Dask-specific that used to live inline in panobbgo.core. dask is imported lazily — only when a strategy actually runs with evaluation_method = "dask" — so the rest of the framework carries no Dask code paths or import-time dependency.

The functions operate on a StrategyBase instance and use the strategy’s _client / _cluster / _problem_future attributes, which tests and external code set/inspect directly.

class panobbgo.dask_evaluation.DaskEvaluators(strategy: StrategyBase)[source]#

Evaluators view for the Dask backend (compatibility object for strategies that reference strategy.evaluators).

property outstanding: List[str]#
panobbgo.dask_evaluation.check_timeout_problem(problem: Any, logger: Any = None) → None[source]#

Check once, before any task is submitted, that problem works under evaluation.timeout.

With a timeout every call runs in a child interpreter (panobbgo.timeout_call), so the problem must serialize — failing here with a clear TypeError beats failing point by point on the workers. Also warns that a NoisyProblem with resample=True loses its per-point draw counter between calls (each call evaluates a fresh copy), so its noise becomes frozen per point.

panobbgo.dask_evaluation.close(strategy: StrategyBase) → None[source]#

Cancel any outstanding Dask futures and close client + cluster.

panobbgo.dask_evaluation.evaluate_point(problem: Any, point: Any, timeout: float | None = None) → Tuple[Any, float, Any, bool][source]#

The dask task: evaluate one point; returns (result, walltime in seconds, error, timed_out).

A raising objective is reported as (None, walltime, repr(exc), False) rather than raised, so its walltime is booked like the local pool books a failed task’s.

With timeout (evaluation.timeout) the limit is enforced here, on the worker, per call: the objective runs in a child process (panobbgo.timeout_call.call_with_timeout()) whose clock starts when the call starts — queue time on the cluster never counts — and which is killed on expiry, so a hung objective never holds its dask worker. The task then returns (None, walltime, None, True) and the client books a NaN placeholder. Without timeout the objective runs in the worker itself, as before (no subprocess overhead).

panobbgo.dask_evaluation.run_evaluation(strategy: StrategyBase, points: List[Any]) → List[Any][source]#

Run evaluation using Dask distributed computing.

Submits each point as a Dask future, updates the strategy’s task accounting, and returns the newly finished results.

evaluation.timeout is enforced on the worker (evaluate_point()); the client does not expire futures itself. A worker that dies loses its task to dask’s own recovery (it reruns elsewhere, or the future fails and the evaluation is booked as failed), and a task that cannot run because the cluster has no workers is reported by the strategy’s waiting WARNING — neither needs a client-side clock, which would charge queue time.

panobbgo.dask_evaluation.setup_cluster(strategy: StrategyBase, problem: Any) → None[source]#

Set up a Dask cluster based on configuration. Supports both local and remote clusters.

panobbgo.dask_evaluation.wait_any(strategy: StrategyBase, timeout: float) → None[source]#

Block until one outstanding future completes, or timeout seconds.

The pull-when-free loop’s wait while every worker is busy (_pull_pause()). Objects that are not dask futures (test doubles) get a 1 ms sleep instead.

Virtual-clock evaluation#

Deterministic simulation of q parallel workers (evaluation_method = "virtual"); the benchmark harnesses score AOCC over virtual time with panobbgo.ioh_runner.aocc_virtual_time().

Virtual-clock parallel evaluation#

evaluation.method = "virtual": a deterministic discrete-event simulation of q parallel workers (evaluation.virtual_workers), so that asynchronous parallel behaviour can be benchmarked reproducibly on any machine, without real waiting.

The objective is evaluated synchronously, in-process, at the moment a simulated worker picks a candidate up. Only the durations, and therefore the order in which results reach the strategy and their timestamps, are simulated. The same seed gives the same evaluation sequence on every host, whatever its speed. The main loop runs synchronously (every event handler drains before the next decision): optimizer time is taken to be negligible next to an expensive evaluation.

Model#

  • Workers. q simulated workers.

  • Durations. Each call gets a duration from a DurationModel (evaluation.virtual_duration): "constant", "lognormal" (log-space standard deviation evaluation.virtual_duration_sigma, drawn from a keyed RNG stream, see RNG_STREAM_KEY), a number (a constant duration) or x-dependent (a CallableDuration, which needs an explicit nominal mean). The built-in models have mean 1 unless evaluation.virtual_duration_mean says otherwise; the virtual-time metric measures time in units of the model’s mean.

  • Common random numbers. The duration stream is keyed on evaluation.virtual_duration_seed when it is set (the harnesses set it per cell — base seed, problem, dimension, instance, rep — through VirtualSpec.duration_seed, never per strategy), else on the strategy’s own seed. One duration is drawn per dispatch, in dispatch order, by VirtualClock and run_ask_tell() alike, so on one cell the i-th dispatched call takes the same time for every strategy and baseline: a paired comparison is paired in its durations too. (An x-dependent model still sees each strategy’s own points.)

  • Events. A call dispatched at virtual time t with duration d completes at t + d. Completions form a queue ordered by (time, sequence), the sequence number being the dispatch order, so ties are broken deterministically.

  • Policy (evaluation.virtual_policy):

    • "async" (default) — the asynchronous expensive-evaluation policy. There is a decision point at every completion instant: every call completing at that instant is delivered (one new_results batch), the handlers drain, and the strategy is asked for candidates for the free workers only. The main loop sets the strategy’s request cap (StrategyBase.request_cap) to the free workers within the budget, and jobs_per_client = 1, so a bandit pulls, and a block counts, exactly what is dispatched. Nothing is queued beyond the free workers; VirtualClock.admit() is a safety net that hands any surplus back to its heuristic’s queue. If the strategy fills fewer workers than are free, it is asked again at the same instant; if it has nothing, the clock moves to the next completion. With q = 1 the run is strictly one call at a time, each candidate chosen after the previous result arrived. The real asynchronous loop (threaded / processes / dask) runs the same pull-when-free policy by default (evaluation.async_policy = "pull"); it differs only in that results arrive in wall-clock completion order and the handlers do not drain before the next decision. Under a capped bandit a generational arm’s queued generation drains at the bandit’s share of the free workers, so its candidates can get stale while other arms run (a TODO.md follow-up).

    • "sync" — a regression mode that keeps the synchronous batch policy: a strategy batch (sized by the synchronous rule, max_eval / 50 per worker) is queued first in, first out and the results are delivered when the queue has drained. With q = 1, a constant duration and dask.local.n_workers = 1 (which sizes the synchronous batches) it reproduces the evaluation.sync run exactly (tests/test_virtual_clock.py).

  • Timeouts. With evaluation.timeout set, a call whose simulated duration exceeds it is not evaluated: it completes at dispatch + timeout as the usual NaN placeholder (timed_out). The timeout is in virtual time units here. A timeout the problem signals (lib.EvaluationTimedOut, a family’s failure region, known in advance through failure_at) is treated the same way: not evaluated, completing after evaluation.timeout (or its drawn duration when no timeout is set). Crashes are evaluated (and fail) at dispatch. Either failure is one spent, non-improving evaluation for an observer, counted once at completion.

  • Recording. Every result carries t_dispatch and t_complete, its virtual dispatch and completion times (in memory only: the sqlite storage backend does not store them).

Observers#

An evaluation counter such as IOHTracker can follow the clock (strategy._virtual_observer, set by VirtualSpec.apply()): the clock calls begin_call(seq) / end_call() around each objective call and complete_call(seq, t, ok) when the call completes, in completion order. The tracker then records its trace in completion order, with a failed or timed-out call as a spent, non-improving evaluation — the input of aocc_virtual_time().

class panobbgo.virtual_clock.CallableDuration(fn: Callable[[ndarray], float], mean: float)[source]#

x-dependent durations: fn(x) for the point’s coordinates x.

mean (required) is the nominal mean duration the virtual-time metric uses as its unit; it is not estimated from the calls, so two strategies that visit different regions are scored on the same time axis. A run whose observed mean is more than MEAN_TOLERANCE off warns. fn must be deterministic in x (it does not see the RNG), and picklable (a module-level function, not a lambda) if the run goes to a worker process (harness jobs > 1).

describe() → Dict[str, Any][source]#

A JSON-able description (recorded with harness results).

class panobbgo.virtual_clock.ConstantDuration(value: float = 1.0)[source]#

Every call takes value time units (default 1, must be > 0).

describe() → Dict[str, Any][source]#

A JSON-able description (recorded with harness results).

class panobbgo.virtual_clock.DurationModel[source]#

Simulated duration of one evaluation call, in virtual time units.

Subclasses implement __call__(). mean is the model’s nominal mean duration; the anytime metric over virtual time measures time in units of it.

describe() → Dict[str, Any][source]#

A JSON-able description (recorded with harness results).

mean: float = 1.0#

Nominal mean duration (the unit of the virtual-time metric).

class panobbgo.virtual_clock.LogNormalDuration(sigma: float = 0.5, mean: float = 1.0)[source]#

Log-normal durations with the given mean (default 1) and log-space sigma.

log d ~ N(mu, sigma^2) with mu = log(mean) - sigma^2 / 2, so E[d] = mean. sigma = 0.5 gives a coefficient of variation of about 0.53; sigma = 1 about 1.3 (a heavy right tail).

describe() → Dict[str, Any][source]#

A JSON-able description (recorded with harness results).

class panobbgo.virtual_clock.VirtualClock(strategy: StrategyBase)[source]#

The simulated worker pool of one strategy (strategy._virtual_clock).

Settings are read from the strategy’s config by configure(), which the strategy calls at set-up and again when the run starts, so a harness may change them in between.

admit(points: List[Any]) → List[Any][source]#

Async policy safety net: keep the first candidates the free workers can take, return the rest.

The strategy was asked for at most request_cap() points, so this normally trims nothing; when it does, the strategy’s bookkeeping already counted the surplus (logged at DEBUG).

property busy: int#

Workers running a call (completed-but-undelivered calls have freed theirs).

configure() → None[source]#

Read the evaluation.virtual_* settings from the config.

finish() → None[source]#

End-of-run check: warn if an x-dependent model’s observed mean is far from its nominal mean.

property free: int#

Idle workers.

property jobs_per_client: int | None#

the synchronous rule.

Type:

1 under the async policy; None

n_trimmed#

a strategy that ignores its request cap).

Type:

Candidates admit() had to hand back (should stay 0

now: float#

Current virtual time.

observed_mean() → float | None[source]#

Mean of the durations drawn so far (None before the first call).

request_cap() → int | None[source]#

Async policy: how many candidates the strategy may produce now (free workers, within the budget).

step(points: List[Any], retry: bool = False) → None[source]#

One main-loop pass: dispatch points, run the clock to the next decision point, deliver.

retry: the strategy rejected candidates in this pass without evaluating them (the failure filter, panobbgo.analyzers.failure_model); with a worker free it is asked again at this instant instead of the clock waiting for a completion, so a rejection costs no virtual time.

class panobbgo.virtual_clock.VirtualSpec(workers: int = 4, duration: Any = 'constant', sigma: float = 0.5, mean: float | None = None, policy: str = 'async', duration_seed: int | None = None)[source]#

Settings of a virtual-clock run, as a harness passes them.

apply() switches a constructed strategy to evaluation.method = "virtual" with these settings. A spec travels to worker processes with the harness’s jobs > 1: an x-dependent duration must then be picklable (a module-level function or a CallableDuration of one), not a lambda.

apply(strategy: StrategyBase, observer: Any = None) → None[source]#

Configure strategy (not yet started) for a virtual-clock run; observer: see the module docstring.

duration: Any = 'constant'#

"constant", "lognormal", a number, a DurationModel or a callable f(x).

duration_seed: int | None = None#

Seed of the duration stream (common random numbers). The harnesses set it per cell, the same for every strategy on the cell (with_cell(), a _derive_seed of the cell under DURATION_STREAM_IDENTITY); None: the strategy’s own seed.

mean: float | None = None#

Nominal mean duration; required for a callable duration, default 1 otherwise.

model() → DurationModel[source]#

The duration model these settings describe.

policy: str = 'async'#

"async" (default) or "sync" (see the module docstring).

sigma: float = 0.5#

Log-space standard deviation of the "lognormal" model.

to_dict() → Dict[str, Any][source]#

JSON-able description: {"workers": q, "policy": ..., **model.describe(), "durations": "crn"}.

durations: "crn" records that durations are common random numbers per cell (results from before 2026-09-26 lack it: their streams were keyed per strategy). The per-cell seed itself is not recorded.

with_cell(seed: int) → VirtualSpec[source]#

This spec with the duration stream of one cell (seed: derived per cell under DURATION_STREAM_IDENTITY).

workers: int = 4#

Number of simulated workers q.

panobbgo.virtual_clock.make_duration_model(spec: str | float | int | DurationModel | Callable[[ndarray], float] = 'constant', sigma: float = 0.5, mean: float | None = None) → DurationModel[source]#

Build a DurationModel from a config value.

spec is a DurationModel (returned as is), "constant" (duration mean, default 1), "lognormal" (mean mean, default 1, log-space sigma), a number or numeric string (a constant duration, e.g. from YAML), or a callable f(x) — which needs an explicit mean (a CallableDuration).

panobbgo.virtual_clock.validate_config(config: Any) → List[str][source]#

Error messages for the evaluation.virtual_* settings (empty if they are valid).

Per-call timeout in a child process#

How evaluation.timeout is enforced on a dask worker.

One evaluation under a hard time limit, in a child interpreter#

call_with_timeout() evaluates problem(point) in a fresh child Python process and kills that child — with everything it started — when the call runs longer than timeout seconds. It is how evaluation.timeout is enforced where the evaluation runs on a dask worker (panobbgo.dask_evaluation): the clock starts when the call starts in the child — not at submission, so queue time on the cluster never counts — and expiry kills exactly that call, so a hung objective never holds its dask worker.

Mechanics:

  • The child is started with subprocess (python -P -m panobbgo.timeout_call), not multiprocessing: dask worker processes are daemonic by default, and a daemonic process may not have multiprocessing children. Its import path is exactly the parent’s sys.path (-P: the child’s cwd is not prepended).

  • It runs in its own process group; the parent always ends the call with killpg — after a timeout, and also after a successful call, so no background grandchild of the objective outlives it.

  • Orphan protection. The child watches a dedicated pipe from the parent: when the parent dies (a dask worker killed by the nanny), the pipe hits EOF and the child kills its own process group. On Linux the kernel also sends it SIGTERM when its parent dies (PR_SET_PDEATHSIG), whose handler kills the whole group — not just the child, which would leave the objective’s subprocesses running (kill_group_with_parent()).

  • The result travels as a length-prefixed frame (8-byte big-endian length + pickle) over a private copy of the child’s stdout; the parent reads exactly that many bytes, so an objective that forks (keeping the pipe open) cannot make a finished call look timed out. Whatever the objective prints goes to stderr. The child ends with os._exit once the frame is written, so a non-daemon thread left by the objective cannot keep it alive.

State caveat. Each call evaluates a fresh copy of the problem (the worker’s copy, serialized once per worker and cached). State the problem object accumulates while evaluating does not carry over from one call to the next — counters, caches, a problem-held RNG (which would repeat its draws). In particular NoisyProblem with resample=True counts evaluations per point in the problem object, so under dask with evaluation.timeout every re-evaluation of a point draws the same noise (as with resample=False); panobbgo.dask_evaluation.check_timeout_problem() warns about it.

class panobbgo.timeout_call.TimedCall(result: Any = None, error: str | None = None, timed_out: bool = False, seconds: float = 0.0)[source]#

The outcome of call_with_timeout().

Exactly one of: result (the objective returned), error (it raised, or the child could not start/load it), timed_out. seconds is the running time of the call itself (child start-up excluded).

panobbgo.timeout_call.call_with_timeout(problem: Any, point: Any, timeout: float) → TimedCall[source]#

Evaluate problem(point) in a child process, killing it after timeout seconds of running time.