ADR 0002: the CatalogItem, Listing and InventoryFeed aggregates, the NodeStatusView, their invariants and the assumptions the model left open
Status
Accepted (2026-10-23). Design source: retail-network-docs model/model.yaml,
context offer-availability, the pack pages (aggregate-design-canvas,
use-cases, domain-events, bounded-context-canvas) and the Model Gap Register
items G23 and G24, whose "Proposed resolution" is final (contracts-delta.md).
2026-11-19: A22's keepWrites call is replaced by the OUTCOME replay class of the problem catalogue, and the FAILED feed's two causes no longer share one answer: see ADR 0016.
Context
The model gives three aggregate roots, each its own transaction boundary:
CatalogItem, Listing and InventoryFeed. One command, ApplyInventoryFeed,
changes many Listing aggregates and one InventoryFeed together, and
DiscontinueItem changes a CatalogItem and every Listing of the item. The
model's phrase "applied atomically across every listing" therefore cannot mean
one aggregate per transaction (G23): the unit of work is the transaction
boundary and spans several aggregates (A11). 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,catalog,listing,feed,nodestatus}. Pure Go: no I/O,time.Nowand id generation are never called;nowand ids are passed in. Dependency direction:listing<-feed;catalog,listing,feedandnodestatususeshared.sharedholdsErrValidation(problemvalidation-failed, 422),ErrIllegalTransition(problemillegal-transition, 409),ErrInvalidSnapshot(a persisted row that breaks an invariant: an internal error, never a client error), theEventinterface, theHeaderand the identifier checks.ErrNotFoundis NOT a domain error: it is the port sentinelports.ErrNotFound.ErrConcurrentUpdateis raised by the repository on a version mismatch.- Each aggregate has a constructor or command method per model command, a
Snapshot()and a validatingRestore(Snapshot), and aVersion()for optimistic concurrency. The version counts saves: a command that raises several events (A6) gives them all the same version. 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). - Bounds that exist because of Postgres
integerare plain literal constants (const MaxInt32 = 2147483647).
CatalogItem (internal/domain/catalog)
States ACTIVE, DISCONTINUED; transition ACTIVE -> DISCONTINUED
(DiscontinueItem). DISCONTINUED is terminal.
| Invariant | Err | Enforced by |
|---|---|---|
| title, length, width, height and weight are valid; dimensions and weight are positive | ErrInvalidItemDimensions (422 invalid-item-dimensions) | catalog.Create |
Check order in Create: id, title (ErrValidation), then dimensions and weight
(ErrInvalidItemDimensions). Discontinuing a DISCONTINUED item is a no-op that
raises no event (A3).
Listing (internal/domain/listing)
States LIVE, SUPPRESSED; a suppressed listing carries a reason
(NODE_NOT_SELLABLE, DISCONTINUED). Transitions: LIVE -> SUPPRESSED
(SuppressListing), SUPPRESSED -> LIVE (RestoreListing). ApplyAvailability
replaces the Availability{availableQty, basis, asOf, feedId} value object and
does not change the state.
| Invariant | Err | Enforced by |
|---|---|---|
availableQty >= 0 | ErrNegativeAvailability (422 negative-availability) | Listing.ApplyAvailability |
an update with asOf <= the current asOf is ignored (monotonic per listing) | ErrStaleAvailability (never an HTTP answer; slug stale-availability is reserved) | Listing.ApplyAvailability; the caller skips the line |
| a listing on a non-ACTIVE node is SUPPRESSED | ErrNodeNotSellable (409 node-not-sellable) | listing.Create (starts SUPPRESSED, A5) and Listing.Restore (refuses while the node is not sellable) |
| one listing per (catalogItemId, nodeId) | ErrDuplicateListing (409 duplicate-listing) | the use case pre-check and the unique index (catalog_item_id, node_id) |
Restore check order: the listing is SUPPRESSED (else ErrIllegalTransition);
its reason is not DISCONTINUED (else ErrIllegalTransition, final); the node is
sellable (else ErrNodeNotSellable). Suppress from LIVE suppresses with the
given reason; from SUPPRESSED(NODE_NOT_SELLABLE) with DISCONTINUED it upgrades
the reason and raises ListingSuppressed again (A4); any other Suppress of a
SUPPRESSED listing is ErrIllegalTransition. The policy use cases skip listings
for which the command would be illegal, so a replay raises no event.
InventoryFeed (internal/domain/feed)
States RECEIVED, APPLIED, FAILED, SUPERSEDED (G23 adds SUPERSEDED).
Transitions: RECEIVED -> APPLIED, RECEIVED -> FAILED, RECEIVED -> SUPERSEDED
(all ApplyInventoryFeed) and FAILED -> RECEIVED (the same feedId sent again).
APPLIED and SUPERSEDED are terminal.
| Invariant | Err | Enforced by |
|---|---|---|
| every line names a listing of the feed's node | ErrListingNotOnNode (422 listing-not-on-node) | InventoryFeed.Apply (feed becomes FAILED) |
| a feed is applied at most once | ErrFeedAlreadyApplied (409 feed-already-applied) | InventoryFeed.Resubmit and the use case (an APPLIED or SUPERSEDED id) |
| a quantity is not negative | ErrNegativeAvailability | InventoryFeed.Apply (feed becomes FAILED) |
| at most 10000 lines, at most one per listing, valid basis, quantity at most 2147483647 | ErrValidation (422 validation-failed) | feed.NewSubmission (nothing is recorded) |
InventoryFeed.Apply validates every line first (listing on the node, quantity),
then applies; it returns the first offending line in line order. It returns the
changed listings and their ListingAvailabilityChanged events and the counters.
feed.Superseded(asOf, lastApplied) is the node-level rule of G23.
NodeStatusView (internal/domain/nodestatus)
A local read model, not an aggregate of the model, with its own optimistic
version: per node a status (PROPOSED, ACTIVE, SUSPENDED, RETIRED) and the
instant of that status. Observe(status, at) folds one node-topology event; it is
a pure function so the ordering rules (A13) are mutation-tested.
Assumptions
- A1 Ids.
catalogItemIdandlistingIdare minted by the service asitem-<uuid v4>andlst-<uuid v4>;feedIdis chosen by the caller (vendor-connectivity). All ids andnodeIdare opaque: 1 to 64 characters from A-Z a-z 0-9 . _ : -, starting with a letter or a digit (shared.ValidID). - A2 Bounds.
title: 1 to 200 characters, trimmed, no control characters.lengthMm,widthMm,heightMm,weightG: 1 to 2147483647 (both a non-positive value and one above the bound areErrInvalidItemDimensions).availableQty: 0 to 2147483647. A feed has at most 10000 lines (G23). - A3 Discontinue twice.
DiscontinueItemon aDISCONTINUEDitem answers 200 with the item unchanged and raises nothing (the pack proposes it;ErrIllegalTransitionis not used for it). - A4 Discontinuing suppresses the listings (G24). In the same transaction every
listing of the item that is not already
SUPPRESSED(DISCONTINUED)is suppressed with reasonDISCONTINUED, oneListingSuppressedeach. A listing that was suppressed forNODE_NOT_SELLABLEchanges reason and raises the event again, so that a laterNodeActivatedcan never restore it.DISCONTINUEDis final. A listing created for aDISCONTINUEDitem startsSUPPRESSED(DISCONTINUED). Creating a listing for an unknowncatalogItemIdisErrNotFound(404). - A5 Initial state (G24). A listing starts
LIVEonly when the localNodeStatusViewsays the node isACTIVE. For any other status, and for a node the view does not know yet, it startsSUPPRESSEDwith reasonNODE_NOT_SELLABLE: an unknown node is not known to be sellable, and the firstNodeActivatedrestores the listing, so event lag between node-topology and this context never needs a retry from merchandising.DISCONTINUEDwins overNODE_NOT_SELLABLEwhen both apply. - A6 Created and suppressed.
ListingCreateddoes not carry the state (the model's field list is final), so a listing that startsSUPPRESSEDraisesListingCreatedand thenListingSuppressedin the same transaction, both with aggregate version 1. - A7 Availability before the first feed.
availableQty 0, basisUNKNOWN, noasOf, nofeedId(omitted on the wire). - A8 Suppressed listings take availability.
ApplyAvailabilityignores the state: aSUPPRESSEDlisting still takes feed lines and raisesListingAvailabilityChanged; the state travels inListingSuppressedandListingRestored. - A9 Applying a line. Check order: basis valid and
asOfset (ErrValidation), quantity (ErrNegativeAvailability, a negative number fails the feed even on a stale line), then staleness (asOf <=current isErrStaleAvailability; an equalasOfis stale). An applied line always replaces the value object and raisesListingAvailabilityChanged, even when quantity and basis are unchanged, becauseasOfandfeedIdchanged and consumers keep the highestasOf. - A10 FullFeedZeroing (G24). A full feed sets
availableQty 0on every listing of the node that has no line, keeping the listing's basis and stamping the feed'sasOfandfeedId. A listing already at 0 is left untouched (no state change, no event), and a listing whoseasOfis not before the feed's is left untouched too; neither is counted as a stale line.SUPPRESSEDlistings are zeroed as well. - A11 Feed outcomes (G23). The feed is one transaction: it saves the feed row
as
RECEIVED, evaluates, and endsAPPLIED,FAILEDorSUPERSEDED. A stale line is skipped and counted (staleCount); a feed whose lines are all stale is stillAPPLIED. A feed whoseasOfis strictly older than theasOfof the lastAPPLIEDfeed of that node isSUPERSEDED(nothing applied, no event); the per-node high-water mark lives innode_feed_marksand only anAPPLIEDfeed advances it. AFAILEDfeed (ErrListingNotOnNodeorErrNegativeAvailability) changes no listing and raises no event; its row stays withfailureCodeand the request is answered 422 withinstance/inventory-feeds/{feedId}. AFAILEDfeedIdmay be sent again (FAILED -> RECEIVED), it must keep itsnodeId(elseErrValidation); anAPPLIEDorSUPERSEDEDid is refused withErrFeedAlreadyApplied. Feeds are retained 30 days (the model); they store counters, not lines. Two feeds of one node are serialised by locking the node's mark row. - A12 Feed shape. The model does not define the lines: a line is
{listingId, availableQty, basis}andasOfis feed-level (the pack's proposal). A partial feed needs at least one line; a full feed may have none (it zeroes the node). Two lines for one listing areErrValidation. - A13 NodeStatusView ordering. A node event carries its own instant
(
activatedAt,suspendedAt,retiredAt; the CloudEventstimeforNodeRegistered). An event older than the instant of the current status is ignored whole (no listing is touched).RETIREDis terminal. An event for an unknown node creates the row (a lostNodeRegisteredmust not blockNodeActivated).NodeRegisteredfor a known node is a no-op. An event that repeats the current status is not ignored: the policy runs again and finds nothing to change. - A14 SuppressOnNodeUnavailable. On
NodeSuspendedorNodeRetiredeveryLIVElisting of the node is suppressed withNODE_NOT_SELLABLE. OnNodeActivatedevery listing of the node suppressed forNODE_NOT_SELLABLEis restored; listings suppressed forDISCONTINUEDare left alone. A listing for which the command would be illegal or refused (ErrIllegalTransition,ErrNodeNotSellable) is skipped silently, which makes a replay a no-op. - A15 Concurrency. Every save is optimistic. A command use case runs its whole
attempt again once on
ErrConcurrentUpdatebefore it reports 409concurrent-update; the Kafka consumer relies on the same single retry and then on redelivery (the transaction, including the inbox row, rolled back). - A16 Pagination.
GET /catalogandGET /listingsare keyset paginated by id ascending (limit1 to 500, default 100;afteris the previous page'snextCursor, which is the last id of the page). An invalidlimitisErrValidation. The model has no pagination; the catalogue is about 10^6 items. - A17 Wire types. The producer's choices inside the wire conventions of
contracts-delta.md: ids and enums are strings, quantities and dimensions are integers, instants are RFC 3339 UTC strings, absent optionals are omitted. They are documented inapis/asyncapi.yamland ADR 0004. - A18 Problem slugs. One slug per model
Errname (kebab-case withoutErr):invalid-item-dimensions,negative-availability,stale-availability(reserved),node-not-sellable,duplicate-listing,listing-not-on-node,feed-already-applied; plus the sharednot-found,illegal-transition,concurrent-update(the pack'sconcurrent-modificationis superseded by the model conventions),validation-failed. - A19 Retention. Idempotency keys 24 hours (model conventions); inventory
feeds and processed (inbox) events 30 days. A background janitor in
cmd/apideletes older rows. - A20 No tombstones. Nothing is deleted from the domain: a node's listings are suppressed, never removed; a discontinued item stays in the catalogue.
Consequences
- Each invariant has a named error, a problem slug (A18) and a domain test; the
Restoreboundary tests pin the persisted-row checks. ApplyInventoryFeedis the only multi-aggregate write besidesDiscontinueItemand the node policies; all three run in oneUnitOfWork, with bulk listing saves, so a 10000-line feed is one transaction.- The unresolved model questions are reported as
model_gaps: A3, A5, A6, A8, A9, A10, A12, A13, A16.
Amendment 2026-10-23: assumptions found while building the adapters
- A21 Instant precision. Every instant the domain keeps (
asOf, node status instants, event times) is UTC at microsecond precision (shared.UTCtruncates). That is what a Postgrestimestamptzstores, so the instant the domain compared is the instant the database returns, and "newer than" cannot flip across a round trip. Two instants less than a microsecond apart are the same instant. - A22 A FAILED feed survives the Idempotency-Key savepoint.
POST /inventory-feedsanswers 422 for a FAILED feed, and the middleware drops the writes of a 4xx. The FAILED row is a recorded fact (A11) thatGET /inventory-feeds/{feedId}must show, so that one handler asks the middleware to commit it (keepWrites); every other 4xx still leaves nothing behind. The 422 carries the instance/inventory-feeds/{feedId}. See ADR 0005. - A23 A node event that can never be applied is dead-lettered. An event of a
consumed type whose payload lacks
nodeIdor its instant, or whose values the use case refuses (ErrValidation), goes toretailnetwork.node-topology.events.dlqat once; a transient failure is retried five times first. A message that is not a CloudEvent, or a type this service does not consume, is skipped. See ADR 0005. - A24 Zeroing a listing already at 0. Part of A10, restated because a client
can trip over it: a full feed that omits a listing never fed (0,
UNKNOWN, noasOf) leaves it untouched, andzeroedCountdoes not count it.
Amendment 2026-11-08: the owner as a third cause (ADR 0013)
- A25 Precedence of the suppression reasons. A listing shows one reason, the
highest active cause:
DISCONTINUED(final) >NODE_NOT_SELLABLE>OWNER_SUSPENDED. A4's upgrade generalises:Suppresson aSUPPRESSEDlisting is legal only for a reason that outranks the current one. When a higher cause clears (NodeActivated,SellerReinstated),Listing.Reconcilehands the listing to the remaining highest cause with oneListingSuppressed, or restores it when none holds. A5's initial state takes the owner into account the same way (aSUSPENDEDowner starts the listingSUPPRESSED(OWNER_SUSPENDED)unless a higher cause applies). A14'sNodeActivatedrestore therefore leaves a listing whose owner is suspended atOWNER_SUSPENDED.
Addendum 2026-11-13: current state
- The Listing uniqueness rule above is now one listing per (
catalogItemId,nodeId,ownerRef), not per (catalogItemId,nodeId):CreateListing.pairTaken(internal/application/usecases/listings.go) looks the pair up by item and node for an operator-owned listing and by item, node and owner for a seller's, and the database key islistings_item_node_owner_key(migration0002_catalog_packaging_and_listing_owner). Changed by ADR 0006, item 8. - A suppressed listing can also carry the reason
OWNER_SUSPENDED(listing.ReasonOwnerSuspendedininternal/domain/listing/listing.go), raised byinternal/application/usecases/seller_events.gowhen seller-inbound suspends the owner. Added by ADR 0013; the precedence is A25 above.