File size: 5,454 Bytes
c28b1a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
--- a/src/aggregates/base.py
+++ b/src/aggregates/base.py
@@ -22,3 +22,8 @@ class Aggregate(ABC):
     @abstractmethod
     def value(self):
         """The current result. Pure: no state change."""
+
+    @abstractmethod
+    def combine(self, other):
+        """Fold another aggregate of the same kind into this one (used
+        when two sessions turn out to be one)."""
--- a/src/aggregates/basic.py
+++ b/src/aggregates/basic.py
@@ -30,6 +30,9 @@ class Count(Aggregate):
     def value(self):
         return self._n
 
+    def combine(self, other):
+        self._n += other._n
+
 
 class Sum(Aggregate):
     """Sum of a numeric field over contributing events (0 when none)."""
@@ -46,6 +49,9 @@ class Sum(Aggregate):
     def value(self):
         return self._total
 
+    def combine(self, other):
+        self._total += other._total
+
 
 class Min(Aggregate):
     """Minimum of a numeric field (None when no event contributed)."""
@@ -62,6 +68,10 @@ class Min(Aggregate):
     def value(self):
         return self._min
 
+    def combine(self, other):
+        if other._min is not None and (self._min is None or other._min < self._min):
+            self._min = other._min
+
 
 class Max(Aggregate):
     """Maximum of a numeric field (None when no event contributed)."""
@@ -77,3 +87,7 @@ class Max(Aggregate):
 
     def value(self):
         return self._max
+
+    def combine(self, other):
+        if other._max is not None and (self._max is None or other._max > self._max):
+            self._max = other._max
--- a/src/aggregates/distinct.py
+++ b/src/aggregates/distinct.py
@@ -21,3 +21,6 @@ class DistinctCount(Aggregate):
 
     def value(self):
         return len(self._seen)
+
+    def combine(self, other):
+        self._seen |= other._seen
new file mode 100644
--- /dev/null
+++ b/src/assign.py
@@ -0,0 +1,41 @@
+"""Event-time placement of an admissible event among a key's open sessions.
+
+Open sessions for a key are kept in start order, and any two neighbours
+are separated by more than the gap (otherwise they would be one session).
+An incoming timestamp therefore lands in exactly one of three ways: it is
+close enough to a single session to join it (in its interior, within the
+gap after its end, or within the gap before its start), it falls between
+two sessions within the gap of both — in which case those sessions were
+always one session and must be unified — or it is beyond the gap of every
+neighbour and opens a new session at its position.
+"""
+
+from __future__ import annotations
+
+from bisect import bisect_right
+
+OPEN = "open"
+ATTACH = "attach"
+MERGE = "merge"
+
+
+def place(sessions, ts, gap):
+    """Decide where ``ts`` lands among ``sessions`` (sorted by start).
+
+    Returns ``(OPEN, insert_index)``, ``(ATTACH, session_index)``, or
+    ``(MERGE, left_index)`` — merge unifies ``left_index`` with
+    ``left_index + 1``.
+    """
+    starts = [session.start for session in sessions]
+    index = bisect_right(starts, ts)
+    pred = sessions[index - 1] if index > 0 else None
+    succ = sessions[index] if index < len(sessions) else None
+    near_pred = pred is not None and ts - pred.end <= gap
+    near_succ = succ is not None and succ.start - ts <= gap
+    if near_pred and near_succ:
+        return (MERGE, index - 1)
+    if near_pred:
+        return (ATTACH, index - 1)
+    if near_succ:
+        return (ATTACH, index)
+    return (OPEN, index)
--- a/src/sessions.py
+++ b/src/sessions.py
@@ -28,9 +28,19 @@ class Session:
 
     def extend(self, event):
         """Credit a further event to this session."""
-        self.end = event.ts
+        if event.ts < self.start:
+            self.start = event.ts
+        if event.ts > self.end:
+            self.end = event.ts
         self._apply(event)
 
+    def merge_from(self, other):
+        """Unify another session's events into this one."""
+        self.start = min(self.start, other.start)
+        self.end = max(self.end, other.end)
+        for name, aggregate in self._aggregates.items():
+            aggregate.combine(other._aggregates[name])
+
     def aggregate_values(self):
         """Current aggregate results, keyed by configured name."""
         return {name: agg.value() for name, agg in self._aggregates.items()}
--- a/src/tracker.py
+++ b/src/tracker.py
@@ -15,6 +15,7 @@ downstream as it happens).
 
 from __future__ import annotations
 
+from src import assign
 from src.sessions import Session
 
 
@@ -33,11 +34,18 @@ class Sessionizer:
             self._metrics.increment("events_dropped_late")
             return False
         sessions = self._open.setdefault(event.key, [])
-        last = sessions[-1] if sessions else None
-        if last is not None and event.ts - last.end <= self._config.gap:
-            last.extend(event)
+        action, index = assign.place(sessions, event.ts, self._config.gap)
+        if action == assign.MERGE:
+            keep = sessions[index]
+            other = sessions.pop(index + 1)
+            keep.extend(event)
+            keep.merge_from(other)
+        elif action == assign.ATTACH:
+            sessions[index].extend(event)
         else:
-            sessions.append(Session(event.key, event, self._config.aggregates))
+            sessions.insert(
+                index, Session(event.key, event, self._config.aggregates)
+            )
             self._metrics.increment("sessions_opened")
         return True