Skip to content

Score-Based Allocation

Allocation distributes limited supply across competing demands using a deterministic, score-based priority system. It runs after the supply pipeline step (auto-triggered) or standalone via CLI/API, over a 13-week default horizon (one fiscal quarter).

Allocation Overview — KPI row + per-demand fulfillment grid (Oct 2026)


Table of Contents


Overview

When demand exceeds supply, not every order can be fulfilled. Allocation answers the question: which demands get the available stock, and how much?

Mirabelle's allocation engine solves this by assigning every demand a composite score derived from business rules (priority class, strategic value, urgency, fairness), then allocating supply greedily from the highest-scored demand downward. The result is a deterministic, auditable, and explainable assignment of inventory to orders.

When does it run?

Trigger Description
Auto (pipeline) After the supply step completes, allocation runs automatically on the netted forecast and planned supply
Manual (API) POST /api/allocation/run
Manual (CLI) python -m files.run_pipeline --only allocation

13-week horizon

The default horizon is 13 weeks (one quarter). Beyond 13 weeks the candidate cardinality grows prohibitively large for typical datasets. Override with the ALLOCATION_HORIZON_WEEKS environment variable.


Core Concepts

Demands

Each demand represents a single (item, site, week) combination requiring supply:

Source Meaning
Unconsumed forecast Table: PIPE_forecast_netting.
Description: net demand after netting (statistical + maintenance minus returns, minus firm-order consumption).
Firm future orders Table: master.demand_orders (Layer 0).
Description: order-book lines from the planning week onward; the old is_forecast = false flag was replaced by the planning-week is_open partition.

Firm-order metadata (customer name, per-week priority class) resolves at read time from Layer 0, keyed on week index — convention-independent.

The netting step (see Supply Planning > Netting) already combines unconsumed forecast with firm demand into supply_plan_qty. Allocation consumes this final figure.

Supplies

Each supply record represents inventory or planned orders available to fulfil demands:

Source Meaning
On-hand inventory Table: master.on_hand.
Details: aggregated per (item, site, type) where planning_type IN ('good', 'new').
Planned supply orders Table: PIPE_supply_recommendations.
Details: statuses planned, firm, released, or in_transit; orders may be purchase, transfer, make, or repair.

Allocation Unit

One demand is one (item, site, week) tuple. The engine never splits a single demand across multiple supply sources for the same week—though partial fulfilment is allowed when total supply is insufficient.

Composite Score

Every eligible (demand, supply) pair receives a composite score:

total_score = priority + aging + lateness
             + strategic + revenue + criticality + consequence
             − routing_penalty − reservation_penalty

Higher total scores are allocated first. The fairness penalty is not part of this sum — it is computed after allocation as a diagnostic (see Fairness tab). The score breakdown is stored per allocation and is fully explainable (see Explainability).


The 8-Pass Algorithm

The allocation engine (implemented in Rust for performance) executes eight deterministic passes:

flowchart LR
    A[1. Enrich] --> B[2. Seed Fairness]
    B --> C[3. Build Reservations]
    C --> D[4. Generate Candidates]
    D --> E[5. Filter Hard Constraints]
    E --> F[6. Score Candidates]
    F --> G[7. Sort by Score]
    G --> H[8. Greedy Allocation]
Pass What happens
1 · Enrich backlog Compute backlog_days = current_date − required_date for each demand; attach priority class and strategic/revenue/criticality weights from master.item.
2 · Seed fairness tracker Register each demand's group (channel, customer class, or program) and quantity in the fairness state machine.
3 · Build reservations Fence a portion of each supply for high-priority future demands, such as AOG orders arriving within the lookahead window.
4 · Generate candidates Create demand/supply pairs where item_id and location_id match and supply arrives within the demand's maximum-delay tolerance.
5 · Filter hard constraints Remove candidates that violate hard routing rules, such as a supply location outside the allowed set; excluded candidates never return.
6 · Score candidates Compute the composite score in parallel. Components include priority, aging, lateness and business weights; routing and reservation penalties reduce the score.
7 · Sort descending Sort all scored candidates by total_score DESC, with deterministic (demand_id, supply_id) tiebreaking.
8 · Greedy allocation Walk the sorted list, checking remaining supply, remaining demand, and the fairness hard cap; allocate min(demand_remaining, supply_remaining) and update trackers until candidates are exhausted.

Determinism

The same inputs always produce the same outputs, including tiebreaks. Re-running allocation with unchanged data yields identical results.


Policy Tabs (the Scenario Editor)

Seven policy types control allocation behaviour. Each is stored as a parameter set in the database and resolved per scenario (with optional segment-level overrides).

Allocation policy is edited on Pipelines → Allocation: click a scenario row (or its Edit button) to open the scenario editor popup — Info plus one tab per policy type (Priority, Starvation, Reservation, Fairness, Routing, Aging, Lateness). Each type tab lists that type's parameter sets — ordered by priority, drag to reorder, the default row is the catch-all — and expanding a set opens its parameters and segment links. A scenario is linked per pipeline in the pipeline editor's Allocation dropdown; a pipeline with no linked scenario runs on engine default policies.

Info tab

Name and description of the scenario (auto-saved as you type), plus the pipelines currently linked to it. Create, clone and delete actions live on the scenario list.

Priority tab

Priority Policy

The priority policy defines the base score each priority class receives and the multipliers applied to business weights.

Where does a demand's priority class come from? One of aog / critical / premium / standard / low, resolved in this order:

  1. The week's firm order lines (master.demand_orders, edited on the Demand Orders grid) — the highest-ranked class among the week's lines wins; a blank never replaces an existing value
  2. Fallback: the item's class (master.item, edited on the Items grid; database default standard)
  3. Final fallback: standard

The class is then mapped to a number by the scenario's priority scores table:

Priority Class Default Score Typical Use
AOG 10 000 Aircraft-on-ground / emergency — must ship immediately
Critical 5 000 Key customer commitments, contractual SLAs
Premium 2 000 High-value orders, strategic accounts
Standard 1 000 Normal business demand
Low 100 Fill-in orders, low-margin SKUs

Three global weight factors scale the business-weight components (strategic_weight, revenue_weight, criticality_weight are per-item columns on the Items grid — revenue_weight is not derived from the item's price; it is whatever strategic number the planner or the customer extract stores):

Factor Affects Default
strategic_weight_factor demand.strategic_weight × factor 1.0
revenue_weight_factor demand.revenue_weight × factor 1.0
criticality_weight_factor demand.criticality_weight × factor 1.0

Worked cases — priority & weights (engine-verified)

Four 10-unit demands compete for 30 units; default scores, no weights.

Demand Class Priority Revenue Total Served
AOG line aog 10 000 0 10 000 1st (10)
PREMIUM premium 2 000 0 2 000 2nd (10)
STD + revenue 800 standard 1 000 800 1 800 3rd (10)
LOW low 100 0 100 ❌ short 10

A revenue weight of 800 lifts a standard demand (1 800) but not past premium (2 000) — the weight would have to bridge the whole score gap between the classes. Weights reorder demands within the ladder; the ladder itself comes from the scores table.

The table is the only truth: with scores {"low": 9, "aog": 1}, a low demand (total 9) outranks an AOG demand (total 1). The class names carry no built-in order.

All weights 0: changing any weight factor has no effect (there is nothing to amplify).

Starvation tab

The starvation policy prevents demands that keep losing from waiting forever: a demand overdue beyond the threshold earns a bonus that buys rank.

Parameter Default Meaning
enabled true Activate anti-starvation logic
escalation_threshold_days 14 Days a demand must be overdue before escalation begins
score_per_extra_day 50 Bonus points added per day beyond the threshold
max_starvation_bonus 3 000 Cap on total starvation bonus (0 = uncapped)
auto_upgrade_priority false Bump the demand's effective PriorityClass one level once the threshold is crossed

A demand X days overdue earns (X − 14) × 50, capped at 3 000. The bonus lands in the aging component and stacks with any aging policy (see the Aging tab).

Worked cases — what waiting buys (engine-verified)

A low demand (base 100), default settings:

Overdue Bonus Total Beats a fresh…
14 d 0 100 nothing (loses to standard 1 000)
30 d 800 900 — (still loses to standard)
51 d 1 850 1 950 — (loses to premium by 50)
70 d 2 800 2 900 premium (head-to-head verified)
365 d 3 000 (cap) 3 100 premium — never critical (5 000) or AOG (10 000)

The cap is the reconciliation knob: by default a demand can wait its way up to roughly premium level, but a genuinely urgent critical or AOG order always wins. Raise max_starvation_bonus to let extreme waiting buy more.

With auto_upgrade_priority: a low demand overdue ≥ 14 days is scored as standard (1 000) plus the bonus — 30 days overdue totals 1 800; a year still caps at 1 000 + 3 000 = 4 000.

Reservation tab

The reservation policy fences a portion of supply for high-priority future demands — stock held back so a demand arriving shortly cannot be crowded out by today's orders.

Parameter Default Meaning
enabled true Activate reservation fences
lookahead_days 14 How far ahead to scan for protected demand
min_protected_priority PREMIUM Demands at or above this class get fences
penalty 2 000 Score penalty for a lower-priority demand drawing from fenced stock
safety_margin 0.0 Extra buffer fraction added to the reserved quantity

Each future demand within the lookahead window at/above the protected class fences qty × (1 + safety_margin) on the matching (item, location) supply. The fence is soft: a lower-priority demand may still draw from fenced stock, but its score pays the penalty (2 000 by default) — while the fence owner (any demand at/above the fence's class) draws at full score.

Worked case — reservation (engine-verified)

100 units on hand; an AOG demand of 80 arrives in 10 days (inside the 14-day lookahead); a standard demand of 50 is due now.

Demand Score Outcome
AOG due +10d 10 000 takes 80 (the 20 free units first, then 60 of its own fence)
Standard due now 1 000 − 2 000 = −1 000 short 50 — nothing left

The standard demand paid the penalty and lost the free remainder the owner consumed first. With penalty raised to 99 999 the fence becomes an effective block (the intent of the old doc example) — the default 2 000 makes fenced stock unattractive but reachable.

Fairness tab

The fairness policy tracks the share of allocated units going to each demand group (group_field: channel, customer_class or program — empty target_shares means equal shares).

Parameter Default (seeded) Meaning
enabled true Activate fairness tracking
group_field customer_class Dimension for grouping
target_shares {"Retail": 0.40, "Wholesale": 0.35, "Direct": 0.25} Group → target share of allocated units
tolerance 0.05 Allowed overage above the target share before penalties/caps
penalty_per_over_unit 80 Diagnostic penalty per unit above share
hard_cap false If true, block further allocation to groups over their share

The fairness penalty never changes the ranking — it is computed after allocation and reported on the explanations as a diagnostic. The only lever that changes who gets units is hard_cap: true.

Worked case — hard cap (engine-verified)

30 units; four 10-unit demands in channels A, A, A, B; target_shares {"A": 1.0, "B": 1.0} (50/50), tolerance 0.10, hard cap on.

Step Group mix Result
A1 takes 10 A = 10/10 → 100 % served
A2 100 % > 50 %+10 % → capped blocked
A3 capped blocked
B1 takes 10 10 vs 10 = 50/50 served

Final: A1 + B1 served; A2/A3 short. Same run with hard_cap: false: all three A demands are served first (equal scores, id tie-break) and B1 gets nothing — the overage only shows up as a fairness diagnostic on the explanations.

Routing tab

The routing policy validates that a supply source is compatible with a demand's fulfilment constraints.

Constraint Effect
forbidden_locations / forbidden_pools Always hard — the candidate is removed
allowed_locations / allowed_source_types / allowed_pools Hard (block) or soft (penalise) per hard_mode
preferred_locations Always soft — not being preferred costs the penalty

Each soft violation costs routing_violation_penalty (default 100 in the engine, 500 in the seeded default set). Multiple routing policies can coexist, each keyed by policy_id; the scenario's default policy (is_default) applies to every demand.

Worked case — soft vs hard (engine-verified)

One 10-unit demand; two supplies at its location: inventory (INVENTORY) and a transfer (TRANSFER). Policy allows source type INVENTORY only, penalty 100.

Mode Result
Soft (hard_mode: false) TRANSFER candidate scores 100 lower — INVENTORY serves first, transfer is still reachable if inventory runs out
Hard (hard_mode: true) TRANSFER candidate is removed entirely — with 10 units of inventory against a 15-unit demand, the demand is partially filled (10/15) and the transfer's 10 units are never touched

A policy filters or penalises candidates; it does not create a transfer lane.

Aging tab

The aging policy adds urgency as a demand waits — an additional term on top of the starvation bonus (they stack in the same score component).

Mode Formula
none 0
linear multiplier × backlog_days
exponential multiplier × backlog_days^exponent

Worked case — stacking (engine-verified)

A standard demand 30 days overdue, linear aging × 10/day, default starvation (threshold 14, 50/day):

aging base    = 10 × 30 = 300
starvation    = (30 − 14) × 50 = 800
aging component = 1 100   → total = 1 000 + 1 100 = 2 100

2 100 beats a fresh premium demand (2 000) — waiting 30 days with these settings overtakes premium. Exponential × 1.5 at 30 days: 10 × 30^1.5 ≈ 1 643 on its own.

Lateness tab

The lateness curve scores the expected delivery delay of a (demand, supply) pairing: supply.available_date − demand.required_date, only when positive. The curve is a piecewise-linear list of (days, points) breakpoints — interpolated between points, flat beyond the last one. The seeded default set carries LAT_DEFAULT: [[0, 0], [3, 500], [7, 2000], [14, 5000]].

Worked case — the seeded default curve (engine-verified)

A standard demand required 5 days ago; supplies arriving at various delays:

Supply delay Curve value Demand total
on time 0 1 000
3 d 500 (breakpoint) 1 500
5 d 1 250 (interpolated) 2 250
7 d 2 000 (breakpoint) 3 000
14+ d 5 000 (flat cap) 6 000

The lateness term is ADDED, not subtracted

The value is a boost to the pairing that would suffer the most delay, not a penalty — a pairing facing a bigger expected delay ranks higher, so the engine secures stock for the demand that would otherwise be hit worst. (The curve's (days, points) shape reads like a penalty table, and the other "penalty" terms are subtracted — the naming is misleading.) No test pins an intended sign; if you want late supplies to rank lower, invert the curve's point values (negative points).


The Final Choice and Ordering

All the terms above land in one sum per (demand, supply) pairing — there are no rounds, vetoes or separate queues:

total_score = priority + aging(+starvation) + lateness
             + strategic + revenue + criticality + consequence
             − routing_penalty − reservation_penalty

The engine then:

  1. Generates candidates — every (demand, supply) pair with matching item + location whose delay fits the demand's max_delay_days
  2. Removes hard-blocked candidates — forbidden locations/pools, disallowed locations/source-types in hard_mode, fairness hard_cap during allocation
  3. Sorts by total score descending — ties broken deterministically by demand_id, then supply_id
  4. Allocates greedily down the sorted list: each pairing takes min(demand remaining, supply remaining) until supplies run out

How the points of view reconcile:

Point of view Term Sign Reconciled by
Static importance (class) priority + the scores table — its gaps set how much other terms must earn to cross
Waiting time aging + starvation + threshold (floor), per-day rate, cap (the ceiling on what waiting can ever buy)
Expected delay lateness + the curve — boosts the pairing that would suffer most
Item value strategic/revenue/criticality + per-item weights × factors — bridges gaps between classes
Supply fitness routing, reservation − demotions; hard modes become absolute vetoes
Group balance fairness (none) diagnostic only, unless hard_cap acts

Reading the magnitudes

With default scores (AOG 10 000 / Critical 5 000 / Premium 2 000 / Standard 1 000 / Low 100) and default starvation (14 d, 50/day, cap 3 000): waiting can lift a demand roughly one class level (a year-old standard demand tops out at 4 000 — past premium, never past critical); weights bridge gaps only as large as their value (a revenue weight of 800 lifts a standard demand to 1 800 — still below premium); hard blocks are absolute (a forbidden location never allocates, whatever its score would have been).

What actually fires on the pipeline today

The allocation step's demands are netting forecast weeks — always dated from the planning week onward — so the engine-derived backlog_days is always 0 and starvation and aging never fire there. Lateness, routing, reservation and fairness are all live. Starvation/aging matter only where demands can be past-dated (backorder / order-book carries), which the current demand loader does not produce.


Allocation Overview (Dashboard → Allocation)

The Allocation view on the Dashboard (/dashboard?tab=allocation) is a KPI row + the per-demand fulfillment grid — one row per demand of the latest completed run.

Allocation Overview — KPI row + per-demand fulfillment grid (Oct 2026)

KPI Row

See Allocation Overview KPIs for the definitions, the policy settings that trigger each card, and read-only PostgreSQL and ClickHouse queries to reconcile the numbers.

KPI cards filter the list (user directive: "pushing one of the KPIs should filter"): every KPI with a per-demand predicate renders as a toggle button with an active ring and an "N of M demands" count —

KPI Filter
Fill Rate → "Fully filled" status = full
Total Backlog shortfall > 0
Unmet unfulfilled
Partially partial
Routing / Fair-Share violations flag set

Allocated Qty and Protected Inventory stay inert. An empty grid shows an honest reason (no completed run vs. filter vs. run has no demands).

The Demands Grid

GET /api/allocation/overview/demands returns one row per demand — requested/allocated/shortfall, fill %, status (full/partial/unfulfilled from PIPE_allocation_unfulfilled), real priority/customer (read-time firm metadata), lateness (worst available_date − required_date across its allocated sources: OH_* = planning today, SO_* = PIPE_supply_recommendations.arrival_week, FIRM_* = MASTER_supply_orders_firm.arrival_dt) and sources (per-supply qty/type/arrival). Rendered by AllocationDemandsTable.jsx (ag-grid: sortable columns + floating filters).

Row click → /series/{item_id}_{site_id}?tab=allocation — the series detail Allocation tab, with the clicked demand pre-selected so the Explainability panel carries it. Drill nav arrows (↑/←/→ mounted beside the detail tabs) walk the grid's displayed order (each hop navigates + selects the walked demand); ↑ returns to the Overview, which scrolls to + flashes the last-viewed demand.

The Supply Path Modal lives on the detail tab

The demand↔supply DAG modal is opened from the detail Allocation tab's demand-table rows / timeline bars (which pass the (item, site) pair) — the overview rows carry no item/site ids on their detail endpoints.

The old Overview panels (flow DAG, capacity card, backlog heatmap, fair-share card, five secondary tabs) and their backend endpoints were removed with the Oct 2026 redesign; the series-detail Allocation tab (timeline, competition, consumption, explainability) is unchanged below.


Detail View

Click any item/site row to drill into the Allocation Detail view.

Allocation Detail

Header KPIs

KPI Source
Item & Site names master.item, master.site
On-hand quantity master.on_hand (all pools)
Total demand Sum of all demands for this (item, site)
Allocated Sum of allocated quantity
Unmet Sum of shortfall quantity
Protected Quantity held by reservations
Routing violations Count of allocations with routing penalty > 0

Time-Phased Allocation Timeline

The Time-Phased Allocation Timeline is a Gantt-style chart (AllocationTimeline.jsx) that shows, for the selected part (item_id + site_id), how each demand week was matched against available supply.

Allocation Detail

Layout

Row band What it shows
Bottom rows [S] Supply buckets — on-hand inventory (OH_…), purchase orders, transfers, repairs. Each bar is one week wide, positioned at the supply's available_date. Colour by source type (green = inventory, indigo = purchase order, violet = manufacturing, amber = transfer, pink = repair).
Top rows Demand weeks. The demand_id is built as D_{item_id}_{site_id}_W{week_index} (e.g. D_14_303_W6), so one bar appears per forecast week in the horizon. Colour by priority class (red = AOG, orange = critical, yellow = premium, blue = standard, grey = low).

Bar styling encodes fulfilment status:

Style Meaning
Solid fill Fully allocated (status = full)
Right-edge stripe Partial allocation (status = partial)
Dashed red outline + faded fill Unfulfilled (status = unfulfilled)
Solid red border Late fulfilment (lateness_days > 0)

Purple dashed vertical lines mark reservation fences (supply held back for future high-priority demand).

Hover tooltip

Hovering a demand bar shows:

Field Meaning
Demand ID D_{item}_{site}_W{n}
Priority AOG / Critical / Premium / Standard / Low
Status full / partial / unfulfilled
Requested Total quantity demanded that week
Allocated Quantity actually satisfied
Score Composite allocation score (see below)
⏱ late Days late, if the supply arrives after the required date

Click → Supply Path

Clicking a demand bar selects it and opens the Supply Path Modal (see below), which traces the complete demand → supply → source chain for that single week. Clicking a supply bar selects that supply in the consumption table.

How the numbers are computed

The chart is fed by GET /api/allocation/detail/{item_id}/{site_id}/timeline. For each demand week it aggregates, in ClickHouse, the PIPE_allocation_results rows grouped by demand_id:

SELECT demand_id, sum(allocated_qty), sum(total_score)
FROM PIPE_allocation_results
WHERE pipeline_id = … AND scenario_id = … AND archive_date = … AND run_id = …
  AND item_id = {item} AND site_id = {site}
GROUP BY demand_id ORDER BY sum(allocated_qty) DESC LIMIT 18

It then reconciles against PIPE_allocation_unfulfilled:

  • Demand is in the unfulfilled table → requested = requested_qty + allocated_qty, allocated = allocated_qty, status = unfulfilled or partial
  • Demand is NOT in the unfulfilled table → treated as fully filled: requested = allocated = sum(allocated_qty), status = full

The Score field

Score is sum(total_score) — the composite allocation priority the Rust engine computed per (demand, supply) candidate, summed across every supply that fed that demand week:

total_score = priority + aging + lateness
             + strategic + revenue + criticality + consequence
             − routing_penalty − reservation_penalty

(The fairness penalty is a post-allocation diagnostic — not part of this sum.)

The score is independent of quantity — it reflects priority and business weights, not how much was committed. With default allocation_priority settings, standard = 1 000, critical = 5 000, aog = 10 000 (see Priority tab). A score of 6 000 on a standard demand typically means 6 supply candidates were scored for that week (6 × 1 000), or a mix of priority + aging components.

Troubleshooting — "Requested 0, Allocated 0, Score 6000"

If every bar shows Requested 0, Allocated 0 but a non-zero Score, two things are true at once:

  1. Bars render → there are PIPE_allocation_results rows for this (item, site) — the empty-state guard did not trigger, so the run produced scored candidate rows.
  2. Requested/Allocated = 0 → sum(allocated_qty) per demand_id rounds to 0, and there is no matching row in PIPE_allocation_unfulfilled. The endpoint then takes the fallback branch where requested = allocated ≈ 0 and (incorrectly) labels the status "full".

The non-zero Score is the unrounded sum(total_score): the engine scored demand for this part against available supply, but committed ~0 quantity to it (supply exhausted by higher-priority demands, or near-zero supply_plan_qty).

Diagnose with these ClickHouse queries

Replace :pid, :sid, :ad with the active pipeline / scenario / archive_date (the same values the page uses — visible in the URL query string):

-- 1. What's actually stored for this part's allocation rows
SELECT demand_id, supply_id, allocated_qty, total_score, score_priority
FROM PIPE_allocation_results
WHERE pipeline_id = :pid AND scenario_id = :sid AND archive_date = :ad
  AND item_id = 14 AND site_id = 303
ORDER BY demand_id, total_score DESC;

-- 2. Are there shortfall / unfulfilled rows for it?
SELECT demand_id, requested_qty, allocated_qty, shortfall_qty, arrayJoin(reasons)
FROM PIPE_allocation_unfulfilled
WHERE pipeline_id = :pid AND scenario_id = :sid AND archive_date = :ad
  AND item_id = 14 AND site_id = 303;

-- 3. The demand qty that was fed in (should be > 0)
SELECT item_id, site_id, forecast_week, supply_plan_qty
FROM PIPE_forecast_netting
WHERE pipeline_id = :pid AND scenario_id = :sid AND archive_date = :ad
  AND item_id = 14 AND site_id = 303 AND supply_plan_qty > 0
ORDER BY forecast_week;

-- 4. The supply that was available to satisfy it
SELECT supply_id, source_type, qty_available, available_date
FROM PIPE_supply_recommendations
WHERE pipeline_id = :pid AND scenario_id = :sid AND archive_date = :ad
  AND item_id = 14 AND site_id = 303;

Query 1 reveals whether allocated_qty is genuinely tiny (rounding to 0) or exactly 0. Query 2 confirms whether the missing-unfulfilled-row path is why requested collapses to 0. If query 2 is empty while query 1 has zero-qty rows, those demands should have been written to PIPE_allocation_unfulfilled — the shortfall rows were dropped during write_results_ch().

Demo — competition scenarios on /series/14_303

A seeded demo on item 14 / site 303 (pipeline 4) makes the timeline a meaningful competition showcase. It is set up by files/scripts/seed_alloc_demo_14_303.py (idempotent; --restore undoes it).

What was wrong before: the seeded demand for 14_303 was ~0.4 units/week (sub-unit → rounded to 0 in the tooltip), no firm orders → no customer, and supply far exceeded demand → nothing competed.

The demo seed creates 13 weekly firm orders (160 units total) attached to named customers with mixed priority classes, against ~117 units of available supply (50 on-hand + 67 planned):

Week Qty Customer Priority Outcome
W2 25 UAE Team Emirates AOG (10 000) ✅ full
W4 18 Visma-Lease a Bike critical (5 000) ✅ full
W0 15 Ineos Grenadiers premium (2 000) ✅ full
W6 14 Ineos Grenadiers premium (2 000) ✅ full
W1 10 Berlin Cycling Club standard (1 000) ✅ full
W10 11 Équipe Amateurs Tour standard (1 000) ✅ full
W12 16 Berlin Cycling Club standard (1 000) ◐ partial (9/16)
W3 8 Barcelona Riders Club standard ❌ unfulfilled
W5 10 Équipe Amateurs Tour standard ❌ unfulfilled
W8 12 Berlin Cycling Club standard ❌ unfulfilled
W7 8 Barcelona Riders Club low (100) ❌ unfulfilled
W9 7 Barcelona Riders Club low ❌ unfulfilled
W11 6 Barcelona Riders Club low ❌ unfulfilled

The story for a demo: with demand (160) exceeding supply (117), the engine rations by composite score. AOG and critical orders consume the on-hand pool first; premium orders follow; standard orders split the remainder (some full, one partial); and the low-priority amateur orders plus the late standard orders receive nothing — visible as dashed-red unfulfilled bars. Hover any bar to see the customer name, priority class, requested vs allocated, and the composite score.

Re-running the demo (after editing the seed quantities or to refresh after a forecast re-run):

python files/scripts/seed_alloc_demo_14_303.py            # seed firm orders + on-hand
python -m files.run_pipeline --only netting    --pipeline-id 4 --scenario-id 4
python files/scripts/seed_alloc_demo_14_303.py --restore   # undo

Netting must be re-run so the firm orders flow into PIPE_forecast_netting.supply_plan_qty (= unconsumed forecast + firm demand), which is what allocation consumes. Allocation is then re-run from the series page (it reads the latest run for the pipeline's supply_scenario_id).

Two bugs fixed to make the demo work

  1. Customer never shown — the timeline/demands/graph endpoints hardcoded "customer": "" and "priority_class": "standard". They now look up the firm-order customer name + per-week priority from the order-grain demand layer (master.demand_orders order-book rows), matched by week-index (files/api/main.py: _alloc_firm_meta_by_week).
  2. Firm-order priority never reached the scores — load_demands snapped firm-order dates to Monday-of-week, but this tenant's forecast weeks start on Sunday, so the firm-meta key never matched the netting forecast_week and every demand fell back to standard. Fixed by keying firm-meta on the week-index ((date - planning_today).days // 7), which is convention-independent (files/allocation_runner.py: load_demands).

Supply Path Modal

Clicking a demand bar in the Time-Phased Allocation timeline or a row in the Demand Allocation table opens a centered overlay that shows the complete supply path for that single demand.

Supply Path Modal — multi-source allocation with a transfer leg

The modal lays out the chain left-to-right in three columns:

Column What it shows
Source (left) Upstream origin: SOURCE WAREHOUSE (TRANSFER), Supplier (PURCHASE_ORDER), Production Line (MANUFACTURING), Repair Pool (REPAIR). No node for INVENTORY since on-hand IS the source.
Supply (middle) One node per allocated supply. Each shows supply_id, source type, allocated qty, available qty, arrival/release weeks, and ERP status. Firm supplies carry a 🔒 FIRM badge.
Demand (right) The demand node with priority class, item name, requested vs allocated qty.

Edges carry the quantity flowing through them and the lead time for upstream legs.

The right-hand side panel summarises the demand, lists each contributing allocation (with the firm/recommendation share visualised), and remains in sync as you pan or zoom the graph. Close with the × button or the Esc key.

Demands Table

Column Description
Demand ID Unique identifier (e.g. D_123_45_W6)
Priority Class AOG / Critical / Premium / Standard / Low
Required Date Week the demand is due
Requested Qty Total quantity demanded
Allocated Qty Quantity satisfied
Unallocated Qty Remaining shortfall
Score Composite score of the winning allocation
Score Breakdown Expandable: priority, aging, lateness, strategic, revenue, criticality, penalties
Status full / partial / unfulfilled
Flags Routing violation, fairness-adjusted, reservation-blocked

Supplies Table

Column Description
Supply ID OH_ prefix = on-hand; SO_ prefix = supply order
Source Type inventory / purchase_order / make / transfer / repair
Available Date When the supply becomes usable
Qty Available Total quantity
Qty Allocated Quantity consumed by allocations
Qty Reserved Quantity held by reservation fences
Qty Remaining Unallocated surplus
Utilization Allocated ÷ Available (percentage)
Consuming Demands List of demand IDs fed by this supply

Reservations

If the reservation policy is active, this panel shows:

  • Reservation type (e.g. future_premium)
  • Protected quantity
  • Lookahead horizon (days)
  • Protected priority classes (e.g. premium, aog)
  • Reason text

Competition View

Select a supply ID to see which demands compete for it. The competition panel lists all demands paired with that supply, sorted by composite score descending, showing:

  • Demand ID and priority class
  • Requested and allocated quantity
  • Composite score and full breakdown
  • Routing / fairness / reservation flags

This is the key tool for answering: "Why did demand X lose to demand Y?"


Explainability

Every allocation (or unfulfilled demand) has a human-readable explanation. The explain endpoint returns a structured narrative describing exactly how the score was computed and which policies influenced the outcome.

API

GET /api/allocation/explain/{demand_id}?pipeline_id=1&scenario_id=1

Response Structure

{
  "demand_id": "D_123_45_W3",
  "priority_class": "STANDARD",
  "requested_qty": 200,
  "allocated_qty": 150,
  "unallocated_qty": 50,
  "status": "partial",
  "score": 1847.3,
  "score_breakdown": {
    "priority_component":    1000.0,
    "aging_component":       320.0,
    "lateness_component":    0.0,
    "strategic_component":   250.0,
    "revenue_component":    277.3,
    "criticality_component": 0.0,
    "consequence_component": 0.0,
    "routing_penalty":       0.0,
    "reservation_penalty":   0.0,
    "fairness_penalty":      50.0
  },
  "allocation_narrative": [
    "Demand 'D_123_45_W3' (STANDARD) allocated 150.000 units from supply 'OH_123_45_2' at location '45'",
    "Score: 1847.30 = priority(1000.0) + aging(320.0) + lateness(0.0) + strategic(250.0) + revenue(277.3) + criticality(0.0) - routing(0.0) - reservation(0.0)",
    "Fair-share issue: group 'Retail' ended above target share and tolerance (diagnostic 50.0, not part of ranking)"
  ],
  "competing_demands": [ "..." ]
}

fairness_penalty is reported outside the sum — a diagnostic computed from the final allocation mix (see Fairness tab).

Narrative for Unfulfilled Demands

If a demand received no allocation, the explanation includes one of:

Reason Meaning
No matching supply available for this item/location No supply exists at the same site for this item
All supply candidates blocked by hard routing/pool constraints Supply exists but routing policy disallows the pairing
Insufficient supply after higher-priority allocations Supply was fully consumed by higher-scoring demands

If starvation is active and the demand is overdue, an additional line notes the waiting period and escalation threshold.


Running Allocation

Navigate to Processes in the sidebar and include the allocation step in the pipeline. Allocation auto-triggers after the supply step completes.

curl -X POST "<api-host>/api/allocation/run?pipeline_id=1&scenario_id=1"

Response:

{
  "status": "ok",
  "run_id": 42,
  "metrics": {
    "fill_rate": 0.87,
    "demands_fully_filled": 312,
    "demands_partially_filled": 28,
    "demands_unfilled": 17,
    "elapsed_ms": 340
  }
}

python -m files.run_pipeline --only allocation --pipeline-id 1 --scenario-id 1

Or run the allocation runner directly:

python files/allocation_runner.py --pipeline-id 1 --scenario-id 1

Options:

Flag Description
--dry-run Run the engine but do not write results to the database
--segment-id N Prefer parameter sets linked to segment N for global policy types
--verbose Enable debug-level logging

Configuration

Allocation is configured through parameter sets stored in {schema}.allocation_parameter_set. Each parameter set has a parameter_type, a JSONB params column, and optional segment links via allocation_parameter_set_segment.

Parameter Set Types

Type Scope Description
allocation_priority Global (one per run) PriorityScores table + weight multipliers
allocation_starvation Global (one per run) StarvationConfig
allocation_reservation Global (one per run) ReservationConfig
allocation_fairness Global (one per run) FairnessConfig
allocation_routing Policy (many per scenario) One RoutingPolicy per row
allocation_aging Policy (many per scenario) One AgingPolicy per row
allocation_lateness Policy (many per scenario) One LatenessCurve per row

Resolution Order

For global types (priority, starvation, reservation, fairness), the engine resolves parameters in this order:

  1. Segment-specific parameter set — if the demand's segment has a linked parameter set via allocation_parameter_set_segment, use it
  2. Scenario default — the parameter set with is_default = TRUE for this scenario and type
  3. First available — if no default is flagged, use the first parameter set of the correct type (ordered by sort_order)

For policy types (routing, aging, lateness), all parameter sets for the scenario are collected. If a segment is specified, only policies linked to that segment (or policies with no segment links) are included.

Where parameters are managed

Allocation parameters are managed in Pipelines → Allocation: the allocation scenario list, linked per pipeline via the pipeline editor dropdown. Clicking a scenario opens the scenario editor popup — Info plus one tab per policy type (Priority, Starvation, Reservation, Fairness, Routing, Aging, Lateness), each with a short hover tooltip explaining what it configures. Each type tab lists that type's parameter sets (ordered by priority, drag to reorder, the default row is the catch-all); expanding a set opens its parameters and segment links. The last tab you visited and each type's unfolded set are remembered when you leave and come back.

Changes require a re-run

Modifying allocation parameters does not retroactively change existing allocation results. You must re-run allocation for new parameters to take effect.

Segment-Level Overrides

To override a parameter for a specific segment:

  1. Create a new parameter set of the desired type
  2. Link it to the target segment via the segment assignment UI in Settings
  3. Re-run allocation

The engine will automatically prefer the segment-linked parameter set over the scenario default.


Result Tables

Allocation results are written to three ClickHouse tables (atomic replace per pipeline):

Table Contents
PIPE_allocation_results One row per allocation: demand_id, supply_id, allocated_qty, all score components, all penalties, explanation text
PIPE_allocation_unfulfilled One row per unfulfilled demand: requested, allocated, shortfall, and reasons
PIPE_allocation_explanations One row per narrative step (indexed by demand_id, step)

A PostgreSQL allocation_run record tracks each execution with timestamps, counts, fill rate, and the resolved configuration.