Wiki · Workflow companion

USDA lot drawdown commit

A USDA commodity lot is exhausted. Compute the weighted-average cost from the remaining lots, flag every open quote touching the commodity SKU for re-quote, push the new cost basis, and reconcile against the USDA program allocation.

Mixed · Some steps live, others stubbed
What this is

USDA lot drawdown commit

USDA commodity drawdown is the workflow that keeps weighted-average costing honest when a lot exhausts. The pricing of every assembly that uses the commodity (barrel cheddar, etc) depends on which lot we're drawing from — if a lot ends and we forget to recompute, every quote and pricing_master row sourced from that commodity is wrong.

The cascade re-bases the vendor_costs entry, recomputes the assembly_cost_rollup for every affected assembly, flags open quotes for re-quote, and updates the USDA program reconciliation status.

Risk level 4 (high) — because the cost basis touches active customer pricing.

When to use it

Trigger conditions

Heuristic

The cost_diff_reasonable precondition warns if the new lot's cost differs by >30% from the exhausted lot. This catches the most common data error: wrong lot mapped to wrong commodity.

Step-by-step what happens

The 4 beats

  1. 01

    INSERT new vendor_costs row

    INSERT into vendor_costs with the new weighted-average unit_cost and effective_from. The prior row remains (active=false implicit via effective_from ordering).

    Writes vendor_costs
    Time ~80ms
    Kind d1_write
    Status stub
  2. 02

    Recompute affected assemblies

    Call recompute_assembly_cost_rollup for each assembly whose BOM references the commodity sku. Rollups persist with fresh last_computed.

    Writes assembly_cost_rollup
    Time ~200ms per assembly
    Kind chat_tool
    Status stub
  3. 03

    Flag affected open quotes

    For each quote in (draft, proposed, sent) with a line on the commodity sku, stage flag_stale_quote in proposed_actions.

    Writes proposed_actions
    Time ~50ms per quote
    Kind stage_proposed_action
    Status real
    Note one_per affected quote
  4. 04

    USDA program reconciliation

    UPDATE usda_commodity_programs SET reconciliation_status='pending' for affected programs. Surfaces in the USDA reconciliation queue.

    Writes usda_commodity_programs
    Time ~80ms
    Kind d1_write
    Status stub
Outcomes

What's different after the workflow runs

New cost basis
Applied
≤ 10s
Assemblies
Recomputed
per BOM hit
Quotes
Flagged
in proposed_actions
USDA reconcile
Pending
queued
Failure modes

What can go wrong and how to recover

No next lot available

Precondition blocks: current_lots.length > 0. This means we have no commodity supply for the SKU. Manual escalation: USDA program manager to provision a new lot.

Cost differential >30%

Precondition warns. Likely a data error (wrong lot mapped). Mike verifies the lot assignment before approving.

Assembly recompute partial

Retry policy is 2 linear-backoff attempts. Persistent failures alert; manual POST /admin/assembly/recompute recovers.

No quotes affected

Sometimes a commodity drawdown happens with no open quotes. Cascade still completes; no flag rows stage.

Related

Adjacent workflows + diagrams

For developers

Code paths + invariants

ConcernWhere
Workflow contractworkflow_definitions WHERE workflow_type='usda_drawdown_commit'
Lot tableusda_commodity_lots
Program tableusda_commodity_programs
Cost-basis patternweighted-average across active lots
Reflexion tagusda_drawdown,sku:<sku>
Risk level4
Expected duration~30 min
Triggerevent · sources=inventory_threshold_cron, manual_lot_close
// Weighted-average across remaining active lots const avg = currentLots.reduce( (sum, l) => sum + (l.remaining_qty * l.unit_cost), 0 ) / currentLots.reduce((sum, l) => sum + l.remaining_qty, 0); await db.run( "INSERT INTO vendor_costs (vendor_item_id, unit_cost, effective_from, source, status) " + "VALUES (?, ?, ?, 'usda_drawdown', 'active')", [vendor_item_id, avg, effective_from] );
Changelog

Dated trail · spot stale claims

Dated trail of when this doc was last touched, what changed, and what to look at if it feels stale.

DateRoundChangeTouched by
2026-05-26R586Added CHANGELOG · SCHEMA · RUNBOOK · BACKLOG sections — wiki became best-in-class operating documentation.Mike + Claude
2026-05-25R584/R585Wiki originally shipped — 8-section structure (hero / what / when / steps / outcomes / failure-modes / related / for-developers).Mike + Claude
If today is more than 60 days past the latest changelog row, treat live system behavior as the source of truth. The doc may have drifted — verify against the workflow contract in workflow_definitions WHERE workflow_type='usda_drawdown_commit' before acting on these claims.
Schema · data contract

The machine-readable spec

Canonical fields, table names, endpoint signatures. What code should match, what tests should assert. workflow_type · usda_drawdown_commit · risk_level · 3.

Inputs (required + optional)

FieldTypeDescription
entitlement_idstringUSDA entitlement reference. Required.
item_idintegerRequired — the USDA-eligible item.
draw_qtydecimalQuantity to draw. Required.
draw_datedateEffective date.

D1 tables written

TableOperationTrigger
usda_drawdownsINSERTFIFO drawdown record
proposed_actionsINSERTDrawdown commit proposal
usda_entitlement_balanceUPDATE (post-HITL)Decrement balance
eventsINSERT (usda.drawn)downstream bid_price_update (net cost shift)

Endpoints called

MethodPathPurpose
POST/api/workflow/executeRunner entrypoint
GET/api/usda/entitlements/:id/balanceLive balance

Events fired

event_typeWhenSubscribers
usda.drawnPost-HITL commitbid_price_update on barrel cheddar lines
Runbook · when it breaks

It broke at 2am — what now

Different from "how do I use this." This is the page Mike pulls up when something is wrong: logs to check, recovery steps, who to escalate to.

Scenario · Drawdown committed but balance didn't decrement

Post-HITL UPDATE didn't fire.

  1. Verify: SELECT balance FROM usda_entitlement_balance WHERE entitlement_id=?
  2. Manual decrement: UPDATE ... SET balance = balance - ?
  3. Log: Add a usda_drawdowns row if missing.

Scenario · Balance went negative

Drawdown exceeded available — FIFO check failed.

  1. Check: SELECT balance FROM usda_entitlement_balance WHERE entitlement_id=?
  2. Roll back: UPDATE usda_drawdowns SET status='rolled_back' WHERE id=<id>; restore balance.
  3. Fix the FIFO: Drawdown workflow must verify balance >= draw_qty before staging.

Scenario · Drawdown affected barrel cheddar pricing but bid wasn't updated

usda.drawn event subscribed but bid_price_update didn't trigger.

  1. Check subscriptions: SELECT * FROM event_subscriptions WHERE event_type_pattern IN ('usda.drawn','usda.*')
  2. Manual trigger: Use propose_price_change with new net cost.

Logs to check

Kill switch · emergency stop

If this workflow is misbehaving in a high-impact way (creating bad proposed_actions in volume, pushing wrong things to NS), flip a kill switch:

See kill-switches-state-machine.html for the full state machine + recovery procedure.

Escalation

Primary: Mike Levine (single-admin) · mikelevine@globalfoodsolutions.co. For prolonged outage during business hours, notify warehouse lead + accounting lead so they can defer dependent work.

Backlog · open questions

What's not done · what's uncertain

What's not done, what's uncertain, what we punted. Captured so it survives context switches and doesn't die in someone's head.