ADR 0002: the NodeScorecard aggregate, its invariants and the assumptions the model left open
Status
Accepted (2026-10-23). Design source: retail-network-docs model/model.yaml,
context node-performance (aggregates, policies, publishes, consumes), the
pack pages aggregate-design-canvas and domain-events, the Model Gap Register
(G20, G33) and the orchestrator's contracts-delta (E18).
Context
The model gives one aggregate root, NodeScorecard, identified by
scorecardId = nodeId + ':' + window; every node has two, the 7-day (7d) and
the 30-day (30d) scorecard. Its commands are RecordObservation and
Recompute; it raises NodeScorecardUpdated and NodeThresholdBreached. The
model is silent on most of what a scorecard needs to be computable: metric
definitions, denominators, the late-ack window, freshness sampling, the direction
of "downward", thresholds, creation, and which PromiseBroken causes count. G33
fixes minObservations = 50, "the first observation creates a PROVISIONAL card,
and recompute below the minimum stays PROVISIONAL without publishing", and the
node-attributable causes; G20/E18 fix that PROVISIONAL adds no handicap and that
consumers use the 30d window. Every other detail 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,scorecard}. Pure Go: no I/O,time.Nowand id generation are never called;nowis passed in.scorecarddepends onsharedonly.sharedholdsErrValidation(problemvalidation-failed, 422),ErrIllegalTransition(problemillegal-transition, 409),ErrInvalidSnapshot(a persisted row that breaks an invariant: an internal error), theEventinterface and the identifier checks.ErrNotFoundis the port sentinelports.ErrNotFound;ErrConcurrentUpdateis raised by the repository on a version mismatch. Neither is a domain error.- The aggregate has
New, command methods,Snapshot()and a validatingRestore(Snapshot), and aVersion()for optimistic concurrency. Every command that changes it increments the version; the repository stores with the expectationstored version == Version()-1(0for a create). - Bounds that exist for Postgres limits are plain literals
(
MaxInt32 = 2147483647).
NodeScorecard
States PROVISIONAL and GRADED. Transitions (model): PROVISIONAL -> GRADED,
GRADED -> GRADED, GRADED -> PROVISIONAL, all by Recompute. Creation is the
first RecordObservation for the node (A1); PROVISIONAL -> PROVISIONAL is a
recompute that stays below the minimum (A5). There is no terminal state.
| Invariant | Err | Enforced by |
|---|---|---|
| rates are in [0,1] | ErrRateOutOfRange | NewMetrics (also rejects NaN, a negative freshness or a negative observation count) |
a grade requires observations >= minObservations | ErrInsufficientObservations | GradeFor(metrics): refuses to grade a thin window. Recompute branches on the count first and moves the scorecard to PROVISIONAL instead (A10) |
| an observation is counted once (idempotent on source event id) | ErrDuplicateObservation | NodeScorecard.RecordObservation; the consumer treats it as success (A20) |
Other validation errors wrap ErrValidation: an invalid node id or window, an
observation without a source event id or an instant, an unknown observation kind.
Policies
Grading (model): A when onTimeHandoverRate >= 0.98 and promiseKeptRate >= 0.97 and lateAckRate <= 0.01; B at 0.95 / 0.94 / 0.03; C at 0.90 / 0.90 / 0.05;
otherwise D. ThresholdAlert (model): publish NodeThresholdBreached when a
metric crosses its threshold downward (A11).
Assumptions (the model is silent)
- A1. Aggregate shape and creation. A
NodeScorecardholds the observations counted in its window, keyed by the source CloudEventsid.RecordObservationis one use case that records ONE observation on BOTH scorecards of the node in one transaction; the first observation for a node creates both,PROVISIONAL, version 1 (G33).RecordObservationraises no event. - A2. Which consumed events are observations. The observations are the
measured outcomes:
ACK_ACCEPTED(PurchaseOrderAccepted),ACK_REJECTED(PurchaseOrderRejected),ACK_EXPIRED(PurchaseOrderExpired),HANDOVER(PackageHandedOver),PROMISE_KEPT(PromiseKept),PROMISE_BROKEN(PromiseBroken, node-attributable causes only, A8) andFEED_APPLIED(InventoryFeedApplied).PurchaseOrderIssuedandVendorShipmentConfirmedare facts about a purchase order, not outcomes: they upsert the localPurchaseOrderFacts(ADR 0003) and are not counted.observationsinMetricsis therefore the number of measured outcomes in the window, sominObservations = 50means fifty outcomes, not fifty messages. The model's RecordObservation wording for the two fact events is narrowed on purpose: a purchase order that was issued and never resolved is not evidence yet. - A3. Observation instant and window. The instant
Atof an observation is the fact's own instant:acceptedAt,rejectedAt, the expired order'sackBy,handedOverAt,deliveredAt(a broken promise withoutdeliveredAtuses the envelopetime) andappliedAt. An observation counts in a window atnowwhenAtis afternow - window(a future instant counts: clocks skew).Recomputedrops observations that are no longer inside the window. - A4. Events consumed without effect.
VendorOnboarded,SubmissionProcessed,NodeRegisteredandNodeOperationalProfileDeclaredare subscribed to and acknowledged, and only their inbox row is written. The model gives them no use here: the first two carry nonodeId, and a scorecard is computed from observed facts, never from the declared profile (business decision 1). They stay subscribed so a later decision (a node directory, the declared-versus-measured view) needs no new consumer group. Open question. - A5. Metrics, general rules. Each metric is a numerator over a denominator
with a better-direction (below). A metric with an empty denominator reports its
best value (rate
1for the higher-is-better rates,0for the rest). APROVISIONALscorecard still carries the metrics of what was observed (the REST read shows them), but itsgradeisPROVISIONAL.minObservationsisMinObservations = 50(G33). - A6. onTimeHandoverRate (higher is better) =
HANDOVERobservations that are on time /HANDOVERobservations. On time meanshandedOverAtis NOT after the purchase order'srequiredShipBy(the boundary instant is on time). The vendor's ownshippedAtis never used. - A7. Acknowledgement rates (lower is better). The acknowledged-or-expired
population is the
ACK_ACCEPTED,ACK_REJECTEDandACK_EXPIREDobservations.lateAckRate= (late acknowledgements + expired orders) / that population; an acknowledgement is late when it falls in the LAST 10% of the ack window[issuedAt, ackBy](ackedAt >= ackBy - (ackBy - issuedAt)/10, so an acknowledgement at or afterackByis late); an expired order is always late.issuedAtis the CloudEventstimeofPurchaseOrderIssued(the instant the order was issued).rejectRate=ACK_REJECTED/ that population;expiryRate=ACK_EXPIRED/ that population. An acceptance or rejection for a purchase order whose issue was not seen cannot be judged: the use case fails withErrPurchaseOrderUnknown, which the consumer treats as transient (retried, then dead-lettered, ADR 0003). - A8. promiseKeptRate (higher is better) =
PROMISE_KEPT/ (PROMISE_KEPT+PROMISE_BROKEN). G33 names the node-attributable causesLATE_HANDOVER,VENDOR_REJECTandACK_EXPIRED, but delivery-promise's publishedPromiseBroken.causeisLATE,LOSTorRETURNED(itsapis/asyncapi.yaml). Reading:LATE(delivered afterdeliverByLatest, a node's handover is the usual reason) counts against the node together with the three G33 literals, in case a producer sends them;LOSTandRETURNED(network and shopper) and any unknown cause do not: no observation is recorded and the inbox row is the only trace. Model gap: the G33 names and the delivery-promise vocabulary differ; the orchestrator should align them. - A9. feedFreshnessP95Minutes (lower is better). The samples are the gaps
between consecutive
FEED_APPLIEDobservations of the node inside the window, ordered byAt; each gap is truncated to whole minutes. The value is the 95th percentile by the nearest-rank method (ceil(0.95 * n)-th smallest); fewer than two feeds give no sample and0(A5). The trailing gap tonowis not a sample, so a recompute without new facts never changes it. - A10. Grade assignment.
GradeFor(metrics)appliesGradingand refuses withErrInsufficientObservationsbelowMinObservations.Recomputecomputes the metrics, then: below the minimum the state isPROVISIONALand the grade is empty (on the wirePROVISIONAL), else the state isGRADEDwith the grade ofGradeFor. All comparisons use the unrounded rates; a rate is a ratio of two integers, so49/50equals the literal0.98. - A11. Alert thresholds and "downward". The model names no threshold per
metric. The thresholds are the
Cbounds for the three graded metrics (the edge of aD) and these defaults for the rest, one table in the code:onTimeHandoverRate >= 0.90,promiseKeptRate >= 0.90,lateAckRate <= 0.05,rejectRate <= 0.10,expiryRate <= 0.05,feedFreshnessP95Minutes <= 240. "Downward" is a worsening: a higher-is-better metric that moves from>=the threshold to below it, or a lower-is-better metric that moves from<=the threshold to above it, between the scorecard's previous GRADED computation and the new GRADED one. No alert without both sides (a first graded recompute, or one coming fromPROVISIONAL, has no baseline). OneNodeThresholdBreachedper metric that crossed;valueis the new value,thresholdthe bound. - A12. Wire types. Rates are numbers in [0,1], unrounded;
feedFreshnessP95Minutesandobservationsare integers (durations and counts are integers on the wire);computedAtis the recompute instant, RFC 3339 UTC;gradeisA,B,C,DorPROVISIONAL. TheNodeScorecardUpdateddatais the model list exactly. - A13. When a recompute publishes. A recompute saves the scorecard (new
computedAt, version) every time. It raisesNodeScorecardUpdatedwhen the state, the grade or any metric differs from the previous computation, exceptPROVISIONAL -> PROVISIONAL, which never publishes (G33).GRADED -> PROVISIONALdoes publish (gradePROVISIONAL): consumers must not keep acting on a grade the window no longer supports.NodeThresholdBreachedonly goes with an update. Both events carry the recompute instant (computedAt, CloudEventstime). - A14. Window slide. Observations that left the window are dropped from the
scorecard at
Recompute; a scorecard whose window emptied isPROVISIONALwith best-value metrics andobservations = 0. - A15. Recompute trigger. A single
Recomputeuse case, driven by a scheduler incmd/apieveryRECOMPUTE_INTERVAL(default one minute), recomputes every scorecard that is due: it has observations recorded since its last recompute (dirty) or its oldest observation has left the window (expires_at <= now). Several replicas are safe: the version check makes the loser skip the scorecard. - A16. Ids.
nodeIdis a node-topology id (shared.ValidID, 1 to 64 characters ofA-Za-z0-9._:-) and must not contain:; thescorecardIdisnodeId:window, at most 68 characters. Source event ids are 1 to 200 characters without control characters. - A17. Concurrency. Two consumers can record observations for the same node at
once; the second save fails with
ports.ErrConcurrentUpdateand the whole attempt (inbox row, load, record, save) runs again on fresh state, up to five times. - A18. REST additions.
GET /scorecards?grade=takes the optional filterswindow,limit(1 to 500, default 100) andafter(keyset onscorecardId); the response hasnextCursorwhen more rows exist.GET /scorecards/{nodeId}answersnot-founduntil the first observation. The only problem types of this context arenot-foundandvalidation-failed: the three invariants are consumer-side. - A19. Bounds.
observationsis bounded byMaxInt32 = 2147483647(a Postgresinteger). A node id is at most 64 characters. - A20. Duplicates. A redelivered event is stopped by the inbox (
processed_events) first.ErrDuplicateObservationis the aggregate's second line when the same source id arrives through a path the inbox did not see; the consumer treats it as success. - A21. Idempotency keys. Both REST routes are reads, so no route takes an
Idempotency-Key. The HTTP adapter still ships the fleet middleware and theidempotency_keystable (decision D3) for any future POST/PUT; nothing uses them today. - A22. Load shape. A recorded observation loads, and a save rewrites the observation set of, the two scorecards of one node (the 30d card holds about a month of outcomes of ONE node). That is acceptable for the "medium" throughput of the model; a compacted counter representation is the follow-up if a node's volume grows by orders of magnitude.
- A23. Streams.
NodeThresholdBreachedis analytics-only: it goes ONLY toretailnetwork.node-performance.analyticswith the dataschema streamanalytics;NodeScorecardUpdatedgoes ONLY to.events(contracts-delta shared conventions). The model pack put both on.events; the cross-context rule wins.
Consequences
- delivery-promise and order-sourcing read the 30d
NodeScorecardUpdated; aPROVISIONALgrade adds no handicap (G20, E18). model_gapsfor the orchestrator: A2 (observation set), A4 (events with no use), A7 (the 10% rule needsissuedAt), A8 (cause vocabulary), A9 (freshness sampling), A11 (thresholds), A13 (publish rule), A15 (recompute scheduler), A18 (REST additions), A23 (analytics stream).- Adding a metric changes
Metrics,NewMetrics, the OpenAPI schema and theNodeScorecardUpdatedmessage together (additive evolution).
Addendum 2026-11-13: current state
NodeScorecard.Recompute raises a third event, NodeTierEligibilityChanged, on the 7d scorecard when the fast-tier eligibility flag flips (two events per flip, one per tier; internal/domain/scorecard/eligibility.go:115, ADR 0013). The 7d scorecard also holds that flag, a reinstatement streak and its last UTC day (FastTierState, eligibility.go:37), so "it raises NodeScorecardUpdated and NodeThresholdBreached" and A13's "both events" describe the first two events only.