Fix the stock count fold for inventory events
Your task
Your warehouse service updates stock counts from inventory events. EventBridge delivers each event at least once, so the same event can arrive twice. The old handler read the count, added the delta and wrote it back, and counts drifted under load. The new version folds a batch of events in one pass, the way an atomic update with a dedupe key on the event id would.
An assistant wrote apply_inventory_deltas(event_ids, deltas, starting_count). It is in the editor. It has a bug. Find it and fix it.
Input and output:
event_ids: the id of each event, in arrival order. Ids can repeat, and""is a valid id.deltas: the stock change each event carries.deltas[i]belongs toevent_ids[i].starting_count: the stock count before the batch.- Return the final stock count, an integer.
Rules the tests check:
- Pair the two lists by position. If one list is longer, ignore its extra items.
- Apply each event id once. The first event with a given id counts. A later event with the same id is a redelivery and changes nothing, even when its delta is different.
- Add every counted delta to
starting_count. Do not clamp: the result can be negative.
Examples
apply_inventory_deltas(event_ids: list[str], deltas: list[int], starting_count: int) -> intExample 1
Input
apply_inventory_deltas(["e1", "e2"], [5, -2], 10)Output
13Example 2
Input
apply_inventory_deltas(["e1", "e1"], [5, 5], 0)Output
5