EasyObservabilityPython 3

Sliding Window Error Counter

Track top recent errors while every read path lazily removes expired events.

25m3 sample tests6 hidden tests

Build a deterministic counter for recent errors in a rolling time window.

Requirements

  • Define ErrorCounter(window_seconds, now).
  • record(message) stores one error occurrence at the current time.
  • count() returns the number of non-expired errors.
  • top(k) returns (message, count) pairs for the top k messages, ordered by count descending then message ascending.
  • If k <= 0, top(k) returns an empty list.
  • Every read path must treat expired events as missing. record may also purge expired events, preventing unbounded storage growth.
  • An event expires when now() - event_time >= window_seconds.
  • Ties in top(k) sort alphabetically by message (already implied by count-desc then message-asc).

Example

python
1clock = {"t": 0} 2counter = ErrorCounter(10, now=lambda: clock["t"]) 3counter.record("timeout") 4counter.record("timeout") 5counter.record("rate_limit") 6assert counter.count() == 3 7assert counter.top(2) == [("timeout", 2), ("rate_limit", 1)] 8clock["t"] = 10 9assert counter.count() == 0

Constraints

  • Use deterministic injected time.
  • Use standard-library Python only.
  • Don't scan expired data forever if many events are recorded.

Editor