Cancellation reasons belong to the path, not the caller
When an order gets cancelled, two different pieces of code want the reason. One is the guard that decides whether this actor may cancel for that reason at all. The other is the timeline, which has to explain the cancellation to somebody reading it a month later. Most systems split those jobs, a validation list somewhere near the API and a free-text note on the record, and the history that comes out cannot be grouped, because every row is a sentence somebody typed by hand.
In order-lifecycle (github.com/shipmindlabs/order-lifecycle) both jobs live in the same declaration. A cancellation path names the state it leaves, the actor allowed to fire it, where the order lands, what follows, and the reasons it accepts. That list is the check and the wording at once.
The constraint that made it hard#
Cancellation is not one rule. The actor that may cancel changes with the state, and the set of reasons that makes sense there changes with it. A customer cancelling an unshipped paid order picks from a short menu. A warehouse rejecting the same order picks from a different short menu. A courier failing a delivery is on a third one, and the order does not even end up in the same state. Meanwhile the write-off of an item that came back unsellable has no menu at all, since nobody can enumerate in advance why a returned thing is worthless.
So the vocabulary has to be per-path, and it has to be allowed to be empty without that meaning "no reason required".
The declaration#
A path is a frozen dataclass. reasons sits next to roles and conditions, in the same table:
from order_lifecycle import (
CHANGED_MIND,
COURIER,
CUSTOMER,
DAMAGED,
DUPLICATE,
OUT_OF_STOCK,
SUPPORT,
UNDELIVERABLE,
WAREHOUSE,
CancellationPath,
CancellationPolicy,
)
POLICY = CancellationPolicy(
(
CancellationPath(
PAID,
CANCELLED,
CANCEL,
roles={CUSTOMER, SUPPORT},
reasons=(CHANGED_MIND, DUPLICATE),
follow_up=refund,
),
CancellationPath(
PAID,
CANCELLED,
REJECT,
roles=WAREHOUSE,
reasons=(OUT_OF_STOCK, DAMAGED),
follow_up=(refund, restock),
),
CancellationPath(
SHIPPED,
RETURNED,
FAIL,
roles=COURIER,
reasons=(UNDELIVERABLE, DAMAGED),
follow_up=collect_parcel,
),
CancellationPath(RETURNED, CANCELLED, CANCEL, roles=WAREHOUSE),
)
)Four rows, four different answers to "why". The last one declares nothing, which is the open vocabulary. Notice too that DAMAGED appears twice: the same code means the same thing whether the warehouse found it before hand-over or the courier did, and that is what a shared constant buys you over two separate strings.
A path refuses a terminal source state at construction time. There is no cancelling a delivered order, and that counts as a declaration error rather than a runtime refusal.
The check: match by code, so a constant and a string are interchangeable#
Whatever the caller hands over gets normalized first. as_reasons accepts one reason, a bare code, or any iterable of either, in order, and defaults to the empty tuple:
from order_lifecycle.cancellation import as_reason, as_reasons
as_reasons(None) # -> ()
as_reasons(CHANGED_MIND) # -> (CHANGED_MIND,)
as_reason("out_of_stock") # -> CancellationReason(code='out_of_stock', detail='')
as_reasons((OUT_OF_STOCK, "damaged")) # -> two reasons, in that orderThat as_reason("out_of_stock") is not the OUT_OF_STOCK constant, because it has no detail, and equality would reject it. So matching runs on code alone: the path takes the caller's code, from a CancellationReason or from a stripped string, and compares it against each declared candidate in declaration order. A caller that keeps an HTTP form field and posts reason="duplicate" behaves exactly like one that imported DUPLICATE, which is what makes the thing usable from an API boundary without a translation layer.
A code that is not on the list is refused, and so is a missing one:
POLICY.cancel(Machine(TABLE, PAID), role=CUSTOMER, reason="duplicate")
# -> cancelled
POLICY.cancel(Machine(TABLE, PAID), role=CUSTOMER, reason=OUT_OF_STOCK)
# ReasonNotAccepted: cancelling 'paid' with trigger 'cancel' requires one of:
# changed_mind, duplicate; reason 'out_of_stock' is not one of them
POLICY.cancel(Machine(TABLE, PAID), role=CUSTOMER)
# ReasonNotAccepted: ... requires one of: changed_mind, duplicate;
# no reason was givenOUT_OF_STOCK is a perfectly valid reason in the state paid, on the warehouse's path, under the REJECT trigger. The actor is what makes it wrong here, and the error carries the accepted codes so a client does not have to guess what the menu was.
The ordering inside CancellationPolicy.cancel matters more than it looks: resolve the path, run accept on the reason, and only then call machine.apply(..., reason=recorded). A refused reason never reaches the machine, so no before hook ran, no follow_up fired, and nothing was appended to the history. A rejected cancellation leaves no trace of having been attempted, and the refusal is free.
The record: the declaration owns the sentence#
A CancellationReason carries a code and an optional detail, and exposes the phrase a history entry should quote:
@dataclass(frozen=True, slots=True)
class CancellationReason:
code: str
detail: str = ""
@property
def sentence(self) -> str:
return self.detail or self.code.replace("_", " ")When a code matches, accept returns found.sentence, the sentence of the declared reason rather than the one that was passed in. So every order cancelled under CHANGED_MIND gets the same line in its timeline:
machine = POLICY.cancel(Machine(TABLE, PAID), role=CUSTOMER, reason=CHANGED_MIND)
machine.history.last.reason
# 'the customer no longer wants the order'The same rule has a sharp edge. A caller that constructs CancellationReason("damaged", "box crushed in transit") has its detail dropped. The code matches, so the entry records what DAMAGED declares, 'the goods were damaged before hand-over'. The caller's wording loses on purpose. The entry gets quoted in a timeline rendered as <timestamp> paid --reject--> cancelled by <actor>: <sentence>, and that line is the one a support agent, an auditor and a report all read. It should not depend on who was typing.
That is the trade we are making explicitly: wherever a vocabulary exists, the caller may choose from it but may not reword it.
An open vocabulary where nothing can be enumerated#
The last path in the policy declares no reasons, and accept then takes the other branch: an empty string for None, and str(reason) otherwise, which for a CancellationReason is its sentence and for a bare string is the string.
machine = POLICY.cancel(Machine(TABLE, RETURNED), role=WAREHOUSE, reason="unsellable")
machine.history.last.reason
# 'unsellable'That is probably the right shape for a write-off. Nobody is going to produce the complete list of ways a returned item can be worthless, and a closed list that is wrong is worse than no list, because it pushes the real reason into a comment field, or into other. An open path also accepts a missing reason and records an empty string, because "required" is a property of the vocabulary and there isn't one here.
The offer is read off the same declaration#
Because the reasons are data, the menu the UI renders and the list the check enforces cannot drift apart:
POLICY.reasons_for(PAID, role=CUSTOMER) # -> (CHANGED_MIND, DUPLICATE)
POLICY.reasons_for(PAID, role=WAREHOUSE) # -> (OUT_OF_STOCK, DAMAGED)
POLICY.reasons_for(PAID) # -> () guarded path, no role supplied
[str(path) for path in POLICY.available(SHIPPED, role=COURIER)]
# ['shipped --fail--> returned [courier] (undeliverable, damaged) -> collect parcel']reasons_for answers for one state and actor, while CancellationPolicy.reasons collects every declared reason across the policy once, so the full set of sentences an order's timeline can ever contain is enumerable before a single order exists. A conditional path drops out of both listings when its conditions are not met, with the conditions unevaluated if no context was supplied. The offer is exactly what cancel would accept for the same arguments, including nothing.
What it costs to run#
Three costs, all real.
First, the caller's wording is lost on any path with a vocabulary. If the operational detail genuinely matters, a parcel photo reference or a carrier's own failure string, it does not belong in the reason. It belongs wherever the order keeps its payload, and the reason stays the classification.
Second, the history stores the reason as text, not as a code. What makes the history groupable is that the text is declaration-owned, so identical sentences mean identical codes. The flip side is that changing a reason's detail does not rewrite entries already appended: the history is append-only, so a wording change splits the group at the moment of deployment. If reporting has to survive that, group on the sentences as they were, or keep the code alongside the order.
Third, somebody has to maintain the per-path lists, and the temptation is to declare one global menu and be done. We have not found that worth it. The menu is the thing that differs per state and actor; collapsing it means reintroducing the validation branch the table was meant to remove, and then the error message can no longer tell a caller what it should have sent.
The gain is narrow and it holds: a refused reason costs nothing and names the alternatives, and every cancellation for the same code reads identically in every order's timeline. One declaration does both, and that is why they stay consistent.