Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
98a5dcc
feat: add schemas package and datafile sections for modules
fahad19 Nov 27, 2026
7cfd4a8
fix: read $, \s, the dot and large numbers in conditions as JavaScrip…
fahad19 Nov 27, 2026
16e6234
feat(schemas): read patterns with the u flag and fail closed as JavaS…
fahad19 Nov 27, 2026
130db02
feat: evaluate package entries with module phases, as getters do
fahad19 Nov 27, 2026
37ccb14
feat(cli): run schema specs with featurevisor.schemas
fahad19 Nov 27, 2026
fab827d
perf: skip module phases no module has, and parse package conditions …
fahad19 Nov 28, 2026
7a64a58
docs: follow the JavaScript SDK page in the README
fahad19 Nov 28, 2026
977dcab
feat: changed keys in context_set and segments in datafile_set
fahad19 Nov 28, 2026
7a217bf
perf: work out datafile_set details only for someone who reads them
fahad19 Nov 28, 2026
5b40e54
refactor(schemas): keep child, field_keys, has_checks and validate_ru…
fahad19 Nov 28, 2026
e7469b7
refactor(schemas): drop validate_rules and has_checks, which nothing …
fahad19 Nov 28, 2026
7c18583
refactor(schemas): avalidate is the one asynchronous form, on handles…
fahad19 Nov 29, 2026
b7e5822
test(schemas): a default annotation, and one a mutation sets
fahad19 Nov 29, 2026
50b006d
docs(schemas): the default annotation in Read annotations
fahad19 Nov 29, 2026
c86d3b0
feat(schemas): issues entries wait only for the fields they compare, …
fahad19 Nov 29, 2026
44bf11d
refactor(schemas): follow the simplified JavaScript package
fahad19 Nov 29, 2026
a2ab372
docs: beforeEvaluation runs for a schema validation too
fahad19 Nov 29, 2026
af7930e
fix(schemas): follow the JavaScript release fixes
fahad19 Nov 30, 2026
9047d80
refactor(schemas): a field's handle comes from field(path), not at(path)
fahad19 Nov 30, 2026
b17946a
refactor(schemas): a handle says what a field renders as with render_…
fahad19 Nov 30, 2026
39f3bd1
chore(release): 4.1.0
fahad19 Nov 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,027 changes: 673 additions & 354 deletions README.md

Large diffs are not rendered by default.

931 changes: 931 additions & 0 deletions conformance/schemas-datafile.json

Large diffs are not rendered by default.

4,521 changes: 4,521 additions & 0 deletions conformance/schemas-validation.json

Large diffs are not rendered by default.

768 changes: 768 additions & 0 deletions conformance/sdk-conditions.json

Large diffs are not rendered by default.

1,104 changes: 1,104 additions & 0 deletions conformance/sdk-events.json

Large diffs are not rendered by default.

460 changes: 460 additions & 0 deletions conformance/sdk-package-conditions.json

Large diffs are not rendered by default.

941 changes: 941 additions & 0 deletions conformance/sdk-sections.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "featurevisor"
version = "4.0.0"
version = "4.1.0"
description = "Featurevisor SDK for Python: feature flags, experiments and remote configuration"
readme = "README.md"
requires-python = ">=3.10"
Expand Down
4 changes: 2 additions & 2 deletions src/featurevisor/_evaluation_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,13 @@ def identity(options: dict[str, Any]) -> tuple[Any, ...]:
return (options.get("type"), options.get("featureKey"), options.get("variableKey"))

@contextmanager
def frame(self, options: dict[str, Any]) -> Iterator[None]:
def frame(self, options: dict[str, Any], parent: dict[str, Any] | None = None) -> Iterator[None]:
identity = self.identity(options)
if len(self.active) + len(self.segments) > 256:
raise RequirementInputError("Evaluation dependency depth exceeded")
if identity in self.active or any(identity == self.identity(current) for current in self.current):
raise RequirementInputError("Circular evaluation requirement")
parent = dependency_of(options)
parent = parent if parent is not None else dependency_of(options)
self.active.append(identity)
self.current.append(parent)
try:
Expand Down
9 changes: 7 additions & 2 deletions src/featurevisor/child.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import TYPE_CHECKING, Any

from .emitter import Emitter
from .events import get_params_for_sticky_features_set_event, get_params_for_sticky_variables_set_event
from .events import get_changed_context_keys, get_params_for_sticky_features_set_event, get_params_for_sticky_variables_set_event

if TYPE_CHECKING:
from .instance import Featurevisor
Expand Down Expand Up @@ -44,9 +44,14 @@ def close(self) -> None:
self.emitter.clear_all()

def set_context(self, context: dict[str, Any], replace: bool = False) -> None:
previous = self.context
self.context = dict(context) if replace else {**self.context, **context}
self._state_version += 1
self.emitter.trigger("context_set", {"context": self.context, "replaced": replace})
details: dict[str, Any] = {"context": self.context, "replaced": replace}
# Only a listener reads the changed keys, so only then are they worked out.
if self.emitter.listeners.get("context_set"):
details["keys"] = get_changed_context_keys(previous, self.context, None if replace else context)
self.emitter.trigger("context_set", details)

def get_context(self, context: dict[str, Any] | None = None) -> dict[str, Any]:
return self.parent.get_context({**self.context, **(context or {})})
Expand Down
2 changes: 1 addition & 1 deletion src/featurevisor/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def build_parser() -> argparse.ArgumentParser:
common.add_argument("--target", type=nonempty_value, action="append", default=[])
common.add_argument("--set")
test_parser = subparsers.add_parser("test", parents=[common], allow_abbrev=False)
test_parser.add_argument("--entity-type", "--entityType", dest="entityType", choices=("feature", "segment", "variable", "scenario"))
test_parser.add_argument("--entity-type", "--entityType", dest="entityType", choices=("feature", "segment", "variable", "scenario", "schema"))
test_parser.add_argument("--json", action="store_true")
test_parser.add_argument("--pretty", action="store_true")
test_parser.add_argument("--case", dest="case_id")
Expand Down
12 changes: 12 additions & 0 deletions src/featurevisor/compare_versions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import re
from typing import Any

SEMVER_REGEX = re.compile(
r"^[v^~<>=]*?([0-9]+)(?:\.([x*]|[0-9]+)(?:\.([x*]|[0-9]+)(?:\.([x*]|[0-9]+))?(?:-([0-9a-z\-]+(?:\.[0-9a-z\-]+)*))?(?:\+[0-9a-z\-]+(?:\.[0-9a-z\-]+)*)?)?)?$",
Expand Down Expand Up @@ -61,3 +62,14 @@ def compare_versions(v1: str, v2: str) -> int:
if p1 or p2:
return -1 if p1 else 1
return 0


def is_valid_version(version: Any) -> bool:
"""Whether the version operators can compare a value, as a schema's format "semver" asks."""
if not isinstance(version, str):
return False
try:
compare_versions(version, version)
return True
except Exception:
return False
64 changes: 53 additions & 11 deletions src/featurevisor/conditions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import datetime as dt
import math
import re
from dataclasses import dataclass
from typing import Any, Callable
Expand All @@ -14,13 +15,29 @@
MAX_PORTABLE_DATE = dt.datetime(9999, 12, 31, 23, 59, 59, 999000, tzinfo=dt.timezone.utc)


def normalize_portable_regex(pattern: str) -> str:
"""Use JS ASCII digit and word shorthands without altering Unicode whitespace."""
_PORTABLE_SPACES = "\\t\\n\\x0b\\f\\r \\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff"
_PORTABLE_NOT_SPACES = ("\\x00-\\x08\\x0e-\\x1f\\x21-\\x9f\\xa1-\\u167f\\u1681-\\u1fff\\u200b-\\u2027\\u202a-\\u202e"
"\\u2030-\\u205e\\u2060-\\u2fff\\u3001-\\ufefe\\uff00-\\U0010ffff")


def normalize_portable_regex(pattern: str, flags: str = "") -> str:
"""A portable pattern in Python's syntax, meaning what it means in JavaScript with the same flags.

\\d and \\w are ASCII, \\s is JavaScript's whitespace, a dot refuses only
JavaScript's line terminators, and without m a $ matches at the very end,
never before a final line break as Python's does.
"""
multiline = "m" in flags
dot_all = "s" in flags
inside = {
"d": "0-9", "D": r"\x00-\x2F\x3A-\U0010FFFF",
"w": "A-Za-z0-9_", "W": r"\x00-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\U0010FFFF",
"s": _PORTABLE_SPACES, "S": _PORTABLE_NOT_SPACES,
}
outside = {
"d": "[0-9]", "D": "[^0-9]", "w": "(?-i:[A-Za-z0-9_])", "W": "(?-i:[^A-Za-z0-9_])",
"s": f"[{_PORTABLE_SPACES}]", "S": f"[^{_PORTABLE_SPACES}]",
}
outside = {"d": "[0-9]", "D": "[^0-9]", "w": "(?-i:[A-Za-z0-9_])", "W": "(?-i:[^A-Za-z0-9_])"}
result: list[str] = []
in_class = False
index = 0
Expand All @@ -31,10 +48,19 @@ def normalize_portable_regex(pattern: str) -> str:
result.append((inside if in_class else outside).get(escaped, pattern[index:index + 2]))
index += 2
continue
if char == "[" and not in_class:
if in_class:
if char == "]":
in_class = False
elif char == "[":
in_class = True
elif char == "]" and in_class:
in_class = False
elif char == "$" and not multiline:
result.append("\\Z")
index += 1
continue
elif char == "." and not dot_all:
result.append("[^\\n\\r\\u2028\\u2029]")
index += 1
continue
result.append(char)
index += 1
return "".join(result)
Expand Down Expand Up @@ -79,11 +105,19 @@ def prepare_conditions(conditions: Any) -> Any:
return conditions


def _binary64(number: int | float) -> float:
"""A number as JavaScript reads it, a double, so integers above 2^53 compare as JavaScript compares them."""
try:
return float(number)
except OverflowError:
return math.inf if number > 0 else -math.inf


def _strict_equal(left: Any, right: Any) -> bool:
if isinstance(left, bool) or isinstance(right, bool):
return isinstance(left, bool) and isinstance(right, bool) and left == right
if isinstance(left, (int, float)) and isinstance(right, (int, float)):
return left == right
return _binary64(left) == _binary64(right)
if left is None or right is None:
return left is None and right is None
if isinstance(left, str) and isinstance(right, str):
Expand Down Expand Up @@ -250,14 +284,15 @@ def _value_is_matched(
if operator == "notMatches":
return not get_regex(value, regex_flags).search(context_value)
if not isinstance(context_value, bool) and not isinstance(value, bool) and isinstance(context_value, (int, float)) and isinstance(value, (int, float)):
left, right = _binary64(context_value), _binary64(value)
if operator == "greaterThan":
return context_value > value
return left > right
if operator == "greaterThanOrEquals":
return context_value >= value
return left >= right
if operator == "lessThan":
return context_value < value
return left < right
if operator == "lessThanOrEquals":
return context_value <= value
return left <= right
if operator == "exists":
return context_value is not MISSING
if operator == "notExists":
Expand All @@ -275,3 +310,10 @@ def _value_is_matched(
if operator == "notIncludes":
return not any(_strict_equal(value, candidate) for candidate in context_value)
return False


def get_portable_timestamp(value: Any) -> dt.datetime | None:
"""A portable timestamp, as before, after and a schema's format "date-time" read
it, to the millisecond, or None: years 0001 to 9999, offsets up to 14 hours,
and fractions up to nine digits."""
return _to_datetime(value)
20 changes: 11 additions & 9 deletions src/featurevisor/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def evaluate_with_modules(options: dict[str, Any]) -> dict[str, Any]:
modules_manager = options["modulesManager"]
module_options = None
current_options = options
if modules_manager.modules:
if modules_manager.has_before_evaluation:
private = {key: value for key, value in options.items()
if key == "_evaluationSession" or key.startswith("__featurevisor_")}
module_options = {key: value for key, value in options.items() if key not in private}
Expand All @@ -71,8 +71,8 @@ def evaluate_with_modules(options: dict[str, Any]) -> dict[str, Any]:
):
evaluation["variableValue"] = current_options["defaultVariableValue"]
# Evaluation callbacks may install a module after the initial
# empty-list check. Its after hook must still see public options.
if modules_manager.modules:
# check. Its after hook must still see public options.
if modules_manager.has_after_evaluation:
if module_options is None:
module_options = {key: value for key, value in options.items()
if key != "_evaluationSession" and not key.startswith("__featurevisor_")}
Expand Down Expand Up @@ -243,13 +243,15 @@ def evaluate(options: dict[str, Any]) -> dict[str, Any]:
return evaluation

bucket_key = get_bucket_key(featureKey=feature_key, bucketBy=feature["bucketBy"], context=context, diagnostics=diagnostics)
bucket_key = modules_manager.run_bucket_key_modules(
{"featureKey": feature_key, "context": context, "bucketBy": feature["bucketBy"], "bucketKey": bucket_key}
)
if modules_manager.has_bucket_key:
bucket_key = modules_manager.run_bucket_key_modules(
{"featureKey": feature_key, "context": context, "bucketBy": feature["bucketBy"], "bucketKey": bucket_key}
)
bucket_value = get_bucketed_number(bucket_key)
bucket_value = modules_manager.run_bucket_value_modules(
{"featureKey": feature_key, "bucketKey": bucket_key, "context": context, "bucketValue": bucket_value}
)
if modules_manager.has_bucket_value:
bucket_value = modules_manager.run_bucket_value_modules(
{"featureKey": feature_key, "bucketKey": bucket_key, "context": context, "bucketValue": bucket_value}
)

matched_traffic = datafile.get_matched_traffic(feature["traffic"], context, options)
matched_allocation = datafile.get_matched_allocation(matched_traffic, bucket_value) if type_ != "flag" and matched_traffic else None
Expand Down
19 changes: 17 additions & 2 deletions src/featurevisor/evaluation_data_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ def __init__(self) -> None:
self.value: Any = None


# The datafile's own keys, and the tester's helper key. Every other top level key is a section or carried as it is.
DATAFILE_KEYS = frozenset({
"schemaVersion", "revision", "featurevisorVersion", "segments", "features", "variables", "_segment_test_keys",
})


class _InstanceEvaluationDataProvider:
def __init__(self, *, datafile: DatafileContent, diagnostics: _EvaluationDiagnostics) -> None:
helpers: Any = datafile.get("_segment_test_keys", {})
Expand All @@ -38,6 +44,8 @@ def __init__(self, *, datafile: DatafileContent, diagnostics: _EvaluationDiagnos
self.segments = datafile.get("segments", {})
self.features = datafile.get("features", {})
self.variables = datafile.get("variables", {})
# Every other top level key, such as a "schemas" section, kept as the datafile has it.
self.sections = {key: value for key, value in datafile.items() if key not in DATAFILE_KEYS}
self.regex_cache: dict[str, re.Pattern[str]] = {}
self.expression_cache: dict[str, Any] = {}
self.prepared_expression_cache: dict[str, Any] = {}
Expand Down Expand Up @@ -108,7 +116,14 @@ def get_datafile(self) -> dict[str, Any]:
"features": self.features,
"variables": self.variables,
}
return {key: value for key, value in datafile.items() if value is not None}
result: dict[str, Any] = {key: value for key, value in datafile.items() if value is not None}
result.update(self.sections)
return result

def get_section(self, name: str) -> dict[str, Any] | None:
"""A section by name, such as "schemas": a top level key besides the SDK's own whose value is an object."""
section = self.sections.get(name)
return section if isinstance(section, dict) else None

def get_segment(self, segment_key: str) -> Segment | None:
return self._entity("segment", segment_key, self.segments)
Expand Down Expand Up @@ -185,7 +200,7 @@ def get_regex(self, regex_string: str, regex_flags: str = "") -> re.Pattern[str]
flags |= re.MULTILINE
if "s" in regex_flags:
flags |= re.DOTALL
self.regex_cache[key] = re.compile(normalize_portable_regex(regex_string), flags)
self.regex_cache[key] = re.compile(normalize_portable_regex(regex_string, regex_flags), flags)
return self.regex_cache[key]

def all_conditions_are_matched(self, conditions: Any, context: Context) -> bool:
Expand Down
Loading