ADR 0002: the Node, Lane, ServiceArea and Region aggregates, their invariants and the assumptions the model left open
Status
Accepted (2026-10-23). Design source: retail-network-docs model/model.yaml,
context node-topology (aggregates, node_types, lane_rules) and the pack
pages aggregate-design-canvas, use-cases and domain-events.
Context
The model gives four aggregate roots, each its own transaction boundary:
Node, Lane, ServiceArea and Region. Three invariants span aggregates
(vendor node code, open lane per triple, region code) and four more read a
second aggregate (lane endpoints, service-area station and region, node region).
The model is silent on a number of details; every one the implementation had to
decide is an assumption below, flagged A<n>, and is also reported to the
orchestrator as a model gap. The model is not edited here.
Decision
Layout and conventions
internal/domain/{shared,region,node,lane,servicearea}. Pure Go: no I/O,time.Nowand id generation are never called;nowand ids are passed in. Dependency direction:region<-node<-lane,servicearea; everything may useshared.sharedholds what more than one aggregate raises or implements:ErrValidation(problemvalidation-failed, 422),ErrIllegalTransition(problemillegal-transition, 409),ErrInvalidSnapshot(a persisted row that breaks an invariant; an internal error, never a client error) and theEventinterface.ErrNotFoundis NOT a domain error: it is the port sentinelports.ErrNotFoundof the application layer (step 2).ErrConcurrentUpdateis raised by the repository on a version mismatch, also not by the domain.- Each aggregate has a constructor or command method per model command, a
Snapshot()and a validatingRestore(Snapshot), and aVersion()for optimistic concurrency. A command returns the raised events;Version()after the command is the version the events carry, and the repository stores with the expectationstored version == Version()-1(0for a create). Events are typed structs whose fields are exactly the model'sdatalist (ADR 0004). - The node-type table (
node_types: operators, capabilities, subtypes) and the lane-pair table (lane_rules.allowed) are typed tables in the domain, each row pinned by a test against the model's values.
Node
States PROPOSED, ACTIVE, SUSPENDED, RETIRED; transitions (command): PROPOSED -> ACTIVE
(ActivateNode), ACTIVE -> SUSPENDED (SuspendNode), SUSPENDED -> ACTIVE
(ActivateNode), ACTIVE -> RETIRED and SUSPENDED -> RETIRED (RetireNode).
DeclareOperationalProfile changes no state and is accepted in PROPOSED,
ACTIVE and SUSPENDED. A transition not in the table raises
ErrIllegalTransition, except any command on a RETIRED node, which raises
ErrNodeRetired.
| Invariant | Err | Enforced by |
|---|---|---|
| operator allowed for the node type (parcel nodes are NETWORK-operated) | ErrOperatorNotAllowedForNodeType | node.Register |
vendorNodeCode unique per vendor | ErrVendorNodeCodeTaken | repository unique index (vendor_id, vendor_node_code); the use case pre-checks (A10) |
| profile revision strictly increases | ErrStaleProfileRevision | Node.DeclareProfile |
FULFILLMENT_CENTER has at least one cutoff and handlingTime > 0 before activation, and every later revision of an ACTIVE one keeps both | ErrIncompleteOperationalProfile | Node.Activate, Node.DeclareProfile |
| every day of a cutoff falls inside that day's operating hours | ErrCutoffOutsideOperatingHours | NewOperationalProfile |
regionId names a defined Region | ErrUnknownRegion | node.Register (given the *region.Region the use case loaded; nil or a different id means unknown) |
subtype, when given, is one of the type's subtypes | ErrSubtypeNotAllowed | node.Register |
sortDwellMinutes only for SORTATION_CENTER and AIR_HUB | ErrSortDwellNotAllowed | Node.DeclareProfile |
| RETIRED is terminal | ErrNodeRetired | every command |
Capabilities are derived from the node type and never stored or accepted
(DefaultCapabilitiesByType). AcceptsDemand() is true only for an ACTIVE node
with the OUTBOUND capability (business decision 2).
Check order in Register: enumerations valid; operator allowed; remaining value
checks (id, vendor reference, time zone, location); region; subtype. In
DeclareProfile: retired; revision stale; profile shape and cutoff windows;
completeness of an ACTIVE fulfillment centre; sort dwell.
Lane
States OPEN, CLOSED; transition OPEN -> CLOSED (CloseLane); no reopen.
| Invariant | Err | Enforced by |
|---|---|---|
| origin and destination differ | ErrLaneLoop | lane.Open |
(origin type, destination type) is in lane_rules.allowed | ErrLaneTypePairNotAllowed | lane.Open |
| both ends ACTIVE when opening | ErrLaneEndpointNotActive | lane.Open (a nil end counts as not active) |
| at most one OPEN lane per (origin, destination, mode) | ErrDuplicateLane | repository partial unique index; the use case pre-checks (A10) |
Order: values valid; loop; type pair; endpoints active. Closing an already
CLOSED lane raises ErrIllegalTransition.
ServiceArea
One state ASSIGNED (initial); transition ASSIGNED -> ASSIGNED (AssignServiceArea).
The first assignment creates the aggregate; later ones call Reassign.
| Invariant | Err | Enforced by |
|---|---|---|
| the assigned node is an ACTIVE DELIVERY_STATION | ErrNotADeliveryStation | servicearea.Assign, Reassign (a nil station counts as not one) |
| assignment version strictly increases | ErrStaleAssignmentVersion | Reassign (and Assign: version must be >= 1) |
| the region is a defined Region and equals the station's region | ErrUnknownRegion | Assign, Reassign (given the *region.Region the use case loaded) |
Order: prefix and version valid; station; version; region. The region of the prefix is taken from the station, never from the caller.
Region
One state DEFINED (initial); no transition.
| Invariant | Err | Enforced by |
|---|---|---|
| region code unique | ErrRegionCodeTaken | repository unique index on code; the use case pre-checks (A10) |
Assumptions (the model is silent)
- A1 Time zone. The domain checks the shape of an IANA name (
Area/Location, letters, digits,_,-,+), not that the host tz database knows it: resolving it is I/O and belongs to the HTTP adapter if wanted. - A2 Vendor reference. A
VENDORnode needs avendorRefwith a non-blankvendorIdandvendorNodeCode; aNETWORKnode must not carry one. Violations areErrValidation. Operator is checked against the type first, so a NETWORK operator on a fulfillment centre isErrOperatorNotAllowedForNodeType, not a missing reference. - A3 Profile time zone.
Node.timezoneis fixed at registration. A profile declares its owntimezoneand the domain does not require it to equal the node's. (Model gap: should it?) - A4 Cutoff window. A day's hours are same-day
start < end(no overnight shift); a cutoff is inside whenstart <= localTime <= end(both ends inclusive). A cutoff withoutdaysapplies to every operating day; if the node has no operating day at all, that cutoff is outside the operating hours (ErrCutoffOutsideOperatingHours). Two cutoffs with the samelocalTimeand an overlapping effective day set areErrValidation(one pickup departure per cutoff). Holidays do not remove a weekday from the cutoff check. - A5 Completeness scope. Only a FULFILLMENT_CENTER needs cutoffs and a handling time above zero. Any other node type may be activated with no profile at all, and a profile may carry zero cutoffs. A PROPOSED or SUSPENDED fulfillment centre may hold an incomplete profile; re-activation re-checks the current one.
- A6 Declared by.
declaredByVENDORis refused (ErrValidation) for a NETWORK-operated node;NETWORK_OPSmay declare any node's profile. - A7 Profile values.
profileRevision,handlingTimeMinutes,sortDwellMinutes,maxOrders, throughputvalue,nominalTransitMinutesandassignmentVersionare bounded above by the literal2147483647(Postgresinteger);handlingTimeMinutesandsortDwellMinutesare >= 0;maxOrdersand the cap are >= 1;throughputCap.unitmust beORDER;holidaysare ISOYYYY-MM-DDdates, stored sorted, duplicates refused. - A8 Suspend reason.
reasonis required (non-blank) on SuspendNode. - A9 Wire types.
datais camelCase;subtype,vendorIdandvendorNodeCodeofNodeRegisteredare JSONnullwhen not applicable;sortDwellMinutes, cutoffdaysandmaxOrdersare omitted when unset (ADR 0004,apis/asyncapi.yaml). - A10 Cross-aggregate uniqueness. One aggregate cannot know its siblings, so
ErrVendorNodeCodeTaken,ErrDuplicateLaneandErrRegionCodeTakenare declared in the domain and raised by the repository when its unique index is violated (the use case pre-checks for a friendlier path). The model names the indexes in the canvas. - A11 Identifiers. Ids (
nodeId,laneId,regionId) are opaque strings the application mints: 1 to 64 characters fromA-Z a-z 0-9 . _ : -, starting with a letter or digit.vendorIdandvendorNodeCodeare trimmed non-blank strings of at most 100 characters. A postal prefix is 1 to 16 characters fromA-Z 0-9 -(uppercase only, never normalised) and is matched exactly: the model says nothing about overlapping prefixes such as01and013, so none is resolved. - A12 Region.
codeis 1 to 16 characters fromA-Z 0-9 _ -;nameis non-blank, trimmed, at most 120 characters. - A13 Location.
postalCodeis non-blank, at most 20 characters;countryCodeis two uppercase letters;latin [-90, 90] andlonin [-180, 180], both or neither. - A14 Lane modes. The model gives modes
GROUNDandAIRbut no rule tying a mode to a type pair, so any mode is allowed on any allowed pair. A closed lane is never reopened; a new lane gets a new id and a newLaneOpened. - A15 Reassignment.
Reassignmay name the same station again under a higher version (it still raisesServiceAreaAssigned). Closing a lane and reassigning a prefix do not require the endpoints to still be ACTIVE (SuspendedEndpointsUnusableleaves them as they are). - A16 Unknown references. An unknown node or station id is
ErrNotFound(404) decided by the use case before the domain runs, as the OpenAPI says; the domain'sErrUnknownRegioncovers a region that does not exist for a node body or a station.
Consequences
- Every invariant above has a table-driven test, including the illegal order combinations; the node-type and lane-pair tables are pinned row by row.
- The use cases of step 2 must load the sibling aggregate they pass in
(
*region.Region,*node.Node) and translate a missing one toErrNotFound. - The three repository-raised errors need the Postgres unique indexes of step 3 and a repocontract test for each.
Amendment (step 2, application layer): assumptions A17-A24
Step 2 adds internal/application/{ports,views,usecases,repository} and the
test doubles in internal/adapters/outbound/memory. The model and OpenAPI are
silent on the points below; each is an assumption and is reported as a model gap.
- A17 Retry on conflict. ADR 0003 decision 4 says a version mismatch is
retried once by reloading. It is implemented in the use cases: when a unit of
work fails with
ports.ErrConcurrentUpdate, the whole attempt (load, domain call, save, outbox append) runs once more on fresh state; a second conflict is returned asErrConcurrentUpdate(409). A create re-mints its id on the retry. - A18 Save contract.
Saveexpectsstored version == aggregate.Version()-1(a create expects the id to be free). Creating an id that exists, and updating a row that no longer exists, are bothErrConcurrentUpdate. The repository raisesErrVendorNodeCodeTaken,ErrDuplicateLaneandErrRegionCodeTakenfrom its unique indexes after the version check. - A19 Outbox port.
EventOutbox.Append(ctx, events ...shared.Event)takes the domain events; the adapter encodes the CloudEvents envelope and mints itsidat append (step 4). The use case calls it in the sameUnitOfWork.Doas the aggregate saves, so both commit or roll back together. - A20 Check order in commands. Unknown node, station or lane ids are
ErrNotFoundfirst (A16); then the domain's own checks; the cross-aggregate pre-check (vendor code, open lane, region code) runs after them, so an invalid command is never reported as a taken code. An unknown region id onRegisterNodeor on a station's region isErrUnknownRegion(422), not 404. - A21 Lists.
ListNodesandListLanesreturn every match ordered by id ascending, as an empty list when nothing matches, with no pagination (the model sizes it at about 10^3 nodes and 10^4 lanes). Atypeorstatusfilter that is not an enumeration value isErrValidation(422). - A22 Profile revisions.
NodeRepository.Saveappends the profile revision row (its comment tells an adapter how);NodeRepository.ProfileRevisionsreads them back, oldest first, so ADR 0003's "earlier revisions stay queryable for audit" is testable by the repository contract. No REST operation exposes it yet. - A23 Regions are write-only over REST. The OpenAPI has
defineRegionand nogetRegionorlistRegions, so there is no use case for them and a client cannot discover aregionIdit did not create. Model gap: add the reads, or say that regions are provisioned out of band. - A24 Assignment version below 1. ADR 0002's table lists
ErrStaleAssignmentVersionfor a first assignment whose version is below 1; the domain raisesErrValidation(assignmentVersion must be between 1 and 2147483647), and the use case passes it through. The table row is read as "stale" for a reassignment only. - A25 Region reads (supersedes A23). The orchestrator's decision D5 added
GET /regionsandGET /regions/{regionId}to the model and toapis/openapi.yaml. They are the use casesListRegionsandGetRegionand the port methodRegionRepository.List(every region ordered by id ascending, an empty list when none, no pagination). A23's gap is closed: a client can discover aregionIdit did not create. - A26 Postgres schema. Tables:
regions,nodes,node_profile_revisions,lanes,service_areas(migration 0001) andoutbox_events,idempotency_keys(migration 0002). There is noprocessed_events(inbox) table: this context consumes nothing. The model's enumerations are mirrored asCHECKconstraints, so adding an enumeration value takes a migration. Foreign keys tie nodes to regions and lanes, service areas and revisions to nodes. - A27 Revisions are append-only in the database. A trigger refuses
UPDATEandDELETEonnode_profile_revisions, and a deferred composite foreign key makesnodes.profile_revisionpoint at a stored revision.Saveinserts a revision row only when the snapshot's revision is higher than the highest stored one. - A28 Outbox table.
outbox_eventshas the fleet siblings' shape (event_id,topic,event_type,subject,key,dataschema,value,headers,created_at,published_at,attempts,last_error, unique(event_id, topic)).EventOutbox.Appendencodes through an injectedoutbox.Encoderbefore it writes, so an encoding failure stores no row of the batch. The production encoder and the relay are step 4. - A29 Savepoints. Every repository write runs in a savepoint of the unit of
work's transaction (its own transaction outside a unit). A unique violation
therefore rolls back only that write, and the unit can still return a typed
error or carry on; the outermost
Dostill owns commit and rollback. - A30 Ordering. Lists order by id byte-wise (
COLLATE "C"), the order of the in-memory doubles, not the database locale. - A31 Idempotency table.
idempotency_keys(key)(global since ADR 0012;routeis a plain column) hasresponse_statusandresponse_bodyNULL while the first request is in flight, and an index oncreated_atfor the 24 h cleanup. The middleware (step 5) may add columns (for example response headers) in a later migration. - A32 Adapters.
ids.UUIDmintsnode-<uuid v4>,lane-<uuid v4>,region-<uuid v4>(valid pershared.ValidID);clock.Systemreturns UTC truncated to the microsecond, the precision oftimestamptz, so a stamped time reads back unchanged. A U+0000 in free text is rejected at HTTP (step 5); the domain does not reject it today, and Postgres refuses it (SQLSTATE 22021). - A33 BDD suite.
features/holds the godog runner (features_test.go,package features_test,Paths: ".",Strict: true) and six feature files: regions, node registration, operational profile, lanes, service areas, suspension. The scenarios drive the use cases over the in-memory doubles (the same use cases the REST adapter will call), not HTTP; HTTP behaviour is covered by the adapter's own tests in step 5. The steps name refusals by the REST problem slug, so a scenario reads the same as the contract.
Amendment (step 6, outbox relay and encoders): assumptions A34-A36
- A34 Nullable wire fields.
subtype,vendorIdandvendorNodeCodeofNodeRegisteredare always present andnullwhen they do not apply, asapis/asyncapi.yamlpins them (contracts-delta says optional fields are omitted; these three are the documented exception, see ADR 0004). Every other optional field (sortDwellMinutes, a cutoff'sdaysandmaxOrders, a closed weekday) is omitted. - A35 Stable bytes.
operatingHoursByDayis written Monday first andholidays/cutoffsare always arrays, so an event encodes to the same bytes every time. Instants are RFC 3339 UTC, with the fraction only when non-zero (microsecond precision at most, the precision the clock adapter stamps). - A36 One topic. All nine events are integration events on
retailnetwork.node-topology.events; this context publishes nothing to.analytics. The attempt cap and its ordering trade-off are ADR 0005.
Amendment (step 7, HTTP and cmd/api): assumptions A37-A42
- A37 Key conflict is 422. The same
Idempotency-Keyon the same route with another request fingerprint (method, path, body) is 422idempotency-key-reused, as the fleet siblings do; the OpenAPI lists only 400 for a missing key, so the key problems are documented in ADR 0006, not in the OpenAPI responses. - A38 Refusals are replayed. A 4xx outcome is stored with the key and replayed
(its writes are rolled back); a 5xx is never stored.
idempotency_keysneeded no new column: the replay content type is derived from the status. Pointer 2026-11-19: since ADR 0020 only a refusal whose class is FINAL is stored; a RETRYABLE one releases the key. - A39 Malformed input. JSON that is invalid, has an unknown field, a wrong
type or no body is 400
malformed-request-body; an invalid enumeration or a missing required value that reaches the domain is 422validation-failed. A NUL in the path is 404not-found, in the query 400malformed-request-query, in the body 400malformed-request-body. - A40 Lists.
GET /nodes,GET /lanesandGET /regionsanswer{items, nextCursor}and are keyset-paginated by id (ADR 0012, which supersedes the unpaginated lists of A21 and A25). - A41 Probes are outside the business contract.
/healthzand/readyzare not operations ofapis/openapi.yaml; they are documented in ADR 0006 and README. - A42 No Location header. Creates answer 201 with the resource and no
Locationheader (the OpenAPI declares none).
Amendment (lane cost declaration, ADR 0014): assumption A43
- A43 Lane cost is planner-declared cents. The model names no cost for a
lane, so the least-surprising reading is a declaration: the planner's
marginal cost of moving ONE package-unit across the lane on one departure,
costPerUnitCents, integer cents, 0 to 10000000, no currency (the study network is single-currency). 0 is a legal declaration of zero marginal cost; a lane never declared on also reads 0 but publishes nothing, so a consumer's sum over it is incomplete. Decided in ADR 0014; the model gap stays open until the model names the field.
Amendment (fulfillment centres receive inbound, ADR 0015)
No new assumption: the model already gives FULFILLMENT_CENTER the
capabilities [OUTBOUND, INBOUND], and the build had dropped INBOUND (the
network model's gap G64). Decided in
ADR 0015:
typeRulesgivesFULFILLMENT_CENTEROutboundandInbound; every other row of the node-type table is unchanged.- The Node invariants gain one row:
inboundlimits only for a node type with theINBOUNDcapability,ErrInboundLimitsNotAllowed(422inbound-limits-not-allowed), enforced byNode.DeclareProfilebefore the value checks of ADR 0007.Restoredoes not enforce it, so a revision stored earlier with limits on such a node stays restorable.
Addendum 2026-11-13: current state
A36 counts nine events. Since ADR 0014 the context publishes ten: LaneCostDeclared
(internal/domain/lane/events.go, encoded in internal/adapters/outbound/kafka/encoder.go),
raised by the tenth command, DeclareLaneCost (internal/application/usecases/lanes.go).
All ten are listed in apis/asyncapi.yaml and still go to
retailnetwork.node-topology.events; nothing is published to .analytics.