Fix the lifetime checker for async send buffers

Review the AI's codeMedium15 min

Your task

Your network engine queues a send to the kernel and returns at once, and it crashes under load with garbage on the wire. The buffer is freed while the kernel is still reading it. You are writing a checker that replays an event log and counts every time a buffer's lifetime rule is broken.

An assistant wrote count_lifetime_violations(events). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • events: the log in order, each "op:buffer_id". The ops are alloc, submit (a send using the buffer was queued), complete (one queued send finished) and free.
  • Return the number of violations.

Rules the tests check:

  • Skip an event with no :. Split it at the first :. Trim the op and compare it without regard to case. Trim the id.
  • Each id is unknown until its first alloc, then live, then freed after a free. Each id also has a count of sends in flight.
  • alloc: the id becomes live with 0 sends in flight, whatever it was before.
  • submit: on a freed id, that is a violation. On a live id, add 1 to its sends in flight. On an unknown id, nothing happens.
  • complete: subtract 1 from the sends in flight, but never go below 0.
  • free: on a live id, it is a violation if any send is still in flight. Either way the id becomes freed with 0 sends in flight. A free on an unknown or freed id does nothing.
  • Any other op is ignored.

Examples

count_lifetime_violations(events: list[str]) -> int
Example 1
Inputcount_lifetime_violations(["alloc:1", "submit:1", "free:1", "complete:1"])
Output1
Example 2
Inputcount_lifetime_violations(["alloc:1", "submit:1", "complete:1", "free:1"])
Output0
Example 3
Inputcount_lifetime_violations(["alloc:1", "submit:1", "complete:1", "free:1", "alloc:2", "submit:2", "free:2"])
Output1