recapi 0.4.6__tar.gz → 0.4.8__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.
- {recapi-0.4.6/recapi.egg-info → recapi-0.4.8}/PKG-INFO +2 -2
- {recapi-0.4.6 → recapi-0.4.8}/README.md +1 -1
- {recapi-0.4.6 → recapi-0.4.8}/pyproject.toml +1 -1
- {recapi-0.4.6 → recapi-0.4.8}/recapi/client.py +14 -6
- {recapi-0.4.6 → recapi-0.4.8}/recapi/history.py +28 -8
- {recapi-0.4.6 → recapi-0.4.8/recapi.egg-info}/PKG-INFO +2 -2
- {recapi-0.4.6 → recapi-0.4.8}/tests/test_client.py +54 -0
- {recapi-0.4.6 → recapi-0.4.8}/tests/test_client_vectors.py +53 -0
- {recapi-0.4.6 → recapi-0.4.8}/LICENSE +0 -0
- {recapi-0.4.6 → recapi-0.4.8}/recapi/__init__.py +0 -0
- {recapi-0.4.6 → recapi-0.4.8}/recapi/async_client.py +0 -0
- {recapi-0.4.6 → recapi-0.4.8}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.6 → recapi-0.4.8}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.6 → recapi-0.4.8}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.6 → recapi-0.4.8}/setup.cfg +0 -0
- {recapi-0.4.6 → recapi-0.4.8}/tests/test_async_client.py +0 -0
- {recapi-0.4.6 → recapi-0.4.8}/tests/test_history.py +0 -0
- {recapi-0.4.6 → recapi-0.4.8}/tests/test_stores.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.8
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.8-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -27,7 +27,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
27
27
|
(the dashboard's quick start shows the line with your API's address):
|
|
28
28
|
|
|
29
29
|
```sh
|
|
30
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
30
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.8-py3-none-any.whl
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "recapi"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.8"
|
|
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"
|
|
@@ -29,7 +29,7 @@ from typing import Any, Protocol
|
|
|
29
29
|
|
|
30
30
|
from .history import History, is_id
|
|
31
31
|
|
|
32
|
-
__version__ = "0.4.
|
|
32
|
+
__version__ = "0.4.8"
|
|
33
33
|
|
|
34
34
|
log = logging.getLogger("recapi")
|
|
35
35
|
Tags = Sequence[str] | None
|
|
@@ -311,11 +311,7 @@ class _UserState:
|
|
|
311
311
|
try:
|
|
312
312
|
data = json.loads(raw)
|
|
313
313
|
history = History.decode(data["history"])
|
|
314
|
-
shown = {
|
|
315
|
-
e[0]: list(e[1:])
|
|
316
|
-
for e in data["shown"]
|
|
317
|
-
if isinstance(e, list) and 3 <= len(e) <= 4 and is_id(e[0])
|
|
318
|
-
}
|
|
314
|
+
shown = {e[0]: list(e[1:]) for e in data["shown"] if _is_shown_entry(e)}
|
|
319
315
|
except (ValueError, KeyError, TypeError):
|
|
320
316
|
history = None
|
|
321
317
|
if history is None:
|
|
@@ -327,6 +323,18 @@ class _UserState:
|
|
|
327
323
|
)
|
|
328
324
|
|
|
329
325
|
|
|
326
|
+
def _is_shown_entry(e: object) -> bool:
|
|
327
|
+
# Bad types here would raise much later, in track() on the shop's page, or
|
|
328
|
+
# refuse a whole batch of events at the API.
|
|
329
|
+
return (
|
|
330
|
+
isinstance(e, list)
|
|
331
|
+
and 3 <= len(e) <= 4
|
|
332
|
+
and is_id(e[0])
|
|
333
|
+
and isinstance(e[1], str)
|
|
334
|
+
and all(type(t) is int and abs(t) < 2**63 for t in e[2:])
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
|
|
330
338
|
def _attributable(entry: Sequence[Any], t: int) -> bool:
|
|
331
339
|
if len(entry) < 3:
|
|
332
340
|
return t - entry[1] <= DISPLAY_WINDOW_MS
|
|
@@ -9,6 +9,7 @@ from __future__ import annotations
|
|
|
9
9
|
import copy
|
|
10
10
|
import math
|
|
11
11
|
import re
|
|
12
|
+
import sys
|
|
12
13
|
from typing import Any
|
|
13
14
|
|
|
14
15
|
HALF_LIFE_SECONDS = 604800
|
|
@@ -16,6 +17,8 @@ TOP_K = 50
|
|
|
16
17
|
RECENT_SIZE = 20
|
|
17
18
|
REJECTED_SIZE = 200
|
|
18
19
|
MAX_ID_BYTES = 256
|
|
20
|
+
# The API answers 400 above this, which fails the list: a damaged score is sent as this.
|
|
21
|
+
MAX_REQUEST_WEIGHT = 1e6
|
|
19
22
|
|
|
20
23
|
_RATE = math.log(2) / HALF_LIFE_SECONDS
|
|
21
24
|
# Go's unicode.IsControl, which the API applies to every id: C0, DEL and C1.
|
|
@@ -41,7 +44,13 @@ def _is_weight(value: object) -> bool:
|
|
|
41
44
|
|
|
42
45
|
|
|
43
46
|
def _is_time(value: object) -> bool:
|
|
44
|
-
|
|
47
|
+
# Compared, not converted: a stored 400-digit integer raises OverflowError in
|
|
48
|
+
# math.isfinite, and every later float() would too. NaN and inf fail the bound.
|
|
49
|
+
return (
|
|
50
|
+
isinstance(value, int | float)
|
|
51
|
+
and not isinstance(value, bool)
|
|
52
|
+
and abs(value) <= sys.float_info.max
|
|
53
|
+
)
|
|
45
54
|
|
|
46
55
|
|
|
47
56
|
class History:
|
|
@@ -105,8 +114,12 @@ class History:
|
|
|
105
114
|
self._prune_rejected()
|
|
106
115
|
|
|
107
116
|
def ranked(self, now: float) -> list[tuple[str, float, float]]:
|
|
108
|
-
"""Return (item, weight at ``now``, t) by weight desc, ties by item id asc.
|
|
109
|
-
|
|
117
|
+
"""Return (item, weight at ``now``, t) by weight desc, ties by item id asc.
|
|
118
|
+
|
|
119
|
+
A time ahead of ``now`` reads as ``now``: a clock that ran ahead must not
|
|
120
|
+
grow the weight past what the API takes, or overflow.
|
|
121
|
+
"""
|
|
122
|
+
entries = [(item, s * _decay(max(0, now - t)), t) for item, (s, t) in self.top.items()]
|
|
110
123
|
entries.sort(key=lambda e: (-e[1], e[0]))
|
|
111
124
|
return entries
|
|
112
125
|
|
|
@@ -116,7 +129,10 @@ class History:
|
|
|
116
129
|
|
|
117
130
|
def _prune(self, now: float) -> None:
|
|
118
131
|
if len(self.top) > TOP_K:
|
|
119
|
-
|
|
132
|
+
# Read at the newest entry when an event arrives out of order: at the old
|
|
133
|
+
# event's time ranked() would flatten the newer entries to their score.
|
|
134
|
+
at = max(now, *(t for _, t in self.top.values()))
|
|
135
|
+
self.top = {item: self.top[item] for item, _, _ in self.ranked(at)[:TOP_K]}
|
|
120
136
|
|
|
121
137
|
def _prune_rejected(self) -> None:
|
|
122
138
|
if len(self.rejected) > REJECTED_SIZE:
|
|
@@ -126,12 +142,16 @@ class History:
|
|
|
126
142
|
def wire(self, now: float) -> tuple[list[list[Any]], list[str], list[str]]:
|
|
127
143
|
"""Return the request's ``history`` and ``recent``, and the rejected items.
|
|
128
144
|
|
|
129
|
-
Weights are decayed to ``now
|
|
130
|
-
JS ``Math.round`` (Python's ``round`` rounds half
|
|
131
|
-
whole seconds, never negative.
|
|
145
|
+
Weights are decayed to ``now``, at most what the API accepts, and rounded
|
|
146
|
+
half up to 4 decimals like JS ``Math.round`` (Python's ``round`` rounds half
|
|
147
|
+
to even); ages are whole seconds, never negative.
|
|
132
148
|
"""
|
|
133
149
|
history = [
|
|
134
|
-
[
|
|
150
|
+
[
|
|
151
|
+
item,
|
|
152
|
+
math.floor(min(weight, MAX_REQUEST_WEIGHT) * 1e4 + 0.5) / 1e4,
|
|
153
|
+
max(0, math.floor((now - t) / 1000)),
|
|
154
|
+
]
|
|
135
155
|
for item, weight, t in self.ranked(now)[:TOP_K]
|
|
136
156
|
]
|
|
137
157
|
recent = [item for item, _ in self.recent[-RECENT_SIZE:]]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.8
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.8-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -577,6 +577,60 @@ class Store(APITest):
|
|
|
577
577
|
[e.get("recommendation_id") for e in self.api.events()[0]], [None, None, "rec_1"]
|
|
578
578
|
)
|
|
579
579
|
|
|
580
|
+
def test_a_stored_time_too_big_for_a_float_discards_the_state(self) -> None:
|
|
581
|
+
store = recapi.MemoryStore()
|
|
582
|
+
client = self.client(store=store)
|
|
583
|
+
key = client._key("u", None)
|
|
584
|
+
big = 10**400
|
|
585
|
+
for history in (
|
|
586
|
+
{"top": [["a", 1, big]], "recent": [], "rejected": [], "lastT": None},
|
|
587
|
+
{"top": [["a", big, T0]], "recent": [], "rejected": [], "lastT": None},
|
|
588
|
+
{"top": [], "recent": [["a", big]], "rejected": [], "lastT": None},
|
|
589
|
+
{"top": [], "recent": [], "rejected": [["a", big]], "lastT": None},
|
|
590
|
+
{"top": [], "recent": [], "rejected": [], "lastT": big},
|
|
591
|
+
):
|
|
592
|
+
with self.subTest(history=history):
|
|
593
|
+
store.set(key, json.dumps({"history": history, "shown": []}))
|
|
594
|
+
with self.assertLogs("recapi", "WARNING"):
|
|
595
|
+
client.track("i", 3, user_id="u")
|
|
596
|
+
self.assertEqual(
|
|
597
|
+
[e[0] for e in json.loads(store.get(key))["history"]["top"]], ["i"]
|
|
598
|
+
)
|
|
599
|
+
|
|
600
|
+
def test_a_stored_entry_of_the_wrong_types_is_dropped(self) -> None:
|
|
601
|
+
store = recapi.MemoryStore()
|
|
602
|
+
client = self.client(store=store)
|
|
603
|
+
key = client._key("u", None)
|
|
604
|
+
for entry in (
|
|
605
|
+
["i", "rec_1", "oops"],
|
|
606
|
+
["i", "rec_1", None],
|
|
607
|
+
["i", "rec_1", T0, "x"],
|
|
608
|
+
["i", 5, T0],
|
|
609
|
+
):
|
|
610
|
+
store.set(key, json.dumps({"history": History().encode(), "shown": [entry]}))
|
|
611
|
+
client.track("i", 3, user_id="u")
|
|
612
|
+
client.flush()
|
|
613
|
+
self.assertEqual([e.get("recommendation_id") for e in self.api.events()[0]], [None] * 4)
|
|
614
|
+
|
|
615
|
+
def test_only_a_stored_true_marks_the_history_restored(self) -> None:
|
|
616
|
+
# Anything else asks recapi again: skipping the fetch would lose a
|
|
617
|
+
# returning user's history for good.
|
|
618
|
+
for flag, fetched in ((True, False), (1, True), ("true", True)):
|
|
619
|
+
with self.subTest(flag=flag):
|
|
620
|
+
before = len(self.api.paths())
|
|
621
|
+
store = recapi.MemoryStore()
|
|
622
|
+
client = self.client(store=store)
|
|
623
|
+
history = {
|
|
624
|
+
"top": [["s", 3.0, T0]],
|
|
625
|
+
"recent": [["s", T0]],
|
|
626
|
+
"rejected": [],
|
|
627
|
+
"lastT": T0,
|
|
628
|
+
}
|
|
629
|
+
state = {"history": history, "shown": [], "restored": flag}
|
|
630
|
+
store.set(client._key("u", None), json.dumps(state))
|
|
631
|
+
client.recommend(user_id="u")
|
|
632
|
+
self.assertEqual("/v1/users/u/history" in self.api.paths()[before:], fetched)
|
|
633
|
+
|
|
580
634
|
def test_the_memory_store_keeps_the_most_recently_used_users(self) -> None:
|
|
581
635
|
store = recapi.MemoryStore(max_users=2)
|
|
582
636
|
store.set("a", "1")
|
|
@@ -308,6 +308,59 @@ class ClientVectors(APITest):
|
|
|
308
308
|
sent = {k: body.get(k) for k in ("history", "recent", "exclude")}
|
|
309
309
|
self.assertEqual(sent, case["sent"])
|
|
310
310
|
|
|
311
|
+
def test_a_stored_entry_of_the_wrong_types_is_dropped(self) -> None:
|
|
312
|
+
vectors = VECTORS["stored_state"]
|
|
313
|
+
self.clock = vectors["now_ms"]
|
|
314
|
+
kept = vectors["kept"]
|
|
315
|
+
for case in vectors["cases"]:
|
|
316
|
+
with self.subTest(case=case):
|
|
317
|
+
self.api.calls.clear()
|
|
318
|
+
store = recapi.MemoryStore()
|
|
319
|
+
client = self.client(store=store)
|
|
320
|
+
shown = [case["entry"], kept]
|
|
321
|
+
store.set(
|
|
322
|
+
client._key("u", None),
|
|
323
|
+
json.dumps({"history": vectors["history"], "shown": shown}),
|
|
324
|
+
)
|
|
325
|
+
with self.assertNoLogs("recapi"):
|
|
326
|
+
client.track("i", 3, user_id="u")
|
|
327
|
+
client.track(kept[0], 3, user_id="u")
|
|
328
|
+
client.flush()
|
|
329
|
+
sent = [e.get("recommendation_id") for b in self.api.events() for e in b]
|
|
330
|
+
self.assertEqual(sent, [case["attributed"], kept[1]])
|
|
331
|
+
|
|
332
|
+
def test_a_stored_time_ahead_or_a_huge_weight_keeps_the_list(self) -> None:
|
|
333
|
+
vectors = VECTORS["stored_state"]
|
|
334
|
+
self.clock = vectors["now_ms"]
|
|
335
|
+
|
|
336
|
+
def not_json(name: str) -> None:
|
|
337
|
+
self.fail(f"the state saved {name}, which isn't JSON")
|
|
338
|
+
|
|
339
|
+
for case in vectors["history_cases"]:
|
|
340
|
+
with self.subTest(case["name"]):
|
|
341
|
+
self.api.calls.clear()
|
|
342
|
+
store = recapi.MemoryStore()
|
|
343
|
+
client = self.client(store=store)
|
|
344
|
+
key = client._key("u", None)
|
|
345
|
+
top = [case["entry"], *vectors["rest"]]
|
|
346
|
+
history = {**vectors["history"], "top": top}
|
|
347
|
+
store.set(key, json.dumps({"history": history, "shown": [], "restored": True}))
|
|
348
|
+
self.assertFalse(client.recommend(user_id="u").fallback)
|
|
349
|
+
self.assertEqual(self.api.paths(), ["/v1/recommendations"])
|
|
350
|
+
sent = self.api.calls[0].body["history"]
|
|
351
|
+
self.assertEqual(len(sent), len(case["sent"]))
|
|
352
|
+
for got, want in zip(sent, case["sent"], strict=True):
|
|
353
|
+
self.assertEqual(got[:2], want[:2])
|
|
354
|
+
self.assertLessEqual(got[1], vectors["max_request_weight"])
|
|
355
|
+
if want[2] is None:
|
|
356
|
+
self.assertGreaterEqual(got[2], 0)
|
|
357
|
+
else:
|
|
358
|
+
self.assertEqual(got[2], want[2])
|
|
359
|
+
client.track("d", 3, user_id="u")
|
|
360
|
+
client.track("h", 3, user_id="u")
|
|
361
|
+
saved = json.loads(store.get(key), parse_constant=not_json)
|
|
362
|
+
self.assertIn("o", [entry[0] for entry in saved["history"]["top"]])
|
|
363
|
+
|
|
311
364
|
def test_identify(self) -> None:
|
|
312
365
|
vectors = VECTORS["identify"]
|
|
313
366
|
now = vectors["now_ms"]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|