Fix the idempotency check in a charge endpoint
Your task
Your /charge endpoint takes an Idempotency-Key header, so a client's retries never charge twice. The first version looked the key up, charged the card, then stored the key. Two retries that arrived at the same moment both found nothing, and both charged. The fix is an atomic claim: the first request for a key claims it in one step, before any money moves.
An assistant wrote resolve_charge_attempts(attempt_lines), which decides what each request does. It is in the editor. It has a bug. Find it and fix it.
Input and output:
attempt_lines: the requests in arrival order. Each iskey|tick: the idempotency key and the tick (time step) it arrived on. Requests on the same tick arrive at the same moment.- Return one decision per request, in order:
charge,wait,replayorreject.
Rules the tests check:
- Split a line on
|. Returnrejectunless it has exactly 2 parts, the key is not empty, and the tick is one or more digits from 0 to 9. - Read the tick as a whole number, so
01and1are the same tick. - A rejected request claims nothing.
- The first accepted request for a key claims it:
charge. Remember the tick it claimed on. - A later request for a claimed key, on the same tick as the claim:
wait. The first charge is still in flight. - A later request for a claimed key, on any other tick:
replay. It gets the stored response. - Keys are compared exactly, case included.
Examples
resolve_charge_attempts(attempt_lines: list[str]) -> list[str]Example 1
Input
resolve_charge_attempts(["k1|1", "k1|1", "k2|1"])Output
["charge", "wait", "charge"]Example 2
Input
resolve_charge_attempts(["k1|1", "k1|2"])Output
["charge", "replay"]