Fix the fence check on a Redis lock
Your task
Your daily reconciliation job takes a Redis lock with a 30 second TTL (time to live), so only one worker runs it. When a run takes longer than 30 seconds, the lock expires and a second worker takes over while the first is still writing. The fix is a fencing token: each new lock holder gets a higher number, and the storage refuses writes that carry an older one.
An assistant wrote accept_fenced_writes(write_lines), the check the storage runs on each write. It is in the editor. It has a bug. Find it and fix it.
Input and output:
write_lines: the writes in the order they arrive. Each iswriter|token|payload: who wrote it, the fencing token it carries, and the data.- Return the payloads the storage accepts, in arrival order.
Rules the tests check:
- Split a line on
|. Refuse it unless it has exactly 3 parts, the writer is not empty, and the token is one or more digits from 0 to 9. - Read the token as a whole number. Leading zeros are allowed:
007is 7. - Refuse a token of 0. It means the writer never got the lock.
- Refuse a token lower than the highest token accepted so far. A token equal to it is accepted, so the current holder can write many times.
- A refused write changes nothing. An empty payload is accepted like any other.
- The writer is not used for anything else.
Examples
accept_fenced_writes(write_lines: list[str]) -> list[str]Example 1
Input
accept_fenced_writes(["w1|1|a", "w1|1|b", "w2|2|c"])Output
["a", "b", "c"]Example 2
Input
accept_fenced_writes(["w1|1|start", "w2|2|takeover", "w1|1|late_write"])Output
["start", "takeover"]