Handle transition outcomes
Outcome<E, S, T> is a sealed interface with four variants. Every outcome classifies itself, so a caller that
only needs to know what happened and why reads it without narrowing:
| Variant | status() |
code() |
explanation() |
State written? |
|---|---|---|---|---|
Applied |
APPLIED |
APPLIED |
empty | Yes, the resolved edge committed |
Rejected |
REJECTED |
NO_TRANSITION, GUARD_REJECTED, DETACHED or RESERVED_EXIT |
the policy's reason, the guard's, or the library's fixed text for the last two | No |
Failed |
FAILED |
FAILURE_ROUTED |
the reason the action returned; empty when failsOn or a recovery rule routed a throwable |
Yes, the failure route committed |
Ignored |
IGNORED |
NO_WATCH or NO_RULE_MATCHED for reevaluate, NO_AUTOMATIC_TRANSITION or NO_CANDIDATE_ADMITTED for advance and the attempts of an automatic chain |
empty, except for NO_CANDIDATE_ADMITTED, which names each candidate's rejection |
No |
What each variant adds to the accessors every outcome has:
A cascade returns Applied or Failed to the action that called cascade(...); a rejection inside it aborts the
root instead. Both are provisional there: their hops are written only if the root commits.
Every outcome also has entity(), from(), recordedState(), requestedTransition(), records(),
reactions(), automaticSteps(), starts() and flow(), and the three searches of its automatic steps,
automaticFailure(), automaticAbort() and automaticBlock(). recordedState() is to for Applied, movedTo for
Failed and from for the other two. requestedTransition() is the identifier the caller asked for, the one a reevaluation's watch
selected, or the automatic edge an advance ran; it is empty only for Ignored, which ran no edge at all. Records, journals
and reactions describes what records(), reactions(), automaticSteps(),
starts() and flow() return, and find what the automatic steps did what the
three searches return.
Read the classification with its limits in mind:
recordedState()is what the call recorded, not a read of the entity. An after-commit hook, a watch reaction, an automatic attempt or a later call can move the entity again; read the entity when you need its live state.FAILEDdoes not mean that nothing happened: the failure route committed and the entity is atmovedTo.explanation()holds the reasons the graph declares: a policy's reason, a guard's, or the reason an action returned withActionOutcome.failed(...). The only texts the library writes there are the fixed reason of a terminal state that declares no policy, such asterminal state DONE accepts no transitions, the fixed reasons of the two refusals of a sub-machine:DETACHED, such asno parent holds it in DEPOSIT, andRESERVED_EXIT, such asDEPOSIT_PAID leaves DEPOSIT only when its sub-machine ends, and the text of anadvancethat admitted no automatic edge, which joins the rejection of each one it tried, such asno automatic transition was admitted: COMPLETE_ADDRESS (GUARD addressComplete): address is incomplete. WhenfailsOnor a recovery rule routes an exception, the failure's reason is composed from that exception and may carry internal details; it stays inFailed.reason()andFailed.cause().- A commit here is GraphMaquina writing states through the setters. A JPA or other transaction around the call commits later and can still fail.
- The constant names of
OutcomeStatusandOutcomeCodeare stable identifiers, safe to persist or send. Each code knows the status it refines:OutcomeCode.GUARD_REJECTED.status()isREJECTED.
This method can be added to the quickstart's App:
static String describe(Outcome<Ticket, TicketState, TicketTransition> outcome) {
return outcome.code() + " at " + outcome.recordedState()
+ outcome.explanation().map((String text) -> ": " + text).orElse("");
}
Contents
- Map an outcome to a response
- Read what only one variant carries
- Records, journals and reactions
- Find what the automatic steps did
- Handle a failed call
Map an outcome to a response
A web layer copies the classification into a type it owns, so its contract does not change when the library
does. The HTTP mapping below is one application's policy, not the library's; another application may just as well
answer 409 for every rejection and every handled failure:
record TransitionResponse(
String id,
OutcomeStatus status,
OutcomeCode code,
TicketState from,
TicketState state,
TicketTransition transition,
String explanation) {
static TransitionResponse of(
String id,
Outcome<Ticket, TicketState, TicketTransition> outcome) {
return new TransitionResponse(
id,
outcome.status(),
outcome.code(),
outcome.from(),
outcome.recordedState(),
outcome.requestedTransition().orElse(null),
outcome.explanation().orElse(null));
}
}
static int httpStatus(OutcomeCode code) {
return switch (code) {
case APPLIED, FAILURE_ROUTED, NO_WATCH, NO_RULE_MATCHED,
NO_AUTOMATIC_TRANSITION -> 200;
case NO_TRANSITION, DETACHED, RESERVED_EXIT -> 409;
case GUARD_REJECTED, NO_CANDIDATE_ADMITTED -> 422;
};
}
The switch has no default: it is exhaustive, so a code added by a future release fails the build instead of
falling through. Do not serialize the Outcome itself: it holds the entity, a Throwable, reactions with their own
entities, and the call's flow, whose values are whatever the steps and hooks put. A call failure cannot be serialized
at all: every CallFailedException, whatever its subtype, holds its MachineCall, which is not Serializable, so
writing one to an ObjectOutputStream throws NotSerializableException.
Read what only one variant carries
The sealed variants remain available when a caller needs what only one of them carries: the rejecting guard,
the recovery identifier, the requested destination of a failure or its cause. asApplied(), asRejected(),
asFailed() and asIgnored() return the outcome as that variant, with the outcome's type arguments, or empty:
Optional<String> guard = outcome.asRejected().flatMap(Outcome.Rejected::guard);
Optional<TicketTransition> recovery = outcome.asFailed().map(Outcome.Failed::failureTransition);
Ignored.rejections() lists why an advance with the reason NO_CANDIDATE_ADMITTED ran no automatic edge: one
Eligibility.Ineligible per edge it tried, in the order it tried them, each with the identifier, the state, the
RejectionKind, the guard of a GUARD rejection and the reason. It is empty for every other Ignored.
A switch over the variants reads all of them at once:
static String detail(Outcome<Ticket, TicketState, TicketTransition> outcome) {
return switch (outcome) {
case Outcome.Applied<Ticket, TicketState, TicketTransition> applied ->
applied.transition() + " moved to " + applied.to();
case Outcome.Rejected<Ticket, TicketState, TicketTransition> rejected ->
"Refused " + rejected.transition() + " by "
+ rejected.guard().orElse("the state's policy");
case Outcome.Failed<Ticket, TicketState, TicketTransition> failed ->
failed.failureTransition() + " moved to " + failed.movedTo() + ": "
+ failed.reason();
case Outcome.Ignored<Ticket, TicketState, TicketTransition> ignored ->
"Unchanged at " + ignored.recordedState() + " (" + ignored.reason() + ")"
+ ignored.explanation().map((String text) -> ": " + text).orElse("");
};
}
Technical failures throw instead of becoming a fifth outcome. An abort (TransitionAbortedException), a commit
failure (CommitFailedException) and a failing hook (AfterCommitException) share the supertype
CallFailedException. It says as values which call failed (call()), where it was (phase()), how far it got
in writing states (statesWritten()) and which actions ran (journal()), and it hands out the call's flow
(flow()). A hook fails after state was already written. Handle a failed call shows how to
read them.
Records, journals and reactions
TransitionRecorddescribes a hop the call took: machine key, entity, source, transition identifier, destination, kind, action label and cascade depth. Two actions that share a name and endpoints stay distinguishable because the identifier is part of the record. The records of an outcome and of anAfterCommitExceptionare committed hops. In the trail of any other failure, a record is a hop the call took, and that failure'sstatesWritten()says whether none or some of their states were written.records()andreactions()answer on every outcome. A rootAppliedorFailedreturns the transaction's records and the reactions of its commit;Rejected,Ignoredand a nestedcascaderesult return empty lists, the last because it is provisional and has no independent root commit or reaction list.starts()answers on every outcome too, and is empty in the same cases. When an edge enters a state that holds a sub-machine, the child moves to the initial state of its graph in the same unit of work, and a rootAppliedorFailedreturns aSubmachineStartfor each such start, in log order: the child's machine and entity (key(),child()), the state it had and the one it started in (previous(),initial()), the parent's machine, entity and bound state (parentKey(),parent(),node()), and the depth of the step (depth()). A start is no hop, so it is not inrecords()and runs no hook.flow()answers on every outcome as well. A rootAppliedorFailedhands out the call's flow, frozen once its hooks, its reactions and its automatic steps ran;Ignored, a nestedcascaderesult, and aRejectedor any other root outcome of a call that records no trail and whose steps and hooks wrote nothing to its flow returnFlowView.empty(). Read the flow after the call says what it holds, and record the call's trail how its trail lists the hops and starts ofrecords()andstarts().- A failed call's journal uses
ActionRecordandActionStatus(OK,FAILED,THREW; neverRUNNINGonce the call failed) to report actions that actually ran. A journal is execution evidence, not an undo log for external side effects. - A watch produces
Reaction.Done, carrying its own outcome, with the reaction's own flow, orReaction.Aborted, carrying its exception. Inspect reactions even when the root operation succeeded.Reaction.Abortedcan also report a hook failure after the reaction itself committed; it is not proof that the reaction left state unchanged. A reevaluation that failed carries itsCallFailedException, whosestatesWritten()says whether the reaction wrote anything. An owner lookup fails before any reevaluation, so the reaction carries what it threw: aRuntimeExceptionas it is, and a checked exception or any other throwable that is neither aRuntimeExceptionnor anError, wrapped inUndeclaredThrowableException, with the thread interrupted again when what it threw is anInterruptedException. AnErroris not caught: it propagates to the caller whose commit triggered the reaction. automaticSteps()answers on every outcome too. A rootAppliedorFailedreturns the automatic attempts its commit triggered once its reactions ran;Rejected,Ignoredand a nestedcascaderesult return an empty list. Each entity with a hop or a sub-machine start in the commit, a self-loop or a round trip included, runs its chain, in log order, unless its last hop there is a failure route that does not continue: from the state the commit left it in, while that state has an automatic edge, oneadvanceof the entity after another, each a call of its own with its own outcome and flow. The list holds each chain whole, flat and in order. A chain stops after an attempt that admits no candidate, which the list still holds asAutomaticStep.Donewith itsIgnored, whoserejections()say why; after one whose failure takes a route that does not continue; and after one that aborts, which the list holds asAutomaticStep.Aborted, with the attempt'sCallFailedException, whosestatesWritten()says whether the attempt wrote anything. A chain that reaches a state without automatic edges makes no further attempt. An attempt past the registry'smaxAutomaticChainthat admits a candidate aborts withAutomaticChainExceededExceptionbefore its action runs. The outcome of anadvanceis its first attempt, so the chain of its entity in the list starts with the attempt that followed. Like a reaction's, an attempt's failure never reaches the caller: inspect the steps even when the call succeeded. AnErroris not caught: it propagates to the caller whose commit triggered the attempt.- The deepest commit that moved an entity chains it. When a call made on the same thread inside the post-commit, a hook's call, a watch reaction or an attempt, committed a hop or a start of an entity before that entity's chain began, that call decided the chain, so the commit around it does not chain the entity again; and a chain stops after an attempt whose own post-commit ran such a call for its entity. So the attempts that an attempt's commit triggers for other entities are in that attempt's outcome, and a chain that a watch reaction decided is in that reaction's outcome. A hook's call on another thread is not made inside the post-commit and decides nothing, as when the chain runs says. Entities compare as the commit log compares them, by machine and identity.
- Outside any call, the chain decides whether an attempt follows. After an attempt that ended
Ignored, or whose failure took a route that stops the chain, it stops. Before its first attempt and after any other, it reads the automatic edges of the state the commit or the attempt left the entity in: a state without one ends the chain there, having read no state and run no identity'shashCodeorequals. Otherwise it compares the entity with those that calls nested in the post-commit, or in the attempt's own, moved, which runs thehashCodeandequalsof identities only when such a call moved something. When aGraphDefinitionwritten by hand throws fromautomaticFromthere, or the entity's identity throws fromhashCodeorequalsas it is compared, the chain ends asAutomaticStep.Abortedwith what was thrown: aRuntimeExceptionas it is, any other throwable but anErrorwrapped inUndeclaredThrowableException, with the thread interrupted again for anInterruptedException. Such a step may follow the chain's last attempt. The identity of another entity that throws there ends no chain but that entity's own. The sameautomaticFromthrowing inside an attempt or anadvanceaborts that call inRESOLVE.
Find what the automatic steps did
A call's automatic attempts can fail, abort or stop at a guard after the call itself committed, in its own chains or in chains nested in its reactions and in other attempts. Three methods of every outcome search all of them and return the first one that matches:
| Method | Returns | Present when |
|---|---|---|
automaticFailure() |
Optional<Outcome.Failed<?, ?, ?>> |
an attempt ended in Failed, whether its route stopped the chain or let it go on |
automaticAbort() |
Optional<AutomaticStep.Aborted> |
an attempt aborted, on a domain failure that no route takes, a technical failure, any other exception or maxAutomaticChain, or the reads a chain makes around its attempts threw |
automaticBlock() |
Optional<Outcome.Ignored<?, ?, ?>> |
an attempt admitted none of its candidates, NO_CANDIDATE_ADMITTED; its rejections() say why |
They search in the order the attempts ran. First come the reactions(), each Reaction.Done searched the same way
through its outcome; then the automaticSteps(), in order, each step looked at itself and then searched through its
outcome, its reactions and its steps. So an attempt nested in a reaction comes before the call's own steps. Only
AutomaticStep entries count: a Reaction.Done whose outcome is Failed, or a Reaction.Aborted, is the result of a
watch, which reactions() holds. The types carry wildcards because the attempts can be of other machines: peers,
children and parents. A failure and a block can happen in one call: with a route that continues, the chain goes on
from the recovery state, and automaticFailure() still returns the failure. Rejected and Ignored have neither
steps nor reactions, so the three are empty; the outcome of an advance is its own first attempt, which you read
directly.
advance(entity) goes on from where the entity stands: after a Failed, from the recovery state; after an abort
before any write, from the state the attempt started in. An aborted attempt's cause is its CallFailedException,
whose statesWritten() says whether it wrote: after a setter or a hook threw, the entity may have moved, and
advance goes on from whatever state it has.
Handle a failed call
A call that does not return an outcome throws an Error or one of three CallFailedExceptions, always one of that
very call. A request refused before the call starts is not a call failure: a null argument throws
NullPointerException, an identifier of another catalogue IllegalArgumentException, and a call made where
no call may start ReentrantTransitionException. Read what happened from its values, not from its message:
| Type | phase() |
statesWritten() |
|---|---|---|
TransitionAbortedException and its subclasses |
RESOLVE, GUARD or ACTION |
NONE |
CommitFailedException |
COMMIT |
NONE, or PARTIAL when a setter threw |
AfterCommitException |
HOOK |
ALL |
The phases follow the call: RESOLVE reads the identity and the state, checks the binding of a sub-machine and selects
the edge; GUARD runs the root edge's guards, and is entered only when it has any; ACTION lasts from the passed
guards until the step ends, its cascades, failure route, sub-machine starts and exits included, which never change
the phase; COMMIT checks the original states and calls the setters; HOOK runs the after-commit hooks;
REACTIONS dispatches the watch reactions; and AUTOMATIC_STEPS runs the automatic chains of the entities the commit
moved, which a call of a registry without automatic edges never enters. Only an Error leaves either of the last two
as a failure. The names of CallPhase and StatesWritten are stable identifiers, safe to log or to use as a metric
tag.
call() is the call that failed, the same MachineCall an observer received, and journal() lists the actions that
ran. Any other exception involved is the cause, a failure of another call included, which keeps the flow of its own
call.
flow() is the call's flow, frozen when the call failed and attached before the observers hear of the failure. It
reads like an outcome's, as read the flow after the call shows, and holds what the
call wrote up to the failure:
- An abort undoes no write itself, so the failure keeps what the step that aborted and the steps before it wrote,
except what a rollback removed earlier. A step whose failure its edge expects, a failure its action returned or a
throwable of a type the edge declares, is rolled back whether a route takes the failure or not: an
UnhandledFailureExceptiontherefore lacks the writes of its step and of the steps that step cascaded to. EachCOLLECTelement whose abort the cascade collects is rolled back too, so aCascadeExceptionlacks their writes; an identity whoseequalsorhashCodethrows stops that rollback, which leaves the writes and hops it had not undone. Once a failed cascade poisoned the call, a step whose action still returns or throws such a failure is not rolled back for it: it ends in the failure that poisoned the call and keeps its writes and its hop, unless aCOLLECTcollects that failure, which rolls back the whole element the step ran in. - A
CommitFailedExceptionholds everything the steps wrote. - An
AfterCommitExceptionalso holds what the hooks wrote, the failing hook's writes before it threw included. - When the call records its trail, its flow also lists the hops and starts the call took up to the failure, except
those a rollback removed and the last one when the clock could not read its instant, which fails the call,
followed by a
FlowEntry.Failedentry with the failure, unless the trail's clock threw when the call read that entry's instant, as record the call's trail shows. - A
reevaluatethat fails before it runs an edge, while it reads the state, evaluates its watch or exceeds the limit of a watch chain, hands outFlowView.empty(), unless its machine records its trail: its flow then holds the entity, no value, and theFailedentry alone, or no entry when the clock threw while it read the entry's instant. So does anadvancethat fails while it reads the state or, from aGraphDefinitionwritten by hand, its automatic edges. - Only the failure the call throws carries the call's flow: any other failure of the call holds
FlowView.empty(), such as an element of theerrors()of aCascadeExceptionor aPoisonedUnitOfWorkExceptiona context threw. A call that records no trail and whose steps and hooks wrote nothing to its flow hands outFlowView.empty()too. - An
Errorcarries no flow: it propagates as itself.
With
import io.github.graphmaquina.error.CallFailedException;, this method can be added to the quickstart's App:
static String describe(CallFailedException failure) {
String written = switch (failure.statesWritten()) {
case NONE -> "no state was written";
case PARTIAL -> "some states were written";
case ALL -> "every state was written";
};
// actions may have run even when no state was written
String actions = failure.journal().isEmpty()
? "no action ran"
: failure.journal().size() + " action(s) ran";
return failure.call() + " failed in " + failure.phase() + ": " + written + ", " + actions;
}
statesWritten() describes the setters only: a JPA or other transaction around the call commits or rolls back later,
on its own. Neither the phase nor statesWritten() decides a retry by itself. NONE with an action in the journal
that called a payment service means the payment may have happened although no state moved. Retry only what your
actions make idempotent, and reconcile the rest.
Next: Check an operation before you call it. Back to the documentation index.