alligater 0.3.2__py3-none-any.whl

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.
alligater/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # Alligater
2
+
3
+ This is a flexible feature-gating library.
4
+
5
+ Detailed documentation is in the classes themselves. The quickstart version is:
6
+
7
+ ```py
8
+ from alligater import *
9
+
10
+
11
+
12
+ # 1. Create the gater withe your list of features.
13
+ gater = Alligater(
14
+ features=[
15
+ # This feature will be rolled out randomly to 25% of users.
16
+ Feature(
17
+ 'my_feature',
18
+ variants=[
19
+ Variant('on', True),
20
+ Variant('off', False),
21
+ ],
22
+ rollouts=[Rollout(
23
+ name='my_rollout',
24
+ population=Population.Percent(0.25, 'seed_value'),
25
+ arms=['on'],
26
+ )],
27
+ default_arm='off',
28
+ ),
29
+ ],
30
+ )
31
+
32
+
33
+ # 2. In your code, evaluate your feature when you need to assign a treatment.
34
+
35
+ # The gater can work for arbitrary objects, but by default it expects that
36
+ # the input entity has an `id` attribute or key. This is used for any
37
+ # randomization that happens as part of the feature's logic.
38
+ some_user = {"id": "id_of_the_user"}
39
+
40
+ if gater.my_feature(some_user):
41
+ # The feature returned `True` (the `on` variant) for this user!
42
+ # Apply that logic here.
43
+ ...
44
+ else:
45
+ # The gate returned `False` (the `off` variant).
46
+ ...
47
+ ```
48
+
49
+ ## Features:
50
+
51
+ 1. Create any number of features with any number of treatment options.
52
+ 2. Hierarchical feature definitions. Treatments can be other features. These are evaluated recursively.
53
+ 3. Load feature definitions from YAML (either from a local file or a remote URL).
54
+ 4. Flexible targetting. features can target multiple populations with arbitrarily complex logic, assigning treatments either randomly or explicitly.
55
+ 5. Stable assignments. Choices (even random ones) made by the gater are deterministic. Optionally, assignments can be read from external sources such as a database.
56
+ 6. Robust logging. Assignment choices can be inspected in detail with trace logging. The "state of the world" trace can also be logged as needed for experiment analysis. A couple of logger implementations are provided; the `print` function also works. Logging can be deferred or immediate.
57
+ 7. Targetting expressions can be written in a simple syntax in the YAML files, like `$language In ['en', 'es']`. This gives the YAML configs nearly as much flexibility as defining features in code.
58
+ 8. Features access is threadsafe.
59
+ 9. YAML-based features can be live-reloaded at a configurable interval.
60
+ 10. Complete tests.
61
+
62
+ Read the class documentation for more info!
63
+
64
+ ## To do
65
+
66
+ The current implementation is essentially feature complete. This is a list of
67
+ known limitations:
68
+
69
+ - [ ] Expression DSL does not support Map types (see `crocodsl`).
alligater/__init__.py ADDED
@@ -0,0 +1,302 @@
1
+ import atexit
2
+ import hashlib
3
+ import threading
4
+ from functools import partial
5
+ from typing import Optional, Callable, Any, Tuple
6
+
7
+ from .arm import Arm
8
+ from .cache import AssignmentCache
9
+ from .common import (
10
+ LoadError,
11
+ MissingFeatureError,
12
+ NoAssignment,
13
+ NoConfig,
14
+ NoReload,
15
+ SkipLog,
16
+ ValidationError,
17
+ encode_json,
18
+ simple_object,
19
+ default_now,
20
+ NowFn,
21
+ )
22
+ from .feature import Feature
23
+ from .events import EventLogger
24
+ from .log import (
25
+ DeferrableLogger,
26
+ NetworkLogger,
27
+ ObjectLogger,
28
+ PrintLogger,
29
+ default_logger,
30
+ log,
31
+ )
32
+ from .parse import load_config, parse_yaml, ConfigSource
33
+ from .population import Population
34
+ from .rand import seed
35
+ from .rollout import Rollout
36
+ from .value import CallType, Value
37
+ from .variant import Variant
38
+
39
+
40
+ StickyFn = Callable[[Feature, Any], Tuple[str, Any, int]]
41
+
42
+
43
+ class Alligater:
44
+ """The Alligater object represents the universe of available features.
45
+
46
+ The Alligater instance evaluates features to return an assignment. For
47
+ example:
48
+
49
+ ```
50
+ gater = Alligater(yaml='path/to/my/features.yaml')
51
+
52
+ # Assuming a feature with name "my_feature" was defined in the YAML:
53
+ treatment = gater.my_feature(some_user)
54
+ ```
55
+
56
+ The Alligater instance can be configured with different modes of logging
57
+ in order to preserve and/or debug the assignment decisions it makes.
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ features: list[Feature] | dict[str, Feature] | None = None,
63
+ yaml: ConfigSource | None = None,
64
+ logger: EventLogger = default_logger,
65
+ reload_interval: float = 0,
66
+ sticky: StickyFn | None = None,
67
+ loader_kwargs: dict | None = None,
68
+ now: NowFn = default_now,
69
+ ):
70
+ """Create a new feature gater.
71
+
72
+ Features can either come from a hardcoded predefined list or YAML.
73
+ If YAML is specified, it will override the hardcoded list.
74
+
75
+ Args:
76
+ features - List or dictionary of features.
77
+ yaml - Path to features specified in YAML.
78
+ logger - Function to call to log decisions. See `events` for more
79
+ information about how to interpret gating decisions.
80
+ reload_interval - Number of seconds between checking for YAML changes
81
+ sticky - Optional function to lookup previous assignments for the
82
+ input entity. This will skip full evaluation.
83
+ loader_kwargs - Arguments to pass to the config loader. See the
84
+ method in `parse.py` for details.
85
+ now - Function to call to get the current time.
86
+ """
87
+ log.info("🐊 Loading alligater ...")
88
+
89
+ if isinstance(features, list):
90
+ features = {f.name: f for f in features}
91
+
92
+ # Current time
93
+ self._now = now
94
+ # Trace/event logging function
95
+ self._logger = logger
96
+ # Mutex for shared access to features dict from reloader thread.
97
+ self._cv = threading.Condition()
98
+ # Path to YAML config (either local or remote path)
99
+ self._yaml = yaml
100
+ # Current list of features
101
+ self._features = features.copy() if features else {}
102
+ # Original hard-coded list of features
103
+ self._original_features = features.copy() if features else {}
104
+ # Checksum of the currently loaded YAML config
105
+ self._old_sum = ""
106
+ # Number of seconds to wait between reloads
107
+ self._reload_interval = reload_interval
108
+ # Arguments for `load_config` (See `parse#load_config`.)
109
+ self._loader_kwargs = loader_kwargs if loader_kwargs else {}
110
+ # Sticky assignment fetcher
111
+ self._sticky = sticky
112
+ # Whether loader thread is stopped
113
+ self._stopped = True
114
+ # Background thread
115
+ self._thread = None
116
+ self._local_assignments = AssignmentCache()
117
+
118
+ # Start reloading. This will load one initial time on the main thread,
119
+ # then (if `reload_interval` and `yaml` options are passed) will reload
120
+ # at interval forever in a background thread.
121
+ try:
122
+ self._reload()
123
+ except NoConfig:
124
+ log.warning("😭 No feature path specified for Alligater.")
125
+ except NoReload:
126
+ log.warning("😤 No reload interval specified for Alligater.")
127
+
128
+ if not self._features:
129
+ log.warning(
130
+ "🤬 Alligater was instantiated without any features! Was this intentional?"
131
+ )
132
+
133
+ def __getattr__(self, feature_name):
134
+ """Get a function that will evaluate the given feature.
135
+
136
+ Args:
137
+ feature_name - Name of feature to evaluate
138
+
139
+ Returns:
140
+ Function that can be called with an `entity` to evaluate.
141
+ """
142
+ try:
143
+ with self._cv:
144
+ ft = self._features[feature_name]
145
+ return partial(self, ft)
146
+ except KeyError as e:
147
+ raise MissingFeatureError(feature_name) from e
148
+
149
+ async def __call__(
150
+ self, feature, entity, silent=False, deferred=None, now: Optional[NowFn] = None
151
+ ):
152
+ """Evaluate an entity against the given feature.
153
+
154
+ Args:
155
+ feature - Feature to evaluate
156
+ entity - Arbitrary entity to evaluate
157
+ silent - Whether to suppress logging for this invocation
158
+ deferred - Whether exposure logging should be deferred. Note that
159
+ assignment logging can never be deferred.
160
+ now - Optional function to call to get the current time. (Overrides default.)
161
+
162
+ Returns:
163
+ Wrapped value of the variant to return.
164
+ """
165
+ logger = self._logger if not silent else None
166
+ now_func = now if now else self._now
167
+ value = await feature(
168
+ entity,
169
+ log=logger,
170
+ sticky=self._sticky,
171
+ assignment_cache=self._local_assignments,
172
+ gater=self,
173
+ now=now_func,
174
+ )
175
+ # Note that Logger implementations that aren't DeferrableLoggers
176
+ # log immediately and calling `log` is just a no-op.
177
+ if value.call_type == CallType.ASSIGNMENT:
178
+ value.log()
179
+
180
+ # Log an exposure immediately unless it's deferred.
181
+ if not deferred:
182
+ value.log()
183
+
184
+ return value
185
+
186
+ def stop(self):
187
+ """Stop the background reloader."""
188
+ # Make sure that the logger stops if it can.
189
+ if self._logger and hasattr(self._logger, "stop"):
190
+ self._logger.stop()
191
+
192
+ # Stop internal loader thread if necessary.
193
+ if self._stopped or not self._thread:
194
+ return
195
+
196
+ with self._cv:
197
+ self._stopped = True
198
+ self._cv.notify_all()
199
+ self._thread.join()
200
+ self._thread = None
201
+
202
+ def _reload(self):
203
+ """Start a background process to reload YAML at an interval."""
204
+ if not self._stopped or self._thread:
205
+ log.warning("👀 Called _reload when Alligater was already reloading")
206
+ return
207
+
208
+ # Force a synchronous run of the loader on the main thread
209
+ # If this fails, it'll throw an error on the main thread.
210
+ self._run_reload(once=True)
211
+
212
+ # Start a background loader to reload at interval.
213
+ if not self._reload_interval:
214
+ raise NoReload("No reload interval passed; reloader will not run")
215
+ thread = threading.Thread(target=self._run_reload, args=())
216
+ self._stopped = False
217
+ self._thread = thread
218
+ thread.start()
219
+ atexit.register(self.stop)
220
+
221
+ def _run_reload(self, once=False):
222
+ """Background worker to reload features from YAML.
223
+
224
+ Args:
225
+ once - Whether to force the loader to run only once, immediately.
226
+ """
227
+ while True:
228
+ with self._cv:
229
+ # Don't sleep if this is a one-time run.
230
+ if not once:
231
+ self._cv.wait(timeout=self._reload_interval)
232
+ if self._stopped:
233
+ return
234
+
235
+ if not self._yaml:
236
+ raise NoConfig("No YAML path is specified; (re)loader is exiting.")
237
+
238
+ try:
239
+ log.debug("🕵️‍♀️ Checking for new features ...")
240
+ yaml_str = load_config(self._yaml, **self._loader_kwargs)
241
+ new_sum = self._checksum(yaml_str)
242
+ if new_sum != self._old_sum:
243
+ log.debug("🎉 New features found!")
244
+ # NOTE: When features are reloaded, they are **not**
245
+ # merged with the _current_ list of features, they are
246
+ # always merged with the original hardcoded list. This
247
+ # results in more predictable behavior -- if we always
248
+ # merged with the current list, transient mistakes in
249
+ # a config could propagate forever.
250
+ self._features = parse_yaml(
251
+ yaml_str,
252
+ default_features=self._original_features,
253
+ raise_exceptions=once,
254
+ )
255
+ self._old_sum = new_sum
256
+ log.debug("☺️ Updated to {}!".format(new_sum))
257
+ if once:
258
+ return
259
+ else:
260
+ log.debug("😔 No new features found")
261
+ except Exception as e:
262
+ if once:
263
+ raise LoadError("Failed to load feature spec") from e
264
+ else:
265
+ log.error(
266
+ "😫 Alligater loader encountered an error: {}".format(e)
267
+ )
268
+
269
+ def _checksum(self, s):
270
+ """Compute checksum of a string.
271
+
272
+ Args:
273
+ s - String to hash
274
+
275
+ Returns:
276
+ Unique hash of the input
277
+ """
278
+ return hashlib.sha256(s.encode("utf-8")).hexdigest()
279
+
280
+
281
+ __all__ = [
282
+ "Alligater",
283
+ "Feature",
284
+ "Variant",
285
+ "Arm",
286
+ "Rollout",
287
+ "Population",
288
+ "ValidationError",
289
+ "events",
290
+ "seed",
291
+ "log",
292
+ "encode_json",
293
+ "simple_object",
294
+ "DeferrableLogger",
295
+ "NetworkLogger",
296
+ "ObjectLogger",
297
+ "PrintLogger",
298
+ "NoAssignment",
299
+ "SkipLog",
300
+ "CallType",
301
+ "Value",
302
+ ]
alligater/arm.py ADDED
@@ -0,0 +1,54 @@
1
+ from .common import ValidationError
2
+
3
+
4
+ class Arm:
5
+ """An Arm represents a treatment group as a proportion of a population.
6
+
7
+ The arm specifies a weight, which is a % of its parent population, and the
8
+ name of a variant, which is the treatment this group will receive.
9
+ """
10
+
11
+ def __init__(self, variant_name, weight=None):
12
+ """Create a new Arm representing the given variant.
13
+
14
+ The weight does not need to be specified initially, but it will need
15
+ to be set before `validate` is called.
16
+
17
+ Args:
18
+ variant_name - name of Variant that this Arm represents.
19
+ weight - Optional float weight in [0, 1]
20
+ """
21
+ self.variant_name = variant_name
22
+ self.weight = weight
23
+
24
+ def __eq__(self, other):
25
+ if not isinstance(other, Arm):
26
+ return False
27
+
28
+ return all(
29
+ [
30
+ self.variant_name == other.variant_name,
31
+ self.weight == other.weight,
32
+ ]
33
+ )
34
+
35
+ def __repr__(self):
36
+ return "<Arm name={} weight={}>".format(self.variant_name, self.weight)
37
+
38
+ def to_dict(self):
39
+ return {
40
+ "type": "Arm",
41
+ "variant": self.variant_name,
42
+ "weight": self.weight,
43
+ }
44
+
45
+ def validate(self):
46
+ """Ensure configuration makes sense.
47
+
48
+ Raises:
49
+ ValidationError - if config doesn't make sense
50
+ """
51
+ if self.weight < 0.0:
52
+ raise ValidationError("Arm weight must be positive")
53
+ if self.weight > 1.0:
54
+ raise ValidationError("Arm weight can't be greater than 1.0")
alligater/cache.py ADDED
@@ -0,0 +1,83 @@
1
+ from threading import Lock
2
+ from typing import TYPE_CHECKING, Any, Optional, Tuple
3
+ from datetime import datetime
4
+
5
+ if TYPE_CHECKING:
6
+ from .feature import Feature
7
+
8
+
9
+ EntityId = Tuple[str, str]
10
+ """Composite ID of an entity: class name and ID attribute."""
11
+
12
+ CachedAssignment = Tuple[str, Any, datetime]
13
+ """Cached variant name and value and assignment time."""
14
+
15
+ AssignmentsCache = dict[str, dict[EntityId, CachedAssignment]]
16
+ """Dictionary containing assignments."""
17
+
18
+
19
+ def _entity_id(entity: Any) -> EntityId:
20
+ """Get the ID from an entity.
21
+
22
+ Args:
23
+ entity - Anything with an ID
24
+
25
+ Returns:
26
+ Tuple with typename and ID.
27
+ """
28
+ entity_id = None
29
+ if hasattr(entity, "id"):
30
+ entity_id = entity.id
31
+ elif "id" in entity:
32
+ entity_id = entity["id"]
33
+ else:
34
+ entity_id = repr(entity_id)
35
+
36
+ return type(entity).__name__, entity_id
37
+
38
+
39
+ class AssignmentCache:
40
+ """Cache feature assignments.
41
+
42
+ Currently cache is unbounded since there is the life of the service is not
43
+ long enough for it to matter, but could add TTL.
44
+ """
45
+
46
+ def __init__(self):
47
+ self.cache = AssignmentsCache()
48
+ self.lock = Lock()
49
+
50
+ def clear(self):
51
+ """Clear the cache."""
52
+ with self.lock:
53
+ self.cache.clear()
54
+
55
+ def set(
56
+ self, feature: "Feature", entity: Any, variant: str, value: Any, ts: datetime
57
+ ):
58
+ """Add a new item to the cache.
59
+
60
+ Args:
61
+ feature - Feature to look up
62
+ entity - Entity to look up
63
+ variant - Name of variant to set
64
+ value - Value of the variant to set
65
+ ts - Timestamp of the assignment
66
+ """
67
+ with self.lock:
68
+ if feature.name not in self.cache:
69
+ self.cache[feature.name] = {}
70
+ self.cache[feature.name][_entity_id(entity)] = (variant, value, ts)
71
+
72
+ def get(self, feature: "Feature", entity: Any) -> Optional[CachedAssignment]:
73
+ """Look up cached assignment.
74
+
75
+ Args:
76
+ feature - Feature to look up
77
+ entity - Entity to look up
78
+
79
+ Returns:
80
+ Tuple of cached variant name and value and ts, if it exists, or N
81
+ """
82
+ with self.lock:
83
+ return self.cache.get(feature.name, {}).get(_entity_id(entity), None)
alligater/common.py ADDED
@@ -0,0 +1,178 @@
1
+ import collections.abc
2
+ import dataclasses
3
+ import json
4
+ import uuid
5
+ from datetime import date, datetime
6
+ from typing import Any, Callable
7
+
8
+ from crocodsl.common import utcnow
9
+ from .rand import getrandbits
10
+
11
+
12
+ NowFn = Callable[[], datetime]
13
+ """Function to get the current time."""
14
+
15
+ default_now: NowFn = utcnow
16
+ """Default function to get the current time."""
17
+
18
+
19
+ def get_uuid() -> str:
20
+ """Get a UUID (v4).
21
+
22
+ In tests this can be made deterministic either by patching or seeding the
23
+ random number generator.
24
+
25
+ Returns:
26
+ UUIDv4 as a string
27
+ """
28
+ # Call into `random` explicitly so it can be seeded for tests.
29
+ return str(uuid.UUID(int=getrandbits(128)))
30
+
31
+
32
+ def seq_id(current_id: str) -> str:
33
+ """Get a sequential ID based on the current ID.
34
+
35
+ This breaks the UUID formatting, but has two advantages:
36
+ - Keeps the provenance of the original event from which
37
+ this event was derived.
38
+ - Can help avoid non-determinism in tests.
39
+ provenance of events based on an original ID.
40
+
41
+ Args:
42
+ current_id - Base ID
43
+
44
+ Returns:
45
+ Unique ID based on the current ID.
46
+ """
47
+ base_id, _, seq = current_id.partition(":")
48
+ if seq:
49
+ return f"{base_id}:{int(seq) + 1}"
50
+ return f"{base_id}:1"
51
+
52
+
53
+ def is_non_string_iterable(c: Any) -> bool:
54
+ """Check if this is a collection (but not a string).
55
+
56
+ Args:
57
+ c - anything
58
+ """
59
+ return isinstance(c, collections.abc.Iterable) and not isinstance(c, str)
60
+
61
+
62
+ def simple_object(value: Any, with_type=False):
63
+ """Try to simplify an arbitrary object to a simple object.
64
+
65
+ Args:
66
+ value - Value to simplify
67
+ with_type - Include type information in the object
68
+
69
+ Returns:
70
+ Hopefully a simple JSON-type object.
71
+ """
72
+ if is_non_string_iterable(value):
73
+ return [simple_object(v) for v in value]
74
+
75
+ d = {}
76
+
77
+ # Check if this is a dataclass instance (and not a DataClass type)
78
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
79
+ d = dataclasses.asdict(value)
80
+ # If a dataclass defines a synthetic `id` using the `@property`
81
+ # decorator, make sure it gets included in the serialization.
82
+ if hasattr(value, "id"):
83
+ d["id"] = value.id
84
+ elif hasattr(value, "asdict"):
85
+ d = value.asdict()
86
+ elif hasattr(value, "to_dict"):
87
+ d = value.to_dict()
88
+ elif hasattr(value, "to_json"):
89
+ d = value.to_json()
90
+ else:
91
+ d = json.loads(encode_json(value))
92
+
93
+ if not with_type:
94
+ return d
95
+ return {
96
+ "type": type(value).__name__,
97
+ "value": d,
98
+ }
99
+
100
+
101
+ def _json_default_encoder(obj: Any) -> str:
102
+ """Default serializer to user with json.dumps.
103
+
104
+ Args:
105
+ obj - anything
106
+
107
+ Returns:
108
+ A simple JSON type
109
+ """
110
+ if isinstance(obj, (datetime, date)):
111
+ return obj.isoformat()
112
+ return str(obj)
113
+
114
+
115
+ def encode_json(data: Any) -> str:
116
+ """Encode object as json.
117
+
118
+ Calls json.dumps with a good serializer.
119
+
120
+ Args:
121
+ data - Arbitrary object.
122
+
123
+ Returns:
124
+ Encoded string
125
+ """
126
+ return json.dumps(data, sort_keys=True, default=_json_default_encoder)
127
+
128
+
129
+ class ValidationError(Exception):
130
+ """Error to throw when validating features."""
131
+
132
+ pass
133
+
134
+
135
+ class InvalidConfigError(Exception):
136
+ """Error thrown when YAML config can't be loaded."""
137
+
138
+ pass
139
+
140
+
141
+ class MissingFeatureError(Exception):
142
+ """Error thrown when trying to access an undefined feature."""
143
+
144
+ pass
145
+
146
+
147
+ class NoConfig(Exception):
148
+ """Thrown when no YAML config path is provided."""
149
+
150
+ pass
151
+
152
+
153
+ class NoReload(Exception):
154
+ """Thrown when no reload interval is given."""
155
+
156
+ pass
157
+
158
+
159
+ class LoadError(Exception):
160
+ """Thrown when reloader fails to load YAML."""
161
+
162
+ pass
163
+
164
+
165
+ class NoAssignment(Exception):
166
+ """Entity has not been assigned any variant of this feature.
167
+
168
+ Throw this in the `sticky` callback to indicate the feature should be
169
+ evaluated because there is no assignment yet.
170
+ """
171
+
172
+ pass
173
+
174
+
175
+ class SkipLog(Exception):
176
+ """Raise this exception to prevent logging."""
177
+
178
+ pass