Fix the invariant guard for an event projection
Your task
Your company's event-sourcing framework has two rules that public conventions do not: events must apply in strictly increasing sequence order, and an idempotency key counts as used only once an event with it has actually been applied. An agent wrote a new projection that followed the usual conventions, compiled, and passed its own tests. Your team now runs every projection through a guard that encodes the framework's rules.
An assistant wrote apply_events_with_invariants(seqs, keys). It is in the editor. It has a bug. Find it and fix it.
Input and output:
seqs,keys: two lists of the same length. Event i has sequence numberseqs[i]and idempotency keykeys[i].- Return one label per event, in order:
"applied","duplicate"or"out_of_order".
Rules the tests check. Process the events in order, and use the first rule that applies:
"out_of_order": an event has already been applied, and this event's sequence number is less than or equal to the highest one applied so far. Before anything is applied, any sequence number is fine, 0 and negatives included."duplicate": an event with the same key has already been applied."applied": otherwise.
Only an applied event changes state: it marks its key as used and moves the highest sequence number. A rejected event changes nothing, so its key is still free for a later event.
Examples
apply_events_with_invariants(seqs: list[int], keys: list[str]) -> list[str]apply_events_with_invariants([1, 2, 3], ["a", "b", "c"])["applied", "applied", "applied"]apply_events_with_invariants([1, 2, 3], ["a", "b", "a"])["applied", "applied", "duplicate"]apply_events_with_invariants([5, 3, 6], ["a", "b", "c"])["applied", "out_of_order", "applied"]