Skip to main content

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.

#InvariantEnforced byTyped errorHTTP
T1At most one active claim. A task with an unexpired lease cannot be claimed again.Task.Claimtask.ErrAlreadyClaimed409
T2A claim requires matching capabilities. The claiming station's capability set must contain every required capability.Task.Claim → CapabilitySet.HasAlltask.ErrCapabilityMismatch422
T3An 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 / Completetask.ErrNotClaimed on renew/complete409
T4No double-complete. A completed task rejects every further operation.Task.Claim / RenewLease / Completetask.ErrAlreadyCompleted409
T5Only 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.VerifyHeldBytask.ErrNotOwner409
T6Renew/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.VerifyHeldBytask.ErrNotClaimed409
T7A 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)
T8A 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.CompleteRelocationtask.ErrRelocationConfirmationRequired, task.ErrInvalidRelocationConfirmation422
T9Relocation inputs belong to RELOCATE tasks only.CompleteTask.ExecuteWith, Task.CompleteRelocationtask.ErrNotRelocationTask422

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 if Pending, or Claimed with a lapsed lease. It reports what a caller would find, without mutating.
  • ExpireLeaseIfDue(now) mutates, returning true if it freed the task, so the caller knows it must persist and publish LeaseExpired.

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.

#InvariantEnforced byTyped errorHTTP
S1One occupant at a time. A second check-in is rejected.Station.CheckInstation.ErrOccupied409
S2Check-out requires an occupant.Station.CheckOutstation.ErrNotOccupied409
S3A station cannot accept a task it lacks capabilities for.Station.ValidateAccept → CanAcceptstation.ErrCapabilityMismatch422

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.

Honest status

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.

#InvariantEnforced byTyped errorHTTP
P1Cannot seal without scanned contents. An empty carton is never sealed.Package.Sealpack.ErrNoScannedContents422
P2Cannot seal twice, and cannot scan into a non-Open package.Package.Seal, Package.ScanItempack.ErrAlreadySealed409
P3SLAM requires a sealed package.Package.Weighpack.ErrNotSealed409
P4SLAM runs once. A labelled or diverted package rejects a second weigh-check.Package.Weighpack.ErrAlreadyProcessed409
P5SLAM diverts on weight discrepancy. If |actual − expected| > WeightTolerance the package becomes DIVERTED instead of LABELED.Package.Weigh(not an error — a domain outcome)204
P6Same-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.IsSegregationIncompatiblepack.ErrPackageSegregationViolation409

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.

#InvariantEnforced inErrorHTTP
C1Only required lines may arrive. An arrival for a line outside the order's required set is rejected.OrderConsolidation.RecordArrivalconsolidation.ErrUnknownLine422
C2Arrivals 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).

#InvariantEnforced inErrorHTTP
W1Size is 1..maximum. A batch has at least the anchor and at most PICK_BATCH_MAXIMUM (default 4) members.workbatch.Formworkbatch.ErrBatchSize— (the forming use case never offers more candidates than the maximum)
W2Every member is pickable. A member is a PICK task with a planned from_bin; a blank pick face cannot be a stop.Formworkbatch.ErrMemberNotPickable— (an anchor without a pick face is claimed as an ordinary task and no batch forms, ADR-0062)
W3One priority band. Every member shares the anchor's CPT instant, so a batch can never delay an earlier cutoff.Formworkbatch.ErrCrossesPriorityBand— (companions outside the band are skipped)
W4Cart segregation. Member hazard classes must not conflict under the DOT segregation matrix; an unclassified SKU (class 0) never blocks.Form → pack.IsSegregationIncompatibleworkbatch.ErrSegregationConflict— (conflicting companions are skipped)
W5One 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 0027workbatch.ErrStationHasOpenBatch409 station-has-open-batch
W6Anchor equivalence. The anchor is exactly the task ClaimNext would return, because both use the same claimer.FormWorkBatch shares claim_core.go with ClaimNext——
W7Only an open batch changes. Completing or detaching a member of a COMPLETED or ABANDONED batch is rejected.WorkBatch.CompleteMember / DetachMemberworkbatch.ErrBatchNotOpen409 batch-not-open
W8Member 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, DetachMemberworkbatch.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:

  • SealPackage reads a Task (to validate the caller holds an unexpired claim, via Task.VerifyHeldBy, and that it is a PACK task) but only writes the new Package.
  • RunSlam touches only the Package.
  • CompleteTask touches only the Task.
  • FormWorkBatch writes the WorkBatch and claims each member Task through the per-task compare-and-set; the batch holds a snapshot of the task facts it needs and never re-reads the task pool. CompleteTask and ExpireLeases keep the batch in step by loading and saving it themselves; the aggregates never reference each other.
  • ArriveAtRebin writes the OrderConsolidation and, on the completing arrival, creates a new PACK Task through CreateTask — 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 through CreateTask), stamped by wes-work-planning at release time from product-master's handling classification (the Fragile tag, via wes-work-planning's local copy of product-master's ProductClassified). It does not gate Claim — a fragile task claims exactly like any other, on capabilities alone.
  • Package.FragileHandling() — set once at construction (pack.New), derived by SealPackage from the owning task's Fragile flag 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 and requiredCapabilities already do, and SealPackage — 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 via pack.IsSegregationIncompatible against every prior scanned item's class before appending — invariant P6 above.
  • Package.SortLane() — derived, not stored: HAZMAT_LANE if any scanned item carried a hazard class, else FRAGILE_NO_TILT if FragileHandling(), else STANDARD. 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.