ADR 0002: the DeliveryWave, Route, DeliveryServicePartner and PackageAttemptHistory aggregates, their invariants and the assumptions the model left open
Status
Accepted (2026-10-23).
Context
The model (retail-network-docs model/model.yaml, context last-mile-delivery)
gives three aggregates (DeliveryWave, Route, DeliveryServicePartner), nine
invariants-with-names and six published events. The Gap Register items G5, G11,
G16, G17 and G34 and the orchestrator's contracts-delta (E5, E10, E15) change or
complete them. This ADR is the record of what is built and of every assumption
the model and the register leave open. Assumptions are numbered A1.. and are final
unless the orchestrator overrules them.
Decision
Packages and aggregates
| Package | Aggregate (root id) | States | Raises |
|---|---|---|---|
internal/domain/wave | DeliveryWave (waveId) | OPEN, INDUCTION_CLOSED, DISPATCHED, COMPLETED, CANCELLED | DeliveryWaveScheduled, DeliveryWaveCapacityChanged, DeliveryWaveCancelled |
internal/domain/route | Route (routeId) | PLANNED, OUT_FOR_DELIVERY, COMPLETED | RoutePlanned, PackageOutForDelivery, DeliveryAttempted |
internal/domain/partner | DeliveryServicePartner (dspId) | ACTIVE, INACTIVE | none |
internal/domain/history | PackageAttemptHistory (trackingNumber) | AT_STATION, INDUCTED, DELIVERED, RETURN_INITIATED | PackageInductionDeferred, PackageReturnInitiated |
internal/domain/shared | none | none | the Event interface, Header, shared errors, id and text checks |
Every aggregate is pure Go (no I/O; clock and id are passed in), has a
Snapshot/Restore pair (Restore re-validates every invariant and returns
shared.ErrInvalidSnapshot on a corrupt row) and an optimistic version: a
create is version 1, every command adds one, and a repository saves only when the
stored version is Version()-1.
Transitions
- DeliveryWave: ScheduleWave creates OPEN; OPEN -> INDUCTION_CLOSED (CloseInduction);
INDUCTION_CLOSED -> DISPATCHED (DispatchWave); DISPATCHED -> COMPLETED
(CompleteWave); OPEN -> CANCELLED (CancelWave). InductPackage keeps OPEN and adds
an induction. Every other (state, command) pair is
ErrIllegalTransition, except InductPackage, which isErrInductionClosedin any state but OPEN. - Route: PlanRoute creates PLANNED; PLANNED -> OUT_FOR_DELIVERY (StartRoute); OUT_FOR_DELIVERY -> COMPLETED (CompleteRoute). RecordAttempt keeps OUT_FOR_DELIVERY (and completes the route when it records the last package).
- DeliveryServicePartner: ContractPartner creates ACTIVE; ACTIVE -> INACTIVE (DeactivatePartner, G34).
- PackageAttemptHistory: Arrive creates INDUCTED or AT_STATION; AT_STATION -> INDUCTED (Place); INDUCTED -> AT_STATION (Unplace); INDUCTED -> INDUCTED or AT_STATION or RETURN_INITIATED (RecordFailure); INDUCTED -> DELIVERED (RecordDelivered).
Invariants (the model's Err names, plus the ones this ADR adds)
| Error | Aggregate | Rule | HTTP problem |
|---|---|---|---|
ErrInvalidWaveTimes | wave | inductCutoffAt < windowStart < windowEnd | 422 invalid-wave-times |
ErrWaveFull | wave | assigned stops <= stop capacity | 409 wave-full (policy only) |
ErrInductionClosed | wave | no package joins after induction closes (or after the cutoff) | 409 induction-closed (policy only) |
ErrRouteOverCapacity | route | stops <= the partner's van capacity | 409 route-over-capacity |
ErrRouteNotStarted | route | an attempt only on an OUT_FOR_DELIVERY route | 409 route-not-started |
ErrAlreadyDelivered | route, history | a package is delivered at most once | 409 already-delivered |
ErrInvalidVanCapacity | partner | van capacity > 0 | 422 invalid-van-capacity |
ErrUnknownStation | use case (StationView) | the node is a known DELIVERY_STATION (A1) | 422 unknown-station |
ErrPackageNotOnRoute | route | the attempted package is on the route | 404 package-not-on-route |
ErrAttemptAlreadyRecorded | route | one attempt per package per route | 409 attempt-already-recorded |
ErrPackageNotInducted | route | a route holds only packages inducted in its wave (G34) | 409 package-not-inducted |
ErrPackageAlreadyRouted | route | a package is on at most one route of a wave | 409 package-already-routed |
ErrStopKeyMismatch | route | the packages of one stop share one stopKey (G11) | 409 stop-key-mismatch |
ErrPartnerInactive | route | a route is given only to an ACTIVE partner | 409 partner-inactive |
ErrPartnerStationMismatch | route | the partner works for the wave's station | 409 partner-station-mismatch |
ErrRouteIncomplete | route | a route completes only when every package has an attempt | 409 route-incomplete |
shared.ErrValidation | all | a value-object rule | 422 validation-failed |
shared.ErrIllegalTransition | all | the command is not allowed from the current state | 409 illegal-transition |
ports.ErrConcurrentUpdate | repository | version mismatch | 409 concurrent-update |
ports.ErrNotFound | repository | an addressed aggregate does not exist | 404 not-found |
Assumptions (where the model and the register are silent)
- A1 (G34)
ScheduleWaveandContractPartnerrequirestationNodeIdto be aDELIVERY_STATIONin theStationViewread model (the pack lists the check though no invariant requires it). An unknown or non-station id isErrUnknownStation(422). The check lives in the use case because the view is an application read model. - A2
serviceDateis the station's local calendar date. It is validated as aYYYY-MM-DDdate and not cross-checked againstwindowStartand the station's time zone. - A3
stopCapacityis an integer from 0 to 2147483647 (a plain literal bound for the Postgresinteger); zero is allowed (the model's OpenAPI minimum). - A4 (G11) Capacity is counted in STOPS, not packages:
assignedStopsis the number of distinctstopKeys among the wave's inductions. A package joining a stop already in the wave adds no stop, so it raises noDeliveryWaveCapacityChanged. A package with no label data is its own stop with the keypkg:<trackingNumber>. - A5
InductPackageis accepted only when the wave is OPEN and the instant is beforeinductCutoffAt, elseErrInductionClosed; a new stop on a full wave isErrWaveFull; the same tracking number twice in one wave is the internalErrAlreadyInducted, which the use case treats as a no-op. - A6 Eligible wave search (policy InductOnArrival): the OPEN waves of the
package's station whose
inductCutoffAtis after the instant, ordered byinductCutoffAtthenwaveId; the first that accepts wins;ErrWaveFullandErrInductionClosedmove on to the next wave;ErrConcurrentUpdateretries the whole attempt once (thetransacthelper of node-topology). - A7 The instant of an induction is
arrivedAtforLoadArrived, the attempt'satfor a failed attempt, and the clock's now for a wave cancel, a dispatch leftover and the deferred sweep. - A8
LoadArrivedis acted on when itsnodeTypeisDELIVERY_STATION; whennodeTypeis absent (a producer that predates contracts-delta E3) theStationViewdecides; anything else is ignored. - A9 (G34) A wave completes (DISPATCHED -> COMPLETED) in the same transaction in which its last route completes (every route of the wave COMPLETED). A wave dispatched with no route has nothing to run and completes at once, so the dispatch response may show COMPLETED.
- A10 (G17)
CancelWavestays OPEN -> CANCELLED only (the model's transition); a reason of 1 to 200 characters is required. In the same transaction every package inducted in the wave is re-inducted onto the next eligible wave (A6, A7); a package with no eligible wave is unplaced (A19). The cancelled wave keeps its induction list as a record. - A11
DispatchWavere-inducts, by the same mechanism, the packages inducted in the wave that no route of the wave holds (they would otherwise be stranded). - A12 (G34)
PlanRouterequires: the wave INDUCTION_CLOSED (ErrIllegalTransitionotherwise), the partner ACTIVE (ErrPartnerInactive) and of the wave's station (ErrPartnerStationMismatch), stop numbers 1..n without gaps or duplicates, a tracking number at most once per route, every package inducted in the wave (ErrPackageNotInducted) and on no other route (ErrPackageAlreadyRouted), and one stopKey per stop (ErrStopKeyMismatch). The van capacity is read once at planning; a later partner change re-checks nothing. - A13
Route.stationNodeIdis copied from the wave at planning. - A14
StartRouterequires the route's wave to be DISPATCHED (ErrIllegalTransitionotherwise); the use case reads the wave, it does not change it. - A15
RecordAttemptaccepts one attempt per package per route: a second after a DELIVERED isErrAlreadyDelivered, after a FAILEDErrAttemptAlreadyRecorded.failureReasonis free text (the model defines no vocabulary) of 1 to 200 characters, required when FAILED and forbidden when DELIVERED.atmust not be zero and is stored in UTC; it is not compared with the start of the route. - A16 (G34) A route completes (CompleteRoute, a second save in the same unit of
work) right after the attempt that records its last outstanding package (policy
CompleteRouteOnLastAttempt);
CompleteRoutetherefore has no REST operation, and the domain refuses it withErrRouteIncompletewhile a package has no attempt. A route whose driver never records every package stays OUT_FOR_DELIVERY (listed inmodel_gaps). - A17 (G17) A stop's outcome is derived: unset until every package of the stop has an attempt, then DELIVERED when all were delivered, else FAILED.
- A18 (G16)
PackageAttemptHistoryis a fourth aggregate, one per tracking number (entitypackageattempthistory), created when the package first reaches the station. It counts failed attempts;MaxFailedAttemptsis 3: the third failure raisesPackageReturnInitiatedand ends in RETURN_INITIATED without re-induction. DELIVERED and RETURN_INITIATED are terminal; a later arrival of the package is ignored. A package already INDUCTED ignores a repeated arrival. - A19 (G16)
PackageInductionDeferredis raised each time a package that is at the station finds no wave: on arrival, after a failed attempt, after a wave cancel and for a dispatch leftover. The package is then AT_STATION. Policy InductDeferredOnSchedule: when a wave is scheduled, the AT_STATION packages of its station are inducted into it, oldest arrival first, until the wave is full; a package that still finds no wave raises nothing again. - A20 (G16)
assignmentIdonPackageInductionDeferredis copied from the package'sLabelIssued(therm_package_stopsread model) when the history is created, and omitted when no label data was received. - A21 Idempotency (D3):
idempotency_keyskeyed by (route, key), TTL 24 h; only a 2xx response is stored and replayed; a key reused with a different request body is422 validation-failed. - A22 Streams:
RoutePlannedgoes ONLY to.analytics; all other published events go ONLY to.events(includingDeliveryWaveCancelled, G5). - A23 Subject and Kafka key:
waveIdfor wave events,routeIdfor route events,trackingNumberfor history events. - A24 Wire types: ids and tracking numbers are strings; instants RFC 3339 UTC
strings;
serviceDatea date; counts integers;outcomeDELIVERED|FAILED; optional fields omitted. They are written inapis/asyncapi.yamlandapis/openapi.yaml. - A25
DeactivatePartneris ACTIVE -> INACTIVE only (no reactivation, no event); an INACTIVE partner is given no new route, planned routes are unaffected. - A26 REST additions to the model's list (documented in
apis/openapi.yaml):GET /waves/{waveId}/stops(stops grouped by stopKey, G11),POST /waves/{waveId}/cancellations(G17),GET /routes/{routeId},POST /partners/{dspId}/deactivations(G34). - A27 Ids are minted as a prefix and a UUID v4 (
wave-,route-,dsp-); the opaque id check allows 1 to 64 characters ofA-Z a-z 0-9 . _ : -. - A28
ServiceAreaAssignedis consumed intorm_station_service_areasas the model says, but no decision of this context reads it yet. - A29 A wave's inductions are stored with the wave (one row per package); a wave holds at most one stop per unit of capacity and any number of packages per stop, so its size is bounded by the packages a station receives per wave.
- A30 The planner may declare what ONE stop on a wave costs, in integer cents
(roadmap F7, provider B; ADR 0011):
DeclareCoston a running wave raisesWaveCostDeclared, 0 is a declared zero and an undeclared wave also reads 0 — telling the two apart is the consumer's problem, not the wave's. - A31 The planner may declare the greenhouse emission of ONE stop on a
wave, in grams of CO2 equivalent (roadmap C9, provider; ADR 0016):
DeclareEmissionon a running wave raisesWaveEmissionDeclared, 0 is a declared zero and an undeclared wave also reads 0 — telling the two apart is the consumer's problem, not the wave's. - A32 (addendum to A21, 2026-11-15) A21's idempotency sentence is superseded by
ADR 0010 and no longer describes
what is shipped. The key is global, not scoped by route:
idempotency_keyshas the key alone as its primary key (migration0002) and the fingerprint is method + path + SHA-256 of the body. A key reused with a different method, path or body is 409idempotency-key-reused, not422 validation-failed. A 2xx and a 4xx answer are stored and replayed for 24 h withIdempotency-Replayed: true; a 5xx, an error or a panic is never stored, so the retry re-executes. The TTL is unchanged. (apis/openapi.yaml,internal/adapters/inbound/http/idempotency.goand theidempotency-key-reusedscenarios infeatures/already say so.)
Consequences
- Every rule above has a table-driven domain test; the transitions are tested both ways (legal and illegal).
- The policies that touch several aggregates (re-induction, wave completion, deferred sweep) run in ONE unit of work with the outbox, so a crash cannot lose a failed attempt or a deferral.
- The orchestrator is asked to back-fill the model with: the fourth aggregate, the
four REST additions,
DeactivatePartner, the two G16 events and the stop-based capacity.