Skip to content

Execution budgets and circuit breakers

An execution budget limits the work ExecKernel will accept for an operation: elapsed time, payload size or the amount of data being processed. If a checked limit is exceeded, your application receives an error instead of the normal result. A circuit breaker addresses a different problem: after repeated failures of a custom_rule handler, it temporarily prevents further calls to that handler.

These protections help your application distinguish a choice that fails a business condition from an evaluation that could not complete acceptably. That distinction matters when deciding whether to show “this option is unavailable”, report a temporary technical problem or investigate the graph and its integration.

ExecKernel uses a StopwatchInterface to measure elapsed milliseconds. The default MonotonicStopwatch uses PHP’s monotonic clock, so the duration does not depend on the date assigned to a session or on a change to the wall clock.

This is separate from the TimeProvider used for calendar conditions and session timestamps. As explained in Temporal conditions and TimeDSL, that provider answers which instant is being evaluated. Freezing it makes temporal decisions repeatable; it does not freeze the stopwatch or disable duration limits.

The following values are the constants in PerformanceBudget for this version. They are acceptance thresholds, not a promise that an arbitrary application or server can complete its work within them.

Measured work Limit When the limit is checked Error on overrun
Calculation for start(), choose(), resume() or getPayload(), including payload construction and output hooks 20 ms After successful calculation, before publishing the operation’s success events NodeExecutionTimeExceededException, EK-PERF-001; scope identifies start, choose, resume or preview.
Navigation inside a choice 5 ms navigation limit; 20 ms node limit After calculating the next state Above 20 ms: NodeExecutionTimeExceededException; otherwise above 5 ms: NavigationTimeExceededException. Both use EK-PERF-001.
One evaluated condition 50 ms After its rule returns or throws RuleEvaluationTimeoutException, EK-RULE-004.
One custom_rule condition 2 ms At the same condition check, after the 50 ms check UserRuleTooSlowException, EK-PERF-002. Above 50 ms, the preceding EK-RULE-004 check wins.
A store operation wrapped by TimeoutAwareSessionStore 20 ms Before the store call and after it returns, with the confirmation rules described below SessionPersistenceTimeoutException, EK-PERSIST-003, when the checked operation has not already confirmed a mutation.

These scopes overlap: a choice includes navigation, navigation evaluates conditions, and the engine then prepares the final payload. An inner check can reject the work before an outer check is reached. Passing the condition budget therefore does not guarantee that the complete choice fits its budget.

An output hook runs registered application code while preparing the returned payload. Its work is included because your application waits for that final result.

A value exactly equal to a limit passes: rejection uses >. The condition timer includes the evaluator’s work around the rule and any sandbox call; it is not a measurement of the handler’s PHP instructions alone. The read-only availability query defers custom_rule execution, so it does not run that handler just to measure its cost.

These are checks at execution boundaries. If PHP code blocks inside a call, the engine cannot run its post-check until that call returns or throws. A reported overrun does not imply immediate interruption at the threshold. Process timeouts and sandbox isolation are separate controls; see Rule sandboxing and isolation boundaries.

The factory enables the normal monotonic measurement by default. This explicit construction has the same stopwatch choice:

use ExecKernel\Domain\Engine\MonotonicStopwatch;
use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
$engine = (new ExecKernelFactory())->build(
stopwatch: new MonotonicStopwatch(),
);

The factory shares that stopwatch with the engine, navigator, condition evaluator and payload builder. You do not need to add a performance monitor to enable these checks. A monitor observes activity; the budget checks themselves reject overruns.

The millisecond and byte limits in PerformanceBudget are class constants. This API does not expose a maxRuleMs or maxNavigationMs factory setting. Supplying another StopwatchInterface changes the measurement source, not those thresholds. NullStopwatch returns zero and therefore opts out of duration checks; it is not a higher-budget configuration.

Persistence protection is applied separately to the store your application uses. Given an existing $sessionStore implementing SessionStoreInterface, wrap it and use the wrapper for subsequent operations:

use ExecKernel\SessionStore\TimeoutAwareSessionStore;
$protectedStore = new TimeoutAwareSessionStore($sessionStore);

The default statelessOnFailure is false. A slow read or an unconfirmed save can therefore raise EK-PERSIST-003. A save that the inner store has already acknowledged as persisted remains a confirmed save even if the post-check is late; an acknowledged delete also remains completed. The wrapper records the duration but cannot undo the write.

If you explicitly enable statelessOnFailure: true, supported save failures may instead return a non-persisted SessionPersistenceResult containing the candidate state. Your application must inspect that result; receiving a state does not establish that it was stored. Logical conflicts and inner timeout exceptions are not silently converted to this fallback. Rejected transitions and error recovery explains how to recover a coherent interaction when persistence is uncertain.

Here we use the custom_rule mechanism described in Custom rule evaluation: a graph condition names a registered handler, and the evaluator asks the configured sandbox driver for its decision when the application attempts the choice.

For an isolated comparison, the budget-rule-probe.php example registers a handler called check, supplies a sandbox test double that returns true, and injects a controlled stopwatch. The test double advances that stopwatch by a chosen duration when called. It does not execute the handler code or wait in real time. This makes the duration an explicit test input, rather than a benchmark result. The complete file expects your project’s Composer autoloader at vendor/autoload.php beside it.

The essential wiring is:

$engine = (new ExecKernelFactory())->build(
customRules: ['check' => 'return true;'],
sandboxDriver: $sandbox,
stopwatch: $stopwatch,
);

In this fragment, $sandbox and $stopwatch are the two test doubles defined in the complete example. The graph has one choice, edge 1, with custom_rule handler check. The sandbox decision is the same in both runs:

Injected condition duration Result of choosing edge 1
1.5 ms The choice reaches terminal node 2.
2.5 ms The engine throws UserRuleTooSlowException; the caller’s original state remains at node 1.

For the 2.5 ms run, serializing the exception’s class, ekCode and context gives:

{
"class": "ExecKernel\\Exception\\UserRuleTooSlowException",
"ek_code": "EK-PERF-002",
"context": {
"duration_ms": 2.5,
"max_ms": 2,
"rule": "custom_rule",
"handler": "check",
"edge_id": 1
}
}

The handler returned an affirmative decision, but the result exceeded the accepted duration. Your application should treat this as a technical failure, keep the current interaction coherent and investigate the handler or its execution environment. Showing the normal “condition not met” message would conceal the actual problem.

The original session snapshot is unchanged in this example. That does not roll back external side effects performed by application code or a dependency. Before repeating an operation with an uncertain external result, recover the relevant state as described in the recovery guide.

Configure and understand the custom-rule circuit

Section titled “Configure and understand the custom-rule circuit”

A RuleCircuitBreaker stores failure state for each handler key, such as custom_rule:check. The default evaluator creates one with failureThreshold: 3 and windowMs: 60_000.

It counts exceptions raised during the handler’s evaluation and condition-budget overruns. A normal false result is a successfully evaluated business decision: it clears the accumulated failures, just as a normal true does. Invalid condition parameters or an unknown handler discovered during the preliminary contract check do not count as attempted handler failures. Built-in rules and external rule types registered through the rule registry are outside this custom_rule circuit.

To set another circuit policy, construct the evaluator with a RuleCircuitBreaker. The factory does not expose a circuit-configuration argument. In the following assembly, $registeredHandlers is your existing handler-name-to-code map, and $sandboxDriver is your configured driver:

use ExecKernel\Domain\Engine\{
ConditionEvaluator, CycleBreaker, ExecKernel,
FlowEventsDispatcher, Navigator, PayloadBuilder
};
use ExecKernel\Domain\Engine\Rules\{
RuleCircuitBreaker, RuleCircuitBreakerConfig
};
use ExecKernel\Infrastructure\Time\SystemTimeProvider;
$dispatcher = new FlowEventsDispatcher();
$clock = new SystemTimeProvider();
$circuit = new RuleCircuitBreaker(
new RuleCircuitBreakerConfig(
failureThreshold: 2,
windowMs: 2_000,
),
);
$evaluator = new ConditionEvaluator(
customRules: $registeredHandlers,
dispatcher: $dispatcher,
timeProvider: $clock,
sessionTtlSeconds: null,
ruleCircuitBreaker: $circuit,
sandboxDriver: $sandboxDriver,
);
$navigator = new Navigator(
$evaluator,
new CycleBreaker($dispatcher),
$dispatcher,
);
$engine = new ExecKernel(
$navigator,
new PayloadBuilder(),
$dispatcher,
timeProvider: $clock,
);

This wiring preserves sessionTtlSeconds: null, matching the default factory: configuring the circuit does not introduce an additional session expiry. If your integration uses an expiration policy, pass that policy when constructing the evaluator.

Here, two counted failures within the two-second window, without a successful evaluation between them, open the circuit. windowMs also sets how long it remains open before another real evaluation may try the handler. These short values illustrate the mechanism; choose a policy from your application’s observed failure and recovery behavior.

Stage for that handler What happens
Closed Calls are allowed. Failures accumulate within the window; a successful evaluation clears them.
Open, window not elapsed An attempted evaluation raises RuleCircuitOpenException with EK-RULE-006 before calling the sandbox. An availability query reports the option as blocked.
Open, window elapsed A query can report the custom condition as pending, but leaves the circuit unchanged. The next actual evaluation moves it to half-open and tries the handler.
Half-open trial completes A normal result, including false, closes the circuit. A counted failure reopens it and starts another waiting window.

The circuit uses the operation’s evaluation timestamp to calculate its window. Those timestamps are in Unix seconds and are converted to milliseconds for comparison; they are separate from the monotonic duration measurements above. The next evaluation triggers recovery after the window has elapsed. There is no background timer that runs a recovery call.

Circuit state lives in the RuleCircuitBreaker object. Sessions, edges and graphs that share that object also share the circuit for the same handler name. A newly constructed breaker starts with fresh state; this implementation does not distribute its state across PHP workers or persist it in the session.

For an open circuit, repeated immediate choices add no useful retry opportunity: the handler is not called. Your application can explain that evaluation is temporarily unavailable, refresh availability later and allow the next legitimate attempt when appropriate. Keep the distinction between “pending evaluation” and “accepted choice”: the recovery trial can still return false or fail.

Some protections reject excessive data regardless of how quickly it could be processed:

Data Limit and check What to change in your application
Conditions on one edge At most 32; checked while constructing the graph Simplify the decision or split the process into meaningful steps.
Context At most 128 top-level entries; checked when constructing or merging a Context Keep the values required for navigation in the context.
Nested context arrays Disabled by default; when enabled, ContextValidationPolicy controls maxDepth, default 4 Choose an explicit policy that matches the data you accept.
Normal node / terminal payload At most 65,536 / 131,072 bytes of JSON using JSON_UNESCAPED_UNICODE; checked on the final payload, including hooks and debug Reduce returned content or move large resources behind application links.
History with HistoryOverflowPolicy::REJECT At most 256 entries in each node/edge list Decide how long a session may continue. The default PRESERVE policy retains history beyond this number.

The context update guide explains how merged candidate values are checked before a choice. For example, two individually valid contexts can exceed the entry limit when combined. Payload and context-entry errors both use EK-PERF-003, so inspect the exception class and context rather than treating that code alone as a diagnosis.

Choose protections from what your application needs to bound: its calculation time, handler failure rate, data volume or session lifetime. The configuration and limits reference collects the exact contracts, while Performance and benchmarking addresses measuring your real workload.