```python """Streaming tenant usage aggregator: dedupe, watermark and allowed lateness. Events are processed one at a time as they are pushed; closed windows are emitted immediately, so the full event set is never sorted at once. """ from collections.abc import Mapping class UsagePipeline: """In-memory streaming aggregator keyed by (tenant_id, window_start).""" def __init__(self, window_seconds, allowed_lateness=0): self.window_seconds = self._check_window_seconds(window_seconds) self.allowed_lateness = self._check_allowed_lateness(allowed_lateness) # Public counters. self.duplicates = 0 self.dropped_late = 0 # Highest ts among accepted (non-duplicate) events; None until one arrives. self._watermark = None # event_id values seen during the instance lifetime. self._seen = set() # (tenant_id, window_start) -> [quantity_sum, event_count] self._windows = {} # Windows already handed to the caller; never emitted a second time. self._emitted = set() # ------------------------------------------------------------------ # # Configuration validation # ------------------------------------------------------------------ # @staticmethod def _check_window_seconds(value): if isinstance(value, bool) or not isinstance(value, int): raise ValueError("window_seconds must be a positive integer") if value <= 0: raise ValueError("window_seconds must be a positive integer") return value @staticmethod def _check_allowed_lateness(value): if isinstance(value, bool) or not isinstance(value, int): raise ValueError("allowed_lateness must be a non-negative integer") if value < 0: raise ValueError("allowed_lateness must be a non-negative integer") return value # ------------------------------------------------------------------ # # Event validation # ------------------------------------------------------------------ # @staticmethod def _check_non_empty_string(event, field): if field not in event: raise ValueError("event is missing required field: %s" % field) value = event[field] if not isinstance(value, str) or isinstance(value, bool) or value == "": raise ValueError("%s must be a non-empty string" % field) return value @staticmethod def _check_non_negative_int(event, field): if field not in event: raise ValueError("event is missing required field: %s" % field) value = event[field] # bool is a subclass of int but is not an acceptable integer here. if isinstance(value, bool) or not isinstance(value, int): raise ValueError("%s must be a non-negative integer" % field) if value < 0: raise ValueError("%s must be a non-negative integer" % field) return value @classmethod def _validate(cls, event): """Validate without touching any internal state; returns the fields.""" if not isinstance(event, Mapping): raise ValueError("event must be a mapping") event_id = cls._check_non_empty_string(event, "event_id") tenant_id = cls._check_non_empty_string(event, "tenant_id") ts = cls._check_non_negative_int(event, "ts") quantity = cls._check_non_negative_int(event, "quantity") return event_id, tenant_id, ts, quantity # ------------------------------------------------------------------ # # Public API # ------------------------------------------------------------------ # def push(self, event): """Ingest one event and return the windows that close because of it.""" event_id, tenant_id, ts, quantity = self._validate(event) # Duplicates are ignored entirely: watermark untouched, no counters # other than `duplicates`, nothing returned. if event_id in self._seen: self.duplicates += 1 return [] self._seen.add(event_id) if self._watermark is None or ts > self._watermark: self._watermark = ts window_start = (ts // self.window_seconds) * self.window_seconds window_end = window_start + self.window_seconds # Lateness is decided by the containing window, not by the event ts. if window_end <= self._watermark - self.allowed_lateness: self.dropped_late += 1 return self._drain_closable() key = (tenant_id, window_start) slot = self._windows.get(key) if slot is None: slot = [0, 0] self._windows[key] = slot slot[0] += quantity slot[1] += 1 return self._drain_closable() def flush(self): """Emit every window still open, then clear the window aggregates.""" if not self._windows: return [] pending = list(self._windows) emitted = self._emit(pending) self._windows.clear() return emitted # ------------------------------------------------------------------ # # Internals # ------------------------------------------------------------------ # def _drain_closable(self): """Emit all windows whose end is at or below the allowed-lateness line.""" if self._watermark is None or not self._windows: return [] threshold = self._watermark - self.allowed_lateness closable = [ key for key in self._windows if key[1] + self.window_seconds <= threshold ] return self._emit(closable) def _emit(self, keys): """Materialise and remove the given windows, ordered by (tenant, start).""" results = [] for key in sorted(keys): slot = self._windows.pop(key, None) if slot is None: continue if key in self._emitted: # An already-emitted window must never be emitted again. continue self._emitted.add(key) tenant_id, window_start = key results.append( { "tenant_id": tenant_id, "window_start": window_start, "window_end": window_start + self.window_seconds, "quantity": slot[0], "event_count": slot[1], } ) return results if __name__ == "__main__": pipeline = UsagePipeline(window_seconds=60, allowed_lateness=120) events = [ {"event_id": "evt-001", "tenant_id": "ACME", "ts": 121, "quantity": 5}, {"event_id": "evt-002", "tenant_id": "ACME", "ts": 125, "quantity": 3}, {"event_id": "evt-003", "tenant_id": "BETA", "ts": 130, "quantity": 2}, {"event_id": "evt-001", "tenant_id": "ACME", "ts": 121, "quantity": 5}, {"event_id": "evt-004", "tenant_id": "ACME", "ts": 305, "quantity": 7}, {"event_id": "evt-005", "tenant_id": "ACME", "ts": 119, "quantity": 9}, {"event_id": "evt-006", "tenant_id": "ACME", "ts": 179, "quantity": 1}, {"event_id": "evt-007", "tenant_id": "BETA", "ts": 306, "quantity": 1}, ] for evt in events: print(evt["event_id"], "->", pipeline.push(evt)) print("flush ->", pipeline.flush()) print("flush ->", pipeline.flush()) print("duplicates ->", pipeline.duplicates) print("dropped_late ->", pipeline.dropped_late) ```