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
StrategyBasewhich holds everything together and subclasses instrategiesimplement the actual strategies.
- panobbgo.core.ASYNC_POLICIES: Tuple[str, ...] = ('pull', 'legacy')#
the asynchronous main loop’s policy (see
StrategyBase._free_workers()).- Type:
evaluation.async_policyvalues
- class panobbgo.core.Analyzer(strategy: StrategyBase, name: str | None = None)[source]#
Bases:
ModuleAbstract parent class for all types of analyzers.
- Parameters:
strategy (StrategyBase)
name (str)
@type strategy: StrategyBase
- class panobbgo.core.Event(**kwargs: Any)[source]#
Bases:
objectThis class holds the data for one single
EventBusevent.
- class panobbgo.core.EventBus(config: Any)[source]#
Bases:
objectPublish/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. Consequentlya 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
publishcalls — the property the seeded, reproducible runs rely on (seewait_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”.
- publish(key: str, event: Event | None = None, terminate: bool = False, **kwargs: Any) None[source]#
Publishes a new
Eventto all subscribers, who listen to the givenkey. 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 ownEventinstance.Args:
event: if set, this givenEvent’s payload is sent (and not a new one created).terminate: if True, the subscription ofkeyends after this event(use it for
on_startand similar one-shot lifecycle events).
**kwargs: any additional keyword arguments are stored inside the Eventif
eventisNone.
- register(target: Any) None[source]#
Registers a given
targetfor this EventBus instance: everyon_<key>method it has becomes a subscription tokey.- 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
keyisNone, 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. ReturnsTruewhen the bus is idle,Falseon 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:
ModuleThis 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:
They can be parameterized by passing in optional arguments in the constructor. This should be reflected in the
name!The
EventBusspawns a thread for eachon_*method and calls them when a correspondingEventoccurs.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.
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 benumpy.ndarrayof floats.Additionally, the can get hold of other heuristics or anayzers via the strategy instance.
The
EventBusinside 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:
strategy (StrategyBase)
name (str)
@type strategy: StrategyBase
- WARM_START_MODES: Tuple[str, ...] = ('archive', 'archive_diverse', 'archive_leaf')#
Selector names
archive_seed()understands.None(the default of everywarm_start=constructor argument) means “cold start”, i.e. do not callarchive_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
kgood 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 bywho:"archive"(default) — thekbest results;"archive_diverse"—kwell-separated good results;"archive_leaf"— the best point of each of thekbestSplitterleaves, i.e.kdifferent basins.
Source is the opt-in
Archiveanalyzer when the strategy has one; otherwise theSplitter’s root box, which holds every result inResultform, 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#
Trueiffproduce()would hand out a point right now.The same question as
has_pointsfor a reactive heuristic, and the correct one for anon_demandone, whose queue is empty by construction between round trips. This is the predicate schedulers gate on and the oneStrategyBase._alive()sums over.
- 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 anumpy.ndarrayoffloat64or preferrably a list of them.
Raises
TypeErrorfor 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
nadditional 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_nowaitsilently 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
capwith points fromdraw.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
limitpoints are removed or it is empty.
- property has_points: bool#
Trueiff 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
whotag 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#
Trueiff 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 offat the current one. A scheduler must callproduce()— neverget_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).
- 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. Anon_demandheuristic overrides it and produces the next point synchronously, on the calling thread.timeoutis 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
Splitterwhen this heuristic warm-starts.archive_seed()readsSplitterleaves for"archive_leaf"and falls back to theSplitterroot without anArchive; awarm_start_boxis aSplitterbox. Every heuristic with a warm start stores its mode inself.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. ReturnsTrueiff a seed was actually used. The default isFalse: 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:
HeuristicThis 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:
strategy (StrategyBase)
name (str)
@type strategy: StrategyBase
- class panobbgo.core.Module(strategy: StrategyBase, name: str | None = None)[source]#
Bases:
object“Abstract” parent class for various panobbgo modules, e.g.
HeuristicandAnalyzer.- Parameters:
strategy (StrategyBase)
name (str)
@type strategy: StrategyBase
- budget_progress() float | None[source]#
Fraction of the evaluation budget used,
len(strategy.results) / max_evalin[0, 1].Nonewhen the budget is unknown (nomax_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:
seedif given, else this module’s own.Heuristics that expose a
seedargument use this so an explicit seed pins that component whileNonekeeps 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).
- 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!
- 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 (theSplitter) exactly when some module declares it here; seerequired_analyzers().
- 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 globalnp.randomstate.
- spawn_thread(target: Callable[[], None], name: str | None = None) Thread[source]#
Run
targeton 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:
HeuristicA 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 callf(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 eachf(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 therecv/emithalf and the event-bus thread did thesendhalf. That had three consequences, all removed here:the arm’s output queue was empty whenever the scheduler looked, so any competitor with a stocked queue starved it completely — under
StrategyRoundRobinsuch an arm contributed 0 points besideRandom;Heuristic.activeandStrategyBase._can_still_produce()answered “yes” from the pump thread’s liveness, which never ended, so they were constants;emissions were timing-dependent, which excluded these heuristics from the reproducible
sync_evaluationmode.
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_restarthandler runs on the event-bus thread, so it only records the request (_request_restart()); the nextproduce()replaces the worker (_bridge_respawn()) on the main loop’s thread. Respawning from the bus thread used to rebindp1under aproducethat was mid-recv. A worker that finished (converged, hitmax_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’sxagainst 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 firstf(x).- Parameters:
strategy (StrategyBase)
name (str)
@type strategy: StrategyBase
- 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#
Trueiffproduce()would hand out a point right now.The same question as
has_pointsfor a reactive heuristic, and the correct one for anon_demandone, whose queue is empty by construction between round trips. This is the predicate schedulers gate on and the oneStrategyBase._alive()sums over.
- on_demand: bool = True#
Trueiff 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 offat the current one. A scheduler must callproduce()— neverget_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
infwhen its evaluation failed.Without an answer the worker waits for a value that never comes:
can_producestaysFalseand the arm is dead for the rest of the run, silently.infis whatpipe_objective()makes of any non-finite value. Same thread and locking rules ason_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
EventBusdelivers serially — so it must return promptly and must not do I/O.produce()sends the value on, from the main thread.
- p1: Any = None#
Parent end of the request pipe (
xin,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. Anon_demandheuristic overrides it and produces the next point synchronously, on the calling thread.timeoutis 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:
objectA very simple database of results with a notification for new results. The new results are fed directly by the
StrategyBase, outside of theEventBus.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_resultevent.
- backend: Any#
- get_history(n: int | None = None) Dict[str, Any][source]#
Retrieve the last n results as numpy arrays.
- strategy: StrategyBase#
- exception panobbgo.core.StopHeuristic(msg: str = 'stopped')[source]#
Bases:
ExceptionIndicates 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:
objectThis abstract BaseStrategy is the parent class of all Strategies.
Use it this way:
Subclass it, write your optional initializer, afterwards call the initializer of this class (it will start its the main loop).
Overwrite the
execute(), which returns a list of new search points (by requesting them from theheuristicsvia theget_points()method) and might also emitEvents.
This
executemethod 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_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):fnmust only read — the archive, the heuristics’ state — and must not draw from any shared random stream. Undersync_evaluationit runs after the pass’s handlers have all returned, so what it reads is a deterministic function of the seed.
- property analyzers#
- property avg_time_per_task: float#
average walltime per finished task,
NaNbefore 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_evalin[0, 1],Noneif the budget is unknown (Module.budget_progress()).
- cap_request(n: int) int[source]#
nlimited byrequest_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.
- property failure_model: Any#
The strategy’s
FailureModel, orNonewithout 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 thewhofield (e.g."CMAES:g3:i0"). We first try the full string, then fall back to the prefix before the first:.
- property heuristics#
- init_module(module)[source]#
StrategyBasecalls 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.timeoutand were booked as aNaNresult (_timed_out_result()).
- property name#
- preload_results(results: List[Result]) None[source]#
Book
resultsbefore 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 beforestart().initialize()adds them right after the storage backend’s results: they are in the store, and thenew_resultsevent for them is published, before thestartevent, 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 withmax_eval = Bandkpreloaded results evaluatesB - knew 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
RuntimeErrorafterinitialize()(the preload would never be booked) andTypeErrorfor anything butResult.
- 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, orNonefor no limit. Set by the main loop before eachexecutecall 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’sevaluation.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 streamsspawn_rng()hands out, so neither shifts the other.
- spawn_rng(key: str = '') Generator[source]#
Return the next generator for
keyderived from the master seed.The stream of the n-th call with a given
keyisSeedSequence(seed, spawn_key=(crc32(key), n))— a function ofseed,keyandnonly.Modulepasses 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 fromrng, the strategy-level stream.
- 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_evalclipped to[0, 1];Nonewhen the budget is unknown.n_results is a callable so a strategy stand-in without
resultsdegrades toNoneinstead of raising.
- panobbgo.core.keyed_rng(seed: int, spawn_key: Tuple[int, ...]) Generator[source]#
A generator derived from the master
seedand a stablespawn_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_evalas a positive finite float, orNonewhen 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 theirStrategyBasetwins.
- panobbgo.core.max_eval_or_default(max_eval: Any, default: int) int[source]#
int(max_eval)when the budget is known (seeknown_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 mapsNoneor a non-finite value toinf. A closed pipe raisesSystemExitso the worker shuts down cleanly when the parent terminates it.
- panobbgo.core.rng_stream_key(name: str, occurrence: int) Tuple[int, int][source]#
The
SeedSequencespawn_keyof theoccurrence-th module calledname.
- panobbgo.core.safe_send(output: Any, payload: Any) None[source]#
Worker side: send
payloadover 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 aNaNresult (Result.timed_out), not a failure.evaluation.timeoutis 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.
ProcessPoolruns 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 freshThreadPoolExecutor.ThreadPoolExecutorthreads 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_BREAKSworkers 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:WorkerInitErroris 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 aProcessPool.Not thread-safe: one thread (the strategy’s main loop) submits, polls and closes.
- 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.
timeoutis the per-evaluation limit in seconds of running time (None: no limit).
- wait(deadline: float | None = None, poll_interval: float = 0.001) None[source]#
Block until a task can be harvested (or
deadline).
- waiting() bool[source]#
Truewhile 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:
okwith itsresult, or failed with anerrormessage.pointis the evaluated point, so a failure can be reported to the module that asked for it (thefailed_evaluationsevent).timed_outmarks a failure byevaluation.timeout: the caller books it as aNaNresult 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 ton_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.
timeoutis 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.
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).
- panobbgo.dask_evaluation.check_timeout_problem(problem: Any, logger: Any = None) None[source]#
Check once, before any task is submitted, that
problemworks underevaluation.timeout.With a timeout every call runs in a child interpreter (
panobbgo.timeout_call), so the problem must serialize — failing here with a clearTypeErrorbeats failing point by point on the workers. Also warns that aNoisyProblemwithresample=Trueloses 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 aNaNplaceholder. Withouttimeoutthe 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.timeoutis 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
timeoutseconds.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.
qsimulated workers.Durations. Each call gets a duration from a
DurationModel(evaluation.virtual_duration):"constant","lognormal"(log-space standard deviationevaluation.virtual_duration_sigma, drawn from a keyed RNG stream, seeRNG_STREAM_KEY), a number (a constant duration) or x-dependent (aCallableDuration, which needs an explicit nominalmean). The built-in models have mean 1 unlessevaluation.virtual_duration_meansays 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_seedwhen it is set (the harnesses set it per cell — base seed, problem, dimension, instance, rep — throughVirtualSpec.duration_seed, never per strategy), else on the strategy’s own seed. One duration is drawn per dispatch, in dispatch order, byVirtualClockandrun_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
twith durationdcompletes att + 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 (onenew_resultsbatch), 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, andjobs_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. Withq = 1the 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 / 50per worker) is queued first in, first out and the results are delivered when the queue has drained. Withq = 1, a constant duration anddask.local.n_workers = 1(which sizes the synchronous batches) it reproduces theevaluation.syncrun exactly (tests/test_virtual_clock.py).
Timeouts. With
evaluation.timeoutset, a call whose simulated duration exceeds it is not evaluated: it completes atdispatch + timeoutas the usualNaNplaceholder (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 throughfailure_at) is treated the same way: not evaluated, completing afterevaluation.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_dispatchandt_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 coordinatesx.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 thanMEAN_TOLERANCEoff warns.fnmust be deterministic inx(it does not see the RNG), and picklable (a module-level function, not a lambda) if the run goes to a worker process (harnessjobs > 1).
- class panobbgo.virtual_clock.ConstantDuration(value: float = 1.0)[source]#
Every call takes
valuetime units (default 1, must be > 0).
- class panobbgo.virtual_clock.DurationModel[source]#
Simulated duration of one evaluation call, in virtual time units.
Subclasses implement
__call__().meanis the model’s nominal mean duration; the anytime metric over virtual time measures time in units of it.
- 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-spacesigma.log d ~ N(mu, sigma^2)withmu = log(mean) - sigma^2 / 2, soE[d] = mean.sigma = 0.5gives a coefficient of variation of about 0.53;sigma = 1about 1.3 (a heavy right tail).
- 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).
- finish() None[source]#
End-of-run check: warn if an x-dependent model’s observed mean is far from its nominal mean.
- n_trimmed#
a strategy that ignores its request cap).
- Type:
Candidates
admit()had to hand back (should stay 0
- observed_mean() float | None[source]#
Mean of the durations drawn so far (
Nonebefore 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 toevaluation.method = "virtual"with these settings. A spec travels to worker processes with the harness’sjobs > 1: an x-dependentdurationmust then be picklable (a module-level function or aCallableDurationof 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, aDurationModelor a callablef(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_seedof the cell underDURATION_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.
- 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 underDURATION_STREAM_IDENTITY).
- 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
DurationModelfrom a config value.specis aDurationModel(returned as is),"constant"(durationmean, default 1),"lognormal"(meanmean, default 1, log-spacesigma), a number or numeric string (a constant duration, e.g. from YAML), or a callablef(x)— which needs an explicitmean(aCallableDuration).
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), notmultiprocessing: dask worker processes are daemonic by default, and a daemonic process may not havemultiprocessingchildren. Its import path is exactly the parent’ssys.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
SIGTERMwhen 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._exitonce 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.secondsis the running time of the call itself (child start-up excluded).