Fix the per-account replay of Kafka events
Your task
An assistant's Kafka consumer handed each account event to a thread pool. Events for one account could then be applied out of order, such as a delete before an earlier freeze. Kafka keeps order only by offset, a record's position in its partition. The fix replays each account's events in offset order.
An assistant wrote apply_account_events(event_lines). It is in the editor. It has a bug. Find it and fix it.
Input and output:
event_lines: one string per event,"offset|account_id|op", in the order the workers finished. The list can be empty.- Return
"account_id=state"for every account with at least one valid event, sorted by account id in plain string order.
Rules the tests check:
- Skip a line unless all of these hold:
- it splits on
|into exactly 3 parts; - the offset is one or more digits from 0 to 9;
- the account id is not empty;
- the op is exactly
create,freeze,activateordelete.
- it splits on
- An offset is a whole number written in decimal, so
"0010"is offset 10. - For each account, apply its events in offset order, lowest first. Events with the same offset keep the order they have in the list.
- Every account starts as
absent. Each op changes the state only from certain states:create:absentbecomesactive.freeze:activebecomesfrozen.activate:frozenbecomesactive.delete: any state exceptabsentbecomesdeleted.
- An op in any other state changes nothing, but the account still appears in the result.
Examples
apply_account_events(event_lines: list[str]) -> list[str]Example 1
Input
apply_account_events(["10|a1|create", "11|a1|freeze", "12|a1|delete"])Output
["a1=deleted"]Example 2
Input
apply_account_events(["12|a1|delete", "10|a1|create", "11|a1|freeze"])Output
["a1=deleted"]Example 3
Input
apply_account_events(["11|b|freeze", "10|a|create", "10|b|create", "11|a|delete"])Output
["a=deleted", "b=frozen"]