Fix the snapshot in a request counter
Your task
Your service counts requests per route in memory, and a dashboard reads snapshots of the counts. In the Go version, Snapshot() returned the live map, so the dashboard read it while request handlers were still writing to it. A snapshot must be a copy of the counts at that moment.
An assistant wrote replay_metrics(event_lines), which replays the counter's events in order. It is in the editor. It has a bug. Find it and fix it.
Input and output:
event_lines: the events in order.incr|keyadds 1 to the count forkey.snap|labeltakes a snapshot namedlabel.- Return the lines of every snapshot, snapshots in event order. Each line is
label:key=count.
Rules the tests check:
- Split a line on
|. Skip it unless it has exactly 2 parts. - Skip an
incrwith an empty key. Skip any operation other thanincrandsnap. - A snapshot holds the counts at the moment it is taken. Later increments do not change it.
- Within a snapshot, list every key counted so far, sorted by plain string comparison (character by character on character codes, so
a10comes beforea2). - A snapshot taken before any increment adds no lines. The label may be empty.
Examples
replay_metrics(event_lines: list[str]) -> list[str]Example 1
Input
replay_metrics(["incr|a", "incr|b", "incr|a", "snap|s1"])Output
["s1:a=2", "s1:b=1"]Example 2
Input
replay_metrics(["incr|a", "snap|s1", "incr|a", "incr|c", "snap|s2"])Output
["s1:a=1", "s2:a=2", "s2:c=1"]