ADR 0021: a sweep flags promises whose locked path is running late
Status
Accepted (2026-11-09). Builds on the measured-transit basis of ADR 0014 and the consumed contracts of ADR 0003. Numbers 0020, 0022 and 0023 are reserved for sibling changes built in parallel.
Context
A CONFIRMED promise is re-promised today only when something says its witness path is broken: a cancelled departure, a cancelled wave, a failed or moved booking, an unsourceable node, an exception on a package. A load that is simply running late says nothing. The promise stays CONFIRMED until the package is delivered after the window and the promise is judged BROKEN{LATE}, when it is too late to tell the customer. Public fulfillment networks warn about, and re-date, an order when the carrier leg that carries it has passed its expected arrival and has not been scanned in.
The service already consumes LoadDeparted and LoadArrived from retailnetwork.linehaul-transportation.events (ADR 0014). Both carry the id of the scheduled departureId they belong to (producer schemas LoadDepartedEvent / LoadArrivedEvent), which this service did not read until now. The promise's witness already names its pickup departure, its legs and its delivery wave, and the departure and wave read models hold their scheduled times.
Decision
The contract, verbatim:
- Data: linehaul's
LoadDepartedandLoadArrivedalready carrydepartureId(producer schemaLoadDepartedEvent/LoadArrivedEvent). Extend DP's tolerant consumed copies with the OPTIONALdepartureId(asyncapi consumed schemas too). New local read modelDepartureArrival(rm_departure_arrival:departure_idPK,arrived_at), written onLoadArrivedthat carries adepartureId, pruned past the transit window. Migration 0008. Old events withoutdepartureIdare ignored by this model (counted). - New sweeper pass
FlagPredictedLate(ctx, limit)in the existing clock-driven sweeper (same interval, same batch limit, logged failures; followsweepOnce). For each CONFIRMED promise: for each departuredof the promise's witness path that uses a departure:expectedArrival = d.arrivesAt + max(0, measuredP - scheduled)using the SAME F2 measured-transit adjustment the search uses (reuse it; belowminTransitObservationsthe adjustment is 0). Ifnow > expectedArrival + 15 minutes(constantlateRiskGrace) and there is norm_departure_arrivalrow ford-> flag the promise AT_RISK with the NEW reasonPREDICTED_LATEthrough the existingflagAtRiskpath (add the constant besideReasonNodeUnsourceable). - Re-promise only when needed: a promise flagged
PREDICTED_LATEis NOT sent toReviseAll/RepriceAtRiskwhile its current window is still reachable. Reachable means: (the latest of the witness path's remaining departureexpectedArrivals, shifted by the observed lateness of the late leg) + the existing downstream dwell/last-mile allowance the search uses<=the promise's window end. When it is no longer reachable, the normal re-promise runs. If the code offers no way to compute this from the Witness, STOP that part, ship the flagging only (the promise stays AT_RISK until judged), and report why. - Do not clear the flag when the load arrives later; AT_RISK is already
Active()and the judgement (KEPT/BROKEN) closes it. State this in the ADR as a deliberate limit. - Add
PREDICTED_LATEto the reason enums in openapi/asyncapi (PromiseAtRisk.reason), the docs, and the F9 analytics projection if it enumerates reasons. - Metrics
deliverypromise_predicted_late_flagged_totaland a log line per flag.
How the contract is met in this code base:
- Departures of a witness path. The witness lists the pickup departure and the ordered legs (
Witness.PickupDepartureID,Witness.Legs), so the path is[pickup, legs...]. A NOMINAL witness has none and is never examined. A departure that is missing from the read model, not scheduled or cancelled is skipped (a cancelled one already flagged the promise throughDepartureCancelled). - One adjustment, two users.
search.ExpectedArrival(d, measured)is the one-sided measured-transit adjustment of ADR 0014, now exported from the search package; the search's ownmeasuredAtcalls it. The sweeper passes the same closure the search gets (measuredTransitOf: the current policy's percentile, minimum observations and window), so belowminTransitObservationsthe adjustment is 0. - The arrival model.
rm_departure_arrival(departure_id PK, arrived_at)is written in theLoadArrivedhandler, in the same inbox transaction as the measured-transit pairing, only when the event carries adepartureId; a first arrival is kept, a repeat is ignored. Rows older than the maximum transit window (policy.MaxTransitWindowDays) are deleted on write. An event without adepartureIdwrites no arrival row and incrementsdeliverypromise_departure_arrival_ignored_total; its measured-transit pairing is unchanged. - The sweep.
FlagPredictedLate(ctx, limit)pages through the CONFIRMED promises by id,limitper page (the sweeper's batch size, 100), and returns how many it flagged. Each flag is its own unit of work throughflagAtRisk(..., ReasonPredictedLate), which re-reads the promise and flags it only if it is still CONFIRMED, so a second pass (and a concurrent risk event) flags nothing twice: an AT_RISK promise is not CONFIRMED and is not examined. Each flag logs one INFO line (promiseId, the latedepartureId,expectedArrival) and countsdeliverypromise_predicted_late_flagged_total. A failure of one promise is logged and the pass goes on; the pass error is logged bysweepOncelike any other. - Reachability (
search.PathRisk.Reachable). Let the path legs bed1..dn,Lthe first leg with no arrival row whoseexpectedArrival + lateRiskGraceis beforenow(the late leg), andRthe legs fromLon with no arrival row (the remaining departures).lateness = now - expectedArrival(L): the load is at least that much behind its expected arrival.projected = max over R of expectedArrival + lateness(the latest remaining expected arrival, shifted by the observed lateness of the late leg).- The downstream allowance is the allowance the search itself adds after a station arrival: the sort dwell of every intermediate node the load still has to pass after the late leg (
SortDwellMinutesof the destinations of the legs fromLup to, but not including, the leg that reaches the delivery station) plus the last-mile allowance of the witness wave,wave.windowEnd - wave.inductCutoffAt(the search takes the first wave whose induct cutoff is not before the arrival, so an arrival by the induct cutoff keeps the wave, and the wave's window ends that much later). - Reachable when
projected + dwell + lastMile <= promise.terms.window.latest. - The wave comes from the local DeliveryWaveView by
Witness.DeliveryWaveID. A wave that is missing, cancelled or not scheduled makes the window not reachable, so the normal re-promise runs.
RepriceAtRisk. It lists the AT_RISK promises in pages (oldest first) and, beforeReviseAtRisk, skips each promise whose reason isPREDICTED_LATEand whose window is still reachable; the skipped ones do not count against the batch limit, so they cannot starve the others. A promise that is not reachable, and every other reason, goes to the normal re-promise unchanged. Re-promise searches from now, so it never re-installs the pickup whose cutoff has passed.- No clearing. When the late load arrives later the flag is NOT cleared: AT_RISK is
Active(), and the judgement (KEPT or BROKEN) closes the promise. A deliberate limit: a promise that recovers stays AT_RISK until it is judged; clearing needs a new transition (AT_RISK back to CONFIRMED) that the model does not have and that would raise a second integration event with no consumer asking for it. Customers hear about a lateness once, fromPromiseAtRisk; aPromiseRevisedfollows only when the window cannot be kept. - Contracts.
PREDICTED_LATEjoins the documentedreasonvalues ofPromiseAtRisk(AsyncAPI, the events and use-case pages) and ofatRiskReason(OpenAPI, the generated REST reference). The reason is a free string on the wire, so no consumer breaks. The analytics projection (ADR 0018) projectsPromiseRevised,PromiseKept,PromiseBroken,PromiseUnkeepable,PromiseMadeandDeliveryOfferQuotedand does not projectPromiseAtRisk, so it enumerates no reason and needs no change. - Deploy. No new topic (both events come from the linehaul topic the service already consumes), no env var, no chart value. The pass runs in the existing sweeper at
SWEEP_INTERVAL. Migration 0008 adds the table; it is additive and reversible.
Consequences
- A load that is late and not yet scanned in turns into a
PromiseAtRisk{PREDICTED_LATE}while the customer can still be told, instead of aPromiseBroken{LATE}after delivery. Where the slack of the path (sort dwell, a wave cut off late) still absorbs the delay the promise keeps its window, stays AT_RISK and nothing is re-dated; where it does not, the normal re-promise moves the window (never earlier). - The prediction needs the arrival of the departure, so it works only for loads whose events carry
departureId; older events are counted and ignored. A missedLoadArrived(service down, nodepartureId) looks like a late load: the cost is a falsePromiseAtRiskfor a promise that is reachable, which the reachability test keeps from being re-promised. - The grace (
lateRiskGrace, 15 minutes) and the use of the measured P-service-level adjustment are constants of the pass, notPromisePolicyfields, so no persisted policy changes. - The flag is one-way (see "No clearing"), so a predicted-late promise that recovers shows
atRiskReason = PREDICTED_LATEon its read model until its judgement; consumers that need the recovery read the judgement. - A full scan of the CONFIRMED promises at each sweep reads two or three local rows per promise. That is cheap at the present volume; a prefilter on the scheduled arrival would be the first optimisation if the active set grows.