Skip to main content

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 LoadDeparted and LoadArrived already carry departureId (producer schema LoadDepartedEvent/LoadArrivedEvent). Extend DP's tolerant consumed copies with the OPTIONAL departureId (asyncapi consumed schemas too). New local read model DepartureArrival (rm_departure_arrival: departure_id PK, arrived_at), written on LoadArrived that carries a departureId, pruned past the transit window. Migration 0008. Old events without departureId are ignored by this model (counted).
  • New sweeper pass FlagPredictedLate(ctx, limit) in the existing clock-driven sweeper (same interval, same batch limit, logged failures; follow sweepOnce). For each CONFIRMED promise: for each departure d of 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; below minTransitObservations the adjustment is 0). If now > expectedArrival + 15 minutes (constant lateRiskGrace) and there is no rm_departure_arrival row for d -> flag the promise AT_RISK with the NEW reason PREDICTED_LATE through the existing flagAtRisk path (add the constant beside ReasonNodeUnsourceable).
  • Re-promise only when needed: a promise flagged PREDICTED_LATE is NOT sent to ReviseAll/RepriceAtRisk while its current window is still reachable. Reachable means: (the latest of the witness path's remaining departure expectedArrivals, 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_LATE to the reason enums in openapi/asyncapi (PromiseAtRisk.reason), the docs, and the F9 analytics projection if it enumerates reasons.
  • Metrics deliverypromise_predicted_late_flagged_total and 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 through DepartureCancelled).
  • 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 own measuredAt calls it. The sweeper passes the same closure the search gets (measuredTransitOf: the current policy's percentile, minimum observations and window), so below minTransitObservations the adjustment is 0.
  • The arrival model. rm_departure_arrival(departure_id PK, arrived_at) is written in the LoadArrived handler, in the same inbox transaction as the measured-transit pairing, only when the event carries a departureId; 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 a departureId writes no arrival row and increments deliverypromise_departure_arrival_ignored_total; its measured-transit pairing is unchanged.
  • The sweep. FlagPredictedLate(ctx, limit) pages through the CONFIRMED promises by id, limit per page (the sweeper's batch size, 100), and returns how many it flagged. Each flag is its own unit of work through flagAtRisk(..., 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 late departureId, expectedArrival) and counts deliverypromise_predicted_late_flagged_total. A failure of one promise is logged and the pass goes on; the pass error is logged by sweepOnce like any other.
  • Reachability (search.PathRisk.Reachable). Let the path legs be d1..dn, L the first leg with no arrival row whose expectedArrival + lateRiskGrace is before now (the late leg), and R the legs from L on 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 (SortDwellMinutes of the destinations of the legs from L up 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, before ReviseAtRisk, skips each promise whose reason is PREDICTED_LATE and 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, from PromiseAtRisk; a PromiseRevised follows only when the window cannot be kept.
  • Contracts. PREDICTED_LATE joins the documented reason values of PromiseAtRisk (AsyncAPI, the events and use-case pages) and of atRiskReason (OpenAPI, the generated REST reference). The reason is a free string on the wire, so no consumer breaks. The analytics projection (ADR 0018) projects PromiseRevised, PromiseKept, PromiseBroken, PromiseUnkeepable, PromiseMade and DeliveryOfferQuoted and does not project PromiseAtRisk, 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 a PromiseBroken{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 missed LoadArrived (service down, no departureId) looks like a late load: the cost is a false PromiseAtRisk for 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, not PromisePolicy fields, so no persisted policy changes.
  • The flag is one-way (see "No clearing"), so a predicted-late promise that recovers shows atRiskReason = PREDICTED_LATE on 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.