recapi 0.4.13__tar.gz → 0.4.14__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.13
3
+ Version: 0.4.14
4
4
  Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://recapi.io
@@ -49,7 +49,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
49
49
  (the dashboard's quick start shows the line with your API's address):
50
50
 
51
51
  ```sh
52
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.13-py3-none-any.whl
52
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.14-py3-none-any.whl
53
53
  ```
54
54
 
55
55
  To work on the library itself, install it from a checkout of recapi's repository
@@ -26,7 +26,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
26
26
  (the dashboard's quick start shows the line with your API's address):
27
27
 
28
28
  ```sh
29
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.13-py3-none-any.whl
29
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.14-py3-none-any.whl
30
30
  ```
31
31
 
32
32
  To work on the library itself, install it from a checkout of recapi's repository
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "recapi"
7
- version = "0.4.13"
7
+ version = "0.4.14"
8
8
  description = "Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -30,7 +30,7 @@ from typing import Any, Protocol
30
30
 
31
31
  from .history import History, is_id
32
32
 
33
- __version__ = "0.4.13"
33
+ __version__ = "0.4.14"
34
34
 
35
35
  log = logging.getLogger("recapi")
36
36
  Tags = Sequence[str] | None
@@ -20,6 +20,7 @@ MAX_ID_BYTES = 256
20
20
  # The API answers 400 above this, which fails the list: a damaged score is sent as this.
21
21
  MAX_REQUEST_WEIGHT = 1e6
22
22
 
23
+ _LEVELS = range(1, 11)
23
24
  _RATE = math.log(2) / HALF_LIFE_SECONDS
24
25
  # Go's unicode.IsControl, which the API applies to every id: C0, DEL and C1.
25
26
  _CONTROL = re.compile("[\x00-\x1f\x7f-\x9f]")
@@ -53,10 +54,28 @@ def _is_time(value: object) -> bool:
53
54
  )
54
55
 
55
56
 
57
+ def _level(value: object) -> int:
58
+ """Return a strongest level read from JSON: an integer 1-10, else 0 (unknown)."""
59
+ # 10.0 is 10; a float is compared, not converted (a NaN or 2.5 isn't in the range).
60
+ if isinstance(value, int | float) and not isinstance(value, bool) and value in _LEVELS:
61
+ return int(value)
62
+ return 0
63
+
64
+
65
+ def _strongest(a: int, b: int) -> int:
66
+ """Return the max level of two sides of one entry.
67
+
68
+ Unknown (0) wins, since the unknown side may hold a purchase.
69
+ """
70
+ return 0 if a == 0 or b == 0 else max(a, b)
71
+
72
+
56
73
  class History:
57
74
  """One user's history: weighted top, recent list and rejection marks.
58
75
 
59
- ``top`` maps item -> (score, t), ``recent`` is (item, t) oldest first,
76
+ ``top`` maps item -> (score, t, m), where m is the strongest level applied
77
+ to the entry since it started (0 when unknown: an entry stored or sent
78
+ without it), ``recent`` is (item, t) oldest first,
60
79
  ``rejected`` maps item -> time of the newest rejection, ``last_t`` is the
61
80
  newest event applied to the recent list (None when unknown).
62
81
  """
@@ -64,7 +83,7 @@ class History:
64
83
  __slots__ = ("last_t", "recent", "rejected", "top")
65
84
 
66
85
  def __init__(self) -> None:
67
- self.top: dict[str, tuple[float, float]] = {}
86
+ self.top: dict[str, tuple[float, float, int]] = {}
68
87
  self.recent: list[tuple[str, float]] = []
69
88
  self.rejected: dict[str, float] = {}
70
89
  self.last_t: float | None = None
@@ -91,11 +110,13 @@ class History:
91
110
  del self.rejected[item]
92
111
  current = self.top.get(item)
93
112
  if current is None:
94
- self.top[item] = (float(level), t)
113
+ self.top[item] = (float(level), t, level)
95
114
  elif t >= current[1]:
96
- self.top[item] = (current[0] * _decay(t - current[1]) + level, t)
115
+ m = _strongest(current[2], level)
116
+ self.top[item] = (current[0] * _decay(t - current[1]) + level, t, m)
97
117
  else:
98
- self.top[item] = (current[0] + level * _decay(current[1] - t), current[1])
118
+ m = _strongest(current[2], level)
119
+ self.top[item] = (current[0] + level * _decay(current[1] - t), current[1], m)
99
120
  if self.last_t is None or t >= self.last_t:
100
121
  self.recent = [entry for entry in self.recent if entry[0] != item]
101
122
  self.recent.append((item, t))
@@ -119,7 +140,7 @@ class History:
119
140
  A time ahead of ``now`` reads as ``now``: a clock that ran ahead must not
120
141
  grow the weight past what the API takes, or overflow.
121
142
  """
122
- entries = [(item, s * _decay(max(0, now - t)), t) for item, (s, t) in self.top.items()]
143
+ entries = [(item, s * _decay(max(0, now - t)), t) for item, (s, t, _) in self.top.items()]
123
144
  entries.sort(key=lambda e: (-e[1], e[0]))
124
145
  return entries
125
146
 
@@ -131,7 +152,7 @@ class History:
131
152
  if len(self.top) > TOP_K:
132
153
  # Read at the newest entry when an event arrives out of order: at the old
133
154
  # event's time ranked() would flatten the newer entries to their score.
134
- at = max(now, *(t for _, t in self.top.values()))
155
+ at = max(now, *(e[1] for e in self.top.values()))
135
156
  self.top = {item: self.top[item] for item, _, _ in self.ranked(at)[:TOP_K]}
136
157
 
137
158
  def _prune_rejected(self) -> None:
@@ -144,16 +165,19 @@ class History:
144
165
 
145
166
  Weights are decayed to ``now``, at most what the API accepts, and rounded
146
167
  half up to 4 decimals like JS ``Math.round`` (Python's ``round`` rounds half
147
- to even); ages are whole seconds, never negative.
168
+ to even); ages are whole seconds, never negative. A fourth element is
169
+ the entry's strongest level, left out when unknown.
148
170
  """
149
- history = [
150
- [
171
+ history = []
172
+ for item, weight, t in self.ranked(now)[:TOP_K]:
173
+ entry: list[Any] = [
151
174
  item,
152
175
  math.floor(min(weight, MAX_REQUEST_WEIGHT) * 1e4 + 0.5) / 1e4,
153
176
  max(0, math.floor((now - t) / 1000)),
154
177
  ]
155
- for item, weight, t in self.ranked(now)[:TOP_K]
156
- ]
178
+ if self.top[item][2] > 0:
179
+ entry.append(self.top[item][2])
180
+ history.append(entry)
157
181
  recent = [item for item, _ in self.recent[-RECENT_SIZE:]]
158
182
  return history, recent, self.rejected_order()
159
183
 
@@ -161,7 +185,8 @@ class History:
161
185
  def from_snapshot(cls, snapshot: object) -> History:
162
186
  """Build a history from the server's snapshot, skipping invalid entries.
163
187
 
164
- Each top entry is a score at ``as_of``, each rejected item a mark at
188
+ Each top entry is a score at ``as_of`` with its strongest level (a third
189
+ element, unknown when absent or not 1-10), each rejected item a mark at
165
190
  ``as_of``. ``last_t`` stays unknown: ``as_of`` is the server clock, and a
166
191
  local clock behind it would see every new event as out of order.
167
192
  """
@@ -171,7 +196,7 @@ class History:
171
196
  as_of = snapshot["as_of"]
172
197
  for e in _list(snapshot.get("top")):
173
198
  if isinstance(e, list) and len(e) >= 2 and is_id(e[0]) and _is_weight(e[1]):
174
- state.top[e[0]] = (float(e[1]), as_of)
199
+ state.top[e[0]] = (float(e[1]), as_of, _level(e[2]) if len(e) > 2 else 0)
175
200
  seen: set[str] = set()
176
201
  for item in _list(snapshot.get("recent")):
177
202
  if is_id(item) and item not in seen:
@@ -188,20 +213,22 @@ class History:
188
213
  def merge(self, other: History, now: float) -> History:
189
214
  """Return the union of two histories built from disjoint events.
190
215
 
191
- Top scores add up, expressed at the later of the two times; the recent
216
+ Top scores add up, expressed at the later of the two times, and keep
217
+ the strongest level of the two (unknown if either is); the recent
192
218
  lists are interleaved by time (``self`` first on ties); rejection marks
193
219
  are united, and a mark older than the item's merged entry is dropped,
194
220
  otherwise the item leaves the top and the recent list.
195
221
  """
196
222
  out = History()
197
223
  out.top = dict(self.top)
198
- for item, (s, t) in other.top.items():
224
+ for item, (s, t, m) in other.top.items():
199
225
  mine = out.top.get(item)
200
226
  if mine is None:
201
- out.top[item] = (s, t)
227
+ out.top[item] = (s, t, m)
202
228
  continue
203
229
  later = max(t, mine[1])
204
- out.top[item] = (s * _decay(later - t) + mine[0] * _decay(later - mine[1]), later)
230
+ score = s * _decay(later - t) + mine[0] * _decay(later - mine[1])
231
+ out.top[item] = (score, later, _strongest(m, mine[2]))
205
232
 
206
233
  out.rejected = dict(self.rejected)
207
234
  for item, t in other.rejected.items():
@@ -242,12 +269,18 @@ class History:
242
269
  return self.merge(trimmed, now)
243
270
 
244
271
  def encode(self) -> dict[str, Any]:
245
- """Return the JSON-safe stored form (raw scores), shaped like JS ``encodeState``."""
272
+ """Return the JSON-safe stored form (raw scores), shaped like JS ``encodeState``.
273
+
274
+ ``maxLevel`` is each top entry's strongest level, in top's order (0
275
+ unknown): a key of its own, not a fourth element, so a library from
276
+ before it still reads the state (it rejects a top entry of another length).
277
+ """
246
278
  return {
247
- "top": [[item, s, t] for item, (s, t) in self.top.items()],
279
+ "top": [[item, s, t] for item, (s, t, _) in self.top.items()],
248
280
  "recent": [[item, t] for item, t in self.recent],
249
281
  "rejected": [[item, t] for item, t in self.rejected.items()],
250
282
  "lastT": self.last_t,
283
+ "maxLevel": [m for _, _, m in self.top.values()],
251
284
  }
252
285
 
253
286
  @classmethod
@@ -255,12 +288,20 @@ class History:
255
288
  """Inverse of :meth:`encode`; None for any malformed field.
256
289
 
257
290
  A state stored before rejections existed has no ``rejected``.
291
+ ``maxLevel`` is read leniently: absent, not a list or not as long as
292
+ top, every level is unknown; a value that is not a level 1-10 is unknown.
258
293
  """
259
294
  if not _valid_encoding(raw):
260
295
  return None
261
296
  assert isinstance(raw, dict)
262
297
  state = cls()
263
- state.top = {item: (float(s), t) for item, s, t in raw["top"]}
298
+ levels = raw.get("maxLevel")
299
+ if not isinstance(levels, list) or len(levels) != len(raw["top"]):
300
+ levels = [0] * len(raw["top"])
301
+ state.top = {
302
+ item: (float(s), t, _level(m))
303
+ for (item, s, t), m in zip(raw["top"], levels, strict=True)
304
+ }
264
305
  state.recent = [(item, t) for item, t in raw["recent"]]
265
306
  state.rejected = {item: t for item, t in raw.get("rejected", [])}
266
307
  state.last_t = raw["lastT"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.13
3
+ Version: 0.4.14
4
4
  Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://recapi.io
@@ -49,7 +49,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
49
49
  (the dashboard's quick start shows the line with your API's address):
50
50
 
51
51
  ```sh
52
- pip install https://api.<your-domain>/sdk/python/recapi-0.4.13-py3-none-any.whl
52
+ pip install https://api.<your-domain>/sdk/python/recapi-0.4.14-py3-none-any.whl
53
53
  ```
54
54
 
55
55
  To work on the library itself, install it from a checkout of recapi's repository
@@ -256,7 +256,7 @@ class Recommend(APITest):
256
256
  client.track("b", "cart", user_id="u")
257
257
  result = client.recommend(user_id="u", count=4, placement="home", tags_any=["x"])
258
258
  body = self.last_body("/v1/recommendations")
259
- self.assertEqual(body["history"], [["b", 5.0, 0], ["a", 3.0, 1]])
259
+ self.assertEqual(body["history"], [["b", 5.0, 0, 5], ["a", 3.0, 1, 3]])
260
260
  self.assertEqual(body["recent"], ["a", "b"])
261
261
  self.assertEqual(
262
262
  {k: body[k] for k in ("user_id", "count", "placement", "tags_any")},
@@ -574,6 +574,21 @@ class Store(APITest):
574
574
  client.recommend(user_id="u")
575
575
  self.assertEqual(self.last_body("/v1/recommendations")["history"], [])
576
576
 
577
+ def test_a_history_stored_by_the_previous_version_serves_the_same_lists(self) -> None:
578
+ # No maxLevel: its entries go out as before, an entry tracked since with its level.
579
+ store = recapi.MemoryStore()
580
+ client = self.client(store=store)
581
+ old = {"top": [["a", 3.0, T0]], "recent": [["a", T0]], "rejected": [], "lastT": T0}
582
+ key = client._key("u", None)
583
+ store.set(key, json.dumps({"history": old, "shown": [], "restored": True}))
584
+ client.track("s1", "view", user_id="u")
585
+ client.recommend(user_id="u")
586
+ body = self.last_body("/v1/recommendations")
587
+ self.assertEqual(body["history"], [["a", 3.0, 0], ["s1", 3.0, 0, 3]])
588
+ self.assertEqual(body["recent"], ["a", "s1"])
589
+ saved = json.loads(store.get(key))["history"]
590
+ self.assertEqual(([e[0] for e in saved["top"]], saved["maxLevel"]), (["a", "s1"], [0, 3]))
591
+
577
592
  def test_a_stored_state_keeps_its_valid_and_newest_shown_entries(self) -> None:
578
593
  # Written by another library version or by hand: bad entries are
579
594
  # dropped one by one, and the next save keeps the newest 100.
@@ -947,7 +962,7 @@ class Snapshot(APITest):
947
962
  client.recommend(user_id="u")
948
963
  client.recommend(user_id="u")
949
964
  body = self.last_body("/v1/recommendations")
950
- self.assertEqual(body["history"], [["s", 4.0, 0], ["t", 3.0, 0]])
965
+ self.assertEqual(body["history"], [["s", 4.0, 0], ["t", 3.0, 0, 3]])
951
966
 
952
967
 
953
968
  class Restore(APITest):
@@ -978,7 +993,7 @@ class Restore(APITest):
978
993
  (fetch.method, fetch.headers["authorization"]), ("GET", f"Bearer {KEY}")
979
994
  )
980
995
  body = self.last_body("/v1/recommendations")
981
- self.assertEqual(body["history"], [["s", 3.9997, 60], ["a", 3.0, 0]])
996
+ self.assertEqual(body["history"], [["s", 3.9997, 60], ["a", 3.0, 0, 3]])
982
997
  self.assertEqual((body["recent"], body["exclude"]), (["s", "a"], ["bad"]))
983
998
  self.assertTrue(self.restored(store, client))
984
999
  client.recommend(user_id="u")
@@ -993,7 +1008,7 @@ class Restore(APITest):
993
1008
  client.track("a", "view", user_id="u")
994
1009
  client.recommend(user_id="u")
995
1010
  body = self.last_body("/v1/recommendations")
996
- self.assertEqual((body["history"], body["recent"]), ([["a", 3.0, 0]], ["a"]))
1011
+ self.assertEqual((body["history"], body["recent"]), ([["a", 3.0, 0, 3]], ["a"]))
997
1012
  self.assertEqual(body["exclude"], ["s"])
998
1013
 
999
1014
  def test_a_failed_fetch_keeps_the_local_history_and_is_tried_again(self) -> None:
@@ -1013,7 +1028,7 @@ class Restore(APITest):
1013
1028
  result = client.recommend(user_id="u")
1014
1029
  self.assertEqual(result.recommendation_id, "rec_1")
1015
1030
  body = self.last_body("/v1/recommendations")
1016
- self.assertEqual((body["history"], body["recent"]), ([["a", 3.0, 0]], ["a"]))
1031
+ self.assertEqual((body["history"], body["recent"]), ([["a", 3.0, 0, 3]], ["a"]))
1017
1032
  self.assertFalse(self.restored(store, client))
1018
1033
  self.api.on(self.HISTORY, Reply(200, self.STORED))
1019
1034
  client.recommend(user_id="u")
@@ -1077,7 +1092,7 @@ class Restore(APITest):
1077
1092
  self.api.on(self.HISTORY, reply)
1078
1093
  client.track("a", "view", user_id="u")
1079
1094
  client.recommend(user_id="u")
1080
- want = ([["s", 3.9997, 60], ["a", 3.0, 0], ["b", 3.0, 0]], ["s", "a", "b"])
1095
+ want = ([["s", 3.9997, 60], ["a", 3.0, 0, 3], ["b", 3.0, 0, 3]], ["s", "a", "b"])
1081
1096
  body = self.last_body("/v1/recommendations")
1082
1097
  self.assertEqual((body["history"], body["recent"]), want)
1083
1098
  client.recommend(user_id="u")
@@ -1178,7 +1193,7 @@ class Identify(APITest):
1178
1193
  self.api.on("/v1/recommendations", Reply(200, recs(["z"], rec_id="rec_z")))
1179
1194
  client.recommend(user_id="u")
1180
1195
  body = self.last_body("/v1/recommendations")
1181
- self.assertEqual(body["history"], [["a", 8.0, 0], ["b", 3.0, 0]])
1196
+ self.assertEqual(body["history"], [["a", 8.0, 0, 5], ["b", 3.0, 0, 3]])
1182
1197
  self.assertEqual((body["recent"], body["exclude"]), (["a", "b"], ["x"]))
1183
1198
  self.clock += MINUTE
1184
1199
  client.track("r2", 3, user_id="u") # shown by both lists: the later one wins
@@ -42,17 +42,53 @@ class SharedVectors(unittest.TestCase):
42
42
  _, recent, rejected = state.wire(case["now"])
43
43
  self.assertEqual(recent, case["expected_recent"])
44
44
  self.assertEqual(rejected, case["expected_rejected"])
45
+ self.check_levels(state, case)
46
+
47
+ def check_levels(self, state: History, case: dict) -> None:
48
+ """Compare each entry's strongest level with ``expected_max_level``, if the case has it."""
49
+ if "expected_max_level" in case:
50
+ got = {item: m for item, (_, _, m) in state.top.items()}
51
+ self.assertEqual(got, case["expected_max_level"])
52
+
53
+ def check_level_case(self, state: History, case: dict) -> None:
54
+ rel = VECTORS["tolerance"]["relative"]
55
+ ranked = state.ranked(case["now"])
56
+ self.assertEqual([e[0] for e in ranked], [e[0] for e in case["expected_top"]])
57
+ for (_, got, _), (_, want) in zip(ranked, case["expected_top"], strict=True):
58
+ self.assertLessEqual(abs(got - want), rel * max(1, abs(want)))
59
+ self.assertEqual(state.wire(case["now"])[1], case["expected_recent"])
60
+ self.check_levels(state, case)
61
+
62
+ def test_history_stored_level_vectors(self) -> None:
63
+ self.assertTrue(VECTORS["stored_cases"])
64
+ for case in VECTORS["stored_cases"]:
65
+ with self.subTest(case["name"]):
66
+ state = History.decode(case["stored"])
67
+ assert state is not None, "the stored state did not load"
68
+ for e in case["events"]:
69
+ state.apply(e["item"], e["level"], e["t"])
70
+ self.check_level_case(state, case)
71
+ again = History.decode(json.loads(json.dumps(state.encode())))
72
+ assert again is not None, "the encoded state did not load"
73
+ self.check_level_case(again, case)
74
+
75
+ def test_history_snapshot_level_vectors(self) -> None:
76
+ self.assertTrue(VECTORS["snapshot_cases"])
77
+ for case in VECTORS["snapshot_cases"]:
78
+ with self.subTest(case["name"]):
79
+ state = build([(e["item"], e["level"], e["t"]) for e in case["events"]])
80
+ snapshot = History.from_snapshot(case["snapshot"])
81
+ self.check_level_case(state.merge_snapshot(snapshot, case["now"]), case)
45
82
 
46
83
 
47
84
  class Behaviour(unittest.TestCase):
48
85
  def test_wire_rounds_half_up_and_never_sends_negative_ages(self) -> None:
49
86
  state = History()
50
87
  # JS Math.round(2.00025 * 1e4) / 1e4 is 2.0003; Python's round() says 2.0002.
51
- state.top = {"a": (2.00025, T0), "b": (1.0, T0 + 5000), "c": (1.0, T0 - 61_500)}
88
+ state.top = {"a": (2.00025, T0, 3), "b": (1.0, T0 + 5000, 0), "c": (1.0, T0 - 61_500, 1)}
52
89
  history, _, _ = state.wire(T0)
53
- self.assertEqual([e[0] for e in history], ["a", "b", "c"])
54
- self.assertEqual(history[0], ["a", 2.0003, 0])
55
- self.assertEqual((history[1][2], history[2][2]), (0, 61))
90
+ # The fourth element is the strongest level, left out when unknown.
91
+ self.assertEqual(history, [["a", 2.0003, 0, 3], ["b", 1.0, 0], ["c", 0.9999, 61, 1]])
56
92
 
57
93
  def test_the_lists_are_bounded_and_rejections_alone_are_empty(self) -> None:
58
94
  state = build([(f"i{i:02}", 1 + i % 3, T0 + i) for i in range(60)])
@@ -71,7 +107,7 @@ class Behaviour(unittest.TestCase):
71
107
  "as_of": T0,
72
108
  }
73
109
  state = History.from_snapshot(snapshot)
74
- self.assertEqual(state.top, {"a": (2.0, T0)})
110
+ self.assertEqual(state.top, {"a": (2.0, T0, 0)})
75
111
  self.assertEqual(state.recent, [("a", T0), ("z", T0)])
76
112
  self.assertEqual(state.rejected, {"x": T0})
77
113
  self.assertIsNone(state.last_t)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes