Critical Section
View as MarkdownUse a Critical Section when parallel branches of one Flow must take turns on a sequence of Steps. Only one branch may be inside the sequence at a time.
An example is several reviewers who edit the same contract. Each edit takes three Steps. The first takes the turn. The second makes the change. The third saves it and hands the turn on. Two edits must never interleave.
How it works
A dedicated Channel holds exactly one message. That message is the token.
- One Step publishes the token once, before any branch enters.
- A handoff Step waits for the token with
ForOne. One message satisfies one wait, so only one branch gets it. The other branches keep waiting. - The handoff Step does no protected work. Its
Executeonly moves to the first Step that does. - The last Step of the section publishes the token back. One waiting branch consumes it and enters.
In the example:
StartContractEditsputs the token in the Channel. Then it starts one branch for each edit, plusFinishContractEdits, which waits for every edit to finish.- Each branch waits in
EnterContractEditfor the token. It enters only once it holds the token. EditContractchanges the contract and moves toSaveContractEdit, which records the saved edit and puts the token back. When the reviewer withdraws,EditContractrecords the withdrawal and puts the token back instead.- When the
ExecuteofEnterContractEdit,EditContract, orSaveContractEditruns out of retries,ExecuteFailureroutes it toReleaseContractEditToken. That Step records the failed edit and puts the token back.
Any waiting branch can get the token next, in no fixed order.
Token or Attribute lock
An Attribute lock, such as ExecuteLockAttributes, covers one Step method. It does not cover a WaitFor, and it does not span several Steps. Use a lock when the protected work fits in one Execute. Use a token when the section spans Steps.
Every exit returns the token
The token is an ordinary message. A branch that leaves the section without publishing it back blocks every other branch forever. List each way out of the section, and publish the token on each one.
- Normal exit. The last Step of the section publishes the token.
- Execute failure. Route it with
ExecuteFailureto a Step that publishes the token. Configure that route on every Step of the section. In the example,EnterContractEdit,EditContract, andSaveContractEditall move toReleaseContractEditToken. - WaitFor failure. When a later Step of the section has its own
WaitFor, set itsWaitForFailurepolicy to proceed to itsExecute. ThatExecutesees the failure and publishes the token. - Early exit. An
Executethat leaves the section with a business decision publishes the token in the sameExecute. - Cancellation of the handoff. Canceling the handoff Step is safe, because it does no protected work. If Dex cancels it after its wait consumed the token but before Dex saved its
Executeresult, Dex returns the token to the front of the Channel. Another branch enters. - Cancellation inside the section. Never cancel a Step that does protected work. A canceled Step does not publish the token; see Canceling a Step that publishes. To stop a branch early, send it a stop request that its Steps check, such as an Attribute that an RPC sets. The Step that sees the request leaves through an early exit that publishes the token.
- Closing the Flow.
ForceComplete,ForceFail, a Flow timeout, and a ClientStopFlowend every branch. No branch waits for the token any more.
Dex saves a method's Channel publications together with its result, or not at all. A failed attempt publishes nothing, so a retry cannot create a second token.
A canceled Execute can keep running and writing to external systems after Dex has returned its token. This is another reason never to cancel a Step that does protected work.
Rules
- Publish exactly one token, in the Step that starts the branches or before. A second token lets two branches into the section at once.
- Use the token Channel for the token only.
- Keep the section short. Every other branch waits while one branch is inside.
- Keep the protected state in Attributes; the token's value carries no meaning.
Example
ContractEditFlow starts with a list of edits, one per reviewer. StartContractEdits publishes the token and starts one EnterContractEdit per edit, plus the join FinishContractEdits. EnterContractEdit hands off to EditContract, which records when the edit started. The join completes the Flow with every edit's record. The edit intervals never overlap.
Flags on an edit simulate the other exits. A failed handoff and an edit whose SaveContractEdit fails twice both go to ReleaseContractEditToken. A withdrawn edit leaves early from EditContract. Each of these returns the token, and the other reviewers still get their turn.
CONTRACT_EDIT_TOKEN = Channel("contractEditToken", str)
CONTRACT_EDIT_FINISHED = Channel("contractEditFinished", ContractEditRecord)
CONTRACT_EDIT_RETRY = RetryPolicy(
initial_interval=timedelta(seconds=1), maximum_attempts=2
)
class EnterContractEdit(Step[ContractEdit]):
"""Takes the token and hands off; it does no protected work, so canceling it is safe."""
def get_step_options(self) -> StepOptions:
return StepOptions(execute_retry=CONTRACT_EDIT_RETRY).on_execute_failure_proceed_to(
ReleaseContractEditToken
)
def wait_for(self, context: Context, edit: ContractEdit) -> Wait:
return Wait.until(CONTRACT_EDIT_TOKEN.for_one())
def execute(self, context: Context, edit: ContractEdit) -> StepDecision:
if edit.should_fail_handoff:
raise ContractEditError("contract handoff failed")
return go_to(EditContract, edit)
class EditContract(Step[ContractEdit]):
"""The first Step that works on the contract. Never cancel it."""
def get_step_options(self) -> StepOptions:
return StepOptions(execute_retry=CONTRACT_EDIT_RETRY).on_execute_failure_proceed_to(
ReleaseContractEditToken
Example: examples/python/dex_examples/patterns/critical-section/contract_edit_flow.py
var (
ContractEditToken = dex.DefineChannel[string]("contractEditToken")
ContractEditFinished = dex.DefineChannel[ContractEditRecord]("contractEditFinished")
errContractHandoff = errors.New("contract handoff failed")
errContractEdit = errors.New("contract edit failed")
contractEditRetry = &dex.RetryPolicy{InitialInterval: time.Second, MaximumAttempts: 2}
)
// EnterContractEdit takes the token and hands off; it does no protected work,
// so canceling it is safe.
type EnterContractEdit struct{ dex.StepDefaults }
func (EnterContractEdit) GetStepOptions() *dex.StepOptions {
return &dex.StepOptions{
ExecuteRetry: contractEditRetry,
ExecuteFailure: dex.ProceedToOnExecuteFailure(ReleaseContractEditToken{}, nil),
}
}
func (EnterContractEdit) WaitFor(dex.Context, ContractEdit) (*dex.Wait, error) {
return dex.Until(ContractEditToken.ForOne()), nil
}
func (EnterContractEdit) Execute(_ dex.Context, edit ContractEdit) (*dex.StepDecision, error) {
if edit.ShouldFailHandoff {
return nil, errContractHandoff
}
return dex.GoTo(EditContract{}, edit), nil
}
public static final Channel<String> contractEditToken =
Channel.define("contractEditToken", String.class);
public static final Channel<ContractEditRecord> contractEditFinished =
Channel.define("contractEditFinished", ContractEditRecord.class);
/** Routes an execute failure after the token was consumed to the Step that returns it. */
private static StepOptions contractEditOptions() {
return StepOptions.newBuilder()
.executeRetry(RetryPolicy.newBuilder()
.initialInterval(Duration.ofSeconds(1))
.maximumAttempts(2)
.build())
.onExecuteFailureProceedTo(ReleaseContractEditToken.class)
.build();
}
/** Takes the token and hands off; it does no protected work, so canceling it is safe. */
static final class EnterContractEdit implements Step<ContractEdit> {
@Override
public Class<ContractEdit> getInputType() {
return ContractEdit.class;
}
@Override
public StepOptions getStepOptions() {
return contractEditOptions();
}
@Override
public Wait waitFor(final Context context, final ContractEdit edit) {
Example: examples/java/src/main/java/io/superdurable/dex/patterns/criticalsection/ContractEditFlow.java
export const contractEditToken = new Channel("contractEditToken", stringCodec);
export const contractEditFinished = new Channel(
"contractEditFinished",
jsonCodec<ContractEditRecord>({ typeName: "ContractEditRecord" }),
);
/**
* Takes the token and hands off; it does no protected work, so canceling it
* is safe.
*/
class EnterContractEdit implements Step<ContractEdit> {
public getStepType(): string {
return "EnterContractEdit";
}
public getStepOptions(): StepOptions {
return {
executeRetry: { initialIntervalMs: 1_000, maximumAttempts: 2 },
executeFailure: ExecuteFailure.proceedTo(ReleaseContractEditToken),
};
}
public waitFor(_context: Context, _edit: ContractEdit): Wait {
return Wait.until(contractEditToken.forOne());
}
public execute(_context: Context, edit: ContractEdit): StepDecision {
if (edit.shouldFailHandoff) {
throw new Error("contract handoff failed");
}
Example: examples/typescript/src/patterns/critical-section/contract-edit-flow.ts
pub static CONTRACT_EDIT_TOKEN: LazyLock<Channel<String>> =
LazyLock::new(|| Channel::new("contractEditToken"));
pub static CONTRACT_EDIT_FINISHED: LazyLock<Channel<ContractEditRecord>> =
LazyLock::new(|| Channel::new("contractEditFinished"));
/// Takes the token and hands off; it does no protected work, so canceling
/// it is safe.
#[derive(Default)]
struct EnterContractEdit;
impl Step for EnterContractEdit {
type Input = ContractEdit;
fn options(&self) -> StepOptions<Self::Input> {
contract_edit_options()
}
fn wait_for(&self, _context: &mut Context, _edit: Self::Input) -> HandlerResult<Wait> {
Ok(Wait::until(CONTRACT_EDIT_TOKEN.for_one()))
}
fn execute(&self, _context: &mut Context, edit: Self::Input) -> HandlerResult<StepDecision> {
if edit.should_fail_handoff {
return Err(HandlerError::new(
"ContractHandoffFailed",
"contract handoff failed",
));
}
Ok(StepDecision::go_to(&EditContract, edit))
}
Example: examples/rust/src/control_patterns/critical_section/flow.rs