ADR 0002: the FulfillmentAssignment aggregate, its invariants and the assumptions the model left open
Status
Accepted (2026-10-23). The ordinal AssignmentCost ordering of A12 is superseded by ADR 0011; everything else stands.
Context
The model (contexts[order-sourcing]) has one aggregate, FulfillmentAssignment
(root assignmentId), eight events, six invariants and nine commands. The Model
Gap Register decisions G5, G10, G12, G13, G14, G20 and G26 and contracts-delta
E1, E9 to E13 change or add to it. This ADR fixes what is built. Assumptions are
numbered and final unless the orchestrator overrules them.
Decision
Aggregate and packages
internal/domain/assignment: the aggregate, statesQUEUED,RELEASED,LOCKED,SHIPPED,DELIVERED,UNSOURCEABLE,CANCELLED; value objectsPromiseConstraint{promiseId, tier, deliverByLatest, witnessNodeId, revisionNo},Candidate{nodeId, pickupDepartureId, pickupCutoffAt, legs[], deliveryWaveId, eta, cost},Release{releaseNo, nodeId, releasedAt, requiredShipBy, outcome, reasonCode},ExcludedNode{nodeId, reason},Line{lineNo, catalogItemId, listingId, quantity}.internal/domain/network: the pure value types and merge rules of the five read models (ADR 0003).internal/domain/sourcing: the pure candidate search, theAssignmentCostpolicy and theVirtualQueuerelease point.internal/domain/shared:Event,Header,ErrValidation,ErrIllegalTransition,ErrInvalidSnapshot, id checks.ErrNotFoundandErrConcurrentUpdateare the repository sentinels ofinternal/application/ports, not domain errors.
Transitions as built
[*] -> QUEUED QueueAssignment
QUEUED -> QUEUED ReoptimiseAssignment (same or other node)
QUEUED -> RELEASED ReleaseToNode
QUEUED -> UNSOURCEABLE ReleaseToNode, ReoptimiseAssignment, QueueAssignment (empty candidate set, A4)
RELEASED -> QUEUED HandleNodeRefusal (a candidate is left)
RELEASED -> UNSOURCEABLE HandleNodeRefusal (none left)
RELEASED -> LOCKED LockAssignment
LOCKED -> SHIPPED MarkShipped
SHIPPED -> DELIVERED MarkDelivered (last package)
QUEUED|RELEASED|UNSOURCEABLE -> CANCELLED CancelAssignment (G10 adds UNSOURCEABLE)
UNSOURCEABLE -> QUEUED ApplyRevisedPromise (G13)
any non-terminal -> same ApplyRevisedPromise (constraint only, G13)
DELIVERED and CANCELLED are terminal.
Invariants and their errors
| Rule | Error (problem slug) | Enforced by |
|---|---|---|
a released candidate's eta <= deliverByLatest | ErrCandidateBreaksPromise (candidate-breaks-promise, 422) | every method that sets a candidate |
| no change of node after LOCKED | ErrAssignmentLocked (assignment-locked, 409) | Reoptimise, Release, RefuseRelease on LOCKED, SHIPPED, DELIVERED |
| a refusing node is not released to again for the same promise revision | ErrNodeExcluded (node-excluded, 409) | every method that sets a candidate |
| at most one release PENDING | ErrReleaseInFlight (release-in-flight, 409) | Reoptimise and Release while RELEASED |
assignmentVersion strictly increases | ErrStaleAssignmentVersion (stale-assignment-version, 409) | the optional caller version of Reoptimise; the repository check raises ErrConcurrentUpdate (A22) |
| cancel only before LOCKED | ErrCancelAfterLock (cancel-after-lock, 409) | Cancel on LOCKED, SHIPPED, DELIVERED |
The aggregate also raises ErrReleaseNotPending (a late outcome of an old
release; the consumer records it and moves on) and wraps ErrValidation and
ErrIllegalTransition of shared.
Assumptions (model gaps)
- A1
assignmentIdisasg-<uuid>minted by the use case; a unique key on (orderId,groupNo) makes a repeatedCustomerOrderPlaceda no-op. - A2
FulfillmentQueuedandFulfillmentDeliveredare "analytics only" in the model; byconventions.analytics_rulethey go ONLY toretailnetwork.order-sourcing.analytics. The other eight go ONLY to.events. - A3 The aggregate keeps
destinationPostalPrefixfromCustomerOrderPlaced(G26). The prefix is matched EXACTLY to aServiceArea.postalPrefix, as node-topology's A11 does. - A4 (G26) The candidate set empties:
QueueAssignment,ReoptimiseAssignment, the release re-check and a refusal all move the assignment toUNSOURCEABLEat once and raiseFulfillmentUnsourceable. At queueing the assignment is first savedQUEUED(FulfillmentQueued) and thenUNSOURCEABLE, in one transaction. ReasonNO_CANDIDATE, orNODE_REFUSEDafter a refusal. - A5 Re-optimising:
RELEASEDisErrReleaseInFlight;LOCKED,SHIPPED,DELIVEREDareErrAssignmentLocked;UNSOURCEABLEandCANCELLEDareErrIllegalTransition(409illegal-transition), the register's shared type. An unknown id isnot-found(404), notassignment-not-found. - A6 (G10)
CancelAssignmentis also legal fromUNSOURCEABLE; the trigger isCustomerOrderCancelledafterPromiseUnkeepablereached customer-ordering. - A7 (G12)
CustomerOrderCancelledis a request. FromQUEUED,RELEASEDorUNSOURCEABLEthe result isFulfillmentCancelled. FromLOCKED,SHIPPEDorDELIVEREDthe aggregate keeps its state, bumps its version and raisesFulfillmentCancelRefused(CANCEL_AFTER_LOCK). A repeated request on aCANCELLEDassignment is a no-op. APurchaseOrderAcceptedthat arrives for aCANCELLEDassignment is recorded and logged, nothing else: the model does not say how to undo the vendor's acceptance (open, see model_gaps). - A8 A multi-package group is
DELIVEREDwhen the LAST of itstrackingNumbersis delivered (contracts-delta E1); eachPackageDeliveredis remembered;deliveredAtis the last package's. A tracking number that is not on the shipment isErrValidation(logged by the consumer). - A9 (G13)
ApplyRevisedPromiseapplies in every non-terminal state whenrevisionNois higher than the applied one (else ignored). It replacesdeliverByLatestandwitnessNodeIdwhen present, resets the node exclusions, and ALWAYS raisesFulfillmentConstraintRevised. InUNSOURCEABLEit re-queues when a candidate exists and otherwise staysUNSOURCEABLEsilently (no secondFulfillmentUnsourceable, delivery-promise answers withPromiseUnkeepable). InQUEUEDit re-searches (a changed node raisesFulfillmentReassignedwith reasonPROMISE_REVISED; an empty set isUNSOURCEABLE). InRELEASED,LOCKEDandSHIPPEDonly the constraint changes: the node already committed. - A10 Exclusions are scoped to the promise revision (
revisionNo, initially 0). - A11 Candidate search (
sourcing.Search): a node is eligible when it is anACTIVEFULFILLMENT_CENTERof operatorVENDORwith a declared profile and every line in full (listing present, not suppressed, item not discontinued,availableQty >= quantity). The pickup is a non-cancelled, non-full departure originating at the node withcutoffAt >= now + handlingTime, on an OPEN or unknown lane. From the pickup, onward departures leave the arrival node withcutoffAt >= arrival + sortDwell(0 when undeclared), at most 5 departures per path, no node visited twice, until the destination's delivery station (fromServiceAreaAssigned) is reached; then the earliest non-cancelled wave with remaining stops andinductCutoffAt >= arrivalgiveseta = windowEnd.SAME_DAYneeds subtypeSUB_SAME_DAYorMICROand a pickup that goes straight to the station (no legs). One candidate per (node, pickup departure), the cheapest path.legsare the departure ids after the pickup. - A12
AssignmentCostin integer cost points: 100 per departure after the pickup, plus 10 per hour from the pickup departure to the wave start (rounded down), plus 1000crossRegionPenaltywhen the node's region differs from the destination's, plus the scorecard penalty (A15), plus 500bookPressurePenalty(A16). Ties: the witness node, then the lowernodeId, then the lower pickup departure id. - A13
vendorAckBudgetis 30 minutes (the worked example of the model).releaseAt = max(now, pickupCutoff - handlingTime - ackBudget);SAME_DAYreleases immediately (releaseAt = now). - A14 Reason vocabularies are in ADR 0004.
ExcludedNode.reasonisREJECTED:<reasonCode>orEXPIRED;Release.reasonCodeis the vendor's. - A15 (G20) Scorecard penalty from the
30dwindow only: A 0, B 50, C 200, D 500;PROVISIONALand a missing scorecard 0. The7dwindow is stored and ignored. - A16 The book-pressure view is binary: a
PromiseBookExhaustedfor (nodeId,pickupDepartureId) adds the penalty to candidates that use exactly that node and pickup. Nothing clears it before the departure passes. - A17 (G14)
BookingMovedpoints aLOCKEDassignment'spickupDepartureIdat the new departure (no event; the node never changes).BookingFailedis recorded and logged; the revision that delivery-promise issues is applied by A9. - A18 The release timer and the re-optimisation sweep run inside the service
(
SWEEP_INTERVAL, default 30 s; each pass handles a bounded batch ofQUEUEDrows ordered byreleaseAt). Several instances may run: the version check turns a race intoErrConcurrentUpdate, the loser skips the row. - A19 Linehaul's
BookingMovedandBookingFaileduse entitydeparturein the type; the producer has not published its AsyncAPI yet. Re-check later. - A20 (G5)
DeliveryWaveCancelledis an integration event of last-mile (wave), consumed intoNetworkGraphView. - A21 Bounds: at most 200 lines per group, quantities 1 to 2147483647, ids
1 to 64 characters,
groupNo1 to 2147483647 (plain literal constants). - A22
ErrStaleAssignmentVersionis a caller version mismatch (REST bodyassignmentVersion);ErrConcurrentUpdateis the repository's compare and swap failure. A Kafka-driven use case retries once onErrConcurrentUpdatefrom a fresh load, then lets the consumer redeliver. - A23
PromiseRevised.nodeIdis the new witness node and optional; absent keeps the witness. - A24 (ADR 0011) The World and the request carry no package count
(
Line.Quantitycounts order units), so the money-denominated estimate is the per-unit sum; multiplying bypackagesPerOrderwaits for a package count on the promise or the order.
Consequences
- Every rule above has a table-driven test;
Restorere-validates all of them. model.yamlis not edited; the orchestrator back-fills the model from the final report.
Addendum 2026-11-13: current state
- A18 gives
SWEEP_INTERVALa default of 30 s. The code default is 15 s:defaultSweepInterval = 15 * time.Secondincmd/api/main.go, used byparseSweepIntervalincmd/api/main_workers.go. It has been 15 s since the composition root was added (commit 405dce8, 2026-10-23). - ADR 0005 (item 4, queue sweep),
README.mdanddocs/docs/operations/configuration.mdstate the 15 s default. The Helm valueconfig.sweepIntervalrenders nothing when empty, so the binary default applies (charts/order-sourcing/values.yaml).