GitHub user joeyutong created a discussion: Durable Execution Reconcile
# Durable Execution Reconcile
## Motivation
### Background
`flink-agents` already supports durable execution in two important ways:
1. If a durable call has already completed and its result or exception has been
persisted, recovery can replay the persisted terminal state without
re-executing the external call.
2. If the entire action has already completed, the framework skips the whole
action and only replays persisted memory updates and output events.
### Problem
There is still a recovery gap while a durable call is in progress: the runtime
may have already started the external call, but the call result has not yet
been persisted in a replayable form. If the job fails in that window, recovery
cannot determine whether the external system has already produced side effects,
so the only safe fallback is to execute the call again. For non-idempotent
systems, that can lead to duplication.
### Goal
This proposal improves recovery semantics for that in-progress window without
changing the existing durable execution abstraction. During recovery, the
external system or user code can use a reconcile hook to determine whether the
call should be re-executed or whether a terminal state can be recovered
directly.
## Design
### Overview
1. `DurableCallable` remains the only durable call abstraction.
2. A durable call opts into reconcile support by returning an optional
reconcile callable from `DurableCallable.reconcile()`. Calls that do so are
referred to below as reconcilable durable calls.
3. Only reconcilable durable calls use a two-phase state model: persist
`PENDING` before execution, then finalize the slot as `SUCCEEDED` or `FAILED`.
4. During recovery, if the runtime hits a matching `PENDING` record for the
current call, it executes the reconcile callable first. If that callable
determines a terminal state, the runtime recovers that state directly.
Otherwise, it falls back to the original `call()`.
### API Design
#### Java API
```java
import java.util.concurrent.Callable;
import javax.annotation.Nullable;
public interface DurableCallable<T> {
String getId();
Class<T> getResultClass();
T call() throws Exception;
default @Nullable Callable<T> reconcile() {
return null;
}
}
public final class ReconcileFallbackException extends Exception {
public ReconcileFallbackException(Throwable cause) {
super(cause);
}
}
```
Notes:
- `reconcile()` returns a `Callable<T>` that encapsulates reconcile logic.
Returning `null` means reconcile is not enabled for this durable call.
- The reconcile callable is invoked only on the recovery path after the runtime
matches a `PENDING` slot.
- If the reconcile callable returns a result, the runtime finalizes the current
slot as `SUCCEEDED` and replays the result.
- If the reconcile callable throws an exception that represents a terminal
failure, the runtime finalizes the current slot as `FAILED` and replays that
exception.
- If the reconcile callable throws `ReconcileFallbackException`, the runtime
does not treat that as a terminal failure. Instead, it continues by executing
the original `call()`.
- If reconcile logic encounters query failures, temporary external-system
unavailability, or any other situation where it cannot determine a terminal
state, those exceptions should be explicitly wrapped in
`ReconcileFallbackException` rather than surfaced as terminal failures.
#### Java Example
```java
String orderId = ...;
int amount = ...;
String result =
ctx.durableExecute(
new DurableCallable<String>() {
@Override
public String getId() {
return "charge-card";
}
@Override
public Class<String> getResultClass() {
return String.class;
}
@Override
public String call() throws Exception {
return paymentClient.charge(orderId, amount);
}
@Override
public Callable<String> reconcile() {
return () -> {
try {
PaymentStatus status =
paymentClient.query(orderId);
if (status == PaymentStatus.SUCCEEDED) {
return paymentClient.getResult(orderId);
}
if (status == PaymentStatus.FAILED) {
throw new PaymentFailedException(orderId);
}
throw new IllegalStateException(
"payment status is not terminal");
} catch (PaymentFailedException ex) {
throw ex;
} catch (Exception ex) {
throw new ReconcileFallbackException(ex);
}
};
}
});
```
#### Python API
```python
def durable_execute(
self,
func: Callable[..., T],
*args: Any,
reconcile: Callable[[], T] | None = None,
**kwargs: Any,
) -> T: ...
def durable_execute_async(
self,
func: Callable[..., T],
*args: Any,
reconcile: Callable[[], T] | None = None,
**kwargs: Any,
) -> T: ...
```
Notes:
- `reconcile` is an optional keyword-only reconcile callable. If it is not
provided, the existing completion-only semantics remain unchanged.
- The reconcile callable captures any context needed to query the external
system directly at the call site.
- The semantics of `return result`, `throw exception`, and `throw
ReconcileFallbackException` are the same as in Java.
#### Python Example
```python
result = ctx.durable_execute(
charge_card,
order_id,
amount,
reconcile=lambda: payment_client.reconcile_payment(order_id),
)
```
### State Model
#### CallResult
Add a `status` field to represent the execution state of a reconcilable durable
call:
- `PENDING`: the current slot has not yet been finalized to a terminal state.
Importantly, `PENDING` means only that no terminal state has been persisted
yet; it does not guarantee that the external call has already started or
produced side effects.
- `SUCCEEDED`: a replayable successful result is available.
- `FAILED`: a replayable failure is available.
### Runtime Behavior
#### Execution Path
For a reconcilable durable call, the runtime performs the following steps:
1. Persist a `PENDING` record at the current call index.
2. Execute `call()`.
3. If `call()` succeeds, finalize the current slot as `SUCCEEDED`.
4. If `call()` throws, finalize the current slot as `FAILED`.
Durable calls without a reconcile callable keep the existing completion-only
behavior.
#### Recovery Path
For a reconcilable durable call, the runtime evaluates the current slot using
the existing sequential matching rule driven by `currentCallIndex`:
- If there is no record at the current index:
- persist `PENDING`, execute `call()`, and persist the resulting terminal
state.
- If the record at the current index does not match the current `functionId`
and `argsDigest`:
- clear the current and subsequent records, persist `PENDING`, execute
`call()`, and persist the resulting terminal state.
- If the current slot is `SUCCEEDED`:
- replay the result directly.
- If the current slot is `FAILED`:
- replay the exception directly.
- If the current slot is `PENDING`:
- execute the reconcile callable.
- If the reconcile callable returns a result, finalize the current slot as
`SUCCEEDED` and replay the result.
- If the reconcile callable throws an exception that represents a terminal
failure, finalize the current slot as `FAILED` and replay the exception.
- If the reconcile callable throws `ReconcileFallbackException`, reuse the
current `PENDING` slot and execute the original `call()` without appending
another `PENDING`.
Two points are worth noting:
- Recovery matching is still driven by `currentCallIndex` together with the
current slot's `functionId` and `argsDigest`, not by `getId()` alone.
- The reconcile branch is entered only when the current index matches a
`PENDING` slot for the current call.
#### Cleanup on Call-Order Mismatch
Cleanup behavior remains consistent with the current implementation: when call
order no longer matches, the runtime clears the current slot and all subsequent
call results. Two points are worth noting:
1. `PENDING` records follow the same cleanup rule.
2. After cleanup, the trimmed `ActionState` should be persisted promptly so the
same stale suffix does not keep participating in repeated recovery attempts.
## Implementation
### API
- Java: add a default `reconcile()` method to `DurableCallable` that returns an
optional reconcile callable, plus `ReconcileFallbackException` as the explicit
fallback signal.
- Python: add a keyword-only `reconcile` parameter to
`RunnerContext.durable_execute(...)` and `durable_execute_async(...)`.
### State Model
`CallResult` adds a `status` field with the three states `PENDING`,
`SUCCEEDED`, and `FAILED`.
Also add `ActionState.replaceCallResult(int index, CallResult callResult)` so
the current slot can be updated in place from `PENDING` to `SUCCEEDED` or
`FAILED`.
### Runtime
At method entry, `RunnerContextImpl.durableExecute(...)` and
`JavaRunnerContextImpl.durableExecuteAsync(...)` select either the
completion-only path or the reconcile-aware path based on whether the durable
call provides a reconcile callable.
```java
@Override
public <T> T durableExecute(DurableCallable<T> callable) throws Exception {
Callable<T> reconcileCallable = callable.reconcile();
if (durableExecutionContext == null || reconcileCallable == null) {
// Existing durable call execution path
return durableExecuteCompletionOnly(callable);
}
return durableExecuteWithReconcile(callable, reconcileCallable,
callable::call);
}
```
```java
@Override
public <T> T durableExecuteAsync(DurableCallable<T> callable) throws Exception {
Callable<T> reconcileCallable = callable.reconcile();
if (durableExecutionContext == null || reconcileCallable == null) {
// Existing async durable call execution path
return durableExecuteAsyncCompletionOnly(callable);
}
return durableExecuteWithReconcile(
callable, reconcileCallable, () -> executeAsyncCallable(callable));
}
```
Key implementation constraints:
- On the first execution of a reconcilable durable call, the runtime appends a
`PENDING` record at the current index. The later terminal state must overwrite
that slot instead of appending a new call result.
- When the reconcile callable throws `ReconcileFallbackException`, the runtime
reuses the current `PENDING` slot and executes the original `call()` without
writing another `PENDING`.
- `currentCallIndex` advances only when a terminal state is replayed or the
current slot is finalized as terminal. Writing `PENDING` itself does not
advance the index.
- After mismatch cleanup, the trimmed `ActionState` should be persisted
promptly so the same stale suffix does not repeatedly participate in recovery.
- Sync and async share the same reconcile state machine. Their only difference
is how the original `call()` is executed. In particular, the async path must
guarantee that `PENDING` is already persisted before the underlying call
actually begins.
### Storage and Serialization
`ActionStateKafkaSeder` must remain compatible with both old and new
`CallResult` formats. New code must be able to read older persisted records
that do not contain the `status` field and interpret them using the previous
`SUCCEEDED` / `FAILED` semantics.
## Documentation
- Document reconcilable durable calls and provide an end-to-end example
- Explain the recovery semantics and underlying rationale
- Show how reconcile logic can query external systems
## Testing
- `ActionState` / `CallResult` serialization and deserialization
- Reconcilable durable call sync/async execution and mismatch handling
- Operator and recovery integration tests covering `PENDING ->
success/failure/fallback`, fallback from reconcile callable to the original
`call()`, and mixed ordering between plain durable calls and reconcilable
durable calls
GitHub link: https://github.com/apache/flink-agents/discussions/598
----
This is an automatically sent email for [email protected].
To unsubscribe, please send an email to: [email protected]