Stoppers
stoppers ¶
Stoppers for evolution termination conditions.
This subpackage provides concrete stopper implementations that terminate evolution based on various conditions like timeout, iterations, score, or external signals.
| ATTRIBUTE | DESCRIPTION |
|---|---|
CompositeStopper | Combine multiple stoppers with AND/OR logic. TYPE: |
FileStopper | Stop evolution when a specified file exists. TYPE: |
MaxEvaluationsStopper | Stop evolution after maximum evaluations. TYPE: |
ScoreThresholdStopper | Stop evolution when best score reaches threshold. TYPE: |
SignalStopper | Stop evolution on Unix signals (SIGINT, SIGTERM). TYPE: |
TimeoutStopper | Stop evolution after a specified timeout. TYPE: |
Examples:
Using a timeout stopper:
from gepa_adk.adapters.stoppers import TimeoutStopper
stopper = TimeoutStopper(300.0) # Stop after 5 minutes
Using a score threshold stopper:
from gepa_adk.adapters.stoppers import ScoreThresholdStopper
stopper = ScoreThresholdStopper(0.95) # Stop at 95% accuracy
Using a signal stopper:
from gepa_adk.adapters.stoppers import SignalStopper
async with SignalStopper() as stopper:
# Ctrl+C will gracefully stop evolution
config = EvolutionConfig(stop_callbacks=[stopper])
result = await engine.run(config)
Combining multiple stoppers:
from gepa_adk.adapters.stoppers import (
CompositeStopper,
ScoreThresholdStopper,
TimeoutStopper,
)
# Stop after 5 minutes OR when score >= 0.95
composite = CompositeStopper(
[TimeoutStopper(300), ScoreThresholdStopper(0.95)],
mode="any",
)
See Also
gepa_adk.ports.stopper: StopperProtocol interface.gepa_adk.domain.stopper: StopperState domain model.
Note
This subpackage contains adapters layer implementations. All stoppers implement the StopperProtocol from the ports layer.
CompositeStopper ¶
Combine multiple stoppers with AND/OR logic.
A meta-stopper that composes multiple stoppers into a single stopping condition with configurable logic. Use mode='any' for OR semantics (stop if any stopper fires) or mode='all' for AND semantics (stop only if all stoppers fire).
| ATTRIBUTE | DESCRIPTION |
|---|---|
stoppers | The sequence of stoppers to combine. TYPE: |
mode | Combination mode - 'any' for OR, 'all' for AND. TYPE: |
Examples:
Stop after 5 minutes OR when score reaches 95%:
from gepa_adk.adapters.stoppers import (
CompositeStopper,
ScoreThresholdStopper,
TimeoutStopper,
)
from gepa_adk.domain.stopper import StopperState
composite = CompositeStopper(
[TimeoutStopper(300), ScoreThresholdStopper(0.95)],
mode="any",
)
state = StopperState(
iteration=10,
best_score=0.97, # Exceeds threshold
stagnation_counter=2,
total_evaluations=50,
candidates_count=3,
elapsed_seconds=120.0, # Below timeout
)
composite(state) # Returns True (score threshold met)
Stop only when minimum time AND score threshold are both met:
Note
A composite stopper can contain other composite stoppers for arbitrarily complex stopping conditions like "(A OR B) AND (C OR D)".
Source code in src/gepa_adk/adapters/stoppers/composite.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
__init__ ¶
__init__(
stoppers: Sequence[StopperProtocol],
mode: Literal["any", "all"] = "any",
) -> None
Initialize composite stopper with child stoppers and mode.
| PARAMETER | DESCRIPTION |
|---|---|
stoppers | Sequence of stoppers to combine. Must contain at least one stopper. Each stopper must implement StopperProtocol. TYPE: |
mode | Combination logic - 'any' (OR) or 'all' (AND). Defaults to 'any'. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If stoppers sequence is empty. |
ValueError | If mode is not 'any' or 'all'. |
Examples:
# OR logic - stop if either condition met
composite = CompositeStopper(
[TimeoutStopper(300), ScoreThresholdStopper(0.95)],
mode="any",
)
# AND logic - stop only if both conditions met
composite = CompositeStopper(
[TimeoutStopper(60), ScoreThresholdStopper(0.8)],
mode="all",
)
Note
Consider using 'any' mode for fail-safe conditions (timeout OR resource limit) and 'all' mode for minimum requirements.
Source code in src/gepa_adk/adapters/stoppers/composite.py
__call__ ¶
__call__(state: StopperState) -> bool
Check if evolution should stop based on combined stopper logic.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state snapshot passed to all child stoppers. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | For mode='any': True if any child stopper returns True. |
bool | For mode='all': True only if all child stoppers return True. |
Examples:
composite = CompositeStopper(
[TimeoutStopper(60), ScoreThresholdStopper(0.9)],
mode="any",
)
# Below both thresholds
state1 = StopperState(
iteration=5,
best_score=0.5,
stagnation_counter=0,
total_evaluations=25,
candidates_count=1,
elapsed_seconds=30.0,
)
composite(state1) # False
# Score threshold met
state2 = StopperState(
iteration=10,
best_score=0.95,
stagnation_counter=1,
total_evaluations=50,
candidates_count=2,
elapsed_seconds=45.0,
)
composite(state2) # True (any mode - score threshold met)
Note
Often called after each iteration. For 'any' mode, evaluation short-circuits on first True. For 'all' mode, short-circuits on first False.
Source code in src/gepa_adk/adapters/stoppers/composite.py
__repr__ ¶
Return string representation of the composite stopper.
| RETURNS | DESCRIPTION |
|---|---|
str | String showing the stoppers list and mode. |
Examples:
composite = CompositeStopper(
[TimeoutStopper(60), ScoreThresholdStopper(0.9)],
mode="any",
)
repr(composite)
# "CompositeStopper([TimeoutStopper(...), ScoreThresholdStopper(...)], mode='any')"
Source code in src/gepa_adk/adapters/stoppers/composite.py
MaxEvaluationsStopper ¶
Stop evolution after maximum number of evaluations.
Useful for controlling API costs when evaluations are expensive. Checks the total_evaluations field from StopperState against the configured limit.
| ATTRIBUTE | DESCRIPTION |
|---|---|
max_evaluations | Maximum number of evaluate() calls allowed. TYPE: |
Examples:
Stop after 1000 evaluations:
Check if evolution should stop:
Note
Any evaluation count at or above the limit triggers a stop. This handles the case where batch evaluations cause the count to exceed the exact limit.
Source code in src/gepa_adk/adapters/stoppers/evaluations.py
__init__ ¶
Initialize the stopper with maximum evaluation count.
| PARAMETER | DESCRIPTION |
|---|---|
max_evaluations | Maximum number of evaluate() calls allowed. Must be a positive integer. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If max_evaluations is not positive. |
Note
Configure this value based on your API budget. Each evaluation typically corresponds to one model API call.
Source code in src/gepa_adk/adapters/stoppers/evaluations.py
__call__ ¶
__call__(state: StopperState) -> bool
Check if evolution should stop based on evaluation count.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state snapshot containing the total_evaluations count. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | True if total_evaluations >= max_evaluations, False otherwise. |
Note
Once this returns True, evolution should terminate to stay within the configured evaluation budget.
Source code in src/gepa_adk/adapters/stoppers/evaluations.py
FileStopper ¶
Stop evolution when a specified file exists.
Useful for external orchestration where CI/CD pipelines, job schedulers, or monitoring tools can signal graceful termination by creating a file.
| ATTRIBUTE | DESCRIPTION |
|---|---|
stop_file_path | Path to the stop signal file. TYPE: |
remove_on_stop | If True, remove the file after triggering stop. TYPE: |
Examples:
Stop when file exists:
Auto-remove file after triggering:
Note
Any path that doesn't exist simply won't trigger a stop. Invalid paths are handled gracefully without raising errors.
Source code in src/gepa_adk/adapters/stoppers/file.py
__init__ ¶
Initialize the stopper with a stop file path.
| PARAMETER | DESCRIPTION |
|---|---|
stop_file_path | Path to the stop signal file. Can be a string or Path object. Will be converted to Path internally. TYPE: |
remove_on_stop | If True, automatically remove the stop file after triggering a stop. Defaults to False. TYPE: |
Note
Configure the path based on your orchestration system. Common locations include /tmp/, /var/run/, or project-specific directories.
Source code in src/gepa_adk/adapters/stoppers/file.py
__call__ ¶
__call__(state: StopperState) -> bool
Check if evolution should stop based on file existence.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state snapshot (not used for file-based stopping, but required by the StopperProtocol). TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | True if the stop file exists, False otherwise. |
Note
Once this returns True, the stop file may be removed if remove_on_stop was enabled. Subsequent calls will return False.
Source code in src/gepa_adk/adapters/stoppers/file.py
remove_stop_file ¶
Manually remove the stop file.
This is idempotent - safe to call even if the file doesn't exist. Useful for resetting the stop condition before starting a new evolution run.
Note
Only call this when you explicitly want to remove the stop file. The file is automatically removed during call if remove_on_stop=True.
Source code in src/gepa_adk/adapters/stoppers/file.py
SignalStopper ¶
Stop evolution on Unix signals (SIGINT, SIGTERM).
Handles Ctrl+C (SIGINT) and termination signals gracefully, allowing the current iteration to complete before returning results. Supports both async contexts (using asyncio signal handling) and sync contexts (using traditional signal handlers).
| ATTRIBUTE | DESCRIPTION |
|---|---|
signals | Signals to handle. TYPE: |
Examples:
Using as async context manager:
from gepa_adk.adapters.stoppers import SignalStopper
async with SignalStopper() as stopper:
# stopper.setup() called automatically
config = EvolutionConfig(stop_callbacks=[stopper])
result = await engine.run(config)
# stopper.cleanup() called automatically
Using with custom signals:
import signal
stopper = SignalStopper(signals=[signal.SIGINT])
stopper.setup()
try:
# Only SIGINT will trigger stop
pass
finally:
stopper.cleanup()
Note
Always call cleanup() after evolution completes to restore original signal handlers. The context manager pattern handles this automatically.
Source code in src/gepa_adk/adapters/stoppers/signal.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
__init__ ¶
Initialize signal stopper with signals to handle.
| PARAMETER | DESCRIPTION |
|---|---|
signals | Signals to handle. Defaults to [SIGINT, SIGTERM] which covers Ctrl+C and system termination requests. TYPE: |
Examples:
# Default signals (SIGINT, SIGTERM)
stopper = SignalStopper()
# Custom signals
stopper = SignalStopper(signals=[signal.SIGINT])
Note
Call setup() before evolution starts and cleanup() after evolution completes to properly manage signal handlers.
Source code in src/gepa_adk/adapters/stoppers/signal.py
setup ¶
Install signal handlers.
Must be called before evolution starts. In async contexts, uses asyncio's signal handling. In sync contexts, uses traditional signal handlers.
Examples:
Note
On platforms where certain signals are unavailable (like Windows for SIGTERM), those signals are silently skipped.
Source code in src/gepa_adk/adapters/stoppers/signal.py
__call__ ¶
__call__(state: StopperState) -> bool
Check if evolution should stop due to signal.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state snapshot (not used, but required by StopperProtocol). TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | True if a signal was received, False otherwise. |
Examples:
stopper = SignalStopper()
stopper.setup()
state = StopperState(
iteration=5,
best_score=0.8,
stagnation_counter=0,
total_evaluations=25,
candidates_count=1,
elapsed_seconds=30.0,
)
# Before signal
stopper(state) # False
# After Ctrl+C
# stopper(state) # True
Note
Often called after each iteration. Returns True as soon as a signal is received.
Source code in src/gepa_adk/adapters/stoppers/signal.py
cleanup ¶
Restore original signal handlers.
Should be called after evolution completes to restore the signal handlers that were in place before setup() was called.
Examples:
stopper = SignalStopper()
stopper.setup()
try:
# Run evolution
pass
finally:
stopper.cleanup() # Restore original handlers
Note
On platforms where certain signals are unavailable, those signals are silently skipped during cleanup.
Source code in src/gepa_adk/adapters/stoppers/signal.py
__aenter__ async ¶
__aenter__() -> SignalStopper
Enter async context and install signal handlers.
| RETURNS | DESCRIPTION |
|---|---|
SignalStopper | Self for use as stopper in evolution config. |
Examples:
async with SignalStopper() as stopper:
config = EvolutionConfig(stop_callbacks=[stopper])
result = await engine.run(config)
Note
On entry, signal handlers are installed automatically.
Source code in src/gepa_adk/adapters/stoppers/signal.py
__aexit__ async ¶
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> None
Exit async context and restore signal handlers.
| PARAMETER | DESCRIPTION |
|---|---|
exc_type | Exception type if an exception was raised. TYPE: |
exc_val | Exception value if an exception was raised. TYPE: |
exc_tb | Exception traceback if an exception was raised. TYPE: |
Note
Original signal handlers are restored automatically on exit, even if an exception was raised.
Source code in src/gepa_adk/adapters/stoppers/signal.py
__enter__ ¶
__enter__() -> SignalStopper
Enter sync context and install signal handlers.
| RETURNS | DESCRIPTION |
|---|---|
SignalStopper | Self for use as stopper in evolution config. |
Examples:
with SignalStopper() as stopper:
config = EvolutionConfig(stop_callbacks=[stopper])
result = engine.run(config) # sync run
Note
On entry, signal handlers are installed automatically.
Source code in src/gepa_adk/adapters/stoppers/signal.py
__exit__ ¶
__exit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> None
Exit sync context and restore signal handlers.
| PARAMETER | DESCRIPTION |
|---|---|
exc_type | Exception type if an exception was raised. TYPE: |
exc_val | Exception value if an exception was raised. TYPE: |
exc_tb | Exception traceback if an exception was raised. TYPE: |
Note
Original signal handlers are restored automatically on exit, even if an exception was raised.
Source code in src/gepa_adk/adapters/stoppers/signal.py
ScoreThresholdStopper ¶
Stop evolution when best score reaches threshold.
Terminates evolution when the best achieved score meets or exceeds the configured threshold. Useful for "early success" scenarios where continued evolution beyond a target performance is unnecessary.
| ATTRIBUTE | DESCRIPTION |
|---|---|
threshold | Target score to achieve (evolution stops when best_score >= threshold). TYPE: |
Examples:
Creating a 95% accuracy threshold:
from gepa_adk.adapters.stoppers import ScoreThresholdStopper
from gepa_adk.domain.stopper import StopperState
stopper = ScoreThresholdStopper(0.95)
state = StopperState(
iteration=10,
best_score=0.97,
stagnation_counter=2,
total_evaluations=50,
candidates_count=3,
elapsed_seconds=120.0,
)
stopper(state) # Returns True (should stop)
Note
Any float value can be used as threshold, including negative numbers for domains where scores can be negative (e.g., loss minimization).
Source code in src/gepa_adk/adapters/stoppers/threshold.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
__init__ ¶
Initialize threshold stopper with target score.
| PARAMETER | DESCRIPTION |
|---|---|
threshold | Target score to achieve. Evolution stops when best_score >= threshold. Can be any float value including negative numbers. TYPE: |
Examples:
stopper = ScoreThresholdStopper(0.9) # 90% target
stopper = ScoreThresholdStopper(-0.5) # For negative score domains
Note
Compared to timeout values, threshold has no restrictions on sign or magnitude since score domains vary by application.
Source code in src/gepa_adk/adapters/stoppers/threshold.py
__call__ ¶
__call__(state: StopperState) -> bool
Check if evolution should stop due to reaching threshold.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state snapshot containing best_score. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | True if best score meets or exceeds threshold, False otherwise. |
Examples:
stopper = ScoreThresholdStopper(0.9)
# Below threshold
state1 = StopperState(
iteration=5,
best_score=0.85,
stagnation_counter=0,
total_evaluations=25,
candidates_count=1,
elapsed_seconds=30.0,
)
stopper(state1) # False
# At threshold
state2 = StopperState(
iteration=10,
best_score=0.9,
stagnation_counter=1,
total_evaluations=50,
candidates_count=2,
elapsed_seconds=65.0,
)
stopper(state2) # True
Note
Often called after each iteration. Returns True as soon as the threshold is reached.
Source code in src/gepa_adk/adapters/stoppers/threshold.py
TimeoutStopper ¶
Stop evolution after a specified timeout.
Terminates evolution when wall-clock time exceeds the configured timeout duration. Useful for resource management and CI/CD pipelines.
| ATTRIBUTE | DESCRIPTION |
|---|---|
timeout_seconds | Maximum wall-clock time for evolution. TYPE: |
Examples:
Creating a 5-minute timeout:
from gepa_adk.adapters.stoppers import TimeoutStopper
from gepa_adk.domain.stopper import StopperState
stopper = TimeoutStopper(300.0) # 5 minutes
state = StopperState(
iteration=10,
best_score=0.8,
stagnation_counter=2,
total_evaluations=50,
candidates_count=3,
elapsed_seconds=400.0, # Exceeds timeout
)
stopper(state) # Returns True (should stop)
Note
All timeout values must be positive. Zero and negative values raise ValueError to prevent invalid configurations.
Source code in src/gepa_adk/adapters/stoppers/timeout.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | |
__init__ ¶
Initialize timeout stopper with maximum duration.
| PARAMETER | DESCRIPTION |
|---|---|
timeout_seconds | Maximum wall-clock time for evolution in seconds. Must be a positive value. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If timeout_seconds is zero or negative. |
Examples:
Note
Consider using reasonable timeouts for your use case. Very short timeouts may not allow sufficient evolution progress.
Source code in src/gepa_adk/adapters/stoppers/timeout.py
__call__ ¶
__call__(state: StopperState) -> bool
Check if evolution should stop due to timeout.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state snapshot containing elapsed_seconds. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | True if elapsed time meets or exceeds timeout, False otherwise. |
Examples:
stopper = TimeoutStopper(60.0)
# Not yet timed out
state1 = StopperState(
iteration=5,
best_score=0.5,
stagnation_counter=0,
total_evaluations=25,
candidates_count=1,
elapsed_seconds=30.0,
)
stopper(state1) # False
# Timed out
state2 = StopperState(
iteration=10,
best_score=0.7,
stagnation_counter=1,
total_evaluations=50,
candidates_count=2,
elapsed_seconds=65.0,
)
stopper(state2) # True
Note
Often called after each iteration. Returns True as soon as the time limit is reached.