alligater 0.3.2__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.
Files changed (40) hide show
  1. alligater-0.3.2/PKG-INFO +24 -0
  2. alligater-0.3.2/README.md +4 -0
  3. alligater-0.3.2/alligater/README.md +69 -0
  4. alligater-0.3.2/alligater/__init__.py +302 -0
  5. alligater-0.3.2/alligater/arm.py +54 -0
  6. alligater-0.3.2/alligater/cache.py +83 -0
  7. alligater-0.3.2/alligater/common.py +178 -0
  8. alligater-0.3.2/alligater/events.py +311 -0
  9. alligater-0.3.2/alligater/feature.py +310 -0
  10. alligater-0.3.2/alligater/log.py +383 -0
  11. alligater-0.3.2/alligater/parse.py +332 -0
  12. alligater-0.3.2/alligater/population.py +222 -0
  13. alligater-0.3.2/alligater/rand.py +30 -0
  14. alligater-0.3.2/alligater/rollout.py +280 -0
  15. alligater-0.3.2/alligater/test_common.py +47 -0
  16. alligater-0.3.2/alligater/test_feature.py +224 -0
  17. alligater-0.3.2/alligater/test_gater.py +348 -0
  18. alligater-0.3.2/alligater/test_log.py +959 -0
  19. alligater-0.3.2/alligater/test_parse.py +453 -0
  20. alligater-0.3.2/alligater/value.py +262 -0
  21. alligater-0.3.2/alligater/variant.py +135 -0
  22. alligater-0.3.2/crocodsl/README.md +102 -0
  23. alligater-0.3.2/crocodsl/__init__.py +10 -0
  24. alligater-0.3.2/crocodsl/common.py +145 -0
  25. alligater-0.3.2/crocodsl/expr.py +247 -0
  26. alligater-0.3.2/crocodsl/field.py +33 -0
  27. alligater-0.3.2/crocodsl/func.py +513 -0
  28. alligater-0.3.2/crocodsl/gram/Gram.g4 +104 -0
  29. alligater-0.3.2/crocodsl/gram/Gram.interp +70 -0
  30. alligater-0.3.2/crocodsl/gram/Gram.tokens +47 -0
  31. alligater-0.3.2/crocodsl/gram/GramLexer.interp +102 -0
  32. alligater-0.3.2/crocodsl/gram/GramLexer.py +2035 -0
  33. alligater-0.3.2/crocodsl/gram/GramLexer.tokens +47 -0
  34. alligater-0.3.2/crocodsl/gram/GramListener.py +133 -0
  35. alligater-0.3.2/crocodsl/gram/GramParser.py +1492 -0
  36. alligater-0.3.2/crocodsl/gram/gen.sh +1 -0
  37. alligater-0.3.2/crocodsl/test_expr.py +176 -0
  38. alligater-0.3.2/crocodsl/test_field.py +45 -0
  39. alligater-0.3.2/crocodsl/test_func.py +288 -0
  40. alligater-0.3.2/pyproject.toml +33 -0
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.1
2
+ Name: alligater
3
+ Version: 0.3.2
4
+ Summary: Randomization and gating library for Python.
5
+ License: MIT
6
+ Author: Joe Nudell
7
+ Author-email: jnudell@hks.harvard.edu
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Requires-Dist: antlr4-python3-runtime (==4.10)
14
+ Requires-Dist: mmh3 (>=4.1,<5.0)
15
+ Requires-Dist: pyyaml (>=6.0,<7.0)
16
+ Requires-Dist: requests (>=2.32,<3.0)
17
+ Requires-Dist: urllib3 (>=2.2,<3.0)
18
+ Description-Content-Type: text/markdown
19
+
20
+ Alligater
21
+ ===
22
+
23
+ A small config-based feature gating library for Python.
24
+
@@ -0,0 +1,4 @@
1
+ Alligater
2
+ ===
3
+
4
+ A small config-based feature gating library for Python.
@@ -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`).
@@ -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
+ ]
@@ -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")
@@ -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)