Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(flags): add dormant rules v2 validator and rule warning detectors (#101499)

Anders4c5b7f5be96a
diff --git a/docs/internal/feature-flags/management-warnings.md b/docs/internal/feature-flags/management-warnings.md
index b210bfbfbccf..f14e001da877 100644
--- a/docs/internal/feature-flags/management-warnings.md
+++ b/docs/internal/feature-flags/management-warnings.md
@@ -1,7 +1,7 @@
# Management warnings
The rules v2 management warning contract is dormant.
-It defines a diagnostic value and its wire representation; it has no detectors or production consumers.
+It defines a diagnostic value and its wire representation, and three configuration detectors behind a facade entrypoint that no production write path calls yet.
## Supported codes
@@ -38,8 +38,34 @@ None of these carry a management warning code.
An omitted `attr` and `attr: null` both mean no field and parse as `None`.
Serialization omits `attr` when it is `None`, so explicit null normalizes to an omitted member.
-The five codes are the complete `warning_codes` list of the harness registry at contract package 2.0.0 ([posthog-sdk-test-harness#57](https://github.com/PostHog/posthog-sdk-test-harness/pull/57), unreleased); the DTO rejects any other code.
+The five codes are the complete `warning_codes` list of the harness registry 2.0.0 in contract package 2.0.0, released in [posthog-sdk-test-harness 1.5.0](https://github.com/PostHog/posthog-sdk-test-harness/tree/e487249c34176c053f524d96bf0f99818dc91247/contracts/feature_flag_rules_v2); the DTO rejects any other code.
+`products/feature_flags/backend/test/fixtures/rules_v2_contract/` vendors that release's config schema, registry, warning schema and config fixtures with a digest-checked pin.
Share the diagnostic output type across callers.
Define detector inputs alongside their implementations: rule checks need evaluated targeting and rollout fields, and lifecycle checks need the proposed operation.
-The structural `ConfigV2` reader omits these fields, so it cannot serve as a universal detector input.
+The structural `ConfigV2` reader omits these fields, so it cannot serve as a universal detector input; the rule detectors read `ValidatedConfig` from the strict validator instead.
+
+## Configuration validation and rule detectors
+
+`facade/config_validation.py` validates a complete canonical config version 2 candidate: the document a writer is about to persist, with rule ids and seeds already resolved, plus explicit `ValidationLimits` (the deployment filter byte limit and a per-rule metadata bound) from the trusted caller.
+It returns a `ValidatedConfig` or raises `ConfigValidationError` with every field error in a fixed order (root fields, then each rule's fields in rule order), each as a stable code (`required`, `invalid`, `unknown_field`, `not_unique`, `unsupported`, `limit_exceeded`), a presentation detail and a `filters.…` path.
+It does not read or write the database, assign ids or seeds, check permissions, or mutate the input, and a valid result is not permission to store or activate anything.
+
+The admitted family is deliberately narrower than the published schema: person-assigned boolean flags with `targeted_release` and `percentage_rollout` rules whose targeting uses person properties with the contract's canonical operators.
+String, number and object values, experiment rules, group assignment (`aggregation_group_type_index`) and cohort, group and flag properties are refused with the `unsupported` code, never with a shape code, so a schema-valid contract fixture is not relabelled as malformed and no partially checked document succeeds.
+Cohort and flag references wait for the dependency validation task; the other families wait for their milestones.
+
+`facade/rule_warnings.py` owns the three configuration detectors and `review_config`, the dormant entrypoint that validates a candidate and returns its warnings as `ManagementWarning` values.
+Validation runs first, so a warning never accompanies an invalid document.
+Given the stored `ValidatedConfig`, the entrypoint also compares rule order; without it no reorder warning is claimed.
+
+The detectors reason about one population at a time: the people who satisfy a rule's whole predicate set.
+A rule provably applies to that population when its own predicate set is a subset of the population's; any other relation is inconclusive and stops the analysis, so the detectors never guess how two different predicates overlap and never claim an affected percentage.
+Within a population, percentage rules split people by their assignment hash: rules that share a seed reuse the same hash interval, rules with different seeds are treated as independent, 0% includes nobody and 100% everybody.
+
+- `UNREACHABLE_LOWER_RULE` fires for a rule that no path reaches because earlier applicable rules already settled everyone: a targeted release, a `return_default` rule or a 100% rollout that covers the rule's population, or same-seed rollouts that together close the hash space. A continuing partial rollout, a narrower conditional rule and a same-seed rollout that includes nobody do not block.
+- `ROLLOUT_MISS_CAN_ENTER_LOWER_RULE` fires when a continuing partial rollout serves a value to somebody and a lower rule with the same value provably serves it to people who missed that rollout: a covering targeted release, a rollout with another seed, or a same-seed rollout with a higher percentage. A lower rule with another value, a same-seed rollout at or below the upper percentage, a 0% rule, a terminal rule in between, and an inconclusive overlap all suppress it.
+- `RULE_ORDER_CHANGES_TRAFFIC` fires for a pair of rules present unchanged in both configs whose relative order flipped when some population provably settles on different values in the two orders. Equal values, disjoint or inconclusive targeting, an unmoved terminal rule above both, and rules added, removed or edited by the same change do not produce it: an edited rule is an edit, not a reorder.
+
+Warnings are deterministic and deduplicated per rule or rule pair; `attr` points at the affected rule and `detail` names the other rule by id, never a seed or property value.
+The two lifecycle codes are not detected here; they belong to the reset and conclusion previews.
diff --git a/products/feature_flags/backend/facade/config_validation.py b/products/feature_flags/backend/facade/config_validation.py
new file mode 100644
index 000000000000..e42739901d64
--- /dev/null
+++ b/products/feature_flags/backend/facade/config_validation.py
@@ -0,0 +1,550 @@
+"""Strict validation of a complete config version 2 candidate document.
+
+Boundary: a complete canonical candidate (the document a writer is about to persist, with
+server-assigned rule ids and seeds already resolved) plus explicit limits from the trusted
+caller -> ``validate_config`` -> ``ValidatedConfig``, the evaluated fields the rule warning
+detectors read, or ``ConfigValidationError`` carrying every field error in a fixed order
+(root fields, then each rule's fields in rule order), so the same document always yields
+the same list. Nothing here reads or writes the database, assigns ids or seeds, checks
+permissions, or mutates the input: a validated config says the document is well formed
+and admitted, not that the caller may store it. The later trusted write path resolves
+request input into the final document, calls ``rule_warnings.review_config`` (which
+validates through this module and reports warnings) and persists under the existing row
+lock. No production caller exists yet.
+
+Admitted family: person-assigned boolean flags with targeted_release and
+percentage_rollout rules whose targeting uses person properties. Everything else the
+published contract describes (string/number/object values, experiment rules, group
+assignment, cohort/group/flag properties) is rejected with the ``unsupported`` code, so a
+canonical fixture is never relabelled as malformed and no partially checked document is
+accepted. Shape errors use the other codes. The canonical shape is the harness config
+schema 1.0.0 in contract package 2.0.0; the semantic constraints (unique rule ids, two
+decimal places, byte limits) come from its literal registry.
+"""
+
+import re
+import sys
+import json
+from collections.abc import Callable, Mapping
+from dataclasses import field
+from decimal import Decimal
+from typing import Any, Literal, get_args
+
+from posthog.hogql.property import parse_semver
+
+from posthog.dataclasses import frozen
+from posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORS
+from posthog.models.property.relative_date import determine_parsed_date_for_property_matching
+
+from products.feature_flags.backend.facade.config import FlagReturnType, RuleType, detect_config_format
+from products.feature_flags.backend.types import PropertyFilterType
+
+MAX_RULES = 100
+MAX_PREDICATES_PER_RULE = 100
+MAX_SEED_LENGTH = 400
+MAX_PERCENTAGE_DECIMALS = 2
+
+ConfigErrorCode = Literal["required", "invalid", "unknown_field", "not_unique", "unsupported", "limit_exceeded"]
+RolloutMissPolicy = Literal["continue", "return_default"]
+AdmittedRuleType = Literal["targeted_release", "percentage_rollout"]
+
+RETURN_TYPES: tuple[str, ...] = get_args(FlagReturnType)
+RULE_TYPES: tuple[str, ...] = get_args(RuleType)
+ROLLOUT_MISS_POLICIES: tuple[RolloutMissPolicy, ...] = get_args(RolloutMissPolicy)
+ASSIGNMENT_ALGORITHM = "sha1_60_v1"
+PERSON_ASSIGNMENT = "person"
+PROPERTY_TYPES: tuple[str, ...] = tuple(PropertyFilterType)
+# The contract's closed operator set. It has no aliases: a canonical document stores the
+# operator the evaluator reads, so the v1 ``min``/``max`` spellings are invalid here.
+PROPERTY_OPERATORS: frozenset[str] = frozenset(
+ {
+ "exact",
+ "is_not",
+ "icontains",
+ "not_icontains",
+ "icontains_multi",
+ "not_icontains_multi",
+ "regex",
+ "not_regex",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "semver_gt",
+ "semver_gte",
+ "semver_lt",
+ "semver_lte",
+ "semver_eq",
+ "semver_neq",
+ "semver_tilde",
+ "semver_caret",
+ "semver_wildcard",
+ "is_set",
+ "is_not_set",
+ "is_date_exact",
+ "is_date_after",
+ "is_date_before",
+ "in",
+ "not_in",
+ "flag_evaluates_to",
+ }
+ | set(STRING_PREFIX_SUFFIX_OPERATORS)
+)
+# Operator/value shapes mirror the v1 cross-field tier (filters_validation.py) so a property
+# the v1 evaluator would reject is rejected here too. That module is the v1 tier (it imports
+# the v1 serializer), so the table is repeated rather than coupling this validator to it.
+_DATE_OPERATORS = frozenset({"is_date_exact", "is_date_after", "is_date_before"})
+_STRING_VALUE_OPERATORS = frozenset({"regex", "not_regex", "icontains", "not_icontains"}) | set(
+ STRING_PREFIX_SUFFIX_OPERATORS
+)
+_NUMERIC_COMPARISON_OPERATORS = frozenset({"gt", "gte", "lt", "lte"})
+_LIST_VALUE_OPERATORS = frozenset({"icontains_multi", "not_icontains_multi"})
+_SEMVER_OPERATORS = frozenset({op for op in PROPERTY_OPERATORS if op.startswith("semver_")})
+_NON_PERSON_OPERATORS = frozenset({"in", "not_in", "flag_evaluates_to"})
+
+_ROOT_FIELDS = frozenset({"version", "return_type", "default_value", "rules", "aggregation_group_type_index"})
+# v1-only top-level keys a v2 document must never carry.
+_V1_ONLY_ROOT_FIELDS = frozenset(
+ {
+ "groups",
+ "multivariate",
+ "payloads",
+ "super_groups",
+ "holdout_groups",
+ "holdout",
+ "feature_enrollment",
+ "early_exit",
+ "bucketing_identifier",
+ }
+)
+_COMMON_RULE_FIELDS = frozenset({"id", "rule_type", "targeting", "description", "metadata", "value"})
+_ROLLOUT_RULE_FIELDS = frozenset({"rollout_percentage", "on_rollout_miss", "assignment_algorithm", "seed", "assign_by"})
+_RULE_FIELDS: dict[str, frozenset[str]] = {
+ "targeted_release": _COMMON_RULE_FIELDS,
+ "percentage_rollout": _COMMON_RULE_FIELDS | _ROLLOUT_RULE_FIELDS,
+}
+_PROPERTY_FIELDS = frozenset(
+ {"key", "value", "type", "operator", "group_type_index", "negation", "cohort_name", "group_key_names", "label"}
+)
+_UUID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
+
+
+@frozen
+class ConfigError:
+ code: ConfigErrorCode
+ # Presentation text. Never carries property values, seeds or metadata: the path in
+ # ``attr`` identifies the field and the code identifies the problem.
+ detail: str
+ # Dotted path from the flag's ``filters`` field, e.g. ``filters.rules[2].seed``.
+ attr: str
+
+
+class ConfigValidationError(ValueError):
+ def __init__(self, errors: list[ConfigError]) -> None:
+ super().__init__(f"{errors[0].attr}: {errors[0].detail}")
+ self.errors = tuple(errors)
+
+
+@frozen
+class ValidationLimits:
+ """Deployment limits the trusted caller supplies; the validator invents none.
+
+ ``max_config_bytes`` is the per-flag filters limit the v1 write path already enforces
+ (``settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES``). ``max_metadata_bytes`` bounds one
+ rule's opaque ``metadata`` object; the contract requires a bound but no production
+ value is decided yet, so it is required here rather than defaulted.
+ """
+
+ max_config_bytes: int
+ max_metadata_bytes: int
+
+ def __post_init__(self) -> None:
+ for name in ("max_config_bytes", "max_metadata_bytes"):
+ limit = getattr(self, name)
+ if isinstance(limit, bool) or not isinstance(limit, int) or limit <= 0:
+ raise ValueError(f"{name} must be a positive integer")
+
+
+@frozen
+class Predicate:
+ """One person-property targeting condition in the canonical form the detectors compare.
+
+ Two rules whose predicate sets are equal target the same population; a rule whose set
+ is a superset of another's targets a subset of it. The operator ``None`` reads as
+ ``exact`` and the value is stored as canonical JSON text so the predicate is hashable.
+ """
+
+ key: str
+ operator: str
+ value: str
+ negation: bool
+
+
+@frozen
+class ValidatedRule:
+ id: str
+ rule_type: AdmittedRuleType
+ predicates: frozenset[Predicate]
+ value: bool
+ rollout_percentage: Decimal | None = None
+ on_rollout_miss: RolloutMissPolicy | None = None
+ # Assignment seeds must not reach logs or tracebacks; the detectors only compare them.
+ seed: str | None = field(default=None, repr=False)
+
+
+@frozen
+class ValidatedConfig:
+ """An admitted person-assigned boolean config; the family is fixed, so only the evaluated fields vary."""
+
+ default_value: bool | None
+ rules: tuple[ValidatedRule, ...] # stored order, which is evaluation order
+
+
+def validate_config(document: object, *, limits: ValidationLimits) -> ValidatedConfig:
+ """Validate a complete canonical candidate; raise ``ConfigValidationError`` otherwise.
+
+ Deterministic, side-effect free and bounded by the byte limit, which is checked before
+ anything else is read. The document is not modified.
+ """
+ errors: list[ConfigError] = []
+ if not isinstance(document, Mapping):
+ raise ConfigValidationError([ConfigError(code="invalid", detail="Must be an object.", attr="filters")])
+ size = _encoded_size(document)
+ if size is None:
+ raise ConfigValidationError([ConfigError(code="invalid", detail="Must be a JSON document.", attr="filters")])
+ if size > limits.max_config_bytes:
+ raise ConfigValidationError(
+ [ConfigError(code="limit_exceeded", detail="The configuration is too large.", attr="filters")]
+ )
+
+ if "version" not in document:
+ errors.append(_required("filters.version"))
+ elif detect_config_format(document).kind != "v2":
+ errors.append(ConfigError(code="invalid", detail="Must be config version 2.", attr="filters.version"))
+ for name in document:
+ if name in _ROOT_FIELDS:
+ continue
+ v1_detail = "Config version 1 fields are not allowed in a config version 2 document."
+ errors.append(_unknown_field(f"filters.{name}", v1_detail if name in _V1_ONLY_ROOT_FIELDS else None))
+
+ return_type_ok = _field(document, "return_type", "filters", errors, _one_of(RETURN_TYPES))
+ boolean_family = return_type_ok and document["return_type"] == "boolean"
+ if return_type_ok and not boolean_family:
+ errors.append(
+ ConfigError(
+ code="unsupported",
+ detail=f"Flags returning a {document['return_type']} are not available yet. Only boolean is available.",
+ attr="filters.return_type",
+ )
+ )
+ if "default_value" not in document:
+ errors.append(_required("filters.default_value"))
+ elif boolean_family and not _is_bool_or_none(document["default_value"]):
+ errors.append(ConfigError(code="invalid", detail="Must be true, false or null.", attr="filters.default_value"))
+ if _field(document, "aggregation_group_type_index", "filters", errors, (_is_int, "Must be an integer."), False):
+ errors.append(
+ ConfigError(
+ code="unsupported",
+ detail="Group-assigned flags are not available yet.",
+ attr="filters.aggregation_group_type_index",
+ )
+ )
+
+ rules: list[ValidatedRule] = []
+ if _field(document, "rules", "filters", errors, (lambda v: isinstance(v, list), "Must be an array.")):
+ if len(document["rules"]) > MAX_RULES:
+ errors.append(
+ ConfigError(
+ code="limit_exceeded", detail=f"At most {MAX_RULES} rules are allowed.", attr="filters.rules"
+ )
+ )
+ else:
+ seen_ids: set[str] = set()
+ for index, rule in enumerate(document["rules"]):
+ validated = _validate_rule(rule, f"filters.rules[{index}]", boolean_family, limits, errors)
+ if validated is None:
+ continue
+ if validated.id in seen_ids:
+ errors.append(
+ ConfigError(
+ code="not_unique", detail="Rule ids must be unique.", attr=f"filters.rules[{index}].id"
+ )
+ )
+ seen_ids.add(validated.id)
+ rules.append(validated)
+
+ if errors:
+ raise ConfigValidationError(errors)
+ return ValidatedConfig(default_value=document["default_value"], rules=tuple(rules))
+
+
+def _validate_rule(
+ rule: object, path: str, boolean_family: bool, limits: ValidationLimits, errors: list[ConfigError]
+) -> ValidatedRule | None:
+ if not isinstance(rule, Mapping):
+ errors.append(ConfigError(code="invalid", detail="Must be an object.", attr=path))
+ return None
+ if not _field(rule, "rule_type", path, errors, _one_of(RULE_TYPES)):
+ return None
+ rule_type = rule["rule_type"]
+ if rule_type not in _RULE_FIELDS:
+ errors.append(
+ ConfigError(code="unsupported", detail="Experiment rules are not available yet.", attr=f"{path}.rule_type")
+ )
+ return None
+ for name in rule:
+ if name not in _RULE_FIELDS[rule_type]:
+ rollout_only = "Only percentage_rollout rules have this field."
+ errors.append(_unknown_field(f"{path}.{name}", rollout_only if name in _ROLLOUT_RULE_FIELDS else None))
+
+ before = len(errors)
+ _field(rule, "id", path, errors, (lambda v: isinstance(v, str) and bool(_UUID.fullmatch(v)), "Must be a UUID."))
+ predicates = _validate_targeting(rule, path, errors)
+ _field(rule, "description", path, errors, (lambda v: isinstance(v, str), "Must be a string."), False)
+ if "metadata" in rule:
+ _validate_metadata(rule["metadata"], f"{path}.metadata", limits, errors)
+ if boolean_family:
+ _field(rule, "value", path, errors, (lambda v: isinstance(v, bool), "Must be true or false."))
+
+ rollout: Decimal | None = None
+ if rule_type == "percentage_rollout":
+ rollout = _validate_percentage(rule, path, errors)
+ _field(rule, "on_rollout_miss", path, errors, _one_of(ROLLOUT_MISS_POLICIES))
+ _field(rule, "assignment_algorithm", path, errors, _one_of((ASSIGNMENT_ALGORITHM,)))
+ seed_ok = (
+ lambda v: isinstance(v, str) and 1 <= len(v) <= MAX_SEED_LENGTH,
+ f"Must be between 1 and {MAX_SEED_LENGTH} characters.",
+ )
+ _field(rule, "seed", path, errors, seed_ok)
+ _field(rule, "assign_by", path, errors, _one_of((PERSON_ASSIGNMENT,)), False)
+
+ if len(errors) > before or predicates is None or not boolean_family:
+ return None
+ return ValidatedRule(
+ id=rule["id"],
+ rule_type=rule_type,
+ predicates=predicates,
+ value=rule["value"],
+ rollout_percentage=rollout,
+ on_rollout_miss=rule["on_rollout_miss"] if rollout is not None else None,
+ seed=rule["seed"] if rollout is not None else None,
+ )
+
+
+def _validate_targeting(rule: Mapping[str, Any], path: str, errors: list[ConfigError]) -> frozenset[Predicate] | None:
+ if not _field(rule, "targeting", path, errors, (lambda v: isinstance(v, Mapping), "Must be an object.")):
+ return None
+ targeting = rule["targeting"]
+ path = f"{path}.targeting"
+ for name in targeting:
+ if name != "properties":
+ errors.append(_unknown_field(f"{path}.{name}"))
+ if not _field(targeting, "properties", path, errors, (lambda v: isinstance(v, list), "Must be an array.")):
+ return None
+ properties = targeting["properties"]
+ if len(properties) > MAX_PREDICATES_PER_RULE:
+ errors.append(
+ ConfigError(
+ code="limit_exceeded",
+ detail=f"At most {MAX_PREDICATES_PER_RULE} properties are allowed per rule.",
+ attr=f"{path}.properties",
+ )
+ )
+ return None
+ predicates = [
+ _validate_property(prop, f"{path}.properties[{index}]", errors) for index, prop in enumerate(properties)
+ ]
+ if any(predicate is None for predicate in predicates):
+ return None
+ return frozenset(predicate for predicate in predicates if predicate is not None)
+
+
+def _validate_property(prop: object, path: str, errors: list[ConfigError]) -> Predicate | None:
+ if not isinstance(prop, Mapping):
+ errors.append(ConfigError(code="invalid", detail="Must be an object.", attr=path))
+ return None
+ before = len(errors)
+ for name in prop:
+ if name not in _PROPERTY_FIELDS:
+ errors.append(_unknown_field(f"{path}.{name}"))
+ _field(prop, "key", path, errors, (lambda v: isinstance(v, str) and bool(v), "Must be a non-empty string."))
+ if not _field(prop, "type", path, errors, _one_of(PROPERTY_TYPES)):
+ return None
+ if prop["type"] != PropertyFilterType.PERSON:
+ # Cohort and flag references need the dependency checks of the later dependency
+ # validation task, and group properties need group assignment; none is admitted.
+ # The checks below are person-property checks, so they must not run on these.
+ errors.append(
+ ConfigError(
+ code="unsupported",
+ detail=f"Targeting by {prop['type']} is not available yet. Only person properties are available.",
+ attr=f"{path}.type",
+ )
+ )
+ return None
+
+ # The contract reads an omitted or null operator as ``exact``; its value is still checked.
+ operator = prop.get("operator")
+ if operator is None:
+ operator = "exact"
+ if not isinstance(operator, str) or operator not in PROPERTY_OPERATORS:
+ errors.append(ConfigError(code="invalid", detail="Unknown operator.", attr=f"{path}.operator"))
+ elif operator in _NON_PERSON_OPERATORS:
+ errors.append(
+ ConfigError(
+ code="invalid", detail="Only cohort or flag properties use this operator.", attr=f"{path}.operator"
+ )
+ )
+ else:
+ value_error = _property_value_error(operator, prop.get("value"))
+ if value_error is not None:
+ errors.append(ConfigError(code="invalid", detail=value_error, attr=f"{path}.value"))
+
+ no_group_index = (lambda v: v is None, "Only group properties have a group type index.")
+ _field(prop, "group_type_index", path, errors, no_group_index, False)
+ _field(prop, "negation", path, errors, (_is_bool_or_none, "Must be true, false or null."), False)
+ for name in ("cohort_name", "label"):
+ _field(
+ prop, name, path, errors, (lambda v: v is None or isinstance(v, str), "Must be a string or null."), False
+ )
+ names_ok = (
+ lambda v: v is None or (isinstance(v, Mapping) and all(isinstance(name, str) for name in v.values())),
+ "Must be an object of strings or null.",
+ )
+ _field(prop, "group_key_names", path, errors, names_ok, False)
+
+ if len(errors) > before:
+ return None
+ return Predicate(
+ key=prop["key"],
+ operator=operator,
+ value=json.dumps(prop.get("value"), sort_keys=True, separators=(",", ":")),
+ negation=bool(prop.get("negation")),
+ )
+
+
+def _property_value_error(operator: str, value: Any) -> str | None:
+ if _encoded_size(value, allow_nan=False) is None:
+ return "Must be a finite number."
+ if operator in _DATE_OPERATORS and determine_parsed_date_for_property_matching(value) is None:
+ return "Must be a date."
+ if operator in _STRING_VALUE_OPERATORS and not isinstance(value, str):
+ return "Must be a string."
+ if operator in _NUMERIC_COMPARISON_OPERATORS and not (isinstance(value, str) or _is_number(value)):
+ return "Must be a number or a string."
+ if operator in _LIST_VALUE_OPERATORS and not isinstance(value, list):
+ return "Must be an array."
+ if operator in _SEMVER_OPERATORS:
+ if not isinstance(value, str):
+ return "Must be a semver string."
+ try:
+ parse_semver(value.rstrip(".*") if operator == "semver_wildcard" else value)
+ except (ValueError, IndexError):
+ return "Must be a semver string."
+ return None
+
+
+def _validate_metadata(metadata: object, path: str, limits: ValidationLimits, errors: list[ConfigError]) -> None:
+ if not isinstance(metadata, Mapping):
+ errors.append(ConfigError(code="invalid", detail="Must be an object.", attr=path))
+ return
+ size = _encoded_size(metadata, allow_nan=False)
+ if size is None:
+ errors.append(ConfigError(code="invalid", detail="Must be a JSON object.", attr=path))
+ elif size > limits.max_metadata_bytes:
+ errors.append(ConfigError(code="limit_exceeded", detail="The rule metadata is too large.", attr=path))
+
+
+def _validate_percentage(rule: Mapping[str, Any], path: str, errors: list[ConfigError]) -> Decimal | None:
+ if not _field(rule, "rollout_percentage", path, errors, (_is_number, "Must be a finite number.")):
+ return None
+ value = rule["rollout_percentage"]
+ path = f"{path}.rollout_percentage"
+ if not 0 <= value <= 100:
+ errors.append(ConfigError(code="invalid", detail="Must be between 0 and 100.", attr=path))
+ return None
+ # ``str`` gives the shortest decimal that round-trips the float, so 33.33 has two
+ # places while a binary-float remainder test would call it inexact. Nothing is rounded.
+ decimal_value = Decimal(str(value))
+ exponent = decimal_value.normalize().as_tuple().exponent
+ assert isinstance(exponent, int) # finite values never carry the NaN/infinity markers
+ if -exponent > MAX_PERCENTAGE_DECIMALS:
+ errors.append(
+ ConfigError(
+ code="invalid", detail=f"Must have at most {MAX_PERCENTAGE_DECIMALS} decimal places.", attr=path
+ )
+ )
+ return None
+ return decimal_value
+
+
+_Check = tuple[Callable[[Any], bool], str] # (accepts the value?, detail when it does not)
+
+
+def _field(
+ obj: Mapping[str, Any], name: str, path: str, errors: list[ConfigError], check: _Check, required: bool = True
+) -> bool:
+ """Record ``required``/``invalid`` for ``obj[name]``; True when the field is present and passes the check."""
+ if name not in obj:
+ if required:
+ errors.append(_required(f"{path}.{name}"))
+ return False
+ ok, detail = check
+ if not ok(obj[name]):
+ errors.append(ConfigError(code="invalid", detail=detail, attr=f"{path}.{name}"))
+ return False
+ return True
+
+
+def _one_of(allowed: tuple[str, ...]) -> _Check:
+ detail = f"Must be {', '.join(allowed[:-1])} or {allowed[-1]}." if len(allowed) > 1 else f"Must be {allowed[0]}."
+ return (lambda v: v in allowed, detail)
+
+
+def _required(attr: str) -> ConfigError:
+ return ConfigError(code="required", detail="This field is required.", attr=attr)
+
+
+def _unknown_field(attr: str, detail: str | None = None) -> ConfigError:
+ return ConfigError(code="unknown_field", detail=detail or "Unknown field.", attr=attr)
+
+
+def _is_bool_or_none(value: object) -> bool:
+ return value is None or isinstance(value, bool)
+
+
+def _is_int(value: object) -> bool:
+ return not isinstance(value, bool) and isinstance(value, int)
+
+
+def _is_number(value: object) -> bool:
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return False
+ return -sys.float_info.max <= value <= sys.float_info.max
+
+
+def _has_finite_numbers(value: object) -> bool:
+ if isinstance(value, bool):
+ return True
+ if isinstance(value, int | float):
+ return _is_number(value)
+ if isinstance(value, Mapping):
+ return all(_has_finite_numbers(item) for item in value.values())
+ if isinstance(value, list | tuple):
+ return all(_has_finite_numbers(item) for item in value)
+ return True
+
+
+def _encoded_size(value: object, *, allow_nan: bool = True) -> int | None:
+ """Encoded byte size with the same encoding as the v1 filter-size check, or None when the value is not JSON.
+
+ With ``allow_nan=False``, numbers must fit the finite binary64 range used by the flag service.
+ """
+ try:
+ encoded = json.dumps(value, separators=(",", ":"), sort_keys=True, ensure_ascii=False, allow_nan=allow_nan)
+ if not allow_nan and not _has_finite_numbers(value):
+ return None
+ return len(encoded.encode("utf-8"))
+ # Nesting past the recursion limit in the walk above is one more shape we cannot size.
+ except (TypeError, ValueError, RecursionError):
+ return None
diff --git a/products/feature_flags/backend/facade/rule_warnings.py b/products/feature_flags/backend/facade/rule_warnings.py
new file mode 100644
index 000000000000..eab21086766f
--- /dev/null
+++ b/products/feature_flags/backend/facade/rule_warnings.py
@@ -0,0 +1,250 @@
+"""Rule warning detectors for validated config version 2 documents.
+
+``review_config`` is the dormant entrypoint a later writer calls after resolving a request
+into a complete candidate: it validates the candidate, then reports the three
+configuration warnings (``UNREACHABLE_LOWER_RULE``, ``ROLLOUT_MISS_CAN_ENTER_LOWER_RULE``
+and, given the stored config, ``RULE_ORDER_CHANGES_TRAFFIC``) as the existing
+``ManagementWarning`` DTO. Warnings never make an invalid document acceptable: validation
+raises first. The lifecycle codes (``ASSIGNMENT_RESET_CHANGES_TRAFFIC``,
+``CONCLUSION_EXPANDS_POPULATION``) belong to the operation previews that own those
+operations and are not detected here.
+
+Every detector reasons over one *population*: the people who satisfy a rule's whole
+predicate set. A rule provably applies to that population when its own predicate set is
+a subset (rules AND their properties, so fewer predicates means a wider audience); any
+other relation is inconclusive and stops the walk, so a warning is never derived from a
+guess about how two different predicates overlap. Within a population, percentage rules
+partition people by their assignment hash: the same seed reuses the same hash, and
+different seeds are modelled as independent dimensions. A rollout of ``p`` percent
+includes the hash interval ``(0, p/100]``; 0 percent includes nobody, 100 percent
+everybody. This is decision-level reasoning about who can reach which rule, not a second
+evaluator, and it never claims an exact affected percentage.
+"""
+
+from collections.abc import Iterator
+from fractions import Fraction
+from itertools import product
+
+from posthog.dataclasses import frozen
+
+from products.feature_flags.backend.facade.config_validation import (
+ Predicate,
+ ValidatedConfig,
+ ValidatedRule,
+ ValidationLimits,
+ validate_config,
+)
+from products.feature_flags.backend.facade.warnings import ManagementWarning
+
+_Interval = tuple[Fraction, Fraction] # (lo, hi] of the assignment hash in (0, 1]
+_Box = dict[str, _Interval] # per seed; an absent seed is unconstrained
+_FULL: _Interval = (Fraction(0), Fraction(1))
+
+
+@frozen
+class ConfigReview:
+ config: ValidatedConfig
+ warnings: tuple[ManagementWarning, ...]
+
+
+def review_config(
+ document: object, *, limits: ValidationLimits, current: ValidatedConfig | None = None
+) -> ConfigReview:
+ """Validate a complete candidate and report its configuration warnings.
+
+ ``current`` is the stored config the candidate replaces; without it no reorder
+ comparison is possible and no reorder warning is claimed.
+ """
+ config = validate_config(document, limits=limits)
+ warnings = config_warnings(config)
+ if current is not None:
+ warnings += reorder_warnings(current, config)
+ return ConfigReview(config=config, warnings=warnings)
+
+
+def config_warnings(config: ValidatedConfig) -> tuple[ManagementWarning, ...]:
+ """Warnings a config carries on its own, in rule order and without duplicates."""
+ return (*_unreachable_lower_rules(config), *_rollout_miss_extensions(config))
+
+
+def reorder_warnings(current: ValidatedConfig, proposed: ValidatedConfig) -> tuple[ManagementWarning, ...]:
+ """``RULE_ORDER_CHANGES_TRAFFIC`` for each inverted rule pair whose reorder provably changes a value.
+
+ A pair is inverted when both rules exist unchanged in both configs and their relative
+ order flipped. A change is proven when some population settles on different values in
+ the two orders before any inconclusive rule. A rule that is only present on one side,
+ or whose evaluated content changed, is an edit rather than a reorder, so a value change
+ it causes is never attributed to the order.
+ """
+ unchanged = set(current.rules) & set(proposed.rules)
+ # A terminal miss serves the config default, so when the default is edited too those
+ # outcomes differ because of the edit; only served rule values stay comparable.
+ default_edited = current.default_value != proposed.default_value
+ current_index = {rule.id: index for index, rule in enumerate(current.rules)}
+ proposed_index = {rule.id: index for index, rule in enumerate(proposed.rules)}
+ inversions: dict[tuple[str, str], int] = {}
+ for population in {rule.predicates for rule in (*current.rules, *proposed.rules)}:
+ before = _walk(current, population)
+ after = _walk(proposed, population)
+ for (box_before, outcome_before), (box_after, outcome_after) in product(before.settled, after.settled):
+ earlier = current.rules[outcome_before.rule_index]
+ later = proposed.rules[outcome_after.rule_index]
+ values_differ = outcome_before.value != outcome_after.value
+ values_comparable = not default_edited or (outcome_before.served and outcome_after.served)
+ # Only a pair present in both configs has both indexes, so this covers "unchanged" too.
+ order_flipped = (
+ earlier in unchanged
+ and later in unchanged
+ and current_index[earlier.id] < current_index[later.id]
+ and proposed_index[later.id] < proposed_index[earlier.id]
+ )
+ if (
+ values_differ
+ and values_comparable
+ and order_flipped
+ and (earlier.id, later.id) not in inversions
+ and _intersects(box_before, box_after)
+ ):
+ inversions[(earlier.id, later.id)] = proposed_index[later.id]
+ return tuple(
+ ManagementWarning(
+ code="RULE_ORDER_CHANGES_TRAFFIC",
+ detail=f"Moving rule {later_id} above rule {earlier_id} changes the value some people receive.",
+ attr=f"filters.rules[{index}]",
+ )
+ for (earlier_id, later_id), index in sorted(inversions.items(), key=lambda item: (item[1], item[0]))
+ )
+
+
+def _unreachable_lower_rules(config: ValidatedConfig) -> Iterator[ManagementWarning]:
+ for index, rule in enumerate(config.rules[1:], start=1):
+ walk = _walk(config, rule.predicates, until=index)
+ if walk.closed_by is None:
+ continue
+ blocker = config.rules[walk.closed_by]
+ yield ManagementWarning(
+ code="UNREACHABLE_LOWER_RULE",
+ detail=f"Rule {rule.id} is never reached because rule {blocker.id} already returns a value for everyone it targets.",
+ attr=f"filters.rules[{index}]",
+ )
+
+
+def _rollout_miss_extensions(config: ValidatedConfig) -> Iterator[ManagementWarning]:
+ walks: dict[frozenset[Predicate], _Walk] = {}
+ for upper_index, upper in enumerate(config.rules):
+ if not _continues_after_partial_miss(upper):
+ continue
+ assert upper.rollout_percentage is not None
+ for lower_index in range(upper_index + 1, len(config.rules)):
+ lower = config.rules[lower_index]
+ if lower.value != upper.value:
+ continue
+ population = _overlap(upper, lower)
+ if population is None:
+ continue
+ # A shorter walk settles a prefix of a longer one, so the filter is the `until` bound.
+ if population not in walks:
+ walks[population] = _walk(config, population)
+ served_by = {
+ outcome.rule_index
+ for _, outcome in walks[population].settled
+ if outcome.served and outcome.rule_index <= lower_index
+ }
+ # Both rules must serve somebody here: an upper rule that includes nobody has no rollout to extend.
+ if not {upper_index, lower_index} <= served_by:
+ continue
+ percentage = f"{upper.rollout_percentage.normalize():f}"
+ yield ManagementWarning(
+ code="ROLLOUT_MISS_CAN_ENTER_LOWER_RULE",
+ detail=(
+ f"Rule {upper.id} continues after a rollout miss, so rule {lower.id} serves the same value "
+ f"to people outside its {percentage}% rollout."
+ ),
+ attr=f"filters.rules[{lower_index}]",
+ )
+
+
+def _continues_after_partial_miss(rule: ValidatedRule) -> bool:
+ return (
+ rule.rule_type == "percentage_rollout"
+ and rule.on_rollout_miss == "continue"
+ and rule.rollout_percentage is not None
+ and 0 < rule.rollout_percentage < 100
+ )
+
+
+def _overlap(a: ValidatedRule, b: ValidatedRule) -> frozenset[Predicate] | None:
+ """The narrower of two populations when one provably contains the other, else None."""
+ if a.predicates <= b.predicates:
+ return b.predicates
+ if b.predicates <= a.predicates:
+ return a.predicates
+ return None
+
+
+@frozen
+class _Outcome:
+ value: bool | None # the value served: the rule's, or the config default on a terminal miss
+ served: bool # True when the rule's own value was served, False for a terminal miss
+ rule_index: int
+
+
+@frozen
+class _Walk:
+ settled: tuple[tuple[_Box, _Outcome], ...] # regions with a definite outcome
+ closed_by: int | None # the rule after which nothing was left to evaluate
+
+
+def _has_contradictory_presence_checks(population: frozenset[Predicate]) -> bool:
+ presence: dict[str, set[bool]] = {}
+ for predicate in population:
+ if predicate.operator in ("is_set", "is_not_set"):
+ presence.setdefault(predicate.key, set()).add((predicate.operator == "is_set") != predicate.negation)
+ return any(len(states) > 1 for states in presence.values())
+
+
+def _walk(config: ValidatedConfig, population: frozenset[Predicate], *, until: int | None = None) -> _Walk:
+ """Evaluate ``population`` through the rules before ``until`` (all rules when None).
+
+ Stops at the first rule that does not provably apply to the population; the regions
+ settled before it stay valid, the rest is unknown.
+ """
+ if _has_contradictory_presence_checks(population):
+ return _Walk(settled=(), closed_by=None)
+ open_boxes: list[_Box] = [{}]
+ settled: list[tuple[_Box, _Outcome]] = []
+ for index, rule in enumerate(config.rules[:until]):
+ if not rule.predicates <= population:
+ # Inconclusive: who passes this rule is unknown, so nothing below it can be settled
+ # and the regions that were still open must not be reported as reaching anything.
+ return _Walk(settled=tuple(settled), closed_by=None)
+ next_open: list[_Box] = []
+ for box in open_boxes:
+ if rule.rule_type == "targeted_release":
+ settled.append((box, _Outcome(value=rule.value, served=True, rule_index=index)))
+ continue
+ assert rule.seed is not None and rule.rollout_percentage is not None
+ lo, hi = box.get(rule.seed, _FULL)
+ threshold = Fraction(rule.rollout_percentage) / 100
+ if lo < min(hi, threshold):
+ included = {**box, rule.seed: (lo, min(hi, threshold))}
+ settled.append((included, _Outcome(value=rule.value, served=True, rule_index=index)))
+ if max(lo, threshold) < hi:
+ missed = {**box, rule.seed: (max(lo, threshold), hi)}
+ if rule.on_rollout_miss == "return_default":
+ settled.append((missed, _Outcome(value=config.default_value, served=False, rule_index=index)))
+ else:
+ next_open.append(missed)
+ open_boxes = next_open
+ if not open_boxes:
+ return _Walk(settled=tuple(settled), closed_by=index)
+ return _Walk(settled=tuple(settled), closed_by=None)
+
+
+def _intersects(a: _Box, b: _Box) -> bool:
+ # Every stored interval is non-empty, so only seeds constrained on both sides can be disjoint.
+ for seed in a.keys() & b.keys():
+ (a_lo, a_hi), (b_lo, b_hi) = a[seed], b[seed]
+ if max(a_lo, b_lo) >= min(a_hi, b_hi):
+ return False
+ return True
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/SHA256SUMS b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/SHA256SUMS
new file mode 100644
index 000000000000..23c69841850b
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/SHA256SUMS
@@ -0,0 +1,57 @@
+c26afdb30b22ebc5bc87cad31685ed2fc2b9ffa7cc185e635be702f28d0e6582 README.md
+e9bea9cff58bac0c6c1021e9c8842c53594055b6874a2c58bc4350d0c28a93ca corpus/hash_sha1_60_v1.json
+536c8386eefa75721d113bd8718ddeb7fb1aad3b4f2cce1fbcf516a346a16e26 corpus/legacy_projection.json
+752ff88dcb943ab1e21f9552b0c4ec606029393fca2b565b01a497da89cd8675 corpus/v1_evaluation.json
+f5aa796ba2abf17ab6b2f4706c872f2b15bfa77310cdf0400a3a460db22eda41 fixtures/config/invalid/empty_seed.json
+6fac810e014d81b938f66909808e2a2fc1b7cf4db5462fe6522fde1e045cbdda fixtures/config/invalid/empty_string_value.json
+cbe5d7e00f3abadd490a72055e6197d511fa59f6b3f7062dbacffea426cc5360 fixtures/config/invalid/group_experiment_with_assign_by.json
+82189b24744270ac2e4ad93b97efddbede530e6990d597fe80890cbd2820f70e fixtures/config/invalid/group_percentage_rollout_with_assign_by.json
+f3902f40a82f5f80c88a463768b24922bb787b774cb7cd3c4e77fe0e8748e487 fixtures/config/invalid/missing_experiment_paused.json
+88541b7eb14532becb477a9d62797960d8cfdc38bc101b79c5294c1e611e26ec fixtures/config/invalid/missing_on_rollout_miss.json
+3e35c5e211d8ba159824009be3ed26c4ac6f12c1426109fa1b53b49ff63fc770 fixtures/config/invalid/non_uuid_rule_id.json
+de6c7a55d67adce2042d16db287dfcbe49f502d1e5e2f8e71532d0817e28e169 fixtures/config/invalid/null_experiment_id.json
+8809275942a5fb5ed548d70d819baffa84ee4ccfec7414cc93903cc79f39c550 fixtures/config/invalid/object_value_too_deep.json
+b48ead6599cbb40a2a9eea606544b0ee083bb13ce768d57fc225f2da4924633a fixtures/config/invalid/return_value_type_mismatch.json
+9aeefb4ab1eb4140afb213554a91a2c1c085e54cdbe47734442e65ba9a17f99c fixtures/config/invalid/rollout_percentage_above_maximum.json
+2ca76285c4f9724603eecb980080bf7ddf0ff8dea4458eb60a2699dfad020941 fixtures/config/invalid/seed_too_long.json
+22b5201619d80be17bfb21c9a0bf93472e2231ad4a5f1c6bb8136275e64bb8a4 fixtures/config/invalid/too_few_variants.json
+aacabb57255580136b8e6a984c57cea7367e59ddeffed3d4a40137b804cf4c31 fixtures/config/invalid/too_many_variants.json
+68c83e9c074a0a70e7753a6e52daa414aeb18977abdd9b702ec4c5c61d82c3a4 fixtures/config/invalid/unknown_config_field.json
+f5bba7fa0ea88e43834ac3b5e03ed4f7297ad0bf4ab2f09d962241521dd06787 fixtures/config/invalid/unknown_config_version.json
+8bcc957c38bb2b6a33e244ad1cfe76612cf6f4918c8f0b0cc22f86bd01cd1932 fixtures/config/invalid/unknown_rule_field.json
+f5d71ea6a2ad839fb5f540c8a7f894438fe7c99f152d7469b86af83e938288db fixtures/config/invalid/variant_key_invalid_characters.json
+aecfc8a8f49f1fa5586082fc4b70284a5212e14998984fc3a7bde1520b933095 fixtures/config/invalid/variant_value_type_mismatch.json
+49587173259e8b379c8f473e60af7bce7a52ad8f17088068dec021c2a3f9242d fixtures/config/invalid/version_boolean.json
+4835228c5a390aa2497d4df5bd62a41d775c5ff75363d2f7dca0a5eee9e77649 fixtures/config/invalid/version_string.json
+bd56e3422fee0adf18ee9a4ad13ea96fe9bb4e4d11b3e9e0499e6be985b628e8 fixtures/config/valid/boolean_all_rule_types.json
+bd163291f26d8a851d91ed8c76e4979e9af40608fe0c8a80eefa27c3cdd0f2ad fixtures/config/valid/group_all_rule_types.json
+fb09e42911934248ff767dbcfe61be60fd39483972f3bb8b1f4b1a4e9e46d944 fixtures/config/valid/object_value_max_depth.json
+6a3ce5d6c5522c71969f9141c5da06e0222f797a321de2c5a90c391bcb937947 fixtures/config/valid/reserved_number_value.json
+316ca827654b1a5585d25c534a889e963e5c603d293e605b3902357117802d27 fixtures/config/valid/reserved_object_value.json
+414987b3d374fc5fc2d912616cadce8241be9b346d66d6cf4945ca69c169354d fixtures/config/valid/string_group_assignment.json
+a848ae2e3e0dd2119600bb90ebbcba59040b3bb788586ba127a57eab1848a403 fixtures/config/valid/version_float_literal.json
+f18d0bdb0ae65fc6dfa5150731633fd44ca43b752257b18bf81ab876a38ea0e8 fixtures/wire/call_transport.json
+e3f09c4d8b076ceae55e742de90a42ce05bc4655140e971c63d407f519efe56b fixtures/wire/calls.json
+b6398336370d8807b0874229e8dc94ed1f6e686736764d56666fc48021dabf31 fixtures/wire/definitions.json
+0d267173a7d9d9260d94040ff07d14e0e1c90ccad0928c1de174d37ef135bb04 fixtures/wire/definitions_feed.json
+6c402eae3da68c26e1fb72c0ed5a6c12ec0fd8aa84935f319a75deeee83bdd3c fixtures/wire/errors.json
+06f8b3bb27231abac4cfa65c29078f5a68afe4d4c9443dafc0b338f447838dd3 fixtures/wire/exposure_transport.json
+072119b41ccfa922fc9dc96921f022ff06f2c24c2b7540de673142f11da0b084 fixtures/wire/exposures.json
+07499c5a7ca7467968156ee16fa95bdeb9018c0b841c4ec8f5bffc61d72de4fa fixtures/wire/readers.json
+e34659b62facbc594bdc1ce6c0f127ff25d94672da332670b383d729f45e5960 fixtures/wire/responses.json
+caac24e4c78b7086e13eb15768b5fa0eca65992d0cb0b926da5aa5d167d9878b fixtures/wire/warnings.json
+3ec2f4172f9ca7897522301303b8bdd7f8c3f8d29e718ee4d1a7a0f2ff32e46f manifest.json
+afd25df141b5e05dfa5c8848e1685a4e8b81f3c80fbafc4769c944b815356069 registries/literals.json
+c62900e74546b28a29b0883f4863536846d34b19159f3a8ca8bc0914218dfaa3 rules/response_presence.json
+74e43ed13dbfd578bcb8eedc5a247917788b320829b888eab84ce1126841d63b schemas/config.schema.json
+6d920c77fb7f20c2031dc188d495ed28c3789b3f362334517a2e86021a226e85 schemas/definitions_entry.schema.json
+f361158f8a5572feee09fd03ce8d41f31e077f6003b90f776ea2d9ed9e38dcd8 schemas/definitions_v2.schema.json
+524a2a0cc43e7907598ca49c98209c116ac65ba8ba5c16a54e1c8a4629fd3a2c schemas/experiment_exposure_properties.schema.json
+b26db1aaf9e03764124286e3d9bc0cb263f4521de47e42793560558750c99f3b schemas/feature_flag_called_context.schema.json
+1dd97730c746bc4534c4f47eebd82dac0cc67ceb1e4c53e7540960e7f74b00d9 schemas/flags_response_v3.schema.json
+3b3fb0be1ac89524f1a65bfcde92ba34b3cdc789ebce716c3ef2ad5938d0ce62 schemas/flags_response_v3_presence.schema.json
+9dbf9d76982408badc2409f390311f7150ebee4109ad11528907c55a114a1f9c schemas/hash_sha1_60_v1.schema.json
+37f8f88e7ecc2337bee24972a28dbd5ff11893936732bbb34728fce143f128fc schemas/legacy_projection.schema.json
+a0ec9be52e5ff9b83751283efd10ff071dc62ac90062d34b71594b37261dba8b schemas/management_error.schema.json
+9aafe3c28785298bbc143e170881df43866d1b6f1070f685cbdf3d6e4418f361 schemas/management_warning.schema.json
+3e51e0fad046fd9cd829d76d83b26bb6cd0b26be7a26ba223946ec92dcd7c6ce schemas/v1_evaluation.schema.json
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/SOURCE.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/SOURCE.json
new file mode 100644
index 000000000000..452c81023546
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/SOURCE.json
@@ -0,0 +1,17 @@
+{
+ "source_repository": "https://github.com/PostHog/posthog-sdk-test-harness",
+ "source_path": "contracts/feature_flag_rules_v2",
+ "source_release": "1.5.0",
+ "source_revision": "e487249c34176c053f524d96bf0f99818dc91247",
+ "contract_version": "2.0.0",
+ "config_schema_version": "1.0.0",
+ "registry_version": "2.0.0",
+ "source_sha256sums_digest": "22998a9449a57ee489585ed7b80295d8311af74bfda8a891545330d63df19bc5",
+ "vendored": "SHA256SUMS is the complete upstream index; this directory holds the config schema, literal registry, management warning schema, manifest and config fixtures it lists. The corpus and wire fixtures stay with the Rust runner.",
+ "update_procedure": [
+ "Never edit a vendored file in place. A changed expectation needs a new contract version upstream and a review explanation there.",
+ "To move to a new version: check out the harness at the released revision to vendor, copy the same files from source_path into a sibling directory named after the new contract version, and delete this one.",
+ "Record the release, revision, component versions and the SHA-256 of the upstream SHA256SUMS file (shasum -a 256 SHA256SUMS) in the new SOURCE.json.",
+ "Point CONTRACT_DIR in test_facade_config_validation.py at the new directory."
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/empty_seed.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/empty_seed.json
new file mode 100644
index 000000000000..808246f16b53
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/empty_seed.json
@@ -0,0 +1,19 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "dddddddd-dddd-4ddd-8ddd-dddddddddddd",
+ "rule_type": "percentage_rollout",
+ "targeting": {
+ "properties": []
+ },
+ "value": true,
+ "rollout_percentage": 25,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": ""
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/empty_string_value.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/empty_string_value.json
new file mode 100644
index 000000000000..9377203d8d43
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/empty_string_value.json
@@ -0,0 +1,15 @@
+{
+ "version": 2,
+ "return_type": "string",
+ "default_value": "standard",
+ "rules": [
+ {
+ "id": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": []
+ },
+ "value": ""
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/group_experiment_with_assign_by.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/group_experiment_with_assign_by.json
new file mode 100644
index 000000000000..6da55c0ad12a
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/group_experiment_with_assign_by.json
@@ -0,0 +1,39 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "44444444-4444-4444-8444-444444444444",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": 42,
+ "paused": false,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "experiment-preview",
+ "assign_by": "person",
+ "variants": [
+ {
+ "key": "control",
+ "weight": 50,
+ "value": true
+ },
+ {
+ "key": "test",
+ "weight": 50,
+ "value": true
+ }
+ ],
+ "holdout": {
+ "id": 7,
+ "seed": "holdout-",
+ "exclusion_percentage": 5
+ }
+ }
+ ],
+ "aggregation_group_type_index": 0
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/group_percentage_rollout_with_assign_by.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/group_percentage_rollout_with_assign_by.json
new file mode 100644
index 000000000000..38d0f23415e9
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/group_percentage_rollout_with_assign_by.json
@@ -0,0 +1,21 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "22222222-2222-4222-8222-222222222222",
+ "rule_type": "percentage_rollout",
+ "targeting": {
+ "properties": []
+ },
+ "value": true,
+ "rollout_percentage": 25.5,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "release-preview",
+ "assign_by": "person"
+ }
+ ],
+ "aggregation_group_type_index": 0
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/missing_experiment_paused.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/missing_experiment_paused.json
new file mode 100644
index 000000000000..7dabb0282af8
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/missing_experiment_paused.json
@@ -0,0 +1,31 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": 21,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "missing-pause",
+ "variants": [
+ {
+ "key": "control",
+ "weight": 50,
+ "value": false
+ },
+ {
+ "key": "test",
+ "weight": 50,
+ "value": true
+ }
+ ]
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/missing_on_rollout_miss.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/missing_on_rollout_miss.json
new file mode 100644
index 000000000000..87d9f6500f65
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/missing_on_rollout_miss.json
@@ -0,0 +1,18 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "99999999-9999-4999-8999-999999999999",
+ "rule_type": "percentage_rollout",
+ "targeting": {
+ "properties": []
+ },
+ "value": true,
+ "rollout_percentage": 25,
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "missing-policy"
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/non_uuid_rule_id.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/non_uuid_rule_id.json
new file mode 100644
index 000000000000..550fe30cb462
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/non_uuid_rule_id.json
@@ -0,0 +1,15 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "rule-1",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": []
+ },
+ "value": true
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/null_experiment_id.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/null_experiment_id.json
new file mode 100644
index 000000000000..7e6c8231080d
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/null_experiment_id.json
@@ -0,0 +1,32 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": null,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "null-experiment-id",
+ "variants": [
+ {
+ "key": "control",
+ "weight": 50,
+ "value": false
+ },
+ {
+ "key": "test",
+ "weight": 50,
+ "value": true
+ }
+ ],
+ "paused": false
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/object_value_too_deep.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/object_value_too_deep.json
new file mode 100644
index 000000000000..fbba36171147
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/object_value_too_deep.json
@@ -0,0 +1,57 @@
+{
+ "version": 2,
+ "return_type": "object",
+ "default_value": null,
+ "rules": [
+ {
+ "id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": []
+ },
+ "value": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": false
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/return_value_type_mismatch.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/return_value_type_mismatch.json
new file mode 100644
index 000000000000..0a974d59fb93
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/return_value_type_mismatch.json
@@ -0,0 +1,15 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": []
+ },
+ "value": "enabled"
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/rollout_percentage_above_maximum.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/rollout_percentage_above_maximum.json
new file mode 100644
index 000000000000..a80e13b76daf
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/rollout_percentage_above_maximum.json
@@ -0,0 +1,20 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "22222222-2222-4222-8222-222222222222",
+ "rule_type": "percentage_rollout",
+ "targeting": {
+ "properties": []
+ },
+ "value": true,
+ "rollout_percentage": 150,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "release-preview",
+ "assign_by": "person"
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/seed_too_long.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/seed_too_long.json
new file mode 100644
index 000000000000..6e706d2fdc66
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/seed_too_long.json
@@ -0,0 +1,38 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "44444444-4444-4444-8444-444444444444",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": 42,
+ "paused": false,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss",
+ "assign_by": "person",
+ "variants": [
+ {
+ "key": "control",
+ "weight": 50,
+ "value": true
+ },
+ {
+ "key": "test",
+ "weight": 50,
+ "value": true
+ }
+ ],
+ "holdout": {
+ "id": 7,
+ "seed": "holdout-",
+ "exclusion_percentage": 5
+ }
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/too_few_variants.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/too_few_variants.json
new file mode 100644
index 000000000000..eac34c695e3a
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/too_few_variants.json
@@ -0,0 +1,33 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "44444444-4444-4444-8444-444444444444",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": 42,
+ "paused": false,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "experiment-preview",
+ "assign_by": "person",
+ "variants": [
+ {
+ "key": "only",
+ "weight": 100,
+ "value": true
+ }
+ ],
+ "holdout": {
+ "id": 7,
+ "seed": "holdout-",
+ "exclusion_percentage": 5
+ }
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/too_many_variants.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/too_many_variants.json
new file mode 100644
index 000000000000..60de1041556c
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/too_many_variants.json
@@ -0,0 +1,133 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "44444444-4444-4444-8444-444444444444",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": 42,
+ "paused": false,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "experiment-preview",
+ "assign_by": "person",
+ "variants": [
+ {
+ "key": "variant_0",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_1",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_2",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_3",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_4",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_5",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_6",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_7",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_8",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_9",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_10",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_11",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_12",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_13",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_14",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_15",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_16",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_17",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_18",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_19",
+ "weight": 5,
+ "value": true
+ },
+ {
+ "key": "variant_20",
+ "weight": 0,
+ "value": true
+ }
+ ],
+ "holdout": {
+ "id": 7,
+ "seed": "holdout-",
+ "exclusion_percentage": 5
+ }
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/unknown_config_field.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/unknown_config_field.json
new file mode 100644
index 000000000000..a0903f45bb82
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/unknown_config_field.json
@@ -0,0 +1,7 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [],
+ "groups": []
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/unknown_config_version.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/unknown_config_version.json
new file mode 100644
index 000000000000..3be6d836b204
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/unknown_config_version.json
@@ -0,0 +1,6 @@
+{
+ "version": 3,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": []
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/unknown_rule_field.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/unknown_rule_field.json
new file mode 100644
index 000000000000..75b2e7295bfa
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/unknown_rule_field.json
@@ -0,0 +1,16 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "88888888-8888-4888-8888-888888888888",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": []
+ },
+ "value": true,
+ "implicit_default": false
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/variant_key_invalid_characters.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/variant_key_invalid_characters.json
new file mode 100644
index 000000000000..292ba97aa4f2
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/variant_key_invalid_characters.json
@@ -0,0 +1,38 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "44444444-4444-4444-8444-444444444444",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": 42,
+ "paused": false,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "experiment-preview",
+ "assign_by": "person",
+ "variants": [
+ {
+ "key": "invalid key",
+ "weight": 50,
+ "value": true
+ },
+ {
+ "key": "test",
+ "weight": 50,
+ "value": true
+ }
+ ],
+ "holdout": {
+ "id": 7,
+ "seed": "holdout-",
+ "exclusion_percentage": 5
+ }
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/variant_value_type_mismatch.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/variant_value_type_mismatch.json
new file mode 100644
index 000000000000..6c777d1eef6e
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/variant_value_type_mismatch.json
@@ -0,0 +1,32 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": 21,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "variant-value-type-mismatch",
+ "variants": [
+ {
+ "key": "control",
+ "weight": 50,
+ "value": "false"
+ },
+ {
+ "key": "test",
+ "weight": 50,
+ "value": true
+ }
+ ],
+ "paused": false
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/version_boolean.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/version_boolean.json
new file mode 100644
index 000000000000..44177f13c571
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/version_boolean.json
@@ -0,0 +1,6 @@
+{
+ "version": true,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": []
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/version_string.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/version_string.json
new file mode 100644
index 000000000000..cd2153b082c4
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/invalid/version_string.json
@@ -0,0 +1,6 @@
+{
+ "version": "2",
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": []
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/boolean_all_rule_types.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/boolean_all_rule_types.json
new file mode 100644
index 000000000000..ef901e2a6986
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/boolean_all_rule_types.json
@@ -0,0 +1,71 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "11111111-1111-4111-8111-111111111111",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": [
+ {
+ "key": "account_tier",
+ "type": "person",
+ "operator": "exact",
+ "value": "preview",
+ "label": "Account tier"
+ }
+ ]
+ },
+ "description": "Enable the preview for selected accounts.",
+ "metadata": {
+ "display_color": "blue"
+ },
+ "value": true
+ },
+ {
+ "id": "22222222-2222-4222-8222-222222222222",
+ "rule_type": "percentage_rollout",
+ "targeting": {
+ "properties": []
+ },
+ "value": true,
+ "rollout_percentage": 25.5,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "release-preview",
+ "assign_by": "person"
+ },
+ {
+ "id": "44444444-4444-4444-8444-444444444444",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": 42,
+ "paused": false,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "experiment-preview",
+ "assign_by": "person",
+ "variants": [
+ {
+ "key": "control",
+ "weight": 50,
+ "value": true
+ },
+ {
+ "key": "test",
+ "weight": 50,
+ "value": true
+ }
+ ],
+ "holdout": {
+ "id": 7,
+ "seed": "holdout-",
+ "exclusion_percentage": 5
+ }
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/group_all_rule_types.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/group_all_rule_types.json
new file mode 100644
index 000000000000..4d6a091e86ee
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/group_all_rule_types.json
@@ -0,0 +1,70 @@
+{
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": [
+ {
+ "id": "11111111-1111-4111-8111-111111111111",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": [
+ {
+ "key": "account_tier",
+ "type": "person",
+ "operator": "exact",
+ "value": "preview",
+ "label": "Account tier"
+ }
+ ]
+ },
+ "description": "Enable the preview for selected accounts.",
+ "metadata": {
+ "display_color": "blue"
+ },
+ "value": true
+ },
+ {
+ "id": "22222222-2222-4222-8222-222222222222",
+ "rule_type": "percentage_rollout",
+ "targeting": {
+ "properties": []
+ },
+ "value": true,
+ "rollout_percentage": 25.5,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "release-preview"
+ },
+ {
+ "id": "44444444-4444-4444-8444-444444444444",
+ "rule_type": "experiment",
+ "targeting": {
+ "properties": []
+ },
+ "experiment_id": 42,
+ "paused": false,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "experiment-preview",
+ "variants": [
+ {
+ "key": "control",
+ "weight": 50,
+ "value": true
+ },
+ {
+ "key": "test",
+ "weight": 50,
+ "value": true
+ }
+ ],
+ "holdout": {
+ "id": 7,
+ "seed": "holdout-",
+ "exclusion_percentage": 5
+ }
+ }
+ ],
+ "aggregation_group_type_index": 0
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/object_value_max_depth.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/object_value_max_depth.json
new file mode 100644
index 000000000000..908497db3cb3
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/object_value_max_depth.json
@@ -0,0 +1,55 @@
+{
+ "version": 2,
+ "return_type": "object",
+ "default_value": null,
+ "rules": [
+ {
+ "id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": []
+ },
+ "value": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": {
+ "child": false
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/reserved_number_value.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/reserved_number_value.json
new file mode 100644
index 000000000000..7f933519173a
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/reserved_number_value.json
@@ -0,0 +1,15 @@
+{
+ "version": 2,
+ "return_type": "number",
+ "default_value": 0,
+ "rules": [
+ {
+ "id": "66666666-6666-4666-8666-666666666666",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": []
+ },
+ "value": 1.25
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/reserved_object_value.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/reserved_object_value.json
new file mode 100644
index 000000000000..7284f9543b14
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/reserved_object_value.json
@@ -0,0 +1,24 @@
+{
+ "version": 2,
+ "return_type": "object",
+ "default_value": {
+ "layout": "standard"
+ },
+ "rules": [
+ {
+ "id": "77777777-7777-4777-8777-777777777777",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": []
+ },
+ "value": {
+ "layout": "compact",
+ "options": [
+ 1,
+ true,
+ null
+ ]
+ }
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/string_group_assignment.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/string_group_assignment.json
new file mode 100644
index 000000000000..aebdedb2f441
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/string_group_assignment.json
@@ -0,0 +1,31 @@
+{
+ "version": 2,
+ "return_type": "string",
+ "default_value": "standard",
+ "aggregation_group_type_index": 0,
+ "rules": [
+ {
+ "id": "55555555-5555-4555-8555-555555555555",
+ "rule_type": "percentage_rollout",
+ "targeting": {
+ "properties": [
+ {
+ "key": "region",
+ "type": "group",
+ "operator": "exact",
+ "value": "north",
+ "group_type_index": 0,
+ "group_key_names": {
+ "organization": "Organization"
+ }
+ }
+ ]
+ },
+ "value": "compact",
+ "rollout_percentage": 50,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "group-release"
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/version_float_literal.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/version_float_literal.json
new file mode 100644
index 000000000000..70b2c313344e
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/fixtures/config/valid/version_float_literal.json
@@ -0,0 +1,6 @@
+{
+ "version": 2.0,
+ "return_type": "boolean",
+ "default_value": false,
+ "rules": []
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/manifest.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/manifest.json
new file mode 100644
index 000000000000..40100063dd46
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/manifest.json
@@ -0,0 +1,921 @@
+{
+ "manifest_version": 1,
+ "contract": {
+ "name": "feature_flag_rules_v2",
+ "version": "2.0.0",
+ "config_version": 2
+ },
+ "corpus": {
+ "version": "1.1.0",
+ "config_version_locked": 1,
+ "case_id_pattern": "^[a-z][a-z0-9_]*(\\.[a-z0-9_]+)+$",
+ "published_versions_are_immutable": true,
+ "expectation_change": "Any changed expected value requires a new corpus version and a review explanation."
+ },
+ "schema_dialect": "https://json-schema.org/draft/2020-12/schema",
+ "compatibility": {
+ "published_versions_are_immutable": true,
+ "patch": "Documentation or integrity-tool changes that do not change accepted configs, wire payloads, frozen literals, or fixture expectations.",
+ "minor": "Additive fixtures or artifacts that do not change accepted configs, accepted or rejected wire payloads, frozen literals, or published fixture expectations.",
+ "major": "Any change to accepted or rejected configs, accepted or rejected wire payloads (responses, definitions, events, diagnostics), frozen literals, or published fixture expectations."
+ },
+ "integrity": {
+ "algorithm": "sha256",
+ "index": "SHA256SUMS",
+ "content": "raw_file_bytes",
+ "entry_format": "<lowercase_hex_digest><two_spaces><relative_posix_path><line_feed>",
+ "entry_order": "bytewise_path",
+ "excluded_from_index": [
+ "SHA256SUMS"
+ ]
+ },
+ "artifacts": [
+ {
+ "path": "README.md",
+ "kind": "documentation"
+ },
+ {
+ "path": "registries/literals.json",
+ "kind": "registry",
+ "version": "2.0.0"
+ },
+ {
+ "path": "schemas/config.schema.json",
+ "kind": "schema",
+ "version": "1.0.0"
+ },
+ {
+ "path": "fixtures/config/valid/boolean_all_rule_types.json",
+ "kind": "fixture",
+ "fixture_id": "config.valid.boolean_all_rule_types",
+ "expected": "valid"
+ },
+ {
+ "path": "fixtures/config/valid/string_group_assignment.json",
+ "kind": "fixture",
+ "fixture_id": "config.valid.string_group_assignment",
+ "expected": "valid"
+ },
+ {
+ "path": "fixtures/config/valid/reserved_number_value.json",
+ "kind": "fixture",
+ "fixture_id": "config.valid.reserved_number_value",
+ "expected": "valid"
+ },
+ {
+ "path": "fixtures/config/valid/reserved_object_value.json",
+ "kind": "fixture",
+ "fixture_id": "config.valid.reserved_object_value",
+ "expected": "valid"
+ },
+ {
+ "path": "fixtures/config/valid/version_float_literal.json",
+ "kind": "fixture",
+ "fixture_id": "config.valid.version_float_literal",
+ "expected": "valid"
+ },
+ {
+ "path": "fixtures/config/invalid/unknown_config_version.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.unknown_config_version",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "const",
+ "instance_path": "/version",
+ "message_contains": "2 was expected"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/version_string.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.version_string",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "const",
+ "instance_path": "/version"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/version_boolean.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.version_boolean",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "const",
+ "instance_path": "/version"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/unknown_config_field.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.unknown_config_field",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "additionalProperties",
+ "instance_path": "",
+ "message_contains": "groups"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/unknown_rule_field.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.unknown_rule_field",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "additionalProperties",
+ "instance_path": "/rules/0",
+ "message_contains": "implicit_default"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/missing_on_rollout_miss.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.missing_on_rollout_miss",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "required",
+ "instance_path": "/rules/0",
+ "message_contains": "on_rollout_miss"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/missing_experiment_paused.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.missing_experiment_paused",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "required",
+ "instance_path": "/rules/0",
+ "message_contains": "paused"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/non_uuid_rule_id.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.non_uuid_rule_id",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "pattern",
+ "instance_path": "/rules/0/id"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/empty_seed.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.empty_seed",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "minLength",
+ "instance_path": "/rules/0/seed"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/empty_string_value.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.empty_string_value",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "minLength",
+ "instance_path": "/rules/0/value"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/return_value_type_mismatch.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.return_value_type_mismatch",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "type",
+ "instance_path": "/rules/0/value"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/variant_value_type_mismatch.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.variant_value_type_mismatch",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "type",
+ "instance_path": "/rules/0/variants/0/value"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/null_experiment_id.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.null_experiment_id",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "type",
+ "instance_path": "/rules/0/experiment_id",
+ "message_contains": "integer"
+ }
+ },
+ {
+ "path": "fixtures/config/valid/object_value_max_depth.json",
+ "kind": "fixture",
+ "fixture_id": "config.valid.object_value_max_depth",
+ "expected": "valid"
+ },
+ {
+ "path": "fixtures/config/invalid/object_value_too_deep.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.object_value_too_deep",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "oneOf",
+ "instance_path": "/rules/0/value/child/child/child/child/child/child/child/child/child/child/child/child/child/child/child/child/child/child/child/child"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/rollout_percentage_above_maximum.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.rollout_percentage_above_maximum",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "maximum",
+ "instance_path": "/rules/0/rollout_percentage"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/variant_key_invalid_characters.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.variant_key_invalid_characters",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "pattern",
+ "instance_path": "/rules/0/variants/0/key"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/too_few_variants.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.too_few_variants",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "minItems",
+ "instance_path": "/rules/0/variants"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/too_many_variants.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.too_many_variants",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "maxItems",
+ "instance_path": "/rules/0/variants"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/seed_too_long.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.seed_too_long",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "maxLength",
+ "instance_path": "/rules/0/seed"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/group_percentage_rollout_with_assign_by.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.group_percentage_rollout_with_assign_by",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "not",
+ "instance_path": "/rules/0"
+ }
+ },
+ {
+ "path": "fixtures/config/invalid/group_experiment_with_assign_by.json",
+ "kind": "fixture",
+ "fixture_id": "config.invalid.group_experiment_with_assign_by",
+ "expected": "invalid",
+ "expected_failure": {
+ "keyword": "not",
+ "instance_path": "/rules/0"
+ }
+ },
+ {
+ "path": "fixtures/config/valid/group_all_rule_types.json",
+ "kind": "fixture",
+ "fixture_id": "config.valid.group_all_rule_types",
+ "expected": "valid"
+ },
+ {
+ "path": "schemas/hash_sha1_60_v1.schema.json",
+ "kind": "schema",
+ "version": "1.1.0"
+ },
+ {
+ "path": "schemas/v1_evaluation.schema.json",
+ "kind": "schema",
+ "version": "1.1.0"
+ },
+ {
+ "path": "schemas/legacy_projection.schema.json",
+ "kind": "schema",
+ "version": "1.1.0"
+ },
+ {
+ "path": "corpus/hash_sha1_60_v1.json",
+ "kind": "corpus",
+ "version": "1.1.0",
+ "schema": "schemas/hash_sha1_60_v1.schema.json",
+ "case_ids": [
+ "hash.rollout.ascii_division_edge",
+ "hash.rollout.ascii_excluded",
+ "hash.variant.ascii",
+ "hash.holdout.literal_prefix",
+ "hash.concatenation.no_separator_escaping",
+ "hash.identifier.empty",
+ "hash.identifier.unicode_utf8",
+ "hash.identifier.truncated_ascii",
+ "hash.identifier.truncated_scalar_values",
+ "hash.identifier.exactly_200_multibyte",
+ "hash.identifier.integer_group_key",
+ "threshold.equal_is_included",
+ "threshold.next_binary64_above_is_excluded",
+ "threshold.zero_percent_zero_hash",
+ "threshold.zero_percent_smallest_hash",
+ "threshold.hundred_percent_short_circuit",
+ "threshold.two_decimal_division_equal",
+ "threshold.two_decimal_division_excluded",
+ "threshold.two_decimal_division_included_below_quotient",
+ "variant.zero_hash_first_variant",
+ "variant.boundary_is_exclusive",
+ "variant.just_below_boundary",
+ "variant.accumulated_boundary_left_to_right",
+ "variant.accumulated_boundary_third",
+ "variant.two_decimal_weights_boundary",
+ "variant.hash_one_off_the_end",
+ "variant.sum_below_one_off_the_end",
+ "parity.rollout_identical_bytes",
+ "parity.variant_identical_bytes",
+ "parity.holdout_identical_bytes",
+ "parity.empty_identifier_divergent",
+ "parity.final_variant_fallback_divergent"
+ ]
+ },
+ {
+ "path": "corpus/v1_evaluation.json",
+ "kind": "corpus",
+ "version": "1.1.0",
+ "schema": "schemas/v1_evaluation.schema.json",
+ "case_ids": [
+ "v1.boolean.targeted_match_with_payload",
+ "v1.boolean.targeting_miss",
+ "v1.boolean.rollout_included",
+ "v1.boolean.rollout_excluded",
+ "v1.boolean.rollout_miss_continues_to_lower_condition",
+ "v1.boolean.rollout_miss_early_exit",
+ "v1.boolean.reason_priority_keeps_earlier_rollout_miss",
+ "v1.boolean.reason_priority_prefers_later_rollout_miss",
+ "v1.boolean.null_rollout_is_100",
+ "v1.boolean.empty_distinct_id_included_at_zero_percent",
+ "v1.boolean.empty_distinct_id_included_below_prefix_hash",
+ "v1.multivariate.variant_from_hash_with_payload",
+ "v1.multivariate.variant_from_hash_control",
+ "v1.multivariate.variant_override",
+ "v1.multivariate.invalid_variant_override_uses_hash",
+ "v1.multivariate.partial_rollout_included",
+ "v1.multivariate.partial_rollout_excluded",
+ "v1.multivariate.empty_distinct_id_first_variant",
+ "v1.group.included_by_group_key",
+ "v1.group.excluded_by_group_key",
+ "v1.group.integer_group_key_normalized",
+ "v1.group.missing_group_key",
+ "v1.dependency.satisfied",
+ "v1.dependency.unsatisfied",
+ "v1.dependency.variant_match",
+ "v1.dependency.variant_mismatch",
+ "v1.dependency.missing_target",
+ "v1.holdout.member",
+ "v1.holdout.not_member",
+ "v1.holdout.empty_distinct_id_hashes_prefix",
+ "v1.omission.inactive_flag"
+ ]
+ },
+ {
+ "path": "corpus/legacy_projection.json",
+ "kind": "corpus",
+ "version": "1.1.0",
+ "schema": "schemas/legacy_projection.schema.json",
+ "case_ids": [
+ "projection.boolean_true",
+ "projection.boolean_true_with_payload",
+ "projection.boolean_false_targeting_miss",
+ "projection.boolean_false_out_of_rollout",
+ "projection.variant",
+ "projection.variant_with_payload",
+ "projection.holdout_variant",
+ "projection.no_group_type",
+ "projection.missing_dependency",
+ "projection.failed_evaluation",
+ "projection.inactive_omitted"
+ ]
+ },
+ {
+ "path": "schemas/definitions_entry.schema.json",
+ "kind": "schema",
+ "version": "1.0.0"
+ },
+ {
+ "path": "schemas/definitions_v2.schema.json",
+ "kind": "schema",
+ "version": "1.0.0"
+ },
+ {
+ "path": "schemas/flags_response_v3.schema.json",
+ "kind": "schema",
+ "version": "1.0.0"
+ },
+ {
+ "path": "schemas/flags_response_v3_presence.schema.json",
+ "kind": "schema",
+ "version": "1.0.0"
+ },
+ {
+ "path": "schemas/management_warning.schema.json",
+ "kind": "schema",
+ "version": "1.0.0"
+ },
+ {
+ "path": "schemas/management_error.schema.json",
+ "kind": "schema",
+ "version": "1.0.0"
+ },
+ {
+ "path": "schemas/feature_flag_called_context.schema.json",
+ "kind": "schema",
+ "version": "1.0.0"
+ },
+ {
+ "path": "schemas/experiment_exposure_properties.schema.json",
+ "kind": "schema",
+ "version": "1.0.0"
+ },
+ {
+ "path": "rules/response_presence.json",
+ "kind": "presence_matrix",
+ "version": "1.0.0"
+ },
+ {
+ "path": "fixtures/wire/definitions.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/definitions_entry.schema.json",
+ "case_ids": [
+ "definitions.v2_canonical",
+ "definitions.v1_implicit",
+ "definitions.v1_explicit",
+ "definitions.v2_numeric_version",
+ "definitions.inactive",
+ "definitions.unsupported_version_future",
+ "definitions.unsupported_version_string",
+ "definitions.unsupported_version_boolean",
+ "definitions.unsupported_version_null",
+ "definitions.unknown_semantic_field",
+ "definitions.unknown_rule_field",
+ "definitions.unsupported_rule_type",
+ "definitions.missing_assignment_seed",
+ "definitions.v1_null_version",
+ "definitions.v1_wrong_type_version",
+ "definitions.v1_null_ensure_experience_continuity",
+ "definitions.v1_wrong_type_ensure_experience_continuity",
+ "definitions.v1_explicit_null_row_fields",
+ "definitions.missing_id",
+ "definitions.missing_key",
+ "definitions.missing_active",
+ "definitions.missing_filters",
+ "definitions.unknown_field"
+ ]
+ },
+ {
+ "path": "fixtures/wire/definitions_feed.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/definitions_v2.schema.json",
+ "case_ids": [
+ "definitions_feed.mixed_versions",
+ "definitions_feed.missing_cohorts",
+ "definitions_feed.minimal_events_false",
+ "definitions_feed.minimal_events_true",
+ "definitions_feed.minimal_events_wrong_type",
+ "definitions_feed.null_legacy_row_fields",
+ "definitions_feed.missing_flags",
+ "definitions_feed.missing_group_type_mapping",
+ "definitions_feed.unknown_field"
+ ]
+ },
+ {
+ "path": "fixtures/wire/responses.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/flags_response_v3.schema.json",
+ "case_ids": [
+ "responses.targeting_match_targeted_release",
+ "responses.missing_id",
+ "responses.missing_version",
+ "responses.missing_config_version",
+ "responses.targeting_match_targeted_release_missing_has_experiment",
+ "responses.targeting_match_targeted_release_missing_rule_type",
+ "responses.targeting_match_targeted_release_missing_rule_id",
+ "responses.targeting_match_targeted_release_forbidden_experiment_id",
+ "responses.targeting_match_targeted_release_forbidden_variant_key",
+ "responses.targeting_match_targeted_release_forbidden_holdout_id",
+ "responses.targeting_match_targeted_release_wrong_condition_index",
+ "responses.targeting_match_targeted_release_forbidden_failed",
+ "responses.targeting_match_targeted_release_flag_with_experiment",
+ "responses.targeting_match_percentage_rollout",
+ "responses.targeting_match_percentage_rollout_missing_has_experiment",
+ "responses.targeting_match_percentage_rollout_missing_rule_type",
+ "responses.targeting_match_percentage_rollout_missing_rule_id",
+ "responses.targeting_match_percentage_rollout_forbidden_experiment_id",
+ "responses.targeting_match_percentage_rollout_forbidden_variant_key",
+ "responses.targeting_match_percentage_rollout_forbidden_holdout_id",
+ "responses.targeting_match_percentage_rollout_wrong_condition_index",
+ "responses.targeting_match_percentage_rollout_forbidden_failed",
+ "responses.experiment_split",
+ "responses.experiment_split_missing_has_experiment",
+ "responses.experiment_split_missing_rule_type",
+ "responses.experiment_split_missing_rule_id",
+ "responses.experiment_split_missing_experiment_id",
+ "responses.experiment_split_missing_variant_key",
+ "responses.experiment_split_forbidden_holdout_id",
+ "responses.experiment_split_wrong_condition_index",
+ "responses.experiment_split_forbidden_failed",
+ "responses.experiment_split_contradicted_has_experiment",
+ "responses.rollout_miss_percentage_rollout",
+ "responses.rollout_miss_percentage_rollout_missing_has_experiment",
+ "responses.rollout_miss_percentage_rollout_missing_rule_type",
+ "responses.rollout_miss_percentage_rollout_missing_rule_id",
+ "responses.rollout_miss_percentage_rollout_forbidden_experiment_id",
+ "responses.rollout_miss_percentage_rollout_forbidden_variant_key",
+ "responses.rollout_miss_percentage_rollout_forbidden_holdout_id",
+ "responses.rollout_miss_percentage_rollout_wrong_condition_index",
+ "responses.rollout_miss_percentage_rollout_forbidden_failed",
+ "responses.rollout_miss_experiment",
+ "responses.rollout_miss_experiment_missing_has_experiment",
+ "responses.rollout_miss_experiment_missing_rule_type",
+ "responses.rollout_miss_experiment_missing_rule_id",
+ "responses.rollout_miss_experiment_missing_experiment_id",
+ "responses.rollout_miss_experiment_forbidden_variant_key",
+ "responses.rollout_miss_experiment_forbidden_holdout_id",
+ "responses.rollout_miss_experiment_wrong_condition_index",
+ "responses.rollout_miss_experiment_forbidden_failed",
+ "responses.experiment_paused",
+ "responses.experiment_paused_missing_has_experiment",
+ "responses.experiment_paused_missing_rule_type",
+ "responses.experiment_paused_missing_rule_id",
+ "responses.experiment_paused_missing_experiment_id",
+ "responses.experiment_paused_forbidden_variant_key",
+ "responses.experiment_paused_forbidden_holdout_id",
+ "responses.experiment_paused_wrong_condition_index",
+ "responses.experiment_paused_forbidden_failed",
+ "responses.holdout",
+ "responses.holdout_missing_has_experiment",
+ "responses.holdout_missing_rule_type",
+ "responses.holdout_missing_rule_id",
+ "responses.holdout_missing_experiment_id",
+ "responses.holdout_missing_holdout_id",
+ "responses.holdout_forbidden_variant_key",
+ "responses.holdout_wrong_condition_index",
+ "responses.holdout_forbidden_failed",
+ "responses.no_rule_match",
+ "responses.no_rule_match_missing_has_experiment",
+ "responses.no_rule_match_forbidden_rule_type",
+ "responses.no_rule_match_forbidden_rule_id",
+ "responses.no_rule_match_forbidden_experiment_id",
+ "responses.no_rule_match_forbidden_variant_key",
+ "responses.no_rule_match_forbidden_holdout_id",
+ "responses.no_rule_match_wrong_condition_index",
+ "responses.no_rule_match_forbidden_failed",
+ "responses.missing_group_key",
+ "responses.missing_group_key_missing_has_experiment",
+ "responses.missing_group_key_forbidden_rule_type",
+ "responses.missing_group_key_forbidden_rule_id",
+ "responses.missing_group_key_forbidden_experiment_id",
+ "responses.missing_group_key_forbidden_variant_key",
+ "responses.missing_group_key_forbidden_holdout_id",
+ "responses.missing_group_key_wrong_condition_index",
+ "responses.missing_group_key_forbidden_failed",
+ "responses.dependency_error",
+ "responses.dependency_error_missing_has_experiment",
+ "responses.dependency_error_forbidden_rule_type",
+ "responses.dependency_error_forbidden_rule_id",
+ "responses.dependency_error_forbidden_experiment_id",
+ "responses.dependency_error_forbidden_variant_key",
+ "responses.dependency_error_forbidden_holdout_id",
+ "responses.dependency_error_wrong_condition_index",
+ "responses.dependency_error_missing_failed",
+ "responses.dependency_error_nonnull_value",
+ "responses.error",
+ "responses.error_missing_has_experiment",
+ "responses.error_forbidden_rule_type",
+ "responses.error_forbidden_rule_id",
+ "responses.error_forbidden_experiment_id",
+ "responses.error_forbidden_variant_key",
+ "responses.error_forbidden_holdout_id",
+ "responses.error_wrong_condition_index",
+ "responses.error_missing_failed",
+ "responses.error_nonnull_value",
+ "responses.v1",
+ "responses.omitted",
+ "responses.split_wrong_type_config_version",
+ "responses.split_wrong_type_rule_type",
+ "responses.split_wrong_type_rule_id",
+ "responses.split_wrong_type_experiment_id",
+ "responses.split_wrong_type_variant_key",
+ "responses.forbidden_legacy_enabled",
+ "responses.forbidden_legacy_variant",
+ "responses.split_arm_b_equal_value",
+ "responses.split_string_value",
+ "responses.null_default",
+ "responses.request_failure_omission",
+ "responses.missing_group_nonnull_value",
+ "responses.v1_failed",
+ "responses.v1_quick_win",
+ "responses.v2_forced_variant",
+ "responses.key_mismatch",
+ "responses.failure_envelope",
+ "responses.local_only_reason",
+ "responses.nested_seed",
+ "responses.passthrough_seed",
+ "responses.reserved_number_wire_value",
+ "responses.reserved_object_wire_value",
+ "responses.targeting_match_targeted_release_wrong_rule_type",
+ "responses.experiment_split_wrong_rule_type",
+ "responses.rollout_miss_percentage_rollout_wrong_rule_type",
+ "responses.rollout_miss_experiment_wrong_rule_type",
+ "responses.experiment_paused_wrong_rule_type",
+ "responses.holdout_wrong_rule_type",
+ "responses.targeting_match_targeted_release_null_value",
+ "responses.targeting_match_percentage_rollout_null_value",
+ "responses.experiment_split_null_value",
+ "responses.empty_v2_string",
+ "responses.v1_experiment_without_linkage",
+ "responses.v1_ambiguous_experiment",
+ "responses.flag_key_seed",
+ "responses.seed_named_flag_nested_seed",
+ "responses.flag_key_assignment_seed",
+ "responses.v1_forbidden_rule_id",
+ "responses.v1_forbidden_rule_type",
+ "responses.v1_forbidden_holdout_id",
+ "responses.v1_object_payload",
+ "responses.v1_null_value_not_failed"
+ ]
+ },
+ {
+ "path": "fixtures/wire/warnings.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/management_warning.schema.json",
+ "case_ids": [
+ "warnings.rule_order_changes_traffic",
+ "warnings.unreachable_lower_rule",
+ "warnings.rollout_miss_can_enter_lower_rule",
+ "warnings.assignment_reset_changes_traffic",
+ "warnings.conclusion_expands_population",
+ "warnings.detail_and_attr",
+ "warnings.unknown_code",
+ "warnings.missing_code",
+ "warnings.wrong_detail_type",
+ "warnings.unknown_field"
+ ]
+ },
+ {
+ "path": "fixtures/wire/errors.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/management_error.schema.json",
+ "case_ids": [
+ "errors.validation",
+ "errors.nonfield",
+ "errors.missing_type",
+ "errors.missing_code",
+ "errors.missing_detail",
+ "errors.missing_attr",
+ "errors.wrong_detail_type",
+ "errors.unknown_field"
+ ]
+ },
+ {
+ "path": "fixtures/wire/calls.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/feature_flag_called_context.schema.json",
+ "case_ids": [
+ "calls.targeting_match_targeted_release",
+ "calls.targeting_match_targeted_release_missing_rule_type",
+ "calls.targeting_match_targeted_release_missing_rule_id",
+ "calls.targeting_match_targeted_release_forbidden_experiment_id",
+ "calls.targeting_match_targeted_release_forbidden_variant_key",
+ "calls.targeting_match_targeted_release_forbidden_holdout_id",
+ "calls.targeting_match_percentage_rollout",
+ "calls.targeting_match_percentage_rollout_missing_rule_type",
+ "calls.targeting_match_percentage_rollout_missing_rule_id",
+ "calls.targeting_match_percentage_rollout_forbidden_experiment_id",
+ "calls.targeting_match_percentage_rollout_forbidden_variant_key",
+ "calls.targeting_match_percentage_rollout_forbidden_holdout_id",
+ "calls.experiment_split",
+ "calls.experiment_split_missing_rule_type",
+ "calls.experiment_split_missing_rule_id",
+ "calls.experiment_split_missing_experiment_id",
+ "calls.experiment_split_missing_variant_key",
+ "calls.experiment_split_forbidden_holdout_id",
+ "calls.rollout_miss_percentage_rollout",
+ "calls.rollout_miss_percentage_rollout_missing_rule_type",
+ "calls.rollout_miss_percentage_rollout_missing_rule_id",
+ "calls.rollout_miss_percentage_rollout_forbidden_experiment_id",
+ "calls.rollout_miss_percentage_rollout_forbidden_variant_key",
+ "calls.rollout_miss_percentage_rollout_forbidden_holdout_id",
+ "calls.rollout_miss_experiment",
+ "calls.rollout_miss_experiment_missing_rule_type",
+ "calls.rollout_miss_experiment_missing_rule_id",
+ "calls.rollout_miss_experiment_missing_experiment_id",
+ "calls.rollout_miss_experiment_forbidden_variant_key",
+ "calls.rollout_miss_experiment_forbidden_holdout_id",
+ "calls.experiment_paused",
+ "calls.experiment_paused_missing_rule_type",
+ "calls.experiment_paused_missing_rule_id",
+ "calls.experiment_paused_missing_experiment_id",
+ "calls.experiment_paused_forbidden_variant_key",
+ "calls.experiment_paused_forbidden_holdout_id",
+ "calls.holdout",
+ "calls.holdout_missing_rule_type",
+ "calls.holdout_missing_rule_id",
+ "calls.holdout_missing_experiment_id",
+ "calls.holdout_missing_holdout_id",
+ "calls.holdout_forbidden_variant_key",
+ "calls.no_rule_match",
+ "calls.no_rule_match_forbidden_rule_type",
+ "calls.no_rule_match_forbidden_rule_id",
+ "calls.no_rule_match_forbidden_experiment_id",
+ "calls.no_rule_match_forbidden_variant_key",
+ "calls.no_rule_match_forbidden_holdout_id",
+ "calls.missing_group_key",
+ "calls.missing_group_key_forbidden_rule_type",
+ "calls.missing_group_key_forbidden_rule_id",
+ "calls.missing_group_key_forbidden_experiment_id",
+ "calls.missing_group_key_forbidden_variant_key",
+ "calls.missing_group_key_forbidden_holdout_id",
+ "calls.dependency_error",
+ "calls.dependency_error_forbidden_rule_type",
+ "calls.dependency_error_forbidden_rule_id",
+ "calls.dependency_error_forbidden_experiment_id",
+ "calls.dependency_error_forbidden_variant_key",
+ "calls.dependency_error_forbidden_holdout_id",
+ "calls.error",
+ "calls.error_forbidden_rule_type",
+ "calls.error_forbidden_rule_id",
+ "calls.error_forbidden_experiment_id",
+ "calls.error_forbidden_variant_key",
+ "calls.error_forbidden_holdout_id",
+ "calls.v1",
+ "calls.missing",
+ "calls.inactive",
+ "calls.v1_quick_win",
+ "calls.arm_b_equal_value",
+ "calls.string",
+ "calls.v2_forced_variant",
+ "calls.forbidden_value_number",
+ "calls.forbidden_value_object",
+ "calls.forbidden_value_array",
+ "calls.forbidden_value_null",
+ "calls.forbidden_value_empty_string",
+ "calls.partial_split_diagnostic",
+ "calls.inactive_forbidden_experiment_id",
+ "calls.missing_feature_flag",
+ "calls.missing_feature_flag_response",
+ "calls.unknown_field"
+ ]
+ },
+ {
+ "path": "fixtures/wire/exposures.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/experiment_exposure_properties.schema.json",
+ "case_ids": [
+ "exposures.remote_split",
+ "exposures.local_split",
+ "exposures.arm_b_equal_value",
+ "exposures.successor_experiment",
+ "exposures.string",
+ "exposures.missing_feature_flag",
+ "exposures.wrong_type_feature_flag",
+ "exposures.missing_feature_flag_response",
+ "exposures.wrong_type_feature_flag_response",
+ "exposures.missing_feature_flag_config_version",
+ "exposures.wrong_type_feature_flag_config_version",
+ "exposures.missing_feature_flag_reason_code",
+ "exposures.wrong_type_feature_flag_reason_code",
+ "exposures.missing_feature_flag_variant",
+ "exposures.wrong_type_feature_flag_variant",
+ "exposures.missing_feature_flag_rule_id",
+ "exposures.wrong_type_feature_flag_rule_id",
+ "exposures.missing_feature_flag_rule_type",
+ "exposures.wrong_type_feature_flag_rule_type",
+ "exposures.missing_feature_flag_experiment_id",
+ "exposures.wrong_type_feature_flag_experiment_id",
+ "exposures.missing_experiment_exposure_source",
+ "exposures.wrong_type_experiment_exposure_source",
+ "exposures.missing_locally_evaluated",
+ "exposures.wrong_type_locally_evaluated",
+ "exposures.forbidden_outcome_holdout",
+ "exposures.forbidden_outcome_pause",
+ "exposures.forbidden_outcome_rollout_miss",
+ "exposures.forbidden_outcome_no_rule",
+ "exposures.forbidden_outcome_failed",
+ "exposures.forbidden_value_object",
+ "exposures.forbidden_value_array",
+ "exposures.forbidden_value_null",
+ "exposures.forbidden_value_empty_string",
+ "exposures.holdout_context",
+ "exposures.ingestion_source",
+ "exposures.v1_config",
+ "exposures.forced_variant_context",
+ "exposures.unknown_field"
+ ]
+ },
+ {
+ "path": "fixtures/wire/readers.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/flags_response_v3.schema.json",
+ "case_ids": [
+ "readers.complete_split",
+ "readers.partial_split_missing_config_version",
+ "readers.partial_split_missing_rule_type",
+ "readers.partial_split_missing_rule_id",
+ "readers.partial_split_missing_experiment_id",
+ "readers.partial_split_missing_variant_key",
+ "readers.split_wrong_type_config_version",
+ "readers.split_wrong_type_rule_type",
+ "readers.split_wrong_type_rule_id",
+ "readers.split_wrong_type_experiment_id",
+ "readers.split_wrong_type_variant_key",
+ "readers.wrong_rule_type_literal",
+ "readers.unknown_fields",
+ "readers.old_server_variant",
+ "readers.old_server_boolean",
+ "readers.old_server_null_variant",
+ "readers.old_server_false",
+ "readers.v3_value_takes_precedence",
+ "readers.missing_flag",
+ "readers.targeting_match_targeted_release",
+ "readers.targeting_match_percentage_rollout",
+ "readers.rollout_miss_percentage_rollout",
+ "readers.rollout_miss_experiment",
+ "readers.experiment_paused",
+ "readers.holdout",
+ "readers.holdout_variant_key",
+ "readers.no_rule_match",
+ "readers.missing_group_key",
+ "readers.dependency_error",
+ "readers.error",
+ "readers.error_with_value",
+ "readers.malformed_sibling_isolation",
+ "readers.partial_split_string_value",
+ "readers.v1_at_v3",
+ "readers.v1_failed",
+ "readers.integral_json_number_context",
+ "readers.flag_key_seed"
+ ]
+ },
+ {
+ "path": "fixtures/wire/exposure_transport.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/experiment_exposure_properties.schema.json",
+ "case_ids": [
+ "exposure_transport.exposure_with_transport",
+ "exposure_transport.nested_seed",
+ "exposure_transport.nested_holdout_seed",
+ "exposure_transport.holdout_context",
+ "exposure_transport.forced_variant_context",
+ "exposure_transport.group_type_named_seed"
+ ]
+ },
+ {
+ "path": "fixtures/wire/call_transport.json",
+ "kind": "fixture_set",
+ "version": "1.0.0",
+ "schema": "schemas/feature_flag_called_context.schema.json",
+ "case_ids": [
+ "call_transport.call_with_transport",
+ "call_transport.nested_assignment_seed",
+ "call_transport.prefixed_seed",
+ "call_transport.person_property_named_seed"
+ ]
+ }
+ ],
+ "wire_contract": {
+ "version": "1.0.0",
+ "fixture_version": "1.0.0",
+ "published_versions_are_immutable": true,
+ "producer_schema_sha256": "1dd97730c746bc4534c4f47eebd82dac0cc67ceb1e4c53e7540960e7f74b00d9",
+ "fixture_encoding": "Each case deep-copies its named template, removes the listed existing JSON Pointer members, then sets members by JSON Pointer. Set requires an existing parent. Templates and expectations are JSON, not executable SDK suites.",
+ "compatibility": "New artifacts are additive to contract 1.2.0. Published schema bytes and fixture expectations are immutable. Accepted/rejected wire-contract changes require a new major wire component version; additive cases require a new minor fixture version. Reader expectations never relax producer validation."
+ }
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/registries/literals.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/registries/literals.json
new file mode 100644
index 000000000000..ed8065689791
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/registries/literals.json
@@ -0,0 +1,297 @@
+{
+ "registry_version": "2.0.0",
+ "config_versions": {
+ "v1": 1,
+ "v2": 2,
+ "absent_version_selects": "v1",
+ "unknown_version_result": "unsupported",
+ "version_comparison": "A JSON number selects the version it equals mathematically, so 2.0 selects v2. A JSON string or boolean never selects a version."
+ },
+ "fields": [
+ "aggregation_group_type_index",
+ "assign_by",
+ "assignment_algorithm",
+ "cohort_name",
+ "default_value",
+ "description",
+ "exclusion_percentage",
+ "experiment_id",
+ "group_key_names",
+ "group_type_index",
+ "holdout",
+ "id",
+ "key",
+ "label",
+ "metadata",
+ "negation",
+ "on_rollout_miss",
+ "operator",
+ "paused",
+ "properties",
+ "return_type",
+ "rollout_percentage",
+ "rule_type",
+ "rules",
+ "seed",
+ "targeting",
+ "type",
+ "value",
+ "variants",
+ "version",
+ "weight"
+ ],
+ "rule_types": [
+ {
+ "value": "targeted_release",
+ "writer_status": "enabled"
+ },
+ {
+ "value": "percentage_rollout",
+ "writer_status": "enabled"
+ },
+ {
+ "value": "experiment",
+ "writer_status": "enabled"
+ }
+ ],
+ "return_types": [
+ {
+ "value": "boolean",
+ "writer_status": "enabled"
+ },
+ {
+ "value": "string",
+ "writer_status": "enabled"
+ },
+ {
+ "value": "number",
+ "writer_status": "reserved"
+ },
+ {
+ "value": "object",
+ "writer_status": "reserved"
+ }
+ ],
+ "rollout_miss_policies": [
+ "continue",
+ "return_default"
+ ],
+ "assignment_targets": [
+ "person"
+ ],
+ "assignment_algorithms": [
+ "sha1_60_v1"
+ ],
+ "property_types": [
+ "person",
+ "cohort",
+ "group",
+ "flag"
+ ],
+ "property_operators": [
+ "exact",
+ "is_not",
+ "icontains",
+ "not_icontains",
+ "icontains_multi",
+ "not_icontains_multi",
+ "starts_with",
+ "not_starts_with",
+ "ends_with",
+ "not_ends_with",
+ "regex",
+ "not_regex",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "semver_gt",
+ "semver_gte",
+ "semver_lt",
+ "semver_lte",
+ "semver_eq",
+ "semver_neq",
+ "semver_tilde",
+ "semver_caret",
+ "semver_wildcard",
+ "is_set",
+ "is_not_set",
+ "is_date_exact",
+ "is_date_after",
+ "is_date_before",
+ "in",
+ "not_in",
+ "flag_evaluates_to"
+ ],
+ "reason_codes": [
+ "targeting_match",
+ "experiment_split",
+ "rollout_miss",
+ "experiment_paused",
+ "holdout",
+ "no_rule_match",
+ "flag_disabled",
+ "missing_group_key",
+ "dependency_error",
+ "error"
+ ],
+ "openfeature_mapping": {
+ "specification": "https://openfeature.dev/specification/",
+ "reason_codes": {
+ "targeting_match": {
+ "reason": "TARGETING_MATCH",
+ "error_code": null,
+ "note": "Targeted release, or percentage rollout inclusion. TARGETING_MATCH is this contract's choice for rollout inclusion; OpenFeature also describes pseudorandom assignment with SPLIT and permits custom reasons."
+ },
+ "experiment_split": {
+ "reason": "SPLIT",
+ "error_code": null,
+ "note": "Experiment identity is in flag metadata."
+ },
+ "rollout_miss": {
+ "reason": "DEFAULT",
+ "error_code": null,
+ "note": "A terminal rollout miss under return_default. Value is default_value, or the caller default when null. A continuing miss moves evaluation to the next rule and contributes neither a reason code nor metadata from the missed rule (including rule_id and condition_index) to the final result. The final result uses the terminating rule's reason and metadata, or no_rule_match if no rule terminates."
+ },
+ "experiment_paused": {
+ "reason": "DEFAULT",
+ "error_code": null,
+ "note": "Value is default_value, or the caller default when null."
+ },
+ "holdout": {
+ "reason": "DEFAULT",
+ "error_code": null,
+ "note": "Value is default_value, or the caller default when null."
+ },
+ "no_rule_match": {
+ "reason": "DEFAULT",
+ "error_code": null,
+ "note": "No rule produced a terminal result, including when targeting matched but rollout missed with continue. Value is default_value, or the caller default when null."
+ },
+ "flag_disabled": {
+ "reason": "DISABLED",
+ "error_code": null,
+ "note": "Local definitions only. Remote responses omit an inactive flag."
+ },
+ "missing_group_key": {
+ "reason": "ERROR",
+ "error_code": "INVALID_CONTEXT",
+ "note": "The required group key is missing from additional evaluation-context fields. If a provider binds the group key to OpenFeature targetingKey and that field is missing, use TARGETING_KEY_MISSING instead."
+ },
+ "dependency_error": {
+ "reason": "ERROR",
+ "error_code": "GENERAL",
+ "note": "A dependency is unknown, cyclic, or otherwise unresolvable. reason.description becomes the error message."
+ },
+ "error": {
+ "reason": "ERROR",
+ "error_code": "GENERAL",
+ "note": "reason.description becomes the error message."
+ }
+ },
+ "outcomes_without_reason_code": [
+ {
+ "situation": "Flag absent from the remote response",
+ "reason": "ERROR",
+ "error_code": "FLAG_NOT_FOUND",
+ "note": "Typed accessor returns the caller default."
+ },
+ {
+ "situation": "Unsupported config version or unknown semantic field in definitions, strict local mode",
+ "reason": "ERROR",
+ "error_code": "PARSE_ERROR",
+ "note": "Auto mode falls back remotely before this."
+ },
+ {
+ "situation": "Typed accessor asked for a type the flag does not return",
+ "reason": "ERROR",
+ "error_code": "TYPE_MISMATCH",
+ "note": "No coercion."
+ },
+ {
+ "situation": "Bootstrap value used",
+ "reason": "CACHED",
+ "error_code": null,
+ "note": "STALE when the SDK knows definitions are outdated. No experiment context, no exposure."
+ },
+ {
+ "situation": "Client-side override",
+ "reason": "override",
+ "error_code": null,
+ "note": "Custom reason string. Never TARGETING_MATCH; suppresses $experiment_exposure."
+ },
+ {
+ "situation": "Provider not initialised",
+ "reason": "ERROR",
+ "error_code": "PROVIDER_NOT_READY",
+ "note": "Provider concern."
+ }
+ ],
+ "flag_metadata_keys": [
+ "config_version",
+ "rule_type",
+ "rule_id",
+ "experiment_id",
+ "variant_key",
+ "holdout_id",
+ "id",
+ "version",
+ "reason_code",
+ "condition_index"
+ ]
+ },
+ "warning_codes": [
+ "RULE_ORDER_CHANGES_TRAFFIC",
+ "UNREACHABLE_LOWER_RULE",
+ "ROLLOUT_MISS_CAN_ENTER_LOWER_RULE",
+ "ASSIGNMENT_RESET_CHANGES_TRAFFIC",
+ "CONCLUSION_EXPANDS_POPULATION"
+ ],
+ "semantic_constraints": [
+ {
+ "id": "rule_ids_unique",
+ "scope": "rules",
+ "requirement": "Each rule id is unique in one config. For example, two rules in one config with id aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa are invalid even if their rule_type differs; the same id may appear in separate configs."
+ },
+ {
+ "id": "variant_keys_unique",
+ "scope": "rules[].variants",
+ "requirement": "Each variant key is unique in one variant list. For example, [control, test] is valid and [control, control] is invalid within one rule. Separate rules may each use control and test."
+ },
+ {
+ "id": "variant_weights_sum_100",
+ "scope": "rules[].variants",
+ "requirement": "Each variant weight is a percentage of subjects enrolled by the rule. Weights sum to exactly 100 in stored order; rollout_percentage separately controls enrollment into the rule. For example, [33.33, 33.33, 33.34] is valid, while [33.33, 33.33, 33.33] totals 99.99 and is invalid. Validate the stored decimal percentages exactly (for example, as integer hundredths totaling 10000); do not round an invalid sum to 100. This validation is separate from binary64 accumulation during assignment."
+ },
+ {
+ "id": "percentage_two_decimals",
+ "scope": "all rollout_percentage, weight, and exclusion_percentage values",
+ "requirement": "Percentages have at most two decimal places. JSON Schema multipleOf is not used because binary64 division is inexact for values such as 33.33."
+ },
+ {
+ "id": "number_is_binary64",
+ "scope": "all number and object values",
+ "requirement": "Numbers are finite IEEE-754 binary64 values. Negative zero normalizes to zero. Nonzero underflow to zero is invalid."
+ },
+ {
+ "id": "json_keys_unique",
+ "scope": "all object values",
+ "requirement": "JSON object keys are unique at every depth before ordinary deserialization."
+ },
+ {
+ "id": "json_depth_limit",
+ "scope": "all object values",
+ "requirement": "Object values contain at most 20 object/array levels, counting the root object as level 1. Scalar leaves do not add a level. The config schema enforces this bound with numbered definitions."
+ },
+ {
+ "id": "assignment_target_context",
+ "scope": "randomized rules",
+ "requirement": "Explicit person assignment is valid only for person flags. Group flags use the flag aggregation key and omit assign_by. The config schema enforces omission of assign_by whenever aggregation_group_type_index is present, including index 0."
+ },
+ {
+ "id": "contextual_size_limits",
+ "scope": "config and metadata",
+ "requirement": "The deployment config byte limit and the metadata size limit apply outside JSON Schema validation."
+ }
+ ]
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/schemas/config.schema.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/schemas/config.schema.json
new file mode 100644
index 000000000000..f44d12f0c44a
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/schemas/config.schema.json
@@ -0,0 +1,1005 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "urn:posthog:feature-flag-rules-v2:config:1.0.0",
+ "title": "Feature Flag Rules v2 config",
+ "description": "Canonical stored configuration for Feature Flag Rules config version 2.",
+ "type": "object",
+ "required": [
+ "version",
+ "return_type",
+ "default_value",
+ "rules"
+ ],
+ "properties": {
+ "version": {
+ "const": 2
+ },
+ "return_type": {
+ "enum": [
+ "boolean",
+ "string",
+ "number",
+ "object"
+ ]
+ },
+ "default_value": {
+ "description": "Flag default for a normal result with no assigned value. Null delegates to the caller default. OpenFeature uses the caller default on abnormal execution regardless of this setting."
+ },
+ "rules": {
+ "type": "array",
+ "maxItems": 100,
+ "items": {
+ "$ref": "#/$defs/rule"
+ }
+ },
+ "aggregation_group_type_index": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": false,
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "return_type": {
+ "const": "boolean"
+ }
+ },
+ "required": [
+ "return_type"
+ ]
+ },
+ "then": {
+ "properties": {
+ "default_value": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
+ "rules": {
+ "items": {
+ "$ref": "#/$defs/booleanRuleValues"
+ }
+ }
+ }
+ }
+ },
+ {
+ "if": {
+ "properties": {
+ "return_type": {
+ "const": "string"
+ }
+ },
+ "required": [
+ "return_type"
+ ]
+ },
+ "then": {
+ "properties": {
+ "default_value": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/stringValue"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "rules": {
+ "items": {
+ "$ref": "#/$defs/stringRuleValues"
+ }
+ }
+ }
+ }
+ },
+ {
+ "if": {
+ "properties": {
+ "return_type": {
+ "const": "number"
+ }
+ },
+ "required": [
+ "return_type"
+ ]
+ },
+ "then": {
+ "properties": {
+ "default_value": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/safeNumber"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "rules": {
+ "items": {
+ "$ref": "#/$defs/numberRuleValues"
+ }
+ }
+ }
+ }
+ },
+ {
+ "if": {
+ "properties": {
+ "return_type": {
+ "const": "object"
+ }
+ },
+ "required": [
+ "return_type"
+ ]
+ },
+ "then": {
+ "properties": {
+ "default_value": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/jsonObjectValue"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "rules": {
+ "items": {
+ "$ref": "#/$defs/objectRuleValues"
+ }
+ }
+ }
+ }
+ },
+ {
+ "if": {
+ "required": [
+ "aggregation_group_type_index"
+ ]
+ },
+ "then": {
+ "properties": {
+ "rules": {
+ "items": {
+ "not": {
+ "required": [
+ "assign_by"
+ ]
+ }
+ }
+ }
+ }
+ }
+ }
+ ],
+ "$defs": {
+ "uuid": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
+ },
+ "percentage": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 100
+ },
+ "seed": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 400
+ },
+ "stringValue": {
+ "type": "string",
+ "minLength": 1
+ },
+ "safeNumber": {
+ "type": "number",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ },
+ "jsonObjectValue": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth2"
+ },
+ "x-posthog-open-object": "application_json_value",
+ "description": "At most 20 object/array levels, counting this root object as level 1. Scalar leaves do not add a level. Numbered definitions bound validation recursion."
+ },
+ "metadata": {
+ "type": "object",
+ "additionalProperties": true,
+ "x-posthog-open-object": "opaque_metadata"
+ },
+ "groupKeyNames": {
+ "anyOf": [
+ {
+ "type": "null"
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ },
+ "x-posthog-open-object": "display_group_key_names"
+ }
+ ]
+ },
+ "propertyFilter": {
+ "type": "object",
+ "required": [
+ "key",
+ "type"
+ ],
+ "properties": {
+ "key": {
+ "type": "string",
+ "minLength": 1
+ },
+ "value": {},
+ "type": {
+ "enum": [
+ "person",
+ "cohort",
+ "group",
+ "flag"
+ ]
+ },
+ "operator": {
+ "anyOf": [
+ {
+ "enum": [
+ "exact",
+ "is_not",
+ "icontains",
+ "not_icontains",
+ "icontains_multi",
+ "not_icontains_multi",
+ "starts_with",
+ "not_starts_with",
+ "ends_with",
+ "not_ends_with",
+ "regex",
+ "not_regex",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "semver_gt",
+ "semver_gte",
+ "semver_lt",
+ "semver_lte",
+ "semver_eq",
+ "semver_neq",
+ "semver_tilde",
+ "semver_caret",
+ "semver_wildcard",
+ "is_set",
+ "is_not_set",
+ "is_date_exact",
+ "is_date_after",
+ "is_date_before",
+ "in",
+ "not_in",
+ "flag_evaluates_to"
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "group_type_index": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "negation": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
+ "cohort_name": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "group_key_names": {
+ "$ref": "#/$defs/groupKeyNames"
+ },
+ "label": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "additionalProperties": false
+ },
+ "targeting": {
+ "type": "object",
+ "required": [
+ "properties"
+ ],
+ "properties": {
+ "properties": {
+ "type": "array",
+ "maxItems": 100,
+ "items": {
+ "$ref": "#/$defs/propertyFilter"
+ }
+ }
+ },
+ "additionalProperties": false
+ },
+ "variant": {
+ "type": "object",
+ "required": [
+ "key",
+ "weight",
+ "value"
+ ],
+ "properties": {
+ "key": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "^[a-zA-Z0-9_-]+$"
+ },
+ "weight": {
+ "description": "Percentage of subjects enrolled by the rule assigned to this variant. Variant weights sum to exactly 100; the rule's rollout_percentage separately controls enrollment.",
+ "$ref": "#/$defs/percentage"
+ },
+ "value": {}
+ },
+ "additionalProperties": false
+ },
+ "holdout": {
+ "type": "object",
+ "required": [
+ "id",
+ "seed",
+ "exclusion_percentage"
+ ],
+ "properties": {
+ "id": {
+ "type": "integer"
+ },
+ "seed": {
+ "$ref": "#/$defs/seed"
+ },
+ "exclusion_percentage": {
+ "$ref": "#/$defs/percentage"
+ }
+ },
+ "additionalProperties": false
+ },
+ "targetedReleaseRule": {
+ "type": "object",
+ "required": [
+ "id",
+ "rule_type",
+ "targeting",
+ "value"
+ ],
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/uuid"
+ },
+ "rule_type": {
+ "const": "targeted_release"
+ },
+ "targeting": {
+ "$ref": "#/$defs/targeting"
+ },
+ "description": {
+ "type": "string"
+ },
+ "metadata": {
+ "$ref": "#/$defs/metadata"
+ },
+ "value": {}
+ },
+ "additionalProperties": false
+ },
+ "percentageRolloutRule": {
+ "type": "object",
+ "required": [
+ "id",
+ "rule_type",
+ "targeting",
+ "value",
+ "rollout_percentage",
+ "on_rollout_miss",
+ "assignment_algorithm",
+ "seed"
+ ],
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/uuid"
+ },
+ "rule_type": {
+ "const": "percentage_rollout"
+ },
+ "targeting": {
+ "$ref": "#/$defs/targeting"
+ },
+ "description": {
+ "type": "string"
+ },
+ "metadata": {
+ "$ref": "#/$defs/metadata"
+ },
+ "value": {},
+ "rollout_percentage": {
+ "$ref": "#/$defs/percentage"
+ },
+ "on_rollout_miss": {
+ "enum": [
+ "continue",
+ "return_default"
+ ]
+ },
+ "assignment_algorithm": {
+ "const": "sha1_60_v1"
+ },
+ "seed": {
+ "$ref": "#/$defs/seed"
+ },
+ "assign_by": {
+ "const": "person"
+ }
+ },
+ "additionalProperties": false
+ },
+ "experimentRule": {
+ "type": "object",
+ "required": [
+ "id",
+ "rule_type",
+ "targeting",
+ "experiment_id",
+ "paused",
+ "rollout_percentage",
+ "on_rollout_miss",
+ "assignment_algorithm",
+ "seed",
+ "variants"
+ ],
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/uuid"
+ },
+ "rule_type": {
+ "const": "experiment"
+ },
+ "targeting": {
+ "$ref": "#/$defs/targeting"
+ },
+ "description": {
+ "type": "string"
+ },
+ "metadata": {
+ "$ref": "#/$defs/metadata"
+ },
+ "experiment_id": {
+ "type": "integer"
+ },
+ "paused": {
+ "type": "boolean"
+ },
+ "rollout_percentage": {
+ "$ref": "#/$defs/percentage"
+ },
+ "on_rollout_miss": {
+ "enum": [
+ "continue",
+ "return_default"
+ ]
+ },
+ "assignment_algorithm": {
+ "const": "sha1_60_v1"
+ },
+ "seed": {
+ "$ref": "#/$defs/seed"
+ },
+ "assign_by": {
+ "const": "person"
+ },
+ "variants": {
+ "type": "array",
+ "minItems": 2,
+ "maxItems": 20,
+ "items": {
+ "$ref": "#/$defs/variant"
+ }
+ },
+ "holdout": {
+ "$ref": "#/$defs/holdout"
+ }
+ },
+ "additionalProperties": false
+ },
+ "rule": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/targetedReleaseRule"
+ },
+ {
+ "$ref": "#/$defs/percentageRolloutRule"
+ },
+ {
+ "$ref": "#/$defs/experimentRule"
+ }
+ ]
+ },
+ "booleanRuleValues": {
+ "properties": {
+ "value": {
+ "type": "boolean"
+ },
+ "variants": {
+ "items": {
+ "properties": {
+ "value": {
+ "type": "boolean"
+ }
+ }
+ }
+ }
+ }
+ },
+ "stringRuleValues": {
+ "properties": {
+ "value": {
+ "$ref": "#/$defs/stringValue"
+ },
+ "variants": {
+ "items": {
+ "properties": {
+ "value": {
+ "$ref": "#/$defs/stringValue"
+ }
+ }
+ }
+ }
+ }
+ },
+ "numberRuleValues": {
+ "properties": {
+ "value": {
+ "$ref": "#/$defs/safeNumber"
+ },
+ "variants": {
+ "items": {
+ "properties": {
+ "value": {
+ "$ref": "#/$defs/safeNumber"
+ }
+ }
+ }
+ }
+ }
+ },
+ "objectRuleValues": {
+ "properties": {
+ "value": {
+ "$ref": "#/$defs/jsonObjectValue"
+ },
+ "variants": {
+ "items": {
+ "properties": {
+ "value": {
+ "$ref": "#/$defs/jsonObjectValue"
+ }
+ }
+ }
+ }
+ }
+ },
+ "jsonScalarValue": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "type": "boolean"
+ },
+ {
+ "$ref": "#/$defs/safeNumber"
+ },
+ {
+ "type": "string"
+ }
+ ]
+ },
+ "jsonValueDepth2": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth3"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth3"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth3": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth4"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth4"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth4": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth5"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth5"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth5": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth6"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth6"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth6": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth7"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth7"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth7": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth8"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth8"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth8": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth9"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth9"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth9": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth10"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth10"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth10": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth11"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth11"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth11": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth12"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth12"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth12": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth13"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth13"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth13": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth14"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth14"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth14": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth15"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth15"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth15": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth16"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth16"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth16": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth17"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth17"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth17": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth18"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth18"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth18": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth19"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth19"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth19": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonValueDepth20"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonValueDepth20"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ },
+ "jsonValueDepth20": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/jsonScalarValue"
+ }
+ },
+ {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/jsonScalarValue"
+ },
+ "x-posthog-open-object": "application_json_value"
+ }
+ ]
+ }
+ }
+}
diff --git a/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/schemas/management_warning.schema.json b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/schemas/management_warning.schema.json
new file mode 100644
index 000000000000..55561fbfa8ad
--- /dev/null
+++ b/products/feature_flags/backend/test/fixtures/rules_v2_contract/2.0.0/schemas/management_warning.schema.json
@@ -0,0 +1,31 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://posthog.com/contracts/feature_flag_rules_v2/management_warning.schema.json",
+ "title": "Management warning diagnostic",
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "code"
+ ],
+ "properties": {
+ "code": {
+ "enum": [
+ "RULE_ORDER_CHANGES_TRAFFIC",
+ "UNREACHABLE_LOWER_RULE",
+ "ROLLOUT_MISS_CAN_ENTER_LOWER_RULE",
+ "ASSIGNMENT_RESET_CHANGES_TRAFFIC",
+ "CONCLUSION_EXPANDS_POPULATION"
+ ]
+ },
+ "detail": {
+ "type": "string"
+ },
+ "attr": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "description": "A warning code is normative; optional detail is presentation text and attr identifies a field. This diagnostic shape does not prescribe an endpoint envelope or acknowledgement protocol."
+}
diff --git a/products/feature_flags/backend/test/test_facade_config_validation.py b/products/feature_flags/backend/test/test_facade_config_validation.py
new file mode 100644
index 000000000000..06350fbf7cad
--- /dev/null
+++ b/products/feature_flags/backend/test/test_facade_config_validation.py
@@ -0,0 +1,812 @@
+import re
+import sys
+import json
+import hashlib
+from copy import deepcopy
+from decimal import Decimal
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jsonschema import Draft202012Validator, FormatChecker
+from parameterized import parameterized
+
+from products.feature_flags.backend import filters_validation
+from products.feature_flags.backend.api.feature_flag import calculate_filter_size_bytes
+from products.feature_flags.backend.facade import config_validation
+from products.feature_flags.backend.facade.config_validation import (
+ _COMMON_RULE_FIELDS,
+ _PROPERTY_FIELDS,
+ _ROLLOUT_RULE_FIELDS,
+ _ROOT_FIELDS,
+ _UUID as UUID_PATTERN,
+ ASSIGNMENT_ALGORITHM,
+ MAX_PREDICATES_PER_RULE,
+ MAX_RULES,
+ MAX_SEED_LENGTH,
+ PERSON_ASSIGNMENT,
+ PROPERTY_OPERATORS,
+ PROPERTY_TYPES,
+ RETURN_TYPES,
+ ROLLOUT_MISS_POLICIES,
+ RULE_TYPES,
+ ConfigValidationError,
+ Predicate,
+ ValidatedConfig,
+ ValidatedRule,
+ ValidationLimits,
+ _encoded_size as config_size_bytes,
+ validate_config,
+)
+
+# Vendored from the released harness contract; SOURCE.json records the revision and digests.
+CONTRACT_DIR = Path(__file__).parent / "fixtures" / "rules_v2_contract" / "2.0.0"
+LIMITS = ValidationLimits(max_config_bytes=64 * 1024, max_metadata_bytes=1024)
+
+TARGETED_ID = "11111111-1111-4111-8111-111111111111"
+ROLLOUT_ID = "22222222-2222-4222-8222-222222222222"
+SEED = "release-preview"
+
+
+def targeted(**overrides: Any) -> dict[str, Any]:
+ return {
+ "id": TARGETED_ID,
+ "rule_type": "targeted_release",
+ "targeting": {"properties": []},
+ "value": True,
+ **overrides,
+ }
+
+
+def rollout(**overrides: Any) -> dict[str, Any]:
+ return {
+ "id": ROLLOUT_ID,
+ "rule_type": "percentage_rollout",
+ "targeting": {"properties": []},
+ "value": True,
+ "rollout_percentage": 25,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": ASSIGNMENT_ALGORITHM,
+ "seed": SEED,
+ **overrides,
+ }
+
+
+def person(**overrides: Any) -> dict[str, Any]:
+ return {"key": "account_tier", "type": "person", "operator": "exact", "value": "preview", **overrides}
+
+
+def config(*rules: dict[str, Any], **overrides: Any) -> dict[str, Any]:
+ return {"version": 2, "return_type": "boolean", "default_value": False, "rules": list(rules), **overrides}
+
+
+def without(document: dict[str, Any], key: str) -> dict[str, Any]:
+ return {name: value for name, value in document.items() if name != key}
+
+
+def errors_of(document: object, limits: ValidationLimits = LIMITS) -> list[tuple[str, str]]:
+ with pytest.raises(ConfigValidationError) as exc_info:
+ validate_config(document, limits=limits)
+ return [(error.code, error.attr) for error in exc_info.value.errors]
+
+
+def load_contract(relative: str) -> Any:
+ with (CONTRACT_DIR / relative).open(encoding="utf-8") as handle:
+ return json.load(handle)
+
+
+MANIFEST = load_contract("manifest.json")
+CONFIG_SCHEMA = load_contract("schemas/config.schema.json")
+SCHEMA_VALIDATOR = Draft202012Validator(CONFIG_SCHEMA, format_checker=FormatChecker())
+CONTRACT_FIXTURES = [entry for entry in MANIFEST["artifacts"] if entry["kind"] == "fixture"]
+
+
+VALID_DOCUMENTS: list[tuple[str, dict[str, Any]]] = [
+ ("empty_rules", config()),
+ ("null_default", config(default_value=None)),
+ ("float_version_literal", config(version=2.0)),
+ ("targeted_with_person_property", config(targeted(targeting={"properties": [person()]}))),
+ ("targeted_without_operator", config(targeted(targeting={"properties": [person(operator=None, negation=None)]}))),
+ ("targeted_false_value", config(targeted(value=False))),
+ ("description_and_metadata", config(targeted(description="Preview accounts", metadata={"color": "blue"}))),
+ ("unicode_description_and_metadata", config(targeted(description="Préview 🦔", metadata={"label": "🦔"}))),
+ ("empty_metadata", config(targeted(metadata={}))),
+ (
+ "exact_finite_number_boundaries",
+ config(
+ targeted(
+ targeting={
+ "properties": [person(value=[sys.float_info.max, -sys.float_info.max, int(sys.float_info.max)])]
+ }
+ )
+ ),
+ ),
+ (
+ "metadata_finite_number_boundaries",
+ config(targeted(metadata={"n": [int(sys.float_info.max), -int(sys.float_info.max), True, None, "1e400"]})),
+ ),
+ ("percentage_two_decimals", config(rollout(rollout_percentage=33.33))),
+ ("percentage_zero", config(rollout(rollout_percentage=0))),
+ ("percentage_hundred", config(rollout(rollout_percentage=100))),
+ ("percentage_float_integer", config(rollout(rollout_percentage=25.0))),
+ ("return_default", config(rollout(on_rollout_miss="return_default"))),
+ ("explicit_person_assignment", config(rollout(assign_by=PERSON_ASSIGNMENT))),
+ ("seed_max_length", config(rollout(seed="s" * MAX_SEED_LENGTH))),
+ (
+ "all_operator_value_shapes",
+ config(
+ targeted(
+ targeting={
+ "properties": [
+ person(key="email", operator="icontains", value="@example.com"),
+ person(key="version", operator="semver_gte", value="1.2.3"),
+ person(key="version", operator="semver_wildcard", value="1.*"),
+ person(key="signup", operator="is_date_after", value="2024-01-01"),
+ person(key="seats", operator="gt", value=10),
+ person(key="seats", operator="lt", value="10"),
+ person(key="tags", operator="icontains_multi", value=["a", "b"]),
+ person(key="beta", operator="is_set"),
+ person(key="beta", operator="is_not_set", value=None),
+ person(key="plan", operator="exact", value=["pro", "team"], negation=True),
+ person(
+ key="plan",
+ operator="is_not",
+ value="free",
+ label="Plan",
+ cohort_name=None,
+ group_key_names=None,
+ ),
+ ]
+ }
+ )
+ ),
+ ),
+ ("max_rules", config(*[targeted(id=f"00000000-0000-4000-8000-{index:012d}") for index in range(MAX_RULES)])),
+ (
+ "max_predicates",
+ config(targeted(targeting={"properties": [person(key=f"k{i}") for i in range(MAX_PREDICATES_PER_RULE)]})),
+ ),
+]
+
+INVALID_DOCUMENTS: list[tuple[str, object, list[tuple[str, str]]]] = [
+ ("root_list", [], [("invalid", "filters")]),
+ ("root_none", None, [("invalid", "filters")]),
+ ("root_string", "{}", [("invalid", "filters")]),
+ ("root_not_json", {**config(), "note": {1, 2}}, [("invalid", "filters")]),
+ ("missing_version", without(config(), "version"), [("required", "filters.version")]),
+ ("version_1", config(version=1), [("invalid", "filters.version")]),
+ ("version_string", config(version="2"), [("invalid", "filters.version")]),
+ ("version_bool", config(version=True), [("invalid", "filters.version")]),
+ ("version_null", config(version=None), [("invalid", "filters.version")]),
+ ("version_3", config(version=3), [("invalid", "filters.version")]),
+ ("version_fraction", config(version=2.5), [("invalid", "filters.version")]),
+ ("unknown_root_field", config(future=1), [("unknown_field", "filters.future")]),
+ ("v1_groups", config(groups=[]), [("unknown_field", "filters.groups")]),
+ (
+ "v1_multivariate_and_payloads",
+ config(multivariate=None, payloads={}),
+ [("unknown_field", "filters.multivariate"), ("unknown_field", "filters.payloads")],
+ ),
+ ("missing_return_type", without(config(), "return_type"), [("required", "filters.return_type")]),
+ ("return_type_unknown", config(return_type="json"), [("invalid", "filters.return_type")]),
+ ("return_type_null", config(return_type=None), [("invalid", "filters.return_type")]),
+ ("return_type_string", config(return_type="string", default_value="a"), [("unsupported", "filters.return_type")]),
+ ("return_type_number", config(return_type="number", default_value=0), [("unsupported", "filters.return_type")]),
+ ("return_type_object", config(return_type="object", default_value={}), [("unsupported", "filters.return_type")]),
+ ("missing_default", without(config(), "default_value"), [("required", "filters.default_value")]),
+ ("default_zero", config(default_value=0), [("invalid", "filters.default_value")]),
+ ("default_one", config(default_value=1), [("invalid", "filters.default_value")]),
+ ("default_string", config(default_value="true"), [("invalid", "filters.default_value")]),
+ ("default_list", config(default_value=[]), [("invalid", "filters.default_value")]),
+ (
+ "group_assignment",
+ config(aggregation_group_type_index=0),
+ [("unsupported", "filters.aggregation_group_type_index")],
+ ),
+ (
+ "group_index_string",
+ config(aggregation_group_type_index="0"),
+ [("invalid", "filters.aggregation_group_type_index")],
+ ),
+ (
+ "group_index_null",
+ config(aggregation_group_type_index=None),
+ [("invalid", "filters.aggregation_group_type_index")],
+ ),
+ (
+ "group_index_bool",
+ config(aggregation_group_type_index=True),
+ [("invalid", "filters.aggregation_group_type_index")],
+ ),
+ (
+ "group_index_float",
+ config(aggregation_group_type_index=1.0),
+ [("invalid", "filters.aggregation_group_type_index")],
+ ),
+ ("missing_rules", without(config(), "rules"), [("required", "filters.rules")]),
+ ("rules_object", config(rules={}), [("invalid", "filters.rules")]),
+ ("rules_null", config(rules=None), [("invalid", "filters.rules")]),
+ (
+ "too_many_rules",
+ config(*[targeted(id=f"00000000-0000-4000-8000-{i:012d}") for i in range(MAX_RULES + 1)]),
+ [("limit_exceeded", "filters.rules")],
+ ),
+ ("rule_number", config(rules=[1]), [("invalid", "filters.rules[0]")]),
+ ("rule_null", config(rules=[None]), [("invalid", "filters.rules[0]")]),
+ ("missing_rule_type", config(without(targeted(), "rule_type")), [("required", "filters.rules[0].rule_type")]),
+ ("removed_rule_type", config(targeted(rule_type="variant_rollout")), [("invalid", "filters.rules[0].rule_type")]),
+ ("rule_type_null", config(targeted(rule_type=None)), [("invalid", "filters.rules[0].rule_type")]),
+ ("rule_type_list", config(targeted(rule_type=["targeted_release"])), [("invalid", "filters.rules[0].rule_type")]),
+ ("experiment_rule", config(targeted(rule_type="experiment")), [("unsupported", "filters.rules[0].rule_type")]),
+ (
+ "unknown_rule_field",
+ config(targeted(implicit_default=False)),
+ [("unknown_field", "filters.rules[0].implicit_default")],
+ ),
+ (
+ "targeted_with_rollout_fields",
+ config(targeted(rollout_percentage=25, seed=SEED)),
+ [("unknown_field", "filters.rules[0].rollout_percentage"), ("unknown_field", "filters.rules[0].seed")],
+ ),
+ (
+ "targeted_with_experiment_fields",
+ config(targeted(experiment_id=1, variants=[], holdout=None)),
+ [
+ ("unknown_field", "filters.rules[0].experiment_id"),
+ ("unknown_field", "filters.rules[0].variants"),
+ ("unknown_field", "filters.rules[0].holdout"),
+ ],
+ ),
+ ("missing_id", config(without(targeted(), "id")), [("required", "filters.rules[0].id")]),
+ ("id_not_uuid", config(targeted(id="rule-1")), [("invalid", "filters.rules[0].id")]),
+ ("id_with_trailing_newline", config(targeted(id=TARGETED_ID + "\n")), [("invalid", "filters.rules[0].id")]),
+ (
+ "id_without_hyphens",
+ config(targeted(id="11111111111141118111111111111111")),
+ [("invalid", "filters.rules[0].id")],
+ ),
+ ("id_braced", config(targeted(id="{11111111-1111-4111-8111-111111111111}")), [("invalid", "filters.rules[0].id")]),
+ ("id_number", config(targeted(id=1)), [("invalid", "filters.rules[0].id")]),
+ ("duplicate_ids", config(targeted(), rollout(id=TARGETED_ID)), [("not_unique", "filters.rules[1].id")]),
+ ("missing_targeting", config(without(targeted(), "targeting")), [("required", "filters.rules[0].targeting")]),
+ ("targeting_list", config(targeted(targeting=[])), [("invalid", "filters.rules[0].targeting")]),
+ (
+ "targeting_without_properties",
+ config(targeted(targeting={})),
+ [("required", "filters.rules[0].targeting.properties")],
+ ),
+ (
+ "targeting_unknown_field",
+ config(targeted(targeting={"properties": [], "rollout_percentage": 50})),
+ [("unknown_field", "filters.rules[0].targeting.rollout_percentage")],
+ ),
+ (
+ "properties_object",
+ config(targeted(targeting={"properties": {}})),
+ [("invalid", "filters.rules[0].targeting.properties")],
+ ),
+ (
+ "too_many_properties",
+ config(targeted(targeting={"properties": [person(key=f"k{i}") for i in range(MAX_PREDICATES_PER_RULE + 1)]})),
+ [("limit_exceeded", "filters.rules[0].targeting.properties")],
+ ),
+ (
+ "property_number",
+ config(targeted(targeting={"properties": [1]})),
+ [("invalid", "filters.rules[0].targeting.properties[0]")],
+ ),
+ (
+ "property_unknown_field",
+ config(targeted(targeting={"properties": [person(future=1)]})),
+ [("unknown_field", "filters.rules[0].targeting.properties[0].future")],
+ ),
+ (
+ "property_missing_key",
+ config(targeted(targeting={"properties": [without(person(), "key")]})),
+ [("required", "filters.rules[0].targeting.properties[0].key")],
+ ),
+ (
+ "property_empty_key",
+ config(targeted(targeting={"properties": [person(key="")]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].key")],
+ ),
+ (
+ "property_numeric_key",
+ config(targeted(targeting={"properties": [person(key=1)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].key")],
+ ),
+ (
+ "property_missing_type",
+ config(targeted(targeting={"properties": [without(person(), "type")]})),
+ [("required", "filters.rules[0].targeting.properties[0].type")],
+ ),
+ (
+ "property_unknown_type",
+ config(targeted(targeting={"properties": [person(type="event")]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].type")],
+ ),
+ (
+ "cohort_property",
+ config(targeted(targeting={"properties": [{"key": "id", "type": "cohort", "value": 7, "operator": "in"}]})),
+ [("unsupported", "filters.rules[0].targeting.properties[0].type")],
+ ),
+ (
+ "flag_property",
+ config(
+ targeted(
+ targeting={
+ "properties": [{"key": "12", "type": "flag", "value": True, "operator": "flag_evaluates_to"}]
+ }
+ )
+ ),
+ [("unsupported", "filters.rules[0].targeting.properties[0].type")],
+ ),
+ (
+ "group_property",
+ config(targeted(targeting={"properties": [person(type="group", group_type_index=0)]})),
+ [("unsupported", "filters.rules[0].targeting.properties[0].type")],
+ ),
+ (
+ "operator_alias",
+ config(targeted(targeting={"properties": [person(operator="min", value=1)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].operator")],
+ ),
+ (
+ "operator_unknown",
+ config(targeted(targeting={"properties": [person(operator="contains")]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].operator")],
+ ),
+ (
+ "operator_list",
+ config(targeted(targeting={"properties": [person(operator=["exact"])]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].operator")],
+ ),
+ (
+ "operator_cohort_only",
+ config(targeted(targeting={"properties": [person(operator="in", value=[1])]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].operator")],
+ ),
+ (
+ "operator_flag_only",
+ config(targeted(targeting={"properties": [person(operator="flag_evaluates_to", value=True)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].operator")],
+ ),
+ (
+ "date_value",
+ config(targeted(targeting={"properties": [person(operator="is_date_before", value="not a date")]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "string_operator_number",
+ config(targeted(targeting={"properties": [person(operator="icontains", value=1)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "regex_null",
+ config(targeted(targeting={"properties": [person(operator="regex", value=None)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "prefix_operator_list",
+ config(targeted(targeting={"properties": [person(operator="starts_with", value=["a"])]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "numeric_operator_list",
+ config(targeted(targeting={"properties": [person(operator="gte", value=[])]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "numeric_operator_bool",
+ config(targeted(targeting={"properties": [person(operator="gt", value=True)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "list_operator_string",
+ config(targeted(targeting={"properties": [person(operator="icontains_multi", value="a")]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "semver_not_a_version",
+ config(targeted(targeting={"properties": [person(operator="semver_gt", value="not-a-version")]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "semver_number",
+ config(targeted(targeting={"properties": [person(operator="semver_eq", value=1)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "exact_nan",
+ config(targeted(targeting={"properties": [person(value=float("nan"))]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "omitted_operator_nan",
+ config(targeted(targeting={"properties": [without(person(), "operator") | {"value": float("nan")}]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "null_operator_infinity",
+ config(targeted(targeting={"properties": [person(operator=None, value=float("inf"))]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ (
+ "exact_nested_infinity",
+ config(targeted(targeting={"properties": [person(value=[1, {"n": float("inf")}])]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ ),
+ *[
+ (
+ name,
+ config(targeted(targeting={"properties": [person(value=value)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].value")],
+ )
+ for name, value in [
+ ("exact_huge_integer", 10**400),
+ ("exact_negative_huge_integer", -(10**400)),
+ ("exact_integer_above_binary64_range", int(sys.float_info.max) + 1),
+ ("exact_integer_below_binary64_range", -int(sys.float_info.max) - 1),
+ ("exact_array_huge_integer", [10**400]),
+ ("exact_object_nested_huge_integer", {"n": [1, {"n": -(10**400)}]}),
+ ]
+ ],
+ (
+ "person_with_group_type_index",
+ config(targeted(targeting={"properties": [person(group_type_index=0)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].group_type_index")],
+ ),
+ (
+ "negation_string",
+ config(targeted(targeting={"properties": [person(negation="yes")]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].negation")],
+ ),
+ (
+ "label_number",
+ config(targeted(targeting={"properties": [person(label=1)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].label")],
+ ),
+ (
+ "cohort_name_number",
+ config(targeted(targeting={"properties": [person(cohort_name=1)]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].cohort_name")],
+ ),
+ (
+ "group_key_names_string",
+ config(targeted(targeting={"properties": [person(group_key_names="org")]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].group_key_names")],
+ ),
+ (
+ "group_key_names_non_string_value",
+ config(targeted(targeting={"properties": [person(group_key_names={"org": 1})]})),
+ [("invalid", "filters.rules[0].targeting.properties[0].group_key_names")],
+ ),
+ ("description_null", config(targeted(description=None)), [("invalid", "filters.rules[0].description")]),
+ ("description_number", config(targeted(description=1)), [("invalid", "filters.rules[0].description")]),
+ ("description_high_surrogate", config(targeted(description="\ud800")), [("invalid", "filters")]),
+ ("description_low_surrogate", config(targeted(description="\udfff")), [("invalid", "filters")]),
+ ("metadata_list", config(targeted(metadata=[])), [("invalid", "filters.rules[0].metadata")]),
+ ("metadata_string", config(targeted(metadata="x")), [("invalid", "filters.rules[0].metadata")]),
+ ("metadata_surrogate_key", config(targeted(metadata={"nested": {"\ud800": "value"}})), [("invalid", "filters")]),
+ ("metadata_nan", config(targeted(metadata={"n": float("nan")})), [("invalid", "filters.rules[0].metadata")]),
+ *[
+ (name, config(targeted(metadata={"n": value})), [("invalid", "filters.rules[0].metadata")])
+ for name, value in [
+ ("metadata_huge_integer", 10**400),
+ ("metadata_negative_huge_integer", -(10**400)),
+ ("metadata_integer_above_binary64_range", int(sys.float_info.max) + 1),
+ ("metadata_integer_below_binary64_range", -int(sys.float_info.max) - 1),
+ ("metadata_array_huge_integer", [10**400]),
+ ("metadata_object_nested_huge_integer", {"n": [1, {"n": -(10**400)}]}),
+ ]
+ ],
+ (
+ "metadata_too_large",
+ config(targeted(metadata={"blob": "x" * 2000})),
+ [("limit_exceeded", "filters.rules[0].metadata")],
+ ),
+ ("missing_value", config(without(targeted(), "value")), [("required", "filters.rules[0].value")]),
+ ("value_null", config(targeted(value=None)), [("invalid", "filters.rules[0].value")]),
+ ("value_zero", config(rollout(value=0)), [("invalid", "filters.rules[0].value")]),
+ ("value_one", config(targeted(value=1)), [("invalid", "filters.rules[0].value")]),
+ ("value_string", config(targeted(value="true")), [("invalid", "filters.rules[0].value")]),
+ (
+ "missing_rollout_percentage",
+ config(without(rollout(), "rollout_percentage")),
+ [("required", "filters.rules[0].rollout_percentage")],
+ ),
+ ("rollout_bool", config(rollout(rollout_percentage=True)), [("invalid", "filters.rules[0].rollout_percentage")]),
+ ("rollout_string", config(rollout(rollout_percentage="25")), [("invalid", "filters.rules[0].rollout_percentage")]),
+ ("rollout_null", config(rollout(rollout_percentage=None)), [("invalid", "filters.rules[0].rollout_percentage")]),
+ (
+ "rollout_nan",
+ config(rollout(rollout_percentage=float("nan"))),
+ [("invalid", "filters.rules[0].rollout_percentage")],
+ ),
+ (
+ "rollout_infinity",
+ config(rollout(rollout_percentage=float("inf"))),
+ [("invalid", "filters.rules[0].rollout_percentage")],
+ ),
+ ("rollout_negative", config(rollout(rollout_percentage=-1)), [("invalid", "filters.rules[0].rollout_percentage")]),
+ (
+ "rollout_above_maximum",
+ config(rollout(rollout_percentage=100.01)),
+ [("invalid", "filters.rules[0].rollout_percentage")],
+ ),
+ (
+ "rollout_three_decimals",
+ config(rollout(rollout_percentage=33.333)),
+ [("invalid", "filters.rules[0].rollout_percentage")],
+ ),
+ (
+ "rollout_tiny_fraction",
+ config(rollout(rollout_percentage=1e-7)),
+ [("invalid", "filters.rules[0].rollout_percentage")],
+ ),
+ (
+ "missing_miss_policy",
+ config(without(rollout(), "on_rollout_miss")),
+ [("required", "filters.rules[0].on_rollout_miss")],
+ ),
+ ("unknown_miss_policy", config(rollout(on_rollout_miss="stop")), [("invalid", "filters.rules[0].on_rollout_miss")]),
+ ("null_miss_policy", config(rollout(on_rollout_miss=None)), [("invalid", "filters.rules[0].on_rollout_miss")]),
+ (
+ "missing_algorithm",
+ config(without(rollout(), "assignment_algorithm")),
+ [("required", "filters.rules[0].assignment_algorithm")],
+ ),
+ (
+ "unknown_algorithm",
+ config(rollout(assignment_algorithm="md5")),
+ [("invalid", "filters.rules[0].assignment_algorithm")],
+ ),
+ ("missing_seed", config(without(rollout(), "seed")), [("required", "filters.rules[0].seed")]),
+ ("empty_seed", config(rollout(seed="")), [("invalid", "filters.rules[0].seed")]),
+ ("seed_too_long", config(rollout(seed="s" * (MAX_SEED_LENGTH + 1))), [("invalid", "filters.rules[0].seed")]),
+ ("seed_number", config(rollout(seed=123)), [("invalid", "filters.rules[0].seed")]),
+ ("seed_null", config(rollout(seed=None)), [("invalid", "filters.rules[0].seed")]),
+ ("group_assign_by", config(rollout(assign_by="group")), [("invalid", "filters.rules[0].assign_by")]),
+ ("null_assign_by", config(rollout(assign_by=None)), [("invalid", "filters.rules[0].assign_by")]),
+]
+
+
+class TestValidateConfig:
+ @parameterized.expand(VALID_DOCUMENTS)
+ def test_admitted_documents_validate_and_match_the_canonical_schema(
+ self, _name: str, document: dict[str, Any]
+ ) -> None:
+ snapshot = deepcopy(document)
+ validated = validate_config(document, limits=LIMITS)
+ assert [rule.id for rule in validated.rules] == [rule["id"] for rule in document["rules"]]
+ assert document == snapshot
+ # Admission is narrower than the contract, never wider: everything accepted here is schema-valid.
+ assert not list(SCHEMA_VALIDATOR.iter_errors(document))
+
+ @parameterized.expand(INVALID_DOCUMENTS)
+ def test_rejected_documents_report_deterministic_field_errors(
+ self, _name: str, document: object, expected: list[tuple[str, str]]
+ ) -> None:
+ snapshot = deepcopy(document) if isinstance(document, dict | list) else document
+ assert errors_of(document) == expected
+ assert errors_of(document) == expected
+ if isinstance(document, dict | list):
+ assert document == snapshot
+
+ @parameterized.expand(
+ [
+ ("metadata", lambda deep: config(targeted(metadata={"note": deep})), "filters.rules[0].metadata"),
+ (
+ "property_value",
+ lambda deep: config(targeted(targeting={"properties": [person(value=deep)]})),
+ "filters.rules[0].targeting.properties[0].value",
+ ),
+ ]
+ )
+ def test_deeply_nested_values_are_a_field_error_not_a_crash(self, _name: str, build: Any, attr: str) -> None:
+ # Nesting past the recursion limit stays a few KB, so no byte limit catches it first.
+ deep: Any = 1
+ for _ in range(2000):
+ deep = [deep]
+ assert errors_of(build(deep), ValidationLimits(max_config_bytes=64 * 1024, max_metadata_bytes=64 * 1024)) == [
+ ("invalid", attr)
+ ]
+
+ def test_errors_are_collected_in_a_fixed_order(self) -> None:
+ document = {**without(config(targeted(id="bad")), "default_value"), "future": 1}
+ with pytest.raises(ConfigValidationError) as exc_info:
+ validate_config(document, limits=LIMITS)
+ assert [(error.code, error.attr) for error in exc_info.value.errors] == [
+ ("unknown_field", "filters.future"),
+ ("required", "filters.default_value"),
+ ("invalid", "filters.rules[0].id"),
+ ]
+ assert str(exc_info.value) == "filters.future: Unknown field."
+
+ def test_unsupported_family_is_reported_before_shape_of_its_values(self) -> None:
+ # A canonical string document is refused for the family, not for values this validator cannot judge.
+ document = config(targeted(value="compact"), return_type="string", default_value="standard")
+ assert errors_of(document) == [("unsupported", "filters.return_type")]
+
+ def test_v1_only_fields_name_the_format_clash(self) -> None:
+ with pytest.raises(ConfigValidationError) as exc_info:
+ validate_config(config(groups=[], future=1), limits=LIMITS)
+ details = {error.attr: error.detail for error in exc_info.value.errors}
+ assert "version 1" in details["filters.groups"]
+ assert details["filters.future"] == "Unknown field."
+
+ def test_configuration_byte_limit_is_checked_first(self) -> None:
+ limits = ValidationLimits(max_config_bytes=80, max_metadata_bytes=1024)
+ assert errors_of(config(targeted(rule_type="nonsense")), limits) == [("limit_exceeded", "filters")]
+ assert validate_config(config(), limits=limits).rules == ()
+
+ @parameterized.expand([("zero", 0), ("negative", -1), ("bool", True), ("string", "1"), ("float", 1.5)])
+ def test_limits_must_be_positive_integers(self, _name: str, limit: object) -> None:
+ with pytest.raises(ValueError):
+ ValidationLimits(max_config_bytes=limit, max_metadata_bytes=1) # type: ignore[arg-type]
+ with pytest.raises(ValueError):
+ ValidationLimits(max_config_bytes=1, max_metadata_bytes=limit) # type: ignore[arg-type]
+
+ def test_validated_representation_carries_the_evaluated_fields(self) -> None:
+ document = config(
+ targeted(
+ targeting={
+ "properties": [
+ person(operator=None, negation=None),
+ person(key="beta", operator="is_set", value=None),
+ ]
+ }
+ ),
+ rollout(rollout_percentage=33.33, assign_by=PERSON_ASSIGNMENT, metadata={"note": "x"}),
+ default_value=None,
+ )
+ validated = validate_config(document, limits=LIMITS)
+ assert validated == ValidatedConfig(
+ default_value=None,
+ rules=(
+ ValidatedRule(
+ id=TARGETED_ID,
+ rule_type="targeted_release",
+ predicates=frozenset(
+ {
+ Predicate(key="account_tier", operator="exact", value='"preview"', negation=False),
+ Predicate(key="beta", operator="is_set", value="null", negation=False),
+ }
+ ),
+ value=True,
+ ),
+ ValidatedRule(
+ id=ROLLOUT_ID,
+ rule_type="percentage_rollout",
+ predicates=frozenset(),
+ value=True,
+ rollout_percentage=Decimal("33.33"),
+ on_rollout_miss="continue",
+ seed=SEED,
+ ),
+ ),
+ )
+ assert validated.rules[1].rollout_percentage == Decimal("33.33")
+ assert SEED not in repr(validated)
+
+ @parameterized.expand([("explicit", {"negation": True}), ("omitted", {})])
+ def test_predicates_are_canonical_across_equivalent_spellings(self, _name: str, extra: dict[str, Any]) -> None:
+ plain = validate_config(config(targeted(targeting={"properties": [person(**extra)]})), limits=LIMITS)
+ spelled = validate_config(
+ config(targeted(targeting={"properties": [person(negation=extra.get("negation", None), label="Tier")]})),
+ limits=LIMITS,
+ )
+ assert plain.rules[0].predicates == spelled.rules[0].predicates
+
+
+def _contract_path(instance_path: str, expected: dict[str, Any]) -> str:
+ attr = "filters" + re.sub(r"/(\d+)", r"[\1]", instance_path).replace("/", ".")
+ # Upstream writes the bare field name in `message_contains` for these two keywords, so it is
+ # the missing or unknown field's path segment. Other keywords carry prose (`2 was expected`).
+ if expected["keyword"] in ("required", "additionalProperties"):
+ attr += "." + expected["message_contains"]
+ return attr
+
+
+def _admitted_family(document: dict[str, Any]) -> bool:
+ raw_rules = document.get("rules")
+ rules: list[dict[str, Any]] = (
+ [rule for rule in raw_rules if isinstance(rule, dict)] if isinstance(raw_rules, list) else []
+ )
+ properties: list[dict[str, Any]] = [
+ prop
+ for rule in rules
+ if isinstance(rule.get("targeting"), dict)
+ for prop in rule["targeting"].get("properties", [])
+ if isinstance(prop, dict)
+ ]
+ return (
+ document.get("return_type") == "boolean"
+ and "aggregation_group_type_index" not in document
+ and all(rule.get("rule_type") != "experiment" for rule in rules)
+ and all(prop.get("type") == "person" for prop in properties)
+ )
+
+
+class TestReleasedContract:
+ def test_vendored_contract_is_intact(self) -> None:
+ source = load_contract("SOURCE.json")
+ index_bytes = (CONTRACT_DIR / "SHA256SUMS").read_bytes()
+ assert hashlib.sha256(index_bytes).hexdigest() == source["source_sha256sums_digest"]
+ index = {
+ path: digest for digest, path in re.findall(r"^([0-9a-f]{64}) (.+)$", index_bytes.decode("utf-8"), re.M)
+ }
+ vendored = [
+ path
+ for path in CONTRACT_DIR.rglob("*")
+ if path.is_file() and path.name not in ("SHA256SUMS", "SOURCE.json")
+ ]
+ relatives = {path.relative_to(CONTRACT_DIR).as_posix() for path in vendored}
+ # A deliberate subset of the upstream index: the corpus and wire files stay with the Rust runner.
+ assert relatives <= set(index)
+ for path in vendored:
+ relative = path.relative_to(CONTRACT_DIR).as_posix()
+ assert hashlib.sha256(path.read_bytes()).hexdigest() == index[relative], relative
+ assert {entry["path"] for entry in CONTRACT_FIXTURES} <= relatives
+ assert MANIFEST["contract"]["version"] == source["contract_version"]
+ versions = {artifact["path"]: artifact.get("version") for artifact in MANIFEST["artifacts"]}
+ assert versions["schemas/config.schema.json"] == source["config_schema_version"]
+ assert versions["registries/literals.json"] == source["registry_version"]
+
+ def test_literals_agree_with_the_released_registry(self) -> None:
+ registry = load_contract("registries/literals.json")
+ assert PROPERTY_OPERATORS == set(registry["property_operators"])
+ assert set(PROPERTY_TYPES) == set(registry["property_types"])
+ assert set(ROLLOUT_MISS_POLICIES) == set(registry["rollout_miss_policies"])
+ assert [ASSIGNMENT_ALGORITHM] == registry["assignment_algorithms"]
+ assert [PERSON_ASSIGNMENT] == registry["assignment_targets"]
+ assert MAX_RULES == CONFIG_SCHEMA["properties"]["rules"]["maxItems"]
+ assert MAX_PREDICATES_PER_RULE == CONFIG_SCHEMA["$defs"]["targeting"]["properties"]["properties"]["maxItems"]
+ assert MAX_SEED_LENGTH == CONFIG_SCHEMA["$defs"]["seed"]["maxLength"]
+ assert UUID_PATTERN.pattern == CONFIG_SCHEMA["$defs"]["uuid"]["pattern"]
+ assert set(RETURN_TYPES) == {entry["value"] for entry in registry["return_types"]}
+ assert set(RULE_TYPES) == {entry["value"] for entry in registry["rule_types"]}
+
+ def test_field_name_sets_agree_with_the_released_schema(self) -> None:
+ defs = CONFIG_SCHEMA["$defs"]
+ assert _ROOT_FIELDS == set(CONFIG_SCHEMA["properties"])
+ assert _COMMON_RULE_FIELDS == set(defs["targetedReleaseRule"]["properties"])
+ assert _COMMON_RULE_FIELDS | _ROLLOUT_RULE_FIELDS == set(defs["percentageRolloutRule"]["properties"])
+ assert _PROPERTY_FIELDS == set(defs["propertyFilter"]["properties"])
+
+ def test_operator_tables_match_the_v1_cross_field_tier(self) -> None:
+ # Repeated rather than imported (that module is the v1 tier), so nothing else keeps them equal.
+ assert config_validation._DATE_OPERATORS == filters_validation.DATE_OPERATORS
+ assert config_validation._STRING_VALUE_OPERATORS == filters_validation.STRING_VALUE_OPERATORS
+ assert config_validation._NUMERIC_COMPARISON_OPERATORS == filters_validation.NUMERIC_COMPARISON_OPERATORS
+ assert config_validation._LIST_VALUE_OPERATORS == filters_validation.LIST_VALUE_OPERATORS
+ assert config_validation._SEMVER_OPERATORS == filters_validation.SEMVER_OPERATORS
+
+ def test_size_check_measures_the_same_bytes_as_the_v1_limit(self) -> None:
+ document = config(targeted(targeting={"properties": [person(value="ø")]}, metadata={"note": "x"}))
+ assert config_size_bytes(document) == calculate_filter_size_bytes(document)
+
+ @parameterized.expand([(entry["fixture_id"], entry) for entry in CONTRACT_FIXTURES if entry["expected"] == "valid"])
+ def test_canonical_fixtures_are_never_relabelled_as_malformed(self, _name: str, entry: dict[str, Any]) -> None:
+ document = load_contract(entry["path"])
+ if _admitted_family(document):
+ validate_config(document, limits=LIMITS)
+ return
+ # Schema-valid documents outside the admitted family are refused for that reason alone.
+ assert {code for code, _ in errors_of(document)} == {"unsupported"}
+
+ @parameterized.expand(
+ [(entry["fixture_id"], entry) for entry in CONTRACT_FIXTURES if entry["expected"] == "invalid"]
+ )
+ def test_schema_invalid_fixtures_are_rejected(self, _name: str, entry: dict[str, Any]) -> None:
+ document = load_contract(entry["path"])
+ errors = errors_of(document)
+ if _admitted_family(document):
+ expected_attr = _contract_path(entry["expected_failure"]["instance_path"], entry["expected_failure"])
+ assert any(code != "unsupported" and attr == expected_attr for code, attr in errors), (
+ errors,
+ expected_attr,
+ )
+ else:
+ assert errors
diff --git a/products/feature_flags/backend/test/test_facade_rule_warnings.py b/products/feature_flags/backend/test/test_facade_rule_warnings.py
new file mode 100644
index 000000000000..f24472e7f7c9
--- /dev/null
+++ b/products/feature_flags/backend/test/test_facade_rule_warnings.py
@@ -0,0 +1,487 @@
+import json
+from copy import deepcopy
+from decimal import Decimal
+from typing import Any, get_args
+
+import pytest
+
+from jsonschema import Draft202012Validator
+from parameterized import parameterized
+
+from products.feature_flags.backend.facade.config_validation import (
+ ConfigValidationError,
+ Predicate,
+ RolloutMissPolicy,
+ ValidatedConfig,
+ ValidatedRule,
+)
+from products.feature_flags.backend.facade.rule_warnings import (
+ ConfigReview,
+ config_warnings,
+ reorder_warnings,
+ review_config,
+)
+from products.feature_flags.backend.facade.warnings import (
+ ManagementWarning,
+ ManagementWarningCode,
+ serialize_management_warning,
+)
+from products.feature_flags.backend.test.test_facade_config_validation import LIMITS, load_contract
+
+A = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+B = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+C = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+D = "dddddddd-dddd-4ddd-8ddd-dddddddddddd"
+SEED = "release-preview"
+OTHER_SEED = "second-seed"
+
+PRO = Predicate(key="plan", operator="exact", value='"pro"', negation=False)
+FREE = Predicate(key="plan", operator="exact", value='"free"', negation=False)
+NORWAY = Predicate(key="country", operator="exact", value='"NO"', negation=False)
+PLAN_SET = Predicate(key="plan", operator="is_set", value="null", negation=False)
+PLAN_NOT_SET = Predicate(key="plan", operator="is_not_set", value='"ignored"', negation=False)
+PLAN_SET_NEGATED = Predicate(key="plan", operator="is_set", value="null", negation=True)
+COUNTRY_NOT_SET = Predicate(key="country", operator="is_not_set", value="null", negation=False)
+
+
+def targeted(rule_id: str, value: bool = True, *predicates: Predicate) -> ValidatedRule:
+ return ValidatedRule(id=rule_id, rule_type="targeted_release", predicates=frozenset(predicates), value=value)
+
+
+def rollout(
+ rule_id: str,
+ percentage: int | float | str,
+ value: bool = True,
+ *predicates: Predicate,
+ seed: str = SEED,
+ miss: RolloutMissPolicy = "continue",
+) -> ValidatedRule:
+ return ValidatedRule(
+ id=rule_id,
+ rule_type="percentage_rollout",
+ predicates=frozenset(predicates),
+ value=value,
+ rollout_percentage=Decimal(str(percentage)),
+ on_rollout_miss=miss,
+ seed=seed,
+ )
+
+
+def cfg(*rules: ValidatedRule, default: bool | None = False) -> ValidatedConfig:
+ return ValidatedConfig(default_value=default, rules=rules)
+
+
+def codes(warnings: tuple[ManagementWarning, ...]) -> list[tuple[str, str | None]]:
+ return [(warning.code, warning.attr) for warning in warnings]
+
+
+def text(warning: ManagementWarning) -> str:
+ assert warning.detail is not None
+ return warning.detail
+
+
+UNREACHABLE = "UNREACHABLE_LOWER_RULE"
+EXTENDS = "ROLLOUT_MISS_CAN_ENTER_LOWER_RULE"
+REORDER = "RULE_ORDER_CHANGES_TRAFFIC"
+
+
+class TestConfigWarnings:
+ @parameterized.expand(
+ [
+ (
+ "targeted_catch_all_blocks_lower",
+ cfg(targeted(A), targeted(B, False)),
+ [(UNREACHABLE, "filters.rules[1]")],
+ ),
+ (
+ "return_default_catch_all_is_terminal",
+ cfg(rollout(A, 25, miss="return_default"), targeted(B)),
+ [(UNREACHABLE, "filters.rules[1]")],
+ ),
+ (
+ "zero_percent_return_default_is_terminal",
+ cfg(rollout(A, 0, miss="return_default"), targeted(B)),
+ [(UNREACHABLE, "filters.rules[1]")],
+ ),
+ (
+ "hundred_percent_continue_is_terminal",
+ cfg(rollout(A, 100), rollout(B, 50, seed=OTHER_SEED)),
+ [(UNREACHABLE, "filters.rules[1]")],
+ ),
+ (
+ "wider_terminal_rule_blocks_narrower",
+ cfg(targeted(A, True, PRO), targeted(B, False, PRO, NORWAY)),
+ [(UNREACHABLE, "filters.rules[1]")],
+ ),
+ (
+ "same_seed_rules_close_the_hash_space",
+ cfg(rollout(A, 60), rollout(B, 40, False, seed=SEED, miss="return_default"), targeted(C)),
+ [(UNREACHABLE, "filters.rules[2]")],
+ ),
+ (
+ "every_lower_rule_is_reported",
+ cfg(targeted(A), targeted(B), targeted(C, False)),
+ [(UNREACHABLE, "filters.rules[1]"), (UNREACHABLE, "filters.rules[2]")],
+ ),
+ ("continuing_partial_rollout_is_not_terminal", cfg(rollout(A, 99, False), targeted(B)), []),
+ ("conditional_rule_is_not_a_catch_all", cfg(targeted(A, True, PRO), targeted(B, False)), []),
+ (
+ "narrower_terminal_rule_does_not_block_wider",
+ cfg(targeted(A, True, PRO, NORWAY), targeted(B, False, PRO)),
+ [],
+ ),
+ (
+ "same_seed_no_op_rule_keeps_lower_reachable",
+ cfg(rollout(A, 50), rollout(B, 50, False), targeted(C, False)),
+ [],
+ ),
+ ("zero_percent_continue_is_a_no_op", cfg(rollout(A, 0), targeted(B)), []),
+ (
+ "catch_all_does_not_explain_impossible_lower_population",
+ cfg(targeted(A, False), targeted(B, True, PLAN_SET, PLAN_NOT_SET)),
+ [],
+ ),
+ ]
+ )
+ def test_unreachable_lower_rule(self, _name: str, config: ValidatedConfig, expected: list[tuple[str, str]]) -> None:
+ assert codes(config_warnings(config)) == expected
+
+ def test_unreachable_warning_identifies_the_blocking_rule(self) -> None:
+ (warning,) = config_warnings(cfg(rollout(A, 50, False), targeted(B), targeted(C)))
+ assert warning.attr == "filters.rules[2]"
+ assert C in text(warning) and B in text(warning) and A not in text(warning)
+
+ @parameterized.expand(
+ [
+ ("catch_all_true_after_partial_true", cfg(rollout(A, 25), targeted(B)), [(EXTENDS, "filters.rules[1]")]),
+ (
+ "other_seed_percentage_extends",
+ cfg(rollout(A, 25), rollout(B, 50, seed=OTHER_SEED)),
+ [(EXTENDS, "filters.rules[1]")],
+ ),
+ (
+ "same_seed_higher_percentage_extends",
+ cfg(rollout(A, 25), rollout(B, 50)),
+ [(EXTENDS, "filters.rules[1]")],
+ ),
+ (
+ "two_decimal_boundary_extends",
+ cfg(rollout(A, "33.33"), rollout(B, "33.34")),
+ [(EXTENDS, "filters.rules[1]")],
+ ),
+ (
+ "narrower_lower_rule_overlaps",
+ cfg(rollout(A, 25), targeted(B, True, PRO)),
+ [(EXTENDS, "filters.rules[1]")],
+ ),
+ ("wider_lower_rule_overlaps", cfg(rollout(A, 25, True, PRO), targeted(B)), [(EXTENDS, "filters.rules[1]")]),
+ (
+ "continuing_intervening_rule_does_not_block",
+ cfg(rollout(A, 25), rollout(B, 50, False, seed=OTHER_SEED), targeted(C)),
+ [(EXTENDS, "filters.rules[2]")],
+ ),
+ (
+ "unrelated_intervening_terminal_rule_is_inconclusive",
+ cfg(rollout(A, 25), targeted(B, False, FREE), targeted(C, True, PRO)),
+ [],
+ ),
+ (
+ "each_extending_pair_is_reported_once",
+ cfg(rollout(A, 25), targeted(B), targeted(C)),
+ [(UNREACHABLE, "filters.rules[2]"), (EXTENDS, "filters.rules[1]")],
+ ),
+ (
+ "two_rollouts_each_extend_into_the_same_lower_rule",
+ cfg(rollout(A, 25), rollout(B, 40, seed=OTHER_SEED), targeted(C)),
+ [(EXTENDS, "filters.rules[1]"), (EXTENDS, "filters.rules[2]"), (EXTENDS, "filters.rules[2]")],
+ ),
+ ("lower_rule_serves_another_value", cfg(rollout(A, 25), targeted(B, False)), []),
+ ("same_seed_equal_percentage_cannot_extend", cfg(rollout(A, 25), rollout(B, 25)), []),
+ ("same_seed_lower_percentage_cannot_extend", cfg(rollout(A, 25), rollout(B, 10)), []),
+ ("same_seed_equal_two_decimal_boundary", cfg(rollout(A, "33.33"), rollout(B, "33.33")), []),
+ ("zero_percent_lower_rule_serves_nobody", cfg(rollout(A, 25), rollout(B, 0, seed=OTHER_SEED)), []),
+ (
+ "terminal_miss_never_continues",
+ cfg(rollout(A, 25, miss="return_default"), targeted(B)),
+ [(UNREACHABLE, "filters.rules[1]")],
+ ),
+ ("full_rollout_never_misses", cfg(rollout(A, 100), targeted(B)), [(UNREACHABLE, "filters.rules[1]")]),
+ ("zero_rollout_serves_nobody_to_extend", cfg(rollout(A, 0), targeted(B)), []),
+ (
+ "impossible_upper_population_has_no_rollout_to_extend",
+ cfg(rollout(A, 25, True, PLAN_SET, PLAN_NOT_SET), targeted(B)),
+ [],
+ ),
+ (
+ "impossible_lower_population_cannot_extend_rollout",
+ cfg(rollout(A, 25), targeted(B, True, PLAN_SET, PLAN_NOT_SET)),
+ [],
+ ),
+ (
+ "negated_presence_spells_the_same_impossible_population",
+ cfg(rollout(A, 25), targeted(B, True, PLAN_SET, PLAN_SET_NEGATED)),
+ [],
+ ),
+ (
+ "presence_checks_on_different_keys_can_extend_rollout",
+ cfg(rollout(A, 25, True, PLAN_SET, COUNTRY_NOT_SET), targeted(B)),
+ [(EXTENDS, "filters.rules[1]")],
+ ),
+ (
+ "terminal_catch_all_between_blocks",
+ cfg(rollout(A, 25), targeted(B, False), targeted(C)),
+ [(UNREACHABLE, "filters.rules[2]")],
+ ),
+ (
+ "conditional_terminal_between_is_inconclusive",
+ cfg(rollout(A, 25), targeted(B, False, PRO), targeted(C)),
+ [],
+ ),
+ ("disjoint_targeting_is_inconclusive", cfg(rollout(A, 25, True, PRO), targeted(B, True, FREE)), []),
+ (
+ "upper_rule_emptied_by_same_seed_predecessor",
+ cfg(rollout(A, 40, False), rollout(B, 30), targeted(C)),
+ [],
+ ),
+ (
+ "same_seed_predecessor_raises_the_reach_threshold",
+ cfg(rollout(A, 25), rollout(B, 60, False), rollout(C, 50)),
+ [],
+ ),
+ ]
+ )
+ def test_rollout_miss_can_enter_lower_rule(
+ self, _name: str, config: ValidatedConfig, expected: list[tuple[str, str]]
+ ) -> None:
+ assert codes(config_warnings(config)) == expected
+
+ # A trailing zero is the shape `Decimal.normalize()` renders as `5E+1`; 33.3 and 25 are not.
+ @parameterized.expand([("two_decimals", "33.3", "33.3%"), ("trailing_zero", 50, "50%")])
+ def test_rollout_miss_warning_explains_the_reach_without_the_seed(
+ self, _name: str, percentage: int | str, rendered: str
+ ) -> None:
+ (warning,) = config_warnings(cfg(rollout(A, percentage), targeted(B)))
+ assert warning.attr == "filters.rules[1]"
+ assert A in text(warning) and B in text(warning) and rendered in text(warning)
+ assert SEED not in text(warning)
+
+ @parameterized.expand(
+ [
+ ("single_rule", cfg(rollout(A, 25))),
+ ("different_values_compose", cfg(rollout(A, 25), rollout(B, 25, False, seed=OTHER_SEED))),
+ (
+ "equal_valued_terminal_rules_after_a_partial_false",
+ cfg(rollout(A, 25, False), targeted(B, True, PRO), targeted(C, True, FREE)),
+ ),
+ ("null_default", cfg(rollout(A, 25, miss="return_default"), default=None)),
+ ]
+ )
+ def test_ordinary_composition_produces_no_warning(self, _name: str, config: ValidatedConfig) -> None:
+ assert config_warnings(config) == ()
+
+
+class TestReorderWarnings:
+ @parameterized.expand(
+ [
+ (
+ "different_values_swap",
+ cfg(targeted(A, True), targeted(B, False)),
+ cfg(targeted(B, False), targeted(A, True)),
+ [(REORDER, "filters.rules[0]")],
+ ),
+ (
+ "conditional_false_moves_above_partial_true",
+ cfg(rollout(A, 50), targeted(B, False, PRO)),
+ cfg(targeted(B, False, PRO), rollout(A, 50)),
+ [(REORDER, "filters.rules[0]")],
+ ),
+ (
+ "terminal_miss_moves_above_targeted",
+ cfg(targeted(A), rollout(B, 25, miss="return_default")),
+ cfg(rollout(B, 25, miss="return_default"), targeted(A)),
+ [(REORDER, "filters.rules[0]")],
+ ),
+ (
+ "terminal_miss_with_null_default_moves_above_targeted",
+ cfg(targeted(A), rollout(B, 25, miss="return_default"), default=None),
+ cfg(rollout(B, 25, miss="return_default"), targeted(A), default=None),
+ [(REORDER, "filters.rules[0]")],
+ ),
+ (
+ "same_seed_different_percentages_and_values",
+ cfg(rollout(A, 25, True), rollout(B, 50, False)),
+ cfg(rollout(B, 50, False), rollout(A, 25, True)),
+ [(REORDER, "filters.rules[0]")],
+ ),
+ (
+ "swap_below_an_unchanged_partial_rule",
+ cfg(rollout(C, 50, False), targeted(A, True), targeted(B, False)),
+ cfg(rollout(C, 50, False), targeted(B, False), targeted(A, True)),
+ [(REORDER, "filters.rules[1]")],
+ ),
+ ("identical_order", cfg(targeted(A), targeted(B, False)), cfg(targeted(A), targeted(B, False)), []),
+ (
+ "impossible_rollout_population_has_no_traffic_to_change",
+ cfg(rollout(A, 25, True, PLAN_SET, PLAN_NOT_SET), targeted(B, False)),
+ cfg(targeted(B, False), rollout(A, 25, True, PLAN_SET, PLAN_NOT_SET)),
+ [],
+ ),
+ ("same_value_swap_is_a_no_op", cfg(targeted(A), targeted(B)), cfg(targeted(B), targeted(A)), []),
+ (
+ "continuing_partial_true_below_targeted_true_is_a_no_op",
+ cfg(targeted(A), rollout(B, 25)),
+ cfg(rollout(B, 25), targeted(A)),
+ [],
+ ),
+ (
+ "same_seed_same_percentage_same_value",
+ cfg(rollout(A, 25), rollout(B, 25)),
+ cfg(rollout(B, 25), rollout(A, 25)),
+ [],
+ ),
+ (
+ "terminal_miss_matching_the_default_is_a_no_op",
+ cfg(targeted(A, False), rollout(B, 25, False, miss="return_default")),
+ cfg(rollout(B, 25, False, miss="return_default"), targeted(A, False)),
+ [],
+ ),
+ (
+ "disjoint_targeting_is_inconclusive",
+ cfg(targeted(A, True, PRO), targeted(B, False, FREE)),
+ cfg(targeted(B, False, FREE), targeted(A, True, PRO)),
+ [],
+ ),
+ (
+ "blocked_by_an_unmoved_terminal_rule",
+ cfg(targeted(C, False), targeted(A), targeted(B, False)),
+ cfg(targeted(C, False), targeted(B, False), targeted(A)),
+ [],
+ ),
+ ("added_rule_is_an_edit_not_a_reorder", cfg(targeted(A)), cfg(targeted(B, False), targeted(A)), []),
+ (
+ "edited_value_in_the_pair_is_an_edit_not_a_reorder",
+ cfg(targeted(A), targeted(B)),
+ cfg(targeted(B, False), targeted(A)),
+ [],
+ ),
+ (
+ "edited_targeting_in_the_pair_is_an_edit_not_a_reorder",
+ cfg(targeted(A), targeted(B, False, PRO)),
+ cfg(targeted(B, False, PRO), targeted(A, True, FREE)),
+ [],
+ ),
+ (
+ "edited_default_behind_a_terminal_miss_is_an_edit_not_a_reorder",
+ cfg(targeted(A, False), rollout(B, 25, False, miss="return_default"), default=False),
+ cfg(rollout(B, 25, False, miss="return_default"), targeted(A, False), default=True),
+ [],
+ ),
+ (
+ "edited_default_does_not_hide_a_served_value_change",
+ cfg(targeted(A, False), rollout(B, 25, True, miss="return_default"), default=False),
+ cfg(rollout(B, 25, True, miss="return_default"), targeted(A, False), default=True),
+ [(REORDER, "filters.rules[0]")],
+ ),
+ (
+ "edited_seed_in_the_pair_is_an_edit_not_a_reorder",
+ cfg(rollout(A, 50), targeted(B, False)),
+ cfg(targeted(B, False), rollout(A, 50, seed=OTHER_SEED)),
+ [],
+ ),
+ ("removed_rule_is_an_edit_not_a_reorder", cfg(targeted(B, False), targeted(A)), cfg(targeted(A)), []),
+ ]
+ )
+ def test_rule_order_changes_traffic(
+ self, _name: str, current: ValidatedConfig, proposed: ValidatedConfig, expected: list[tuple[str, str]]
+ ) -> None:
+ assert codes(reorder_warnings(current, proposed)) == expected
+
+ def test_reorder_warning_names_both_rules_and_is_deduplicated(self) -> None:
+ # The same inverted pair is proven for two populations (everyone, and pro accounts) and reported once.
+ current = cfg(targeted(A), targeted(B, False), targeted(D, False, PRO))
+ proposed = cfg(targeted(B, False), targeted(A), targeted(D, False, PRO))
+ warnings = reorder_warnings(current, proposed)
+ assert codes(warnings) == [(REORDER, "filters.rules[0]")]
+ assert A in text(warnings[0]) and B in text(warnings[0]) and D not in text(warnings[0])
+ assert warnings == reorder_warnings(current, proposed)
+
+ def test_reorder_below_a_blocking_rule_is_not_a_traffic_change(self) -> None:
+ # A blocks B for pro accounts in both orders, so only the pair with the catch-all is reported.
+ current = cfg(targeted(A, True, PRO), targeted(B, False, PRO), targeted(C, False))
+ proposed = cfg(targeted(C, False), targeted(B, False, PRO), targeted(A, True, PRO))
+ (warning,) = reorder_warnings(current, proposed)
+ assert warning.attr == "filters.rules[0]"
+ assert A in text(warning) and C in text(warning) and B not in text(warning)
+
+
+ROLLOUT_DOCUMENT: dict[str, Any] = {
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": False,
+ "rules": [
+ {
+ "id": A,
+ "rule_type": "percentage_rollout",
+ "targeting": {"properties": []},
+ "value": True,
+ "rollout_percentage": 25,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": SEED,
+ },
+ {"id": B, "rule_type": "targeted_release", "targeting": {"properties": []}, "value": True},
+ {"id": C, "rule_type": "targeted_release", "targeting": {"properties": []}, "value": False},
+ ],
+}
+
+
+class TestReviewConfig:
+ def test_validates_then_reports_configuration_warnings(self) -> None:
+ document = deepcopy(ROLLOUT_DOCUMENT)
+ review = review_config(document, limits=LIMITS)
+ assert isinstance(review, ConfigReview)
+ assert [rule.id for rule in review.config.rules] == [A, B, C]
+ assert codes(review.warnings) == [(UNREACHABLE, "filters.rules[2]"), (EXTENDS, "filters.rules[1]")]
+ assert document == ROLLOUT_DOCUMENT
+ assert review == review_config(document, limits=LIMITS)
+
+ def test_without_the_stored_config_no_reorder_is_claimed(self) -> None:
+ review = review_config(
+ {**ROLLOUT_DOCUMENT, "rules": [ROLLOUT_DOCUMENT["rules"][0], ROLLOUT_DOCUMENT["rules"][2]]}, limits=LIMITS
+ )
+ assert review.warnings == ()
+
+ def test_reorder_is_compared_against_the_stored_config(self) -> None:
+ current = review_config(ROLLOUT_DOCUMENT, limits=LIMITS).config
+ reordered = {**ROLLOUT_DOCUMENT, "rules": [ROLLOUT_DOCUMENT["rules"][2], *ROLLOUT_DOCUMENT["rules"][:2]]}
+ review = review_config(reordered, limits=LIMITS, current=current)
+ assert codes(review.warnings) == [
+ (UNREACHABLE, "filters.rules[1]"),
+ (UNREACHABLE, "filters.rules[2]"),
+ (REORDER, "filters.rules[0]"),
+ (REORDER, "filters.rules[0]"),
+ ]
+ assert [text(warning).startswith(f"Moving rule {C} above rule ") for warning in review.warnings[2:]] == [
+ True,
+ True,
+ ]
+
+ def test_invalid_candidate_raises_before_any_warning(self) -> None:
+ with pytest.raises(ConfigValidationError):
+ review_config({**ROLLOUT_DOCUMENT, "default_value": 0}, limits=LIMITS)
+
+
+class TestWarningWire:
+ def test_detector_warnings_serialize_against_the_released_schema_without_seeds(self) -> None:
+ current = review_config(ROLLOUT_DOCUMENT, limits=LIMITS).config
+ reordered = {**ROLLOUT_DOCUMENT, "rules": list(reversed(ROLLOUT_DOCUMENT["rules"]))}
+ warnings = review_config(reordered, limits=LIMITS, current=current).warnings
+ assert {warning.code for warning in warnings} == {UNREACHABLE, REORDER}
+ schema = load_contract("schemas/management_warning.schema.json")
+ assert set(schema["properties"]["code"]["enum"]) == set(get_args(ManagementWarningCode))
+ validator = Draft202012Validator(schema)
+ for warning in warnings:
+ wire = serialize_management_warning(warning)
+ assert set(wire) == {"code", "detail", "attr"}
+ assert not list(validator.iter_errors(wire))
+ assert SEED not in json.dumps(wire)