Wait for Half
View as MarkdownStart N SubFlows, wait for half to finish, then stop the unfinished children.
Each child runs in its own SubFlowStep execution. A completed child publishes one message to SubFlowCompletedCh. WaitSubFlows waits for half of those messages, then publishes one AllDoneCh message for every possible unfinished child.
Once half of the children have finished, each waiting SubFlowStep consumes one AllDoneCh message and tries to stop its child. The Step records the outcome in ChildStopOutcomes, keyed by the child Flow ID, then completes gracefully. A successful stop records stopped. A typed error for a missing, inactive, or closing Flow prompts a state read. The Step records the terminal status and any stored result for a closed child. A running, closing, or missing child is recorded as unknown for a later read. Other errors trigger a Step retry.
Core implementation
@dataclass(frozen=True)
class ChildStopOutcome:
status: str
result: str | None = None
CHILD_STOP_OUTCOMES = AttributeMap("ChildStopOutcomes", ChildStopOutcome)
class WaitForHalfInit(Step[list[str]]):
def execute(self, context: Context, requests: list[str]) -> StepDecision:
if not requests:
return graceful_complete()
return go_to_many(
StepMovement.of(WaitSubFlows, len(requests)),
*(StepMovement.of(SubFlowStep, request) for request in requests),
)
class SubFlowStep(Step[str]):
def __init__(
self,
client_provider: Callable[[], AsyncClient],
example_subflow: ExampleSubFlow,
subflow_completed_ch: Channel[bool],
all_done_ch: Channel[bool],
) -> None:
self.client_provider = client_provider
self.example_subflow = example_subflow
self.subflow_completed_ch = subflow_completed_ch
Example: examples/python/dex_examples/patterns/parallel-subflows/wait_for_half_parent_flow.py
var (
SubFlowCompletedCh = dex.DefineChannel[bool]("SubFlowCompletedCh")
AllDoneCh = dex.DefineChannel[bool]("AllDoneCh")
ChildStopOutcomes = dex.DefineAttributeMap[ChildStopOutcome]("ChildStopOutcomes")
)
type ChildStopOutcome struct {
Status string `json:"status"`
Result *string `json:"result,omitempty"`
}
type WaitForHalfParentFlow struct {
dex.FlowDefaults
getClient func() *dex.Client
exampleFlow *ExampleSubFlow
}
func NewWaitForHalfParentFlow(getClient func() *dex.Client, exampleFlow *ExampleSubFlow) *WaitForHalfParentFlow {
return &WaitForHalfParentFlow{getClient: getClient, exampleFlow: exampleFlow}
}
func (flow *WaitForHalfParentFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(waitForHalfInit{}),
dex.DefineStep(subFlowStep{getClient: flow.getClient, exampleFlow: flow.exampleFlow}),
dex.DefineStep(waitSubFlowsStep{}),
}
}
func (*WaitForHalfParentFlow) GetPersistenceSchema() dex.PersistenceSchema {
Example: examples/go/patterns/parallel-subflows/wait_for_half_parent_flow.go
@Component
public final class WaitForHalfParentFlow implements Flow<String[]> {
public final Channel<Boolean> subFlowCompletedCh = Channel.define("SubFlowCompletedCh", Boolean.class);
public final Channel<Boolean> allDoneCh = Channel.define("AllDoneCh", Boolean.class);
public final AttributeMap<ChildStopOutcome> childStopOutcomes =
AttributeMap.define("ChildStopOutcomes", ChildStopOutcome.class);
public record ChildStopOutcome(String status, String result) {}
private final Init initStep = new Init();
private final SubFlowStep subFlowStep;
private final WaitSubFlows waitSubFlowsStep = new WaitSubFlows();
public WaitForHalfParentFlow(final ObjectProvider<Client> clientProvider) {
subFlowStep = new SubFlowStep(clientProvider);
}
public StepList<String[]> getSteps() {
return StepList.startStep(initStep).otherSteps(subFlowStep, waitSubFlowsStep);
}
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of(subFlowCompletedCh, allDoneCh, childStopOutcomes);
}
final class Init implements Step<String[]> {
public Class<String[]> getInputType() { return String[].class; }
public StepDecision execute(final Context context, final String[] requests) {
if (requests.length == 0) return StepDecision.gracefulComplete(null);
final StepMovement<?>[] movements = new StepMovement<?>[requests.length + 1];
movements[0] = StepMovement.of(WaitSubFlows.class, requests.length);
Example: examples/java/src/main/java/io/superdurable/dex/patterns/parallelsubflows/WaitForHalfParentFlow.java
const subFlowCompletedCh = new Channel("SubFlowCompletedCh", booleanCodec);
const allDoneCh = new Channel("AllDoneCh", booleanCodec);
interface ChildStopOutcome {
readonly status: FlowStatus | "stopped" | "unknown";
readonly result?: string;
}
const childStopOutcomes = new AttributeMap("ChildStopOutcomes", jsonCodec<ChildStopOutcome>());
export class WaitForHalfParentFlow implements Flow<readonly string[]> {
private readonly init = new WaitForHalfInit();
private readonly subFlow: SubFlowStep;
private readonly waitSubFlows = new WaitSubFlows();
public constructor(exampleSubFlow: ExampleSubFlow) {
this.subFlow = new SubFlowStep(exampleSubFlow);
}
public getFlowType(): string { return "WaitForHalfParentFlow"; }
public getSteps() { return StepList.startStep(this.init).otherSteps(this.subFlow, this.waitSubFlows); }
public getPersistenceSchema(): PersistenceSchema { return { attributes: [childStopOutcomes], channels: [subFlowCompletedCh, allDoneCh] }; }
}
class WaitForHalfInit implements Step<readonly string[]> {
public readonly inputCodec = stringArrayCodec;
public getStepType(): string { return "Init"; }
public execute(_context: Context, requests: readonly string[]): StepDecision {
if (requests.length === 0) return gracefulComplete();
return goToMany(StepMovement.of(WaitSubFlows, requests.length), ...requests.map((request) => StepMovement.of(SubFlowStep, request)));
}
Example: examples/typescript/src/patterns/parallel-subflows/parallel-subflows.ts
static SUB_FLOW_COMPLETED_CH: LazyLock<Channel<bool>> =
LazyLock::new(|| Channel::new("SubFlowCompletedCh"));
static ALL_DONE_CH: LazyLock<Channel<bool>> = LazyLock::new(|| Channel::new("AllDoneCh"));
static CHILD_STOP_OUTCOMES: LazyLock<AttributeMap<ChildStopOutcome>> =
LazyLock::new(|| AttributeMap::new("ChildStopOutcomes"));
#[derive(Deserialize, Serialize)]
struct ChildStopOutcome {
status: String,
result: Option<String>,
}
#[derive(Default)]
pub struct WaitForHalfParentFlow {
init: WaitForHalfInit,
sub_flow: SubFlowStep,
wait_sub_flows: WaitSubFlows,
}
impl WaitForHalfParentFlow {
pub fn new(client: Arc<Client>) -> Self {
Self { sub_flow: SubFlowStep { client: Some(client) }, ..Self::default() }
}
}
impl Flow for WaitForHalfParentFlow {
type StartInput = Vec<String>;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.init).and(&self.sub_flow).and(&self.wait_sub_flows)
}
Example: examples/rust/src/patterns/parallel_subflows/flow.rs
Children that finish at the threshold
When the report counts every child or a follow-up action depends on how each child ended, the Step reads the child after every stop and records how it ended. When the parent needs only the quorum, it stops the remaining children and moves on without this read. A child can finish at the same moment its stop message arrives, and a Channel condition wins over a SubFlow condition when both are ready, so the Step may stop a child that already ended. After a successful stop, or a refused one such as "not found", "not active", or "closing", read the child through the Client. Record a closed child's terminal status and stored result, so the report counts every child that finished. Read a child that is still running or closing again later. A child that is not found is recorded by business policy, such as "unavailable". Return any other stop or read error so the Step retries. Record every child, finished or stopped, in one record keyed by its SubFlow ID. The example is simplified: it does not read the child's terminal state after a successful stop.
When each child needs its own business identity, start it as a top-level Flow instead. The quorum Step stops each child that has not reported and, when the parent needs its outcome, reconciles it by the rules on that page. Normal reports and reconciled outcomes go into one record, keyed by the child Flow ID.