Aggregates & invariants
Five aggregate roots, each enforcing its own invariants in pure Go with no framework or SQL types anywhere near them. Every invariant listed here has a failing-path unit test — asserting the rule rejects the bad case, not merely that the happy path works. The ddd-crew view of the same five roots (state transitions, handled commands, created events, throughput and size) is the Aggregate Design Canvas.
Task and Package are linked only by OrderRef — a value, not a reference.
Neither aggregate holds a pointer to the other, and neither is loaded to
mutate the other. That is what keeps them separate consistency boundaries.
Task
The unit of physical work. Its invariants are the reason this context exists.
| # | Invariant | Enforced by | Typed error | HTTP |
|---|---|---|---|---|
| T1 | At most one active claim. A task with an unexpired lease cannot be claimed again. | Task.Claim | task.ErrAlreadyClaimed | 409 |
| T2 | A claim requires matching capabilities. The claiming station's capability set must contain every required capability. | Task.Claim → CapabilitySet.HasAll | task.ErrCapabilityMismatch | 422 |
| T3 | An expired lease frees the task. A lapsed claim returns the task to Pending before any further decision is made. | Task.ExpireLeaseIfDue, called from Claim, and checked in RenewLease / Complete | task.ErrNotClaimed on renew/complete | 409 |
| T4 | No double-complete. A completed task rejects every further operation. | Task.Claim / RenewLease / Complete | task.ErrAlreadyCompleted | 409 |
| T5 | Only the claim owner may renew or complete. SealPackage applies the same ownership test, with the lease expiry check, through Task.VerifyHeldBy. A missing or expired lease is ErrNotClaimed (T6, decided 2026-10-06, ADR 0038); only an active lease held by another station is ErrNotOwner. | Task.RenewLease, Task.Complete, Task.VerifyHeldBy | task.ErrNotOwner | 409 |
| T6 | Renew/complete/seal require an active claim. Acting on a Pending task, or on a lapsed lease, is rejected — the same error on every endpoint. | Task.RenewLease, Task.Complete, Task.VerifyHeldBy | task.ErrNotClaimed | 409 |
| T7 | A released move is a valid move (ADR-0047). Non-blank plan id and SKU, move_seq >= 0, kind Relocate / Assign / Vacate, the bins the kind requires present (Relocate both, Assign to_bin, Vacate from_bin), and two known bins differ. | task.NewRelocationMove (the WorkReleased consumer) | task.ErrInvalidRelocationMove, task.ErrUnknownRelocationKind | — (dead-lettered) |
| T8 | A RELOCATE task completes only with the operator's confirmation. After T4–T6: a quantity of at least 1, every side the move left open scanned, a scan of a planned side equal to the plan, and different bins. Complete without it is refused. | Task.Complete, Task.CompleteRelocation | task.ErrRelocationConfirmationRequired, task.ErrInvalidRelocationConfirmation | 422 |
| T9 | Relocation inputs belong to RELOCATE tasks only. | CompleteTask.ExecuteWith, Task.CompleteRelocation | task.ErrNotRelocationTask | 422 |
The ordering inside Claim is itself an invariant
func (t *Task) Claim(stationId, stationCapabilities, now, leaseDuration) error {
if t.status == Completed { return ErrAlreadyCompleted }
t.ExpireLeaseIfDue(now) // an expired lease implicitly frees the task
if t.status == Claimed { return ErrAlreadyClaimed }
if !stationCapabilities.HasAll(t.requiredCapabilities) { return ErrCapabilityMismatch }
t.status = Claimed
t.lease = &Lease{StationId: stationId, Expiry: now.Add(leaseDuration)}
return nil
}
Expiry is evaluated before the already-claimed check. Reverse those two lines and a stale claim would permanently block the task — the very failure the lease was introduced to prevent. This is checked by a failing-path test, not left to code review.
Note also that now is a parameter. The domain never calls time.Now();
time enters through ports.Clock at the application layer. That is what makes
lease expiry testable with a fixed clock instead of time.Sleep.
IsAvailable vs ExpireLeaseIfDue
Two closely related methods with a deliberate difference:
IsAvailable(now)is a pure query — true ifPending, orClaimedwith a lapsed lease. It reports what a caller would find, without mutating.ExpireLeaseIfDue(now)mutates, returningtrueif it freed the task, so the caller knows it must persist and publishLeaseExpired.
Repositories use the first to filter candidates; the sweep uses the second.
Station
A work position. Its job in the model is small on purpose: hold the capability set that filters what its holder can pull.
| # | Invariant | Enforced by | Typed error | HTTP |
|---|---|---|---|---|
| S1 | One occupant at a time. A second check-in is rejected. | Station.CheckIn | station.ErrOccupied | 409 |
| S2 | Check-out requires an occupant. | Station.CheckOut | station.ErrNotOccupied | 409 |
| S3 | A station cannot accept a task it lacks capabilities for. | Station.ValidateAccept → CanAccept | station.ErrCapabilityMismatch | 422 |
OccupantId is an opaque string. There is no roster, no certification record,
no shift window — those belong to workforce-management, which stops at the
process-path boundary. Keeping Station this thin is what keeps that boundary
from leaking.
Occupancy (CheckIn / CheckOut) is exposed over HTTP as
POST /stations/{stationId}/check-ins and POST /stations/{stationId}/check-outs
(ADR-0014); it raises no
domain event. ClaimNext still does not require a station to be occupied
before it can claim — the registered capability set is the only station
state the dispatch path reads. The occupant is read once more at publish
time, to stamp associate_id onto TaskCompleted. POST /stations
returns occupied, always false for a freshly registered station.
Package
Pack output: an order becoming a sealed carton, then passing or failing the SLAM weigh-check.
| # | Invariant | Enforced by | Typed error | HTTP |
|---|---|---|---|---|
| P1 | Cannot seal without scanned contents. An empty carton is never sealed. | Package.Seal | pack.ErrNoScannedContents | 422 |
| P2 | Cannot seal twice, and cannot scan into a non-Open package. | Package.Seal, Package.ScanItem | pack.ErrAlreadySealed | 409 |
| P3 | SLAM requires a sealed package. | Package.Weigh | pack.ErrNotSealed | 409 |
| P4 | SLAM runs once. A labelled or diverted package rejects a second weigh-check. | Package.Weigh | pack.ErrAlreadyProcessed | 409 |
| P5 | SLAM diverts on weight discrepancy. If |actual − expected| > WeightTolerance the package becomes DIVERTED instead of LABELED. | Package.Weigh | (not an error — a domain outcome) | 204 |
| P6 | Same-package DOT hazard segregation. A scanned item's hazard class must be compatible with every already-scanned item's hazard class, per a class-level 49 CFR §177.848-derived matrix. An unclassified item (hazard class 0) never triggers or blocks this — fail-open. | Package.ScanItemWithClass → pack.IsSegregationIncompatible | pack.ErrPackageSegregationViolation | 409 |
P5 is worth dwelling on: a diverted package is not an error. It is a
successful weigh-check with a negative result, so POST /packages/{id}/slam-runs
returns 204 — the same status as a pass — and raises
WeightDiscrepancyDetected and PackageDiverted. A caller learns the
outcome by reading the package back with GET /packages/{id}, whose status
is LABELED or DIVERTED
(ADR-0033). Modelling a divert as a 4xx
would conflate "your request was wrong" with "the carton is wrong," and the
second is a normal, expected operational event.
WeightTolerance is 0.05, in whatever unit the caller supplies weights in —
the aggregate does not carry units. In practice the API examples use
kilograms.
OrderConsolidation
The Rebin fan-in tracker
(ADR-0016): one per
orderRef, recording which of the order's required lines have arrived at
the Rebin wall. Execution-scoped only — it does not model the order itself.
| # | Invariant | Enforced in | Error | HTTP |
|---|---|---|---|---|
| C1 | Only required lines may arrive. An arrival for a line outside the order's required set is rejected. | OrderConsolidation.RecordArrival | consolidation.ErrUnknownLine | 422 |
| C2 | Arrivals are idempotent. Re-recording an arrived line is a no-op (no second ItemArrivedAtRebin, no second save), and once complete the PACK task is created exactly once. | RecordArrival; ArriveAtRebin's HasArrived guard | — | — |
WorkBatch
The pick walk (ADR-0063): the PICK tasks one station holds for one walk,
formed at assignment time inside one priority band. It is not a wave —
nothing waits for a batch to fill and a batch of one (the anchor alone) is
valid. The aggregate (internal/domain/workbatch) is event-free and knows
nothing about claiming or leases: the application layer claims each member
through the existing per-task compare-and-set and publishes the events.
Everything sits behind PICK_BATCH_MODE (off by default, see
Configuration).
| # | Invariant | Enforced in | Error | HTTP |
|---|---|---|---|---|
| W1 | Size is 1..maximum. A batch has at least the anchor and at most PICK_BATCH_MAXIMUM (default 4) members. | workbatch.Form | workbatch.ErrBatchSize | — (the forming use case never offers more candidates than the maximum) |
| W2 | Every member is pickable. A member is a PICK task with a planned from_bin; a blank pick face cannot be a stop. | Form | workbatch.ErrMemberNotPickable | — (an anchor without a pick face is claimed as an ordinary task and no batch forms, ADR-0062) |
| W3 | One priority band. Every member shares the anchor's CPT instant, so a batch can never delay an earlier cutoff. | Form | workbatch.ErrCrossesPriorityBand | — (companions outside the band are skipped) |
| W4 | Cart segregation. Member hazard classes must not conflict under the DOT segregation matrix; an unclassified SKU (class 0) never blocks. | Form → pack.IsSegregationIncompatible | workbatch.ErrSegregationConflict | — (conflicting companions are skipped) |
| W5 | One open batch per station. A station that holds an OPEN batch cannot form another; the database backs it with the partial unique index work_batches_one_open_per_station. | FormWorkBatch over WorkBatchRepo; migration 0027 | workbatch.ErrStationHasOpenBatch | 409 station-has-open-batch |
| W6 | Anchor equivalence. The anchor is exactly the task ClaimNext would return, because both use the same claimer. | FormWorkBatch shares claim_core.go with ClaimNext | — | — |
| W7 | Only an open batch changes. Completing or detaching a member of a COMPLETED or ABANDONED batch is rejected. | WorkBatch.CompleteMember / DetachMember | workbatch.ErrBatchNotOpen | 409 batch-not-open |
| W8 | Member lifecycle. A member goes OPEN → COMPLETED (the last completion flips the batch to COMPLETED) or OPEN → DETACHED (its lease expired and the sweep returned the task to the pool; detaching the last open member makes the batch ABANDONED). A repeated detach is a no-op. | CompleteMember, DetachMember | workbatch.ErrMemberAlreadyCompleted, workbatch.ErrMemberDetached, workbatch.ErrMemberNotInBatch | — |
Companions are the station's active interleaving-hint candidates in rank
order, kept only when still claimable, in the anchor's band, carrying a pick
face, within the station's capabilities and segregation-safe; losing one to
another station is a skip, never an error. Leases stay per task, and
POST /work-batches/{batchId}/lease-renewals renews every still-open member
together (LeaseTogether). The per-stop work clock — tasks.work_started_at,
which makes a batched pick's duration_seconds run from the previous stop's
completion — is ADR-0064.
REST: POST /stations/{stationId}/work-batches (201 with the batch, or 200
with batch: null and only anchor_task_id when the anchor had no pick
face), GET /work-batches/{batchId} and
POST /work-batches/{batchId}/lease-renewals. With the mode not on all
three answer 503 batch-mode-off. MCP: the read-only get_work_batch tool.
Events: WorkBatchFormed, WorkBatchCompleted, WorkBatchAbandoned (see
Domain events).
Consistency boundaries
Each aggregate is one transaction. A use case never mutates two aggregates inside one consistency boundary:
SealPackagereads aTask(to validate the caller holds an unexpired claim, viaTask.VerifyHeldBy, and that it is aPACKtask) but only writes the newPackage.RunSlamtouches only thePackage.CompleteTasktouches only theTask.FormWorkBatchwrites theWorkBatchand claims each memberTaskthrough the per-task compare-and-set; the batch holds a snapshot of the task facts it needs and never re-reads the task pool.CompleteTaskandExpireLeaseskeep the batch in step by loading and saving it themselves; the aggregates never reference each other.ArriveAtRebinwrites theOrderConsolidationand, on the completing arrival, creates a new PACKTaskthroughCreateTask— a new aggregate, not a mutation of an existing one — inside the same unit of work.
The cross-aggregate rule "only the station holding the Pack task's claim may
seal its package" is enforced in the SealPackage use case rather than inside
either aggregate — it is a rule about two aggregates, so it belongs in the
layer that can see both, not inside one of them.
Read models are projections, never state
Queue depth is computed from task state on every request via
TaskRepo.CountByTypeAndStatus(ctx, taskType, task.Pending). There is no
counter field on any aggregate, and nothing to keep in sync. The same applies
to the throughput report: it is derived from the analytics events by a
separate projector into a separate database
(Throughput report), never stored on the
thing the events are about.
Product-classification-derived handling flags
Two flags carry product-classification information from upstream, added on
Task and Package respectively — neither is a new aggregate, and neither
changes an existing invariant:
Task.Fragile()— set once at construction (task.New, threaded throughCreateTask), stamped bywes-work-planningat release time from product-master's handling classification (theFragiletag, via wes-work-planning's local copy of product-master'sProductClassified). It does not gateClaim— a fragile task claims exactly like any other, on capabilities alone.Package.FragileHandling()— set once at construction (pack.New), derived bySealPackagefrom the owning task'sFragileflag rather than accepted as a separate caller-supplied argument. This keeps the derivation in one place: the flag rides in on the Task the same way CPT andrequiredCapabilitiesalready do, andSealPackage— which already loads the Task to validate claim ownership — reads it off that same load.
Hazmat handling needed no structural change: requiredCapabilities
already accepts arbitrary capability strings, Task.Claim's
CapabilitySet.HasAll check already enforces them, and RegisterStation
already accepts arbitrary capabilities for a station. hazmat is simply
documented as a known value in the ubiquitous
language — the mechanism
already existed. See ADR-0009
for the full reasoning.
Live per-item DOT hazard classification, segregation, and SortLane
A second, later addition (ADR-0010)
extends Package further, for a concern Task.Fragile()'s release-time
stamping pattern does not fit: a Pack task's scanned contents are
discovered live at the scan station, not known when the task was
released, so the per-SKU DOT hazard class of each scanned item is looked
up per SKU at seal time inside SealPackage — via the
ports.ProductClassificationLookup outbound port, permissive-by-default —
rather than stamped on Task upstream. Since
ADR-0039 that lookup reads
a local copy of product-master's ProductClassified events
(product_classification_copy), not inventory-storage's REST API.
Package.ScannedHazardClasses()— the DOT hazard class (1-9) recorded for each already-scanned item that came back Hazmat-classified from the lookup. Checked viapack.IsSegregationIncompatibleagainst every prior scanned item's class before appending — invariant P6 above.Package.SortLane()— derived, not stored:HAZMAT_LANEif any scanned item carried a hazard class, elseFRAGILE_NO_TILTifFragileHandling(), elseSTANDARD. Computed on every call from the two inputs above, so it can never drift from them.
SealPackage's per-item lookup fails open for a single SKU's lookup
error (since ADR-0039 a local-copy storage error; that SKU is treated as
unclassified, the rest of the seal
proceeds) — a deliberate asymmetry with inventory-storage's StowStock,
which fails closed for a classified SKU's placement-lookup error. See
ADR-0010 for the full reasoning on both points.