Skip to main content

Domain events

Twenty past-tense facts, all defined in internal/domain/shared/events.go. Every one satisfies the same tiny interface:

type DomainEvent interface {
EventName() string
OccurredAt() time.Time
}

Events are deliberately thin — most carry only the aggregate id. Enrichment for the wire happens in the outbound adapter, never on the event itself (see "Why the events stay thin" below).

How an event leaves the process​

A use case hands its events to ports.EventPublisher. What happens next is decided at the composition root (internal/composition/publisher.go):

EVENT_PUBLISHERDATABASE_URLWhat Publish does
log (default)anyLogs the event to stdout. Nothing reaches Kafka.
kafkasetRuns two encoders inside the use case's own transaction — the integration encoder (internal/adapters/outbound/kafka/publisher.go) and the analytics encoder (analytics_publisher.go) — and inserts one outbox_events row per encoded message. The in-process relay in cmd/execution drains the rows onto Kafka in id order (ADR-0020). cmd/mcp only inserts; it never runs the relay.
kafkaunsetSame two encoders, written straight to the broker through events.MultiPublisher (no transaction to bind them to).

Each encoder has an allowlist. An event outside it is skipped, not errored — that is how the two Rebin events stay in-process.

Wire conventions (all published events)​

  • Envelope: CloudEvents 1.0, structured content mode, built only by internal/adapters/kafka/cloudevents (official sdk-go/v2/event); Kafka header content-type: application/cloudevents+json; charset=UTF-8 (ADR-0032).
  • type: com.warehouse.wes.fulfillment-execution.<entity>.<EventName>, where entity is task or package (the raising aggregate).
  • source: /warehouse/fulfillment-execution.
  • dataschema: urn:warehouse:fulfillment-execution:events:<EventName>:v1 on the integration topic, urn:warehouse:fulfillment-execution:analytics:<EventName>:v1 on the analytics topic.
  • Partition key = subject = the raising aggregate's id (task id or package id), written with the kafkago.Hash balancer, so every event of one aggregate lands on one partition, in order (ADR-0035).
  • id: UUID v4 minted once in Encode and persisted in the outbox row, so a relay retry republishes the same id (the consumer dedupe key).

The catalogue​

EventFull CloudEvents typeRaised by (use case)Domain payloadwarehouse.fulfillment.events (integration) datawarehouse.fulfillment.analytics data
TaskCreatedcom.warehouse.wes.fulfillment-execution.task.TaskCreatedCreateTask (REST POST /tasks, the WorkReleased consumer, and ArriveAtRebin on consolidation)TaskId—task_id, task_type
TaskAvailablecom.warehouse.wes.fulfillment-execution.task.TaskAvailableCreateTask (every creation path, right after TaskCreated) and ExpireLeases (a freed task re-enters the pool, next to LeaseExpired)TaskId (the payload is resolved from the task row in the same transaction)task_id, task_type, site_id, from_location, to_location, required_capabilities, cpt?, priority_band, available_at; only for tasks with a determinable location: RELOCATE and REPLENISH (their planned bins) and a PICK whose plan carries both a site and a pick face — a pick missing either is not announced (Task.Placement(), ADR-0049, ADR-0050, ADR-0062)—
TaskClaimedcom.warehouse.wes.fulfillment-execution.task.TaskClaimedClaimNextTaskId, StationIdtask_id, task_type, station_id, claimed_at (ADR-0049)task_id, task_type, station_id
LeaseExpiredcom.warehouse.wes.fulfillment-execution.task.LeaseExpiredExpireLeasesTaskId—task_id, task_type
TaskCompletedcom.warehouse.wes.fulfillment-execution.task.TaskCompletedCompleteTask (REST and MCP complete_task)TaskId, StationIdtask_id, station_id, work_unit_id, associate_id?, duration_seconds?, task_type?, order_ref? (ADR-0040), line_no? (ADR-0041); RELOCATE tasks only: sku, from_bin, to_bin, quantity, relocation_ref (ADR-0047); REPLENISH tasks only: sku, from_bin, to_bin, quantity, request_ref (ADR-0050)task_id, task_type, station_id, order_ref?, line_no?
TaskCPTMissedcom.warehouse.wes.fulfillment-execution.task.TaskCPTMissedSweepCPTMissesTaskId, OrderRef, TaskType, CPTtask_id, order_ref, task_type?, cpt—
ItemPickedcom.warehouse.wes.fulfillment-execution.task.ItemPicked(no use case raises it today)TaskId—task_id, task_type (encoder exists, never fed)
PackageSealedcom.warehouse.wes.fulfillment-execution.package.PackageSealedSealPackagePackageId—package_id
WeightDiscrepancyDetectedcom.warehouse.wes.fulfillment-execution.package.WeightDiscrepancyDetectedRunSlam (outside tolerance)PackageId, ExpectedWeight, ActualWeightpackage_id, expected_g, actual_g (ADR-0053)package_id, expected_g, actual_g
PackageDivertedcom.warehouse.wes.fulfillment-execution.package.PackageDivertedRunSlam (outside tolerance)PackageIdpackage_id (ADR-0053)package_id
LabelAppliedcom.warehouse.wes.fulfillment-execution.package.LabelAppliedRunSlam (within tolerance)PackageId—package_id
PackageManifestedcom.warehouse.wes.fulfillment-execution.package.PackageManifestedRunSlam (within tolerance, alongside LabelApplied)PackageId, OrderRefpackage_id, order_refpackage_id, order_ref, task_type, station_id, on_time, resolved
TransferPickedcom.warehouse.wes.fulfillment-execution.transfer.TransferPickedCompleteTask (task with a TRANSFER_PICK correlation block)TaskId, correlation blocktransfer_ref, demand_id?, work_unit_id, task_id, work_kind, site_id?, sku?, quantity?—
TransferDispatchedcom.warehouse.wes.fulfillment-execution.transfer.TransferDispatchedCompleteTask (TRANSFER_DISPATCH)TaskId, correlation blocksame shape as TransferPicked—
TransferArrivedcom.warehouse.wes.fulfillment-execution.transfer.TransferArrivedCompleteTask (TRANSFER_ARRIVAL)TaskId, correlation blocksame shape as TransferPicked—
WorkBatchFormedcom.warehouse.wes.fulfillment-execution.workbatch.WorkBatchFormedFormWorkBatch (only with PICK_BATCH_MODE=on)BatchId, StationId, CPT, member facts, versionbatch_id, station_id, cpt, formed_at, version, members[] (task_id, stop_seq, compartment) (ADR-0063)same data
WorkBatchCompletedcom.warehouse.wes.fulfillment-execution.workbatch.WorkBatchCompletedCompleteTask (the last open member completes)BatchId, StationId, member count, walk seconds, versionbatch_id, station_id, member_count, walk_seconds, completed_at, versionsame data
WorkBatchAbandonedcom.warehouse.wes.fulfillment-execution.workbatch.WorkBatchAbandonedExpireLeases (the last open member detaches)BatchId, StationId, member count, versionbatch_id, station_id, member_count, abandoned_at, versionsame data
ItemArrivedAtRebin(none — never encoded)ArriveAtRebinOrderRef, LineId——
OrderConsolidated(none — never encoded)ArriveAtRebin (completing arrival)OrderRef——

? marks a field tagged omitempty — omitted when the value is unavailable (no occupant checked in, no recorded claim, task no longer found). The partition key is the task id for every task.* row, the package id for every package.* row and the batch id for every workbatch.* row.

Source: internal/domain/shared/events.go, internal/adapters/outbound/kafka/publisher.go (inIntegrationContract, TaskCompletedData, TaskCPTMissedData, PackageManifestedData, PackageDivertedData, WeightDiscrepancyDetectedData), internal/adapters/outbound/kafka/task_pool_events.go (TaskAvailableData, TaskClaimedData), internal/adapters/outbound/kafka/analytics_publisher.go (inAnalyticsContract, marshalData), apis/asyncapi.yaml.

Published is not the same as defined

Only TaskAvailable, TaskClaimed, TaskCompleted, TaskCPTMissed, PackageManifested, PackageDiverted and WeightDiscrepancyDetected (plus the three transfer facts and the three WorkBatch* facts) form the integration contract — the two package exception facts were promoted from the analytics topic for exception-management (ADR-0053). Ten events go to the analytics topic (TaskCreated, TaskClaimed, LeaseExpired, TaskCompleted, ItemPicked, PackageSealed, WeightDiscrepancyDetected, LabelApplied, PackageDiverted and PackageManifested), plus the three WorkBatch* occurrences, which are published on both topics only with PICK_BATCH_MODE=on — thirteen in all (inAnalyticsContract); TaskAvailable, TaskCPTMissed, the three transfer facts and the two Rebin events never go there. ItemArrivedAtRebin and OrderConsolidated (ADR-0016) are in neither allowlist and are not in apis/asyncapi.yaml; if they are ever published their entity would be orderconsolidation.

ItemPicked is defined, tested and has an analytics encoder, but no use case raises it. The Pick path is modelled at task granularity (claim → complete) rather than item granularity; the event stays in the catalogue because it is part of the intended model.

Who consumes what​

TopictypeConsumerEffect
warehouse.fulfillment.eventscom.warehouse.wes.fulfillment-execution.task.TaskCompletedwes-work-planningRecordCompletion(work_unit_id) — the drum-buffer-rope feedback edge
warehouse.fulfillment.eventscom.warehouse.wes.fulfillment-execution.task.TaskCompletedlabor-performancePer-associate / per-task-type attribution (ADR-0014, ADR-0023)
warehouse.fulfillment.eventscom.warehouse.wes.fulfillment-execution.task.TaskCPTMissed, com.warehouse.wes.fulfillment-execution.package.PackageManifestedorder-managementRepromiseOrder promise feedback loop (ADR-0025)
warehouse.fulfillment.events...task.TaskAvailable, ...task.TaskClaimedtask-interleavingKeeps its local copy of the open-task pool: TaskAvailable adds (or re-adds) a task, TaskClaimed removes it (ADR-0049)
warehouse.fulfillment.events...package.PackageDiverted, ...package.WeightDiscrepancyDetectedexception-management (planned)Opens its problem-solve case on the divert (ADR-0053)
warehouse.fulfillment.events...transfer.TransferPicked, ...transfer.TransferDispatched, ...transfer.TransferArrivednetwork-inventory-planning (transfer saga), destination receipt/stowTransfer custody facts, one per completed transfer task, selected by work_kind (ADR-0036)
warehouse.fulfillment.events...workbatch.WorkBatchFormed, ...workbatch.WorkBatchCompleted, ...workbatch.WorkBatchAbandonednone on develop yetPer-walk facts, published only with PICK_BATCH_MODE=on. The contract names labor-performance (batch-size reporting) as the intended consumer, but it has no handler for them (x-no-consumer-reason in apis/asyncapi.yaml). TaskCompleted carries optional batch_id / batch_size so a consumer can tell batched picks from single picks (ADR-0063)
warehouse.fulfillment.analytics...task.TaskClaimed, ...task.TaskCompleted, ...task.LeaseExpired, ...package.WeightDiscrepancyDetected, ...package.PackageManifestedthis service's cmd/fulfillment-projector, group fulfillment-analyticsProjects the throughput rollup (Throughput report); every other analytics type is acknowledged without projecting

The downstream consumers are the ones listed in apis/asyncapi.yaml; their consumer-group ids live in their own repositories.

Events consumed from other contexts​

SourceTopicFull typeConsumerGroupEffect
wes-work-planningwarehouse.work-planning.eventscom.warehouse.wes.work-planning.workunit.WorkReleasedinternal/adapters/inbound/kafka/consumer.goWORK_RELEASED_CONSUMER_GROUP (default fulfillment-execution)CreateTask — idempotent on the CloudEvents id via processed_events; a failure after 3 attempts (or any non-CloudEvent) is dead-lettered to warehouse.work-planning.events.dlq when EVENT_PUBLISHER=kafka wires the DLQ writer
process-path-managementwarehouse.process-path-management.eventscom.warehouse.wes.process-path-management.processpath.ProcessPathCreated / ProcessPathUpdated / ProcessPathDeactivatedinternal/adapters/outbound/kafkacatalog/consumer.gounique per process (fulfillment-execution-process-path-catalogue- + host, pid, start time), replays from the first offsetRebuilds the in-memory process-path catalogue — only when PATH_CATALOGUE_SOURCE=kafka

Which use case raises what​

Source: internal/application/usecases/*.go and the two encoders' allowlists. Omits ItemPicked (never raised) and the log publisher. The three WorkBatch* nodes are raised only with PICK_BATCH_MODE=on; the integration encoder drops a TaskAvailable for a task with no determinable location.

RegisterStation, CheckInStation, CheckOutStation, RenewLease and the five reads (GetQueueDepth, GetTasksByOrderRef, GetInstalledCapacity, GetPackage, GetPackagesByOrderRef) raise nothing. Registering or staffing a station is an operational action with no existing fact that fits it, and the deliberate choice was not to invent events just for symmetry. RenewLease changes only the lease expiry.

The calls with two facts​

RunSlam publishes two events on each branch, in a single call:

// outside tolerance
uc.Publisher.Publish(ctx,
shared.NewWeightDiscrepancyDetected(packageId, expectedWeight, actualWeight, now),
shared.NewPackageDiverted(packageId, now),
)
// within tolerance
uc.Publisher.Publish(ctx,
shared.NewLabelApplied(packageId, now),
shared.NewPackageManifested(packageId, p.OrderRef(), now),
)

They are separate on purpose. WeightDiscrepancyDetected is the measurement — it carries both weights and is what a quality or loss-prevention consumer wants. PackageDiverted is the routing decision. On the pass branch, LabelApplied is the local fact and PackageManifested is the promise-loop fact order-management keys on.

Note the argument order: the event is constructed as (packageId, expected, actual, now) while the use case's own signature is Execute(ctx, packageId, actualWeight, expectedWeight). The API request body names both fields explicitly (actualWeight, expectedWeight) so callers are never relying on positional order.

TaskCPTMissed re-fires​

SweepCPTMisses changes no task state, so a task that stays open past its CPT raises TaskCPTMissed again on every sweep pass — each a new occurrence with a new id. A consumer must be idempotent on its own business key (order-management's RepromiseOrder is designed for exactly that, per ADR-0025).

Why the events stay thin​

TaskCompleted carries only TaskId and StationId. The wire format needs work_unit_id so Work Planning can correlate the completion back to the unit it released, plus associate_id, duration_seconds and task_type for labor-performance.

None of those are added to the domain event. The integration encoder looks the task back up through ports.TaskRepo (OrderRef(), ClaimedAt(), Type()) and the station through ports.StationRepo (current occupant):

t, err := p.Tasks.FindById(ctx, tc.TaskId)
...
data := TaskCompletedData{
TaskId: string(tc.TaskId),
StationId: string(tc.StationId),
WorkUnitId: workUnitId, // enriched here, in the adapter
...
}

work_unit_id is an integration concern — it exists because a particular downstream consumer needs a particular correlation key. Pushing it into the domain event would make the domain model shaped by a consumer's needs. The analytics encoder applies the same pattern for task_type and for the on-time-to-CPT verdict on PackageManifested (ADR-0026).

associate_id reflects whoever is checked in at publish time, not necessarily whoever performed the whole task — a best-effort fact.

Handling flags did not extend any event payload​

The same discipline applied when Task.Fragile, Task.GiftWrap, Package.FragileHandling, Package.GiftWrapRequested and Package.SortLane() were added: TaskCreated still carries only TaskId, and PackageSealed only PackageId. The flags are visible on the REST responses (TaskResponse.fragile / giftWrap, PackageResponse.fragileHandling / giftWrapRequested / sortLane), which is where anything needing them reads them today. SortLane is a WES-tier decision only — no WCS integration exists to consume it (ADR-0010).

See the Events reference for envelope examples and the Domain Message Flow page for the events in end-to-end scenarios.