From 98a5dcc7e09218e5d18cbf66aa4e0d9f3ad3fb2a Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Fri, 27 Nov 2026 19:53:49 +0100 Subject: [PATCH 01/21] feat: add schemas package and datafile sections for modules Datafiles can carry sections beside the SDK's own keys, such as schemas. The SDK now keeps them through every replace and merge, merging a section by entry as segments merge, and datafile_set details list the changed entries of each section. The module API gains getEntry, getEntryKeys and matchConditions. The last answers a package's conditions, as JSON text or trees, with the instance's engine, in one dependency session whose root is the package's entry, and reads leaves only the package knows, such as input, through readers that tell an absent value from null. Readers return MISSING for no value, and the session names a package entry as {type, key}. The new featurevisor.schemas subpackage validates data against those schemas with the rules, messages, mutations and issues of @featurevisor/schemas, and describes fields for forms through handles, with validate and avalidate for checks in code. It passes the 85 cases of conformance/schemas-validation.json twice and matches the JavaScript package on a datafile the CLI built, issues, messages and handle members included. A schema that references itself follows the value, and one that loops fails closed after 128 nested references with schema_reference_depth. --- README.md | 80 + conformance/schemas-validation.json | 2598 +++++++++++++++++ conformance/sdk-sections.json | 941 ++++++ src/featurevisor/_evaluation_session.py | 4 +- src/featurevisor/compare_versions.py | 12 + src/featurevisor/conditions.py | 7 + src/featurevisor/evaluation_data_provider.py | 17 +- src/featurevisor/events.py | 24 + src/featurevisor/instance.py | 111 +- src/featurevisor/schemas/__init__.py | 127 + src/featurevisor/schemas/_derived.py | 189 ++ src/featurevisor/schemas/_engine.py | 610 ++++ src/featurevisor/schemas/_handle.py | 515 ++++ src/featurevisor/schemas/_json.py | 152 + src/featurevisor/schemas/_messages.py | 205 ++ src/featurevisor/schemas/_paths.py | 103 + src/featurevisor/schemas/_patterns.py | 167 ++ src/featurevisor/schemas/_store.py | 229 ++ src/featurevisor/schemas/_types.py | 219 ++ src/featurevisor/schemas/_views.py | 135 + .../schemas/built-datafile-expected.json | 548 ++++ tests/fixtures/schemas/built-datafile.json | 1 + tests/test_module_conditions.py | 98 + tests/test_schemas.py | 215 ++ tests/test_schemas_conformance.py | 112 + tests/test_sdk_sections.py | 76 + tests/test_sdk_stateful.py | 2 + tests/test_set_datafile_result.py | 2 + 28 files changed, 7495 insertions(+), 4 deletions(-) create mode 100644 conformance/schemas-validation.json create mode 100644 conformance/sdk-sections.json create mode 100644 src/featurevisor/schemas/__init__.py create mode 100644 src/featurevisor/schemas/_derived.py create mode 100644 src/featurevisor/schemas/_engine.py create mode 100644 src/featurevisor/schemas/_handle.py create mode 100644 src/featurevisor/schemas/_json.py create mode 100644 src/featurevisor/schemas/_messages.py create mode 100644 src/featurevisor/schemas/_paths.py create mode 100644 src/featurevisor/schemas/_patterns.py create mode 100644 src/featurevisor/schemas/_store.py create mode 100644 src/featurevisor/schemas/_types.py create mode 100644 src/featurevisor/schemas/_views.py create mode 100644 tests/fixtures/schemas/built-datafile-expected.json create mode 100644 tests/fixtures/schemas/built-datafile.json create mode 100644 tests/test_module_conditions.py create mode 100644 tests/test_schemas.py create mode 100644 tests/test_schemas_conformance.py create mode 100644 tests/test_sdk_sections.py diff --git a/README.md b/README.md index 3c1c19d..f7c4bc3 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,10 @@ The package name is `featurevisor`, and it targets Python 3.10+. - [Child instance](#child-instance) - [Close](#close) - [OpenFeature](#openfeature) +- [Schemas](#schemas) + - [Handles](#handles) + - [Messages](#messages) + - [Checks in code](#checks-in-code) - [Installation](#installation-1) - [Provider setup](#provider-setup) - [Flag key mapping](#flag-key-mapping) @@ -589,6 +593,8 @@ remove_module() f.remove_module("my-module") ``` +The API `setup` receives also reads a datafile's sections, the top level keys besides Featurevisor's own whose values are objects, such as `schemas`. `get_entry(section, key)` returns an entry as stored, so treat it as read only, and `get_entry_keys(section)` lists a section's keys. `match_conditions(conditions, context, options)` answers a package's own conditions with the instance's engine, segments and feature leaves included, and `options["readers"]` answer leaves only the package knows, such as `input`, returning `featurevisor.conditions.MISSING` for no value. Feature and variable leaves reach modules as dependencies, with `dependencyOf` naming the package's entry by `type` and `key`. This is how [schemas](#schemas) read their schemas. + ## Child instance A child snapshots the parent keys that exist when it is spawned. Child values win for those keys. Parent keys introduced later are still inherited. Calling `close()` removes both child-owned listeners and subscriptions delegated to the parent. @@ -727,6 +733,80 @@ An invalid initial datafile in an owned instance fails `set_provider_and_wait` w See the [OpenFeature provider guide](https://featurevisor.com/docs/sdks/openfeature/) for resolution reasons, errors, metadata, tracking, lifecycle, and providers for other languages. +## Schemas + +Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/) a datafile carries, such as a sign up form's request, with the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript. They are the `featurevisor.schemas` subpackage, installed with the SDK and needing nothing more: + +```python +from featurevisor import create_featurevisor +from featurevisor.schemas import create_schemas + +f = create_featurevisor({"datafile": datafile}) +s = create_schemas(f) + +result = s.validate("signUp", request) + +if not result.valid: + for issue in result.issues: + print(issue.field, issue.message) +``` + +A value can be dicts, lists, strings, numbers, booleans and `None`, or a dataclass, a pydantic model, a tuple or another mapping or sequence, which is converted first. A `bool` is never a number, although Python makes it an `int`. `parse` returns the value when it passes and raises a `SchemaValidationError` with the issues when it does not. `flatten()` on a result or an error groups the messages by field name, such as `displayName` or `items.0.name`, for an error response. + +Every call reads the current datafile, so a new datafile takes effect at the next validation. A context passed to `validate` is merged over the instance's, for rules that change by segment. + +### Handles + +`s.get("signUp")` returns a schema's handle, and `at(path)` a field's, such as `address.city` or `items[].name`. A handle describes what its rules imply for rendering a form: + +```python +sign_up = s.get("signUp") + +sign_up.field_keys # ["accountType", "displayName", "taxId"], in the schema's order +sign_up.at("displayName").constraints # required, min_length and max_length +sign_up.at("accountType").options # personal and business, with their titles +sign_up.at("accountType").kind # "select" +``` + +`constraints.attributes()` gives them as HTML attributes, such as `required` and `maxlength`, for a template. `with_input(values)` returns the same handle for the values a form has so far, so its members describe the rules every matching mutation sets, such as a VAT number that becomes required for a business account. + +### Messages + +Issues are worded by the form's messages, then the schema's, then the application's, then a default in English: + +```python +s = create_schemas( + f, + messages={"required": "{title} is required"}, + translate=lambda issue, info: translations.get(issue.code), +) +``` + +A message can also be a function of the params and the info. A translator returning `None` keeps the chosen message. + +### Checks in code + +Refinements check what rules cannot express, and option sources check a value against choices from the application. Both run after the rules, only where the rules found nothing: + +```python +from featurevisor.schemas import OptionSource, Refinement + +async def username_is_free(value, info): + return await users.is_free(value) + +sign_up = s.get( + "signUp", + refine=[Refinement("usernameFree", username_is_free, path="username")], + option_sources=[OptionSource("cities", "city", lookup=lambda value, info: cities.find(value))], +) + +result = await sign_up.avalidate(request) +``` + +`avalidate` awaits every check, running them concurrently, and `aparse` is its `parse`. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. A lookup that finds nothing reports `enum`, and a check that raises reports `refineError`. `await handle.search(query)` returns the source's suggestions. + +Handles are safe to use from many threads. `close()` on the instance, or leaving a `with create_schemas(f) as s:` block, stops its subscriptions and removes its module from the Featurevisor instance. + ## CLI usage Install the package in your Python environment: diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json new file mode 100644 index 0000000..d1d6b64 --- /dev/null +++ b/conformance/schemas-validation.json @@ -0,0 +1,2598 @@ +{ + "kind": "featurevisor.schemas-validation", + "schemaVersion": 2, + "cases": [ + { + "name": "a string passes type string", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string" + } + }, + "schema": "subject", + "value": "a", + "issues": [] + }, + { + "name": "a number fails type string", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string" + } + }, + "schema": "subject", + "value": 1, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "integer rejects a fraction", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer" + } + }, + "schema": "subject", + "value": 1.5, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "integer", + "received": "number" + } + } + ] + }, + { + "name": "integer takes a whole number written with a decimal point", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer" + } + }, + "schema": "subject", + "value": 2.0, + "issues": [] + }, + { + "name": "number takes an integer", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number" + } + }, + "schema": "subject", + "value": 3, + "issues": [] + }, + { + "name": "boolean rejects the string true", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "boolean" + } + }, + "schema": "subject", + "value": "true", + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "boolean", + "received": "string" + } + } + ] + }, + { + "name": "null is not an object", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object" + } + }, + "schema": "subject", + "value": null, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "object", + "received": "null" + } + } + ] + }, + { + "name": "an array is not an object", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object" + } + }, + "schema": "subject", + "value": [], + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "object", + "received": "array" + } + } + ] + }, + { + "name": "an object is not an array", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array" + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "array", + "received": "object" + } + } + ] + }, + { + "name": "a type issue stops the node's other keywords", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "minLength": 5 + } + }, + "schema": "subject", + "value": 1, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "const rejects another value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "const": "GB" + } + }, + "schema": "subject", + "value": "NL", + "issues": [ + { + "code": "const", + "path": [], + "params": { + "const": "GB" + } + } + ] + }, + { + "name": "const null takes null", + "schemas": { + "subject": { + "hash": "subject-1", + "const": null + } + }, + "schema": "subject", + "value": null, + "issues": [] + }, + { + "name": "const compares objects by value, in any key order", + "schemas": { + "subject": { + "hash": "subject-1", + "const": { + "a": 1, + "b": [ + 1, + 2 + ] + } + } + }, + "schema": "subject", + "value": { + "b": [ + 1, + 2 + ], + "a": 1 + }, + "issues": [] + }, + { + "name": "const compares arrays in order", + "schemas": { + "subject": { + "hash": "subject-1", + "const": [ + 1, + 2 + ] + } + }, + "schema": "subject", + "value": [ + 2, + 1 + ], + "issues": [ + { + "code": "const", + "path": [], + "params": { + "const": [ + 1, + 2 + ] + } + } + ] + }, + { + "name": "enum rejects an unlisted value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "enum": [ + "GB", + "NL" + ] + } + }, + "schema": "subject", + "value": "BE", + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + "GB", + "NL" + ] + } + } + ] + }, + { + "name": "enum compares numbers numerically", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number", + "enum": [ + 1, + 2 + ] + } + }, + "schema": "subject", + "value": 1.0, + "issues": [] + }, + { + "name": "minimum is inclusive", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer", + "minimum": 1 + } + }, + "schema": "subject", + "value": 1, + "issues": [] + }, + { + "name": "below minimum", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer", + "minimum": 1 + } + }, + "schema": "subject", + "value": 0, + "issues": [ + { + "code": "minimum", + "path": [], + "params": { + "minimum": 1, + "value": 0 + } + } + ] + }, + { + "name": "maximum is inclusive", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number", + "maximum": 10 + } + }, + "schema": "subject", + "value": 10, + "issues": [] + }, + { + "name": "above maximum", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number", + "maximum": 10 + } + }, + "schema": "subject", + "value": 10.5, + "issues": [ + { + "code": "maximum", + "path": [], + "params": { + "maximum": 10, + "value": 10.5 + } + } + ] + }, + { + "name": "too short", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "minLength": 2 + } + }, + "schema": "subject", + "value": "a", + "issues": [ + { + "code": "minLength", + "path": [], + "params": { + "minLength": 2, + "length": 1 + } + } + ] + }, + { + "name": "too long", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "maxLength": 3 + } + }, + "schema": "subject", + "value": "abcd", + "issues": [ + { + "code": "maxLength", + "path": [], + "params": { + "maxLength": 3, + "length": 4 + } + } + ] + }, + { + "name": "lengths count code points, so an emoji with a skin tone is two", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "maxLength": 2 + } + }, + "schema": "subject", + "value": "👋🏽", + "issues": [] + }, + { + "name": "a length over by code points reports code points", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "maxLength": 1 + } + }, + "schema": "subject", + "value": "👋🏽", + "issues": [ + { + "code": "maxLength", + "path": [], + "params": { + "maxLength": 1, + "length": 2 + } + } + ] + }, + { + "name": "a pattern that does not match", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^[A-Z]{2}$" + } + }, + "schema": "subject", + "value": "gb", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^[A-Z]{2}$" + } + } + ] + }, + { + "name": "a pattern without anchors matches anywhere in the string", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "[0-9]" + } + }, + "schema": "subject", + "value": "a1b", + "issues": [] + }, + { + "name": "a timestamp", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "date-time" + } + }, + "schema": "subject", + "value": "2026-01-31T09:00:00Z", + "issues": [] + }, + { + "name": "a date alone is not a timestamp", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "date-time" + } + }, + "schema": "subject", + "value": "2026-01-31", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "date-time" + } + } + ] + }, + { + "name": "a version", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "semver" + } + }, + "schema": "subject", + "value": "1.2.3", + "issues": [] + }, + { + "name": "a version can be short, as the version operators read it", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "semver" + } + }, + "schema": "subject", + "value": "1.2", + "issues": [] + }, + { + "name": "five parts are not a version", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "semver" + } + }, + "schema": "subject", + "value": "1.2.3.4.5", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "semver" + } + } + ] + }, + { + "name": "a version with a trailing newline is not a version", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "semver" + } + }, + "schema": "subject", + "value": "1.0.0\n", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "semver" + } + } + ] + }, + { + "name": "too few items", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "minItems": 1 + } + }, + "schema": "subject", + "value": [], + "issues": [ + { + "code": "minItems", + "path": [], + "params": { + "minItems": 1, + "count": 0 + } + } + ] + }, + { + "name": "too many items", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "maxItems": 2 + } + }, + "schema": "subject", + "value": [ + "a", + "b", + "c" + ], + "issues": [ + { + "code": "maxItems", + "path": [], + "params": { + "maxItems": 2, + "count": 3 + } + } + ] + }, + { + "name": "a repeated item names the first repeat", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "integer" + }, + "uniqueItems": true + } + }, + "schema": "subject", + "value": [ + 1, + 2, + 1 + ], + "issues": [ + { + "code": "uniqueItems", + "path": [], + "params": { + "index": 2 + } + } + ] + }, + { + "name": "repeats compare objects by value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "object", + "properties": { + "a": { + "type": "integer" + } + } + }, + "uniqueItems": true + } + }, + "schema": "subject", + "value": [ + { + "a": 1 + }, + { + "a": 1 + } + ], + "issues": [ + { + "code": "uniqueItems", + "path": [], + "params": { + "index": 1 + } + } + ] + }, + { + "name": "an array without items holds strings", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array" + } + }, + "schema": "subject", + "value": [ + "a", + 1 + ], + "issues": [ + { + "code": "type", + "path": [ + 1 + ], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "each item's issues carry its index", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + }, + "schema": "subject", + "value": [ + 1, + -1, + "x" + ], + "issues": [ + { + "code": "minimum", + "path": [ + 1 + ], + "params": { + "minimum": 0, + "value": -1 + } + }, + { + "code": "type", + "path": [ + 2 + ], + "params": { + "type": "integer", + "received": "string" + } + } + ] + }, + { + "name": "a missing required key is reported at the key", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + } + }, + "required": [ + "email" + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "required", + "path": [ + "email" + ], + "params": { + "key": "email" + } + } + ] + }, + { + "name": "a key named like an inherited property is not present until given", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "constructor": { + "type": "string" + } + }, + "required": [ + "constructor" + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "required", + "path": [ + "constructor" + ], + "params": { + "key": "constructor" + } + } + ] + }, + { + "name": "an unlisted key is reported at the key", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "a": { + "type": "string" + } + } + } + }, + "schema": "subject", + "value": { + "a": "x", + "b": 1 + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "b" + ], + "params": { + "key": "b" + } + } + ] + }, + { + "name": "properties with no keys take no keys", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": {} + } + }, + "schema": "subject", + "value": { + "a": "x" + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "a" + ], + "params": { + "key": "a" + } + } + ] + }, + { + "name": "additionalProperties true takes any other key and value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "a": { + "type": "string" + } + }, + "additionalProperties": true + } + }, + "schema": "subject", + "value": { + "a": "x", + "b": { + "c": [ + 1 + ] + } + }, + "issues": [] + }, + { + "name": "additionalProperties rules every other key's value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "schema": "subject", + "value": { + "en": "Hi", + "nl": 1 + }, + "issues": [ + { + "code": "type", + "path": [ + "nl" + ], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "an object without properties is flat, taking primitive values", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object" + } + }, + "schema": "subject", + "value": { + "a": 1, + "b": "x", + "c": null, + "d": true + }, + "issues": [] + }, + { + "name": "a flat object rejects a nested value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object" + } + }, + "schema": "subject", + "value": { + "a": [ + 1 + ] + }, + "issues": [ + { + "code": "type", + "path": [ + "a" + ], + "params": { + "type": "primitive", + "received": "array" + } + } + ] + }, + { + "name": "nested issues carry the full path", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "address": { + "type": "object", + "properties": { + "city": { + "type": "string", + "minLength": 2 + } + } + } + } + } + }, + "schema": "subject", + "value": { + "address": { + "city": "A" + } + }, + "issues": [ + { + "code": "minLength", + "path": [ + "address", + "city" + ], + "params": { + "minLength": 2, + "length": 1 + } + } + ] + }, + { + "name": "every issue is reported", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "age": { + "type": "integer", + "minimum": 18 + } + }, + "required": [ + "email" + ] + } + }, + "schema": "subject", + "value": { + "age": 12, + "extra": true + }, + "issues": [ + { + "code": "required", + "path": [ + "email" + ], + "params": { + "key": "email" + } + }, + { + "code": "minimum", + "path": [ + "age" + ], + "params": { + "minimum": 18, + "value": 12 + } + }, + { + "code": "additionalProperties", + "path": [ + "extra" + ], + "params": { + "key": "extra" + } + } + ] + }, + { + "name": "a reference validates with the referenced schema, at the field's path", + "schemas": { + "address": { + "hash": "address-1", + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + }, + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "address": { + "schema": "address" + } + } + } + }, + "schema": "subject", + "value": { + "address": {} + }, + "issues": [ + { + "code": "required", + "path": [ + "address", + "city" + ], + "params": { + "key": "city" + } + } + ] + }, + { + "name": "a reference to a schema the section lacks fails closed", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "address": { + "schema": "address" + } + } + } + }, + "schema": "subject", + "value": { + "address": { + "city": "Leiden" + } + }, + "issues": [ + { + "code": "schemaNotFound", + "path": [ + "address" + ], + "params": { + "schema": "address" + } + } + ] + }, + { + "name": "a key the section lacks fails closed", + "schemas": {}, + "schema": "missing", + "value": "x", + "issues": [ + { + "code": "schemaNotFound", + "path": [], + "params": { + "schema": "missing" + } + } + ] + }, + { + "name": "an enum without a type takes its values, whatever their types", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + 1, + "one", + null + ] + } + }, + "schema": "subject", + "value": "one", + "issues": [] + }, + { + "name": "an enum without a type reports enum for any other value", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + 1, + "one", + null + ] + } + }, + "schema": "subject", + "value": true, + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + 1, + "one", + null + ] + } + } + ] + }, + { + "name": "a const without a type compares an object by value", + "schemas": { + "subject": { + "hash": "subject-1", + "const": { + "tier": 2 + } + } + }, + "schema": "subject", + "value": { + "tier": 2 + }, + "issues": [] + }, + { + "name": "a const without a type reports const for another object", + "schemas": { + "subject": { + "hash": "subject-1", + "const": { + "tier": 2 + } + } + }, + "schema": "subject", + "value": { + "tier": 3 + }, + "issues": [ + { + "code": "const", + "path": [], + "params": { + "const": { + "tier": 2 + } + } + } + ] + }, + { + "name": "a nullable value takes null", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "maxLength": 3 + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": null, + "issues": [] + }, + { + "name": "a nullable value's own branch reports its issues", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "maxLength": 3 + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": "abcd", + "issues": [ + { + "code": "maxLength", + "path": [], + "params": { + "maxLength": 3, + "length": 4 + } + } + ] + }, + { + "name": "a value no branch's type takes fails the oneOf", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "maxLength": 3 + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": 1, + "issues": [ + { + "code": "oneOf", + "path": [], + "params": { + "matches": 0 + } + } + ] + }, + { + "name": "an integer branch selected by a fraction reports its type", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + }, + "schema": "subject", + "value": 1.5, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "integer", + "received": "number" + } + } + ] + }, + { + "name": "branches of one type count the matches, and two is too many", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "minLength": 2 + }, + { + "type": "string", + "pattern": "^a" + } + ] + } + }, + "schema": "subject", + "value": "ab", + "issues": [ + { + "code": "oneOf", + "path": [], + "params": { + "matches": 2 + } + } + ] + }, + { + "name": "branches of one type count the matches, and none fails", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "minLength": 2 + }, + { + "type": "string", + "pattern": "^a" + } + ] + } + }, + "schema": "subject", + "value": "b", + "issues": [ + { + "code": "oneOf", + "path": [], + "params": { + "matches": 0 + } + } + ] + }, + { + "name": "branches of one type count the matches, and one passes", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "minLength": 2 + }, + { + "type": "string", + "pattern": "^a" + } + ] + } + }, + "schema": "subject", + "value": "a", + "issues": [] + }, + { + "name": "a oneOf of consts takes one of them", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "const": "free" + }, + { + "const": "pro" + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": null, + "issues": [] + }, + { + "name": "a oneOf of consts reports enum, with its values, as an enum does", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "const": "free" + }, + { + "const": "pro" + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": "gold", + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + "free", + "pro", + null + ] + } + } + ] + }, + { + "name": "an object branch selected by type reports its fields' issues", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "object", + "properties": { + "code": { + "type": "string" + } + }, + "required": [ + "code" + ] + }, + { + "type": "array" + } + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "required", + "path": [ + "code" + ], + "params": { + "key": "code" + } + } + ] + }, + { + "name": "a mutation applies when its input condition matches, and names itself", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ] + }, + "taxId": { + "type": "string" + } + }, + "required": [ + "accountType" + ], + "mutations": [ + { + "key": "business", + "conditions": [ + { + "input": "accountType", + "operator": "equals", + "value": "business" + } + ], + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "accountType": "business" + }, + "issues": [ + { + "code": "required", + "path": [ + "taxId" + ], + "params": { + "key": "taxId" + }, + "mutation": "business" + } + ] + }, + { + "name": "a mutation does not apply when its input condition does not match", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ] + }, + "taxId": { + "type": "string" + } + }, + "required": [ + "accountType" + ], + "mutations": [ + { + "key": "business", + "conditions": [ + { + "input": "accountType", + "operator": "equals", + "value": "business" + } + ], + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "accountType": "personal" + }, + "issues": [] + }, + { + "name": "a mutation reads the context", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 10 + } + }, + "mutations": [ + { + "key": "dutch", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 3 + } + ] + } + ] + } + }, + "schema": "subject", + "context": { + "country": "nl" + }, + "value": { + "name": "Ada L" + }, + "issues": [ + { + "code": "maxLength", + "path": [ + "name" + ], + "params": { + "maxLength": 3, + "length": 5 + }, + "mutation": "dutch" + } + ] + }, + { + "name": "a mutation whose context does not match leaves the base rules", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 10 + } + }, + "mutations": [ + { + "key": "dutch", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 3 + } + ] + } + ] + } + }, + "schema": "subject", + "context": { + "country": "de" + }, + "value": { + "name": "Ada L" + }, + "issues": [] + }, + { + "name": "a mutation reads a segment", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 10 + } + }, + "mutations": [ + { + "key": "paying", + "conditions": "paying", + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 20 + } + ] + } + ] + } + }, + "schema": "subject", + "segments": { + "paying": { + "hash": "paying-1", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "paid" + } + ] + } + }, + "context": { + "plan": "paid" + }, + "value": { + "name": "Grace Brewster " + }, + "issues": [] + }, + { + "name": "every matching mutation applies, in order, and the last to change a rule names its issue", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "mutations": [ + { + "key": "first", + "conditions": [ + { + "input": "name", + "operator": "exists" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 10 + } + ] + }, + { + "key": "second", + "conditions": [ + { + "input": "name", + "operator": "exists" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 5 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "name": "Lovelace" + }, + "issues": [ + { + "code": "maxLength", + "path": [ + "name" + ], + "params": { + "maxLength": 5, + "length": 8 + }, + "mutation": "second" + } + ] + }, + { + "name": "valueFrom compares two inputs", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "mutations": [ + { + "key": "mismatch", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "confirmPassword", + "maxLength" + ], + "value": 0 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "password": "a", + "confirmPassword": "b" + }, + "issues": [ + { + "code": "maxLength", + "path": [ + "confirmPassword" + ], + "params": { + "maxLength": 0, + "length": 1 + }, + "mutation": "mismatch" + } + ] + }, + { + "name": "valueFrom matches nothing when the inputs agree", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "mutations": [ + { + "key": "mismatch", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "confirmPassword", + "maxLength" + ], + "value": 0 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "password": "a", + "confirmPassword": "a" + }, + "issues": [] + }, + { + "name": "an object in value is a value, never a read", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "mutations": [ + { + "key": "mismatch", + "conditions": [ + { + "input": "confirmPassword", + "operator": "equals", + "value": { + "input": "password" + } + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "confirmPassword", + "maxLength" + ], + "value": 0 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "password": "a", + "confirmPassword": "a" + }, + "issues": [] + }, + { + "name": "matches never takes its pattern from valueFrom", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "mutations": [ + { + "key": "mismatch", + "conditions": [ + { + "input": "confirmPassword", + "operator": "matches", + "valueFrom": { + "input": "password" + } + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "confirmPassword", + "maxLength" + ], + "value": 0 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "password": ".*", + "confirmPassword": "anything" + }, + "issues": [] + }, + { + "name": "an issue entry reports when its conditions match", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": "lovelace", + "confirmPassword": "lovelaced" + }, + "issues": [ + { + "code": "refine", + "path": [ + "confirmPassword" + ], + "params": { + "refine": "passwordsDiffer" + } + } + ] + }, + { + "name": "an issue entry reports nothing when its conditions do not match", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": "lovelace", + "confirmPassword": "lovelace" + }, + "issues": [] + }, + { + "name": "an issue of shape holds every issue entry back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "password": "lovelace", + "confirmPassword": "other" + }, + "issues": [ + { + "code": "required", + "path": [ + "email" + ], + "params": { + "key": "email" + } + } + ] + }, + { + "name": "other issues hold no issue entry back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": "short", + "confirmPassword": "other" + }, + "issues": [ + { + "code": "minLength", + "path": [ + "password" + ], + "params": { + "minLength": 8, + "length": 5 + } + }, + { + "code": "refine", + "path": [ + "confirmPassword" + ], + "params": { + "refine": "passwordsDiffer" + } + } + ] + }, + { + "name": "an issue entry guarded by the context reports for matching users", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "shippingCountry": { + "type": "string" + }, + "billingCountry": { + "type": "string" + } + }, + "issues": [ + { + "key": "dutchShipping", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + }, + { + "input": "shippingCountry", + "operator": "notEquals", + "valueFrom": { + "input": "billingCountry" + } + } + ], + "path": "shippingCountry", + "message": "We ship Dutch orders to the billing country only" + } + ] + } + }, + "schema": "subject", + "context": { + "country": "nl" + }, + "value": { + "shippingCountry": "DE", + "billingCountry": "NL" + }, + "issues": [ + { + "code": "refine", + "path": [ + "shippingCountry" + ], + "params": { + "refine": "dutchShipping" + } + } + ] + }, + { + "name": "an issue entry guarded by the context never reports for other users", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "shippingCountry": { + "type": "string" + }, + "billingCountry": { + "type": "string" + } + }, + "issues": [ + { + "key": "dutchShipping", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + }, + { + "input": "shippingCountry", + "operator": "notEquals", + "valueFrom": { + "input": "billingCountry" + } + } + ], + "path": "shippingCountry", + "message": "We ship Dutch orders to the billing country only" + } + ] + } + }, + "schema": "subject", + "context": { + "country": "de" + }, + "value": { + "shippingCountry": "DE", + "billingCountry": "NL" + }, + "issues": [] + }, + { + "name": "input paths are relative to the node a mutation sits on", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "address": { + "schema": "postal" + } + } + }, + "postal": { + "hash": "postal-1", + "type": "object", + "properties": { + "country": { + "type": "string" + }, + "state": { + "type": "string" + } + }, + "mutations": [ + { + "key": "unitedStates", + "conditions": [ + { + "input": "country", + "operator": "equals", + "value": "US" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "required" + ], + "value": [ + "state" + ] + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "address": { + "country": "US" + } + }, + "issues": [ + { + "code": "required", + "path": [ + "address", + "state" + ], + "params": { + "key": "state" + }, + "mutation": "unitedStates" + } + ] + }, + { + "name": "a mutation can change a node's issues, and names the issue they report", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "mutations": [ + { + "key": "paid", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "paid" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "issues" + ], + "value": [ + { + "key": "nowhere", + "conditions": [ + { + "input": "city", + "operator": "equals", + "value": "Nowhere" + } + ], + "path": "city", + "message": "Name a real city" + } + ] + } + ] + } + ] + } + }, + "schema": "subject", + "context": { + "plan": "paid" + }, + "value": { + "city": "Nowhere" + }, + "issues": [ + { + "code": "refine", + "path": [ + "city" + ], + "params": { + "refine": "nowhere" + }, + "mutation": "paid" + } + ] + }, + { + "name": "a timestamp enum still checks the format", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "date-time", + "enum": [ + "soon" + ] + } + }, + "schema": "subject", + "value": "soon", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "date-time" + } + } + ] + }, + { + "name": "a timestamp const still checks the format", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "date-time", + "const": "soon" + } + }, + "schema": "subject", + "value": "soon", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "date-time" + } + } + ] + } + ] +} diff --git a/conformance/sdk-sections.json b/conformance/sdk-sections.json new file mode 100644 index 0000000..7fcfb50 --- /dev/null +++ b/conformance/sdk-sections.json @@ -0,0 +1,941 @@ +{ + "kind": "featurevisor.sdk-sections", + "schemaVersion": 1, + "evaluationCases": [ + { + "name": "a schemas section changes no evaluation", + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "signUp": { + "hash": "signUp-1", + "type": "object", + "properties": { + "email": { + "type": "string" + } + }, + "required": [ + "email" + ] + } + } + }, + "context": { + "userId": "user-1" + }, + "results": [ + { + "method": "isEnabled", + "args": [ + "checkout" + ], + "value": true + }, + { + "method": "getVariation", + "args": [ + "checkout" + ], + "value": "treatment" + }, + { + "method": "getVariable", + "args": [ + "checkout", + "label" + ], + "value": "Pay now" + }, + { + "method": "getVariable", + "args": [ + "banner" + ], + "value": "Hello" + }, + { + "method": "isEnabled", + "args": [ + "off" + ], + "value": false + } + ] + }, + { + "name": "a section of any name, and top level values that are not objects, change no evaluation", + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "signUp": { + "hash": "signUp-1", + "type": "object", + "properties": { + "email": { + "type": "string" + } + }, + "required": [ + "email" + ] + } + }, + "flows": { + "onboarding": { + "hash": "onboarding-1", + "steps": [ + "welcome", + "plan" + ] + } + }, + "note": "kept", + "list": [ + 1, + 2 + ] + }, + "context": { + "userId": "user-1" + }, + "results": [ + { + "method": "isEnabled", + "args": [ + "checkout" + ], + "value": true + }, + { + "method": "getVariation", + "args": [ + "checkout" + ], + "value": "treatment" + }, + { + "method": "getVariable", + "args": [ + "checkout", + "label" + ], + "value": "Pay now" + }, + { + "method": "getVariable", + "args": [ + "banner" + ], + "value": "Hello" + }, + { + "method": "isEnabled", + "args": [ + "off" + ], + "value": false + } + ] + }, + { + "name": "a datafile given as a string with sections evaluates the same", + "datafile": "{\"schemaVersion\":\"4\",\"revision\":\"1\",\"segments\":{},\"features\":{\"checkout\":{\"hash\":\"checkout-1\",\"bucketBy\":\"userId\",\"traffic\":[{\"key\":\"all\",\"conditions\":\"*\",\"percentage\":100000,\"variation\":\"treatment\"}],\"variablesSchema\":{\"label\":{\"type\":\"string\",\"defaultValue\":\"Pay\"}},\"variations\":[{\"value\":\"control\"},{\"value\":\"treatment\",\"variables\":{\"label\":\"Pay now\"}}]},\"off\":{\"hash\":\"off-1\",\"bucketBy\":\"userId\",\"traffic\":[]}},\"variables\":{\"banner\":{\"hash\":\"banner-1\",\"type\":\"string\",\"defaultValue\":\"Hello\"}},\"schemas\":{\"signUp\":{\"hash\":\"signUp-1\",\"type\":\"object\",\"properties\":{\"email\":{\"type\":\"string\"}},\"required\":[\"email\"]}}}", + "context": { + "userId": "user-1" + }, + "results": [ + { + "method": "isEnabled", + "args": [ + "checkout" + ], + "value": true + }, + { + "method": "getVariation", + "args": [ + "checkout" + ], + "value": "treatment" + }, + { + "method": "getVariable", + "args": [ + "checkout", + "label" + ], + "value": "Pay now" + }, + { + "method": "getVariable", + "args": [ + "banner" + ], + "value": "Hello" + }, + { + "method": "isEnabled", + "args": [ + "off" + ], + "value": false + } + ] + }, + { + "name": "a schema 2 datafile with a schemas section evaluates as before", + "datafile": { + "schemaVersion": "2", + "revision": "1", + "segments": {}, + "features": { + "legacy": { + "hash": "legacy-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "segments": "*", + "percentage": 100000 + } + ] + } + }, + "schemas": { + "signUp": { + "hash": "signUp-1", + "type": "object", + "properties": { + "email": { + "type": "string" + } + }, + "required": [ + "email" + ] + } + } + }, + "context": { + "userId": "user-1" + }, + "results": [ + { + "method": "isEnabled", + "args": [ + "legacy" + ], + "value": true + } + ] + } + ], + "carriageCases": [ + { + "name": "a merge keeps every section and merges it by entry, and a replace keeps exactly what came", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "signUp": { + "hash": "s1" + }, + "address": { + "hash": "a1" + } + } + } + }, + "expectInitial": { + "entryKeys": { + "schemas": [ + "signUp", + "address" + ], + "flows": [] + }, + "entries": [ + { + "section": "schemas", + "key": "signUp", + "value": { + "hash": "s1" + } + } + ] + }, + "operations": [ + { + "action": "setDatafile", + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "signUp": { + "hash": "s2" + } + } + }, + "expect": { + "sections": { + "schemas": [ + "signUp" + ] + }, + "entryKeys": { + "schemas": [ + "signUp", + "address" + ] + }, + "entries": [ + { + "section": "schemas", + "key": "signUp", + "value": { + "hash": "s2" + } + }, + { + "section": "schemas", + "key": "address", + "value": { + "hash": "a1" + } + } + ] + } + }, + { + "action": "setDatafile", + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "3", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + }, + "expect": { + "sections": { + "schemas": [] + }, + "entryKeys": { + "schemas": [ + "signUp", + "address" + ] + } + } + }, + { + "action": "setDatafile", + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "4", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "coupon": { + "hash": "c1" + } + } + }, + "expect": { + "sections": { + "schemas": [ + "signUp", + "address", + "coupon" + ] + }, + "entryKeys": { + "schemas": [ + "coupon" + ] + }, + "entries": [ + { + "section": "schemas", + "key": "signUp", + "value": null + } + ] + } + }, + { + "action": "setDatafile", + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "5", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + }, + "expect": { + "sections": { + "schemas": [ + "coupon" + ] + }, + "entryKeys": { + "schemas": [] + } + } + } + ] + }, + { + "name": "datafiles without sections report none", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + } + }, + "expectInitial": { + "entryKeys": { + "schemas": [] + } + }, + "operations": [ + { + "action": "setDatafile", + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + }, + "expect": { + "sections": {} + } + }, + { + "action": "setDatafile", + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "3", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + }, + "expect": { + "sections": {} + } + } + ] + }, + { + "name": "the SDK's own keys and top level values that are not objects are never sections", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "note": "kept", + "list": [ + 1, + 2 + ] + } + }, + "expectInitial": { + "entryKeys": { + "note": [], + "list": [], + "features": [], + "segments": [], + "variables": [] + }, + "entries": [ + { + "section": "features", + "key": "checkout", + "value": null + } + ] + }, + "operations": [] + } + ] +} diff --git a/src/featurevisor/_evaluation_session.py b/src/featurevisor/_evaluation_session.py index 15bad62..b3f5e4a 100644 --- a/src/featurevisor/_evaluation_session.py +++ b/src/featurevisor/_evaluation_session.py @@ -112,13 +112,13 @@ def identity(options: dict[str, Any]) -> tuple[Any, ...]: return (options.get("type"), options.get("featureKey"), options.get("variableKey")) @contextmanager - def frame(self, options: dict[str, Any]) -> Iterator[None]: + def frame(self, options: dict[str, Any], parent: dict[str, Any] | None = None) -> Iterator[None]: identity = self.identity(options) if len(self.active) + len(self.segments) > 256: raise RequirementInputError("Evaluation dependency depth exceeded") if identity in self.active or any(identity == self.identity(current) for current in self.current): raise RequirementInputError("Circular evaluation requirement") - parent = dependency_of(options) + parent = parent if parent is not None else dependency_of(options) self.active.append(identity) self.current.append(parent) try: diff --git a/src/featurevisor/compare_versions.py b/src/featurevisor/compare_versions.py index 19f5adf..a54f870 100644 --- a/src/featurevisor/compare_versions.py +++ b/src/featurevisor/compare_versions.py @@ -1,6 +1,7 @@ from __future__ import annotations import re +from typing import Any SEMVER_REGEX = re.compile( r"^[v^~<>=]*?([0-9]+)(?:\.([x*]|[0-9]+)(?:\.([x*]|[0-9]+)(?:\.([x*]|[0-9]+))?(?:-([0-9a-z\-]+(?:\.[0-9a-z\-]+)*))?(?:\+[0-9a-z\-]+(?:\.[0-9a-z\-]+)*)?)?)?$", @@ -61,3 +62,14 @@ def compare_versions(v1: str, v2: str) -> int: if p1 or p2: return -1 if p1 else 1 return 0 + + +def is_valid_version(version: Any) -> bool: + """Whether the version operators can compare a value, as a schema's format "semver" asks.""" + if not isinstance(version, str): + return False + try: + compare_versions(version, version) + return True + except Exception: + return False diff --git a/src/featurevisor/conditions.py b/src/featurevisor/conditions.py index 6aa6775..be7e9e5 100644 --- a/src/featurevisor/conditions.py +++ b/src/featurevisor/conditions.py @@ -275,3 +275,10 @@ def _value_is_matched( if operator == "notIncludes": return not any(_strict_equal(value, candidate) for candidate in context_value) return False + + +def get_portable_timestamp(value: Any) -> dt.datetime | None: + """A portable timestamp, as before, after and a schema's format "date-time" read + it, to the millisecond, or None: years 0001 to 9999, offsets up to 14 hours, + and fractions up to nine digits.""" + return _to_datetime(value) diff --git a/src/featurevisor/evaluation_data_provider.py b/src/featurevisor/evaluation_data_provider.py index ddadb57..16aa39a 100644 --- a/src/featurevisor/evaluation_data_provider.py +++ b/src/featurevisor/evaluation_data_provider.py @@ -27,6 +27,12 @@ def __init__(self) -> None: self.value: Any = None +# The datafile's own keys, and the tester's helper key. Every other top level key is a section or carried as it is. +DATAFILE_KEYS = frozenset({ + "schemaVersion", "revision", "featurevisorVersion", "segments", "features", "variables", "_segment_test_keys", +}) + + class _InstanceEvaluationDataProvider: def __init__(self, *, datafile: DatafileContent, diagnostics: _EvaluationDiagnostics) -> None: helpers: Any = datafile.get("_segment_test_keys", {}) @@ -38,6 +44,8 @@ def __init__(self, *, datafile: DatafileContent, diagnostics: _EvaluationDiagnos self.segments = datafile.get("segments", {}) self.features = datafile.get("features", {}) self.variables = datafile.get("variables", {}) + # Every other top level key, such as a "schemas" section, kept as the datafile has it. + self.sections = {key: value for key, value in datafile.items() if key not in DATAFILE_KEYS} self.regex_cache: dict[str, re.Pattern[str]] = {} self.expression_cache: dict[str, Any] = {} self.prepared_expression_cache: dict[str, Any] = {} @@ -108,7 +116,14 @@ def get_datafile(self) -> dict[str, Any]: "features": self.features, "variables": self.variables, } - return {key: value for key, value in datafile.items() if value is not None} + result: dict[str, Any] = {key: value for key, value in datafile.items() if value is not None} + result.update(self.sections) + return result + + def get_section(self, name: str) -> dict[str, Any] | None: + """A section by name, such as "schemas": a top level key besides the SDK's own whose value is an object.""" + section = self.sections.get(name) + return section if isinstance(section, dict) else None def get_segment(self, segment_key: str) -> Segment | None: return self._entity("segment", segment_key, self.segments) diff --git a/src/featurevisor/events.py b/src/featurevisor/events.py index d118e84..390c7bb 100644 --- a/src/featurevisor/events.py +++ b/src/featurevisor/events.py @@ -90,3 +90,27 @@ def _entity_changed(previous, current) -> bool: if previous is None or current is None: return True return not previous.get("hash") or not current.get("hash") or previous.get("hash") != current.get("hash") + + +def get_changed_sections(previous_datafile, new_datafile) -> dict[str, list[str]]: + """The changed entries of every section in either datafile, by hash: added, + changed or, on replace, removed. The first datafile reports every entry.""" + names = [name for name, value in previous_datafile.sections.items() if isinstance(value, dict)] + names += [name for name, value in new_datafile.sections.items() if isinstance(value, dict) and name not in names] + sections: dict[str, list[str]] = {} + for name in names: + before = previous_datafile.get_section(name) or {} + after = new_datafile.get_section(name) or {} + if not before: + sections[name] = list(after.keys()) + continue + keys = [ + key for key, entry in before.items() + if key not in after + or not isinstance(entry, dict) or not entry.get("hash") + or not isinstance(after[key], dict) or not after[key].get("hash") + or entry.get("hash") != after[key].get("hash") + ] + keys += [key for key in after if key not in before] + sections[name] = keys + return sections diff --git a/src/featurevisor/instance.py b/src/featurevisor/instance.py index 377f8e6..8bb5102 100644 --- a/src/featurevisor/instance.py +++ b/src/featurevisor/instance.py @@ -13,6 +13,8 @@ from .helpers import get_value_by_type from ._json import strict_json_loads from .conditions import MISSING, value_is_matched, _strict_equal +from .evaluation_data_provider import DATAFILE_KEYS +from .events import get_changed_sections from .normalize import normalize_datafile, InvalidConditions, ConditionsParseFailure from .diagnostics import DEFAULT_LOG_LEVEL, LOG_LEVELS, _EvaluationDiagnostics, should_report, write_diagnostic_to_console from .mutations import _array_index, apply_variable_operations @@ -96,6 +98,7 @@ def set_datafile(self, datafile, replace: bool = False) -> bool: "variable": parsed.get("variables") or {}} new_datafile.retain_entities(previous_datafile, incoming) details = get_params_for_datafile_set_event(previous_datafile, new_datafile, replace, parsed) + details["sections"] = get_changed_sections(previous_datafile, new_datafile) self.datafile = new_datafile self._state_version += 1 for diagnostic in errors: @@ -711,8 +714,103 @@ def unsubscribe() -> None: "on_diagnostic": on_diagnostic, "reportDiagnostic": lambda diagnostic: self.report_diagnostic(diagnostic, module), "report_diagnostic": lambda diagnostic: self.report_diagnostic(diagnostic, module), + "getEntry": self._get_entry, + "get_entry": self._get_entry, + "getEntryKeys": self._get_entry_keys, + "get_entry_keys": self._get_entry_keys, + "matchConditions": lambda conditions, context=None, options=None: self._match_package_conditions(conditions, context, options, module), + "match_conditions": lambda conditions, context=None, options=None: self._match_package_conditions(conditions, context, options, module), } + def _get_entry(self, section: str, key: str) -> Any: + """An entry of a datafile section, such as ("schemas", "signUp"), as stored, so treat it as read only, or None.""" + entries = self.datafile.get_section(section) + return entries.get(key) if entries is not None else None + + def _get_entry_keys(self, section: str) -> list[str]: + entries = self.datafile.get_section(section) + return list(entries.keys()) if entries is not None else [] + + def _match_package_conditions(self, conditions, context, options, module: FeaturevisorModule) -> bool: + """A package's conditions, answered in one dependency session of their own, + whose feature and variable leaves read as dependencies of the package's entry.""" + options = options or {} + type_ = options.get("type") or module.name or "package" + key = options.get("key") + readers = options.get("readers") or {} + dependencies = self._get_evaluation_dependencies(context or {}) + session = dependencies["_evaluationSession"] + parent = {"type": type_, **({"key": key} if key is not None else {})} + try: + with session.frame({"type": type_, "featureKey": None, "variableKey": key}, parent=parent): + return self._package_conditions_are_matched(conditions, dependencies, readers) + except Exception as error: + self.report_diagnostic({ + "level": "error", "code": "evaluation_error", "message": "matchConditions failed", + "originalError": error, "details": {"type": type_, **({"key": key} if key is not None else {})}, + }, module) + return False + + def _package_conditions_are_matched(self, conditions, dependencies, readers) -> bool: + """A package's conditions, such as a schema mutation's: groups, JSON text and + leaves only the package knows, such as "input", are answered here, and every + other leaf by the instance's engine, in the same session.""" + if isinstance(conditions, str): + if conditions == "*": + return True + text = conditions.lstrip() + # Conditions written as JSON text, as Core writes them by default. A bare segment key stays a key. + if text[:1] in ("{", "[", '"'): + try: + return self._package_conditions_are_matched(strict_json_loads(text), dependencies, readers) + except ValueError: + return False + return self._conditions_are_matched(conditions, dependencies) + if isinstance(conditions, list): + return bool(conditions) and all(self._package_conditions_are_matched(item, dependencies, readers) for item in conditions) + if not isinstance(conditions, dict): + return False + if "attribute" in conditions or "variable" in conditions or "feature" in conditions: + return self._conditions_are_matched(conditions, dependencies) + # A leaf only a package knows, such as "input", is read through the package's reader. + kind = next((name for name in conditions if name in readers), None) + if kind is not None: + return self._reader_leaf_is_matched(conditions, kind, readers, dependencies) + for operator in ("and", "or", "not"): + if operator in conditions: + items = conditions[operator] + if not isinstance(items, list) or not items: + return False + if operator == "or": + return any(self._package_conditions_are_matched(item, dependencies, readers) for item in items) + result = all(self._package_conditions_are_matched(item, dependencies, readers) for item in items) + return not result if operator == "not" else result + return False + + def _reader_leaf_is_matched(self, leaf, kind, readers, dependencies) -> bool: + operator = leaf.get("operator") + if not isinstance(operator, str): + return False + # "value" is always a value. "valueFrom" reads the other side, such as another input. + value = leaf.get("value", MISSING) + if "valueFrom" in leaf: + source = leaf["valueFrom"] + other = next((name for name in source if name in readers), None) if isinstance(source, dict) else None + # A source no reader answers matches nothing, and a pattern read from a value is one nobody reviewed, so it never runs. + if other is None or operator.endswith("atches"): + return False + value = readers[other](source[other]) + actual = readers[kind](leaf[kind]) + if value is MISSING: + # Without a value to compare, JavaScript compares with undefined, which only an absent read equals. + if operator == "equals": + return actual is MISSING + if operator == "notEquals": + return actual is not MISSING + value = None + condition = {"operator": operator, "value": value, "regexFlags": leaf.get("regexFlags", "")} + return value_is_matched(actual, condition, dependencies["datafile"].get_regex) + def clear_module_diagnostic_subscriptions(self, module: FeaturevisorModule) -> None: self.module_diagnostic_subscriptions = [ item for item in self.module_diagnostic_subscriptions if item["moduleId"] != module.id @@ -773,7 +871,7 @@ def _should_report_diagnostic(self, diagnostic_level: str, subscriber_level: str return should_report(subscriber_level, diagnostic_level) def _merge_datafiles(self, previous: dict[str, Any], incoming: dict[str, Any]) -> dict[str, Any]: - return { + merged = { "schemaVersion": incoming.get("schemaVersion"), "revision": incoming.get("revision"), "featurevisorVersion": incoming.get("featurevisorVersion"), @@ -781,6 +879,17 @@ def _merge_datafiles(self, previous: dict[str, Any], incoming: dict[str, Any]) - "features": {**(previous.get("features") or {}), **(incoming.get("features") or {})}, "variables": {**(previous.get("variables") or {}), **(incoming.get("variables") or {})}, } + # Sections merge by entry, as segments do. A top level value that is not an object is replaced whole. + for source in (previous, incoming): + for key, value in source.items(): + if key in DATAFILE_KEYS: + continue + current = merged.get(key) + if source is incoming and isinstance(value, dict) and isinstance(current, dict): + merged[key] = {**current, **value} + else: + merged[key] = value + return merged setLogLevel = set_log_level setDatafile = set_datafile diff --git a/src/featurevisor/schemas/__init__.py b/src/featurevisor/schemas/__init__.py new file mode 100644 index 0000000..8c482e1 --- /dev/null +++ b/src/featurevisor/schemas/__init__.py @@ -0,0 +1,127 @@ +"""Validate data against the schemas a Featurevisor datafile carries. + +The same rules, messages and conditions as @featurevisor/schemas in JavaScript:: + + from featurevisor import create_featurevisor + from featurevisor.schemas import create_schemas + + f = create_featurevisor({"datafile": datafile}) + s = create_schemas(f) + + result = s.validate("signUp", request) + if not result.valid: + return result.flatten() +""" + +from __future__ import annotations + +import threading +from typing import Any, Callable, Mapping, Sequence + +from ._handle import SchemaHandle +from ._store import Store +from ._types import (KINDS, CheckInfo, Constraints, FlattenedIssues, Message, MessageInfo, OptionSource, Refinement, + SchemaIssue, SchemaOption, SchemaValidationError, ValidationResult) + +__all__ = [ + "CheckInfo", + "Constraints", + "FlattenedIssues", + "KINDS", + "Message", + "MessageInfo", + "OptionSource", + "Refinement", + "SchemaHandle", + "SchemaIssue", + "SchemaOption", + "SchemaValidationError", + "Schemas", + "ValidationResult", + "create_schemas", +] + + +class Schemas: + """Validates against the schemas of a Featurevisor instance's datafile. It holds + no copy of them: every handle reads the current datafile when it is used, so a + new datafile takes effect at the next validation.""" + + def __init__(self, f: Any, *, messages: Mapping[str, Message] | None = None, + translate: Callable[[SchemaIssue, MessageInfo], str | None] | None = None) -> None: + self._store = Store(f) + self._messages = dict(messages or {}) + self._translate = translate + self._handles: dict[str, SchemaHandle] = {} + self._listeners: dict[int, Callable[[], None]] = {} + self._next = 0 + self._lock = threading.Lock() + + def get(self, key: str, *, messages: Mapping[str, Mapping[str, Message]] | None = None, + refine: Sequence[Refinement] = (), option_sources: Sequence[OptionSource] = ()) -> SchemaHandle: + """A schema's handle, the same one for the same key, or one with a form's + messages by field path, refinements and option sources.""" + if messages or refine or option_sources: + return SchemaHandle(self, key, {"messages": messages, "refine": list(refine), "option_sources": list(option_sources)}) + with self._lock: + handle = self._handles.get(key) + if handle is None: + handle = self._handles[key] = SchemaHandle(self, key) + return handle + + def validate(self, key: str, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: + return self.get(key).validate(value, context) + + async def avalidate(self, key: str, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: + return await self.get(key).avalidate(value, context) + + def is_valid(self, key: str, value: Any, context: Mapping[str, Any] | None = None) -> bool: + return self.get(key).is_valid(value, context) + + def parse(self, key: str, value: Any, context: Mapping[str, Any] | None = None) -> Any: + """The value, or a SchemaValidationError with the issues found.""" + return self.get(key).parse(value, context) + + def keys(self) -> list[str]: + """The keys of the schemas the datafile carries, sorted.""" + return self._store.keys() + + def has(self, key: str) -> bool: + """Whether the datafile carries a schema.""" + return self._store.entry(key) is not None + + def _listen(self, callback: Callable[[], None]) -> Callable[[], None]: + stop = self._store.f.on("datafile_set", lambda details: callback()) + with self._lock: + listener_id = self._next + self._next += 1 + self._listeners[listener_id] = stop + + def unsubscribe() -> None: + with self._lock: + current = self._listeners.pop(listener_id, None) + if current is not None: + current() + + return unsubscribe + + def close(self) -> None: + """Stops every subscription and removes the module from the Featurevisor instance.""" + with self._lock: + stops = list(self._listeners.values()) + self._listeners.clear() + for stop in stops: + stop() + self._store.close() + + def __enter__(self) -> Schemas: + return self + + def __exit__(self, *exc: Any) -> None: + self.close() + + +def create_schemas(f: Any, *, messages: Mapping[str, Message] | None = None, + translate: Callable[[SchemaIssue, MessageInfo], str | None] | None = None) -> Schemas: + """Schemas for the instance create_featurevisor returns. Pass a child's context to validate instead of a child.""" + return Schemas(f, messages=messages, translate=translate) diff --git a/src/featurevisor/schemas/_derived.py b/src/featurevisor/schemas/_derived.py new file mode 100644 index 0000000..447883d --- /dev/null +++ b/src/featurevisor/schemas/_derived.py @@ -0,0 +1,189 @@ +"""What a handle derives from its node: constraints, choices, kind, field order and annotations.""" + +from __future__ import annotations + +from typing import Any + +from ._engine import Resolver, annotations_of, is_const_list, option_entry, resolve_node +from ._json import is_number, same +from ._types import Constraints, SchemaOption, make_option + + +def non_null_branch(node: dict[str, Any], resolve: Resolver) -> dict[str, Any] | None: + """The branch a nullable field's rules come from: a oneOf whose other branches only allow null.""" + if not isinstance(node.get("oneOf"), list): + return node + branches = [branch for branch in (resolve_node(each, resolve) for each in node["oneOf"]) + if branch is not None and not ("const" in branch and branch["const"] is None)] + return branches[0] if len(branches) == 1 else None + + +def is_object_node(node: dict[str, Any] | None) -> bool: + if not node: + return False + return node.get("type") == "object" or ("type" not in node and isinstance(node.get("properties"), dict)) + + +def takes_null(node: Any, resolve: Resolver, depth: int = 0) -> bool: + """Whether a node takes null: a const null, an enum listing it, or a oneOf branch that does.""" + resolved = resolve_node(node, resolve) + if resolved is None or depth > 64: + return False + if "const" in resolved: + return resolved["const"] is None + if isinstance(resolved.get("enum"), list): + return None in resolved["enum"] + return isinstance(resolved.get("oneOf"), list) and any(takes_null(branch, resolve, depth + 1) for branch in resolved["oneOf"]) + + +def _is_boolean_choice(values: list[Any] | None) -> bool: + return values is not None and any(isinstance(value, bool) for value in values) and all( + isinstance(value, bool) or value is None for value in values) + + +def _empty_fails(rules: dict[str, Any], resolve: Resolver) -> bool: + """Whether an input left empty fails a field's rules, as required tells a browser.""" + if rules.get("type") == "boolean": + return False + if rules.get("type") == "array": + return is_number(rules.get("minItems")) and rules["minItems"] > 0 + values = _values_of(rules, resolve) + return not _is_boolean_choice(values) or not any(value is False for value in values or []) + + +def constraints_of(node: Any, required: bool, resolve: Resolver) -> Constraints: + resolved = resolve_node(node, resolve) + rules = non_null_branch(resolved, resolve) if resolved is not None else None + is_required = required and not takes_null(resolved, resolve) and (rules is None or _empty_fails(rules, resolve)) + if rules is None: + return Constraints(required=is_required) + kind = rules.get("type") + if kind == "string": + return Constraints(required=is_required, + min_length=int(rules["minLength"]) if is_number(rules.get("minLength")) else None, + max_length=int(rules["maxLength"]) if is_number(rules.get("maxLength")) else None) + if kind in ("integer", "number"): + return Constraints(required=is_required, + min=rules["minimum"] if is_number(rules.get("minimum")) else None, + max=rules["maximum"] if is_number(rules.get("maximum")) else None, + step=1 if kind == "integer" else None) + return Constraints(required=is_required, multiple=kind == "array") + + +def field_constraints_of(node: Any, resolve: Resolver) -> dict[str, Constraints]: + """An object's fields' constraints by dot path, nested objects included and lists left to their rows' handles.""" + result: dict[str, Constraints] = {} + + def collect(current: dict[str, Any], prefix: str, depth: int) -> None: + properties = current.get("properties") + if not isinstance(properties, dict) or depth > 64: + return + listed = current.get("required") + required: list[Any] = listed if isinstance(listed, list) else [] + for key, child in properties.items(): + path = prefix + key + result[path] = constraints_of(child, key in required, resolve) + resolved = resolve_node(child, resolve) + if is_object_node(resolved): + collect(resolved, path + ".", depth + 1) # type: ignore[arg-type] + + resolved = resolve_node(node, resolve) + if is_object_node(resolved): + collect(resolved, "", 0) # type: ignore[arg-type] + return result + + +def _choices_of(node: Any, resolve: Resolver, branch: bool = False, depth: int = 0) -> list[SchemaOption] | None: + """A node's choices in the order its rules list them, each as its value with what the schema says about it.""" + resolved = resolve_node(node, resolve) + if resolved is None or depth > 64: + return None + if isinstance(resolved.get("enum"), list): + return [make_option(value, option_entry(resolved, value)) for value in resolved["enum"]] + if "const" in resolved: + return [make_option(resolved["const"], annotations_of(node, resolve) if branch else None)] + if isinstance(resolved.get("oneOf"), list): + # Only a list of choices gives its branches' annotations to the choices. Any other branch's are a field's. + listed = is_const_list(resolved, resolve) + choices: list[SchemaOption] = [] + for each in resolved["oneOf"]: + found = _choices_of(each, resolve, listed, depth + 1) + if found is None: + return None + for option in found: + if not any(same(other.value, option.value) for other in choices): + choices.append(option) + return choices + if resolved.get("type") == "array" and "items" in resolved: + return _choices_of(resolved["items"], resolve, False, depth + 1) + return None + + +def _values_of(node: Any, resolve: Resolver) -> list[Any] | None: + choices = _choices_of(node, resolve) + return None if choices is None else [choice.value for choice in choices] + + +def options_of(node: Any, resolve: Resolver) -> list[SchemaOption]: + return _choices_of(node, resolve) or [] + + +def field_options_of(node: Any, resolve: Resolver) -> dict[str, list[SchemaOption]]: + """An object's fields' choices by dot path, only for fields that list some.""" + result: dict[str, list[SchemaOption]] = {} + + def collect(current: dict[str, Any], prefix: str, depth: int) -> None: + properties = current.get("properties") + if not isinstance(properties, dict) or depth > 64: + return + for key, child in properties.items(): + path = prefix + key + choices = _choices_of(child, resolve) + if choices is not None: + result[path] = choices + resolved = resolve_node(child, resolve) + if is_object_node(resolved): + collect(resolved, path + ".", depth + 1) # type: ignore[arg-type] + + resolved = resolve_node(node, resolve) + if is_object_node(resolved): + collect(resolved, "", 0) # type: ignore[arg-type] + return result + + +def field_keys_of(node: Any, resolve: Resolver) -> list[str]: + """The keys of an object's fields, the ones its order lists first, then the rest as written.""" + resolved = resolve_node(node, resolve) + properties = resolved.get("properties") if resolved else None + if not isinstance(properties, dict): + return [] + keys = list(properties) + order = (annotations_of(node, resolve) or {}).get("order") + first: list[str] = [] + for key in order if isinstance(order, list) else []: + if key in properties and key not in first: + first.append(key) + return first + [key for key in keys if key not in first] + + +def kind_of_field(node: Any, resolve: Resolver, depth: int = 0) -> str | None: + """What a node's rules make a field, or None for a oneOf of shapes.""" + resolved = resolve_node(node, resolve) + if resolved is None or depth > 64: + return None + if isinstance(resolved.get("enum"), list) or "const" in resolved or is_const_list(resolved, resolve): + return "boolean" if _is_boolean_choice(_values_of(resolved, resolve)) else "select" + if isinstance(resolved.get("oneOf"), list): + # A nullable field is what its other branch is. + rules = non_null_branch(resolved, resolve) + return kind_of_field(rules, resolve, depth + 1) if rules is not None else None + kind = resolved.get("type") + if kind == "string": + return {"date-time": "date-time", "semver": "version"}.get(resolved.get("format"), "text") # type: ignore[arg-type] + if kind == "array": + return "multiselect" if kind_of_field(resolved.get("items"), resolve, depth + 1) == "select" else "list" + if kind in ("integer", "number"): + return "number" + if kind == "boolean": + return "boolean" + return "object" if is_object_node(resolved) else None diff --git a/src/featurevisor/schemas/_engine.py b/src/featurevisor/schemas/_engine.py new file mode 100644 index 0000000..4043e04 --- /dev/null +++ b/src/featurevisor/schemas/_engine.py @@ -0,0 +1,610 @@ +"""Compiles schema nodes, as the datafile holds them, into validators: the port of the JavaScript package's engine.""" + +from __future__ import annotations + +import threading +from dataclasses import dataclass, field, replace +from typing import Any, Callable, Mapping, Protocol, Sequence + +from ..compare_versions import is_valid_version +from ..conditions import get_portable_timestamp +from ..mutations import apply_variable_operations +from ._json import ABSENT, is_finite_number, is_integer, is_number, is_primitive, kind_of, same, stringify +from ._messages import Lookup, Scope, Sources, choose_message +from ._patterns import compile_pattern +from ._types import SchemaIssue + + +@dataclass +class Run: + """One validation: where issues go and how they are worded.""" + + schema: str + sources: Sources + translate: Callable[[SchemaIssue, Any], str | None] | None + issues: list[SchemaIssue] = field(default_factory=list) + trial: bool = False + """Counting oneOf branches only notes whether a branch failed, without wording anything.""" + failed: bool = False + shape: int = 0 + """How many issues of shape were found, which hold back the issues of every object around them.""" + depth: int = 0 + """How many references the walk follows at this point, which only a value nested as deep can need.""" + + def trial_run(self) -> Run: + return Run(self.schema, self.sources, self.translate, trial=True, shape=self.shape, depth=self.depth) + + +@dataclass +class Position: + """Where validation is in a value: its path, its message path and the schema messages around it.""" + + path: list[Any] + lookup: Lookup + + +Validator = Callable[[Any, Run, Position], None] + + +class Resolver(Protocol): + def resolve(self, key: str) -> tuple[dict[str, Any], Validator] | None: ... + def node(self, key: str) -> dict[str, Any] | None: ... + def reference_too_deep(self, schema: str) -> None: ... + def match(self, conditions: Any, context: dict[str, Any], input_reader: Callable[[str], Any], schema: str) -> bool: ... + def unsupported_pattern(self, pattern: str) -> None: ... + def mutation_failed(self, schema: str, error: Exception) -> None: ... + + +# References a walk follows inside one another. Only a schema that references itself +# without reading deeper into the value gets this far, so the walk fails closed there. +MAX_REFERENCE_DEPTH = 128 + +SHAPE_CODES = frozenset({"type", "required", "enum", "const", "additionalProperties", "oneOf", "schemaNotFound"}) + + +def report(run: Run, at: Position, code: str, params: dict[str, Any], path: list[Any] | None = None, + lookup: Lookup | None = None, own: str | None = None) -> None: + run.failed = True + if code in SHAPE_CODES: + run.shape += 1 + if run.trial: + return + path = at.path if path is None else path + lookup = at.lookup if lookup is None else lookup + # The field's title, so a message can say {title} is required. + if lookup.title is not None: + params = {**params, "title": lookup.title} + message = choose_message(code, params, path, lookup, run.sources, own) + issue = SchemaIssue(message, tuple(path), code, params, run.schema) + if run.translate is not None: + translated = run.translate(issue, run.sources.info) + if isinstance(translated, str): + issue = replace(issue, message=translated) + run.issues.append(issue) + + +def annotations_of(node: Any, resolve: Resolver, seen: set[str] | None = None) -> dict[str, Any] | None: + """A node's annotations, over those of the schema it references, so the reference's own win.""" + if not isinstance(node, dict): + return None + own = node.get("annotations") if isinstance(node.get("annotations"), dict) else None + schema = node.get("schema") + seen = set() if seen is None else seen + if not isinstance(schema, str) or schema in seen: + return own + seen.add(schema) + referenced = annotations_of(resolve.node(schema), resolve, seen) + if referenced is not None and own is not None: + return {**referenced, **own} + return own if own is not None else referenced + + +def title_of(node: Any, resolve: Resolver) -> str | None: + title = (annotations_of(node, resolve) or {}).get("title") + return title if isinstance(title, str) else None + + +def option_entry(node: dict[str, Any], value: Any) -> dict[str, Any] | None: + """What an enum's options annotation says about one value, keyed by the value, or its JSON text.""" + annotations = node.get("annotations") + options = annotations.get("options") if isinstance(annotations, dict) else None + if not isinstance(options, dict): + return None + entry = options.get(value if isinstance(value, str) else stringify(value)) + return entry if isinstance(entry, dict) else None + + +def _put_titles(params: dict[str, Any], entries: Sequence[Any]) -> None: + titles = [entry.get("title") if isinstance(entry, dict) else None for entry in entries] + if titles and all(isinstance(title, str) for title in titles): + params["titles"] = titles + + +def own_scopes(node: Any, base: int, resolve: Resolver, scopes: list[Scope], seen: set[str] | None = None) -> list[Scope]: + """Schema messages around a field: its own node's, and a referenced schema's root's.""" + if not isinstance(node, dict): + return scopes + if isinstance(node.get("messages"), dict): + scopes.append(Scope(node["messages"], base)) + schema = node.get("schema") + seen = set() if seen is None else seen + if isinstance(schema, str) and schema not in seen: + seen.add(schema) + own_scopes(resolve.node(schema), base, resolve, scopes, seen) + return scopes + + +def resolve_node(node: Any, resolve: Resolver) -> dict[str, Any] | None: + """The node a reference resolves to, through any chain of references.""" + seen: set[str] = set() + current = node + while isinstance(current, dict): + schema = current.get("schema") + if not isinstance(schema, str): + return current + if schema in seen: + return None + seen.add(schema) + current = resolve.node(schema) + return None + + +def _branch_kinds(resolved: dict[str, Any]) -> set[str] | None: + """The kinds of value a branch takes, or None when the branch alone cannot say.""" + if isinstance(resolved.get("oneOf"), list): + return None + kind = resolved.get("type") + if kind: + return {"number" if kind == "integer" else str(kind)} + if "const" in resolved: + return {kind_of(resolved["const"])} + if isinstance(resolved.get("enum"), list): + return {kind_of(option) for option in resolved["enum"]} + return None + + +def is_const_list(node: dict[str, Any], resolve: Resolver) -> bool: + """Whether a node is a oneOf whose every branch is a const, a list of choices like an enum.""" + branches = node.get("oneOf") + return isinstance(branches, list) and bool(branches) and all( + (resolved := resolve_node(branch, resolve)) is not None and "const" in resolved for branch in branches) + + +def _compile_const_list(node: dict[str, Any], resolve: Resolver) -> Validator: + branches = node["oneOf"] + + def validate(value: Any, run: Run, at: Position) -> None: + options = [(resolve_node(branch, resolve) or {}).get("const") for branch in branches] + if not any(same(value, option) for option in options): + params: dict[str, Any] = {"options": options} + _put_titles(params, [annotations_of(branch, resolve) for branch in branches]) + report(run, at, "enum", params) + + return validate + + +def _compile_one_of(node: dict[str, Any], resolve: Resolver) -> Validator: + if is_const_list(node, resolve): + return _compile_const_list(node, resolve) + branch_nodes = node["oneOf"] + branches = [compile_node(branch, resolve) for branch in branch_nodes] + + def validate(value: Any, run: Run, at: Position) -> None: + # The kinds each branch takes, read each time, since a branch's reference can resolve to another schema. + kinds = [] + for branch in branch_nodes: + resolved = resolve_node(branch, resolve) + kinds.append(_branch_kinds(resolved) if resolved is not None else None) + disjoint = all(kind is not None for kind in kinds) and all( + not (kinds[a] & kinds[b]) for a in range(len(kinds)) for b in range(len(kinds)) if a != b) # type: ignore[operator] + if disjoint: + # The value's type selects a branch, whose own issues are the ones reported. + kind = kind_of(value) + for index, kind_set in enumerate(kinds): + if kind in kind_set: # type: ignore[operator] + branches[index](value, run, at) + return + report(run, at, "oneOf", {"matches": 0}) + return + matches = 0 + for branch in branches: + trial = run.trial_run() + branch(value, trial, at) + if not trial.failed: + matches += 1 + if matches != 1: + report(run, at, "oneOf", {"matches": matches}) + + return validate + + +def _number_keyword(node: dict[str, Any], key: str) -> Any: + value = node.get(key) + return value if is_number(value) else None + + +def _compile_string(node: dict[str, Any], resolve: Resolver) -> Validator: + min_length = _number_keyword(node, "minLength") + max_length = _number_keyword(node, "maxLength") + format_ = node.get("format") + source = node.get("pattern") if isinstance(node.get("pattern"), str) else None + pattern = compile_pattern(source) if source is not None else None + + def validate(value: Any, run: Run, at: Position) -> None: + if format_ == "date-time" and get_portable_timestamp(value) is None: + report(run, at, "format", {"format": format_}) + elif format_ == "semver" and not is_valid_version(value): + report(run, at, "format", {"format": format_}) + if min_length is not None or max_length is not None: + length = len(value) + if min_length is not None and length < min_length: + report(run, at, "minLength", {"minLength": min_length, "length": length}) + if max_length is not None and length > max_length: + report(run, at, "maxLength", {"maxLength": max_length, "length": length}) + if source is not None: + if pattern is None: + # A pattern Python cannot compile fails closed, since no value can be shown to match it. + resolve.unsupported_pattern(source) + report(run, at, "pattern", {"pattern": source}) + elif pattern.search(value) is None: + report(run, at, "pattern", {"pattern": source}) + + return validate + + +def _compile_number(node: dict[str, Any]) -> Validator: + minimum = _number_keyword(node, "minimum") + maximum = _number_keyword(node, "maximum") + + def validate(value: Any, run: Run, at: Position) -> None: + if minimum is not None and float(value) < float(minimum): + report(run, at, "minimum", {"minimum": minimum, "value": value}) + if maximum is not None and float(value) > float(maximum): + report(run, at, "maximum", {"maximum": maximum, "value": value}) + + return validate + + +def _compile_array(node: dict[str, Any], resolve: Resolver) -> Validator: + min_items = _number_keyword(node, "minItems") + max_items = _number_keyword(node, "maxItems") + items = compile_node(node["items"], resolve) if "items" in node else None + unique = node.get("uniqueItems") is True + + def validate(value: Any, run: Run, at: Position) -> None: + if min_items is not None and len(value) < min_items: + report(run, at, "minItems", {"minItems": min_items, "count": len(value)}) + if max_items is not None and len(value) > max_items: + report(run, at, "maxItems", {"maxItems": max_items, "count": len(value)}) + if unique: + for index in range(1, len(value)): + if any(same(value[earlier], value[index]) for earlier in range(index)): + report(run, at, "uniqueItems", {"index": index}) + break + mpath = [*at.lookup.mpath, "[]"] + for index, item in enumerate(value): + position = Position([*at.path, index], Lookup(mpath, at.lookup.scopes)) + if items is not None: + items(item, run, position) + elif not isinstance(item, str): + # An array without items holds strings only. + report(run, position, "type", {"type": "string", "received": kind_of(item)}) + + return validate + + +def _compile_object(node: dict[str, Any], resolve: Resolver) -> Validator: + properties = node["properties"] if isinstance(node.get("properties"), dict) else None + compiled = {key: compile_node(property_, resolve) for key, property_ in (properties or {}).items()} + required = [key for key in node.get("required", []) if isinstance(key, str)] if isinstance(node.get("required"), list) else [] + has_additional = "additionalProperties" in node + additional = node.get("additionalProperties") + compiled_additional = compile_node(additional, resolve) if has_additional and additional is not True else None + + def validate(value: Any, run: Run, at: Position) -> None: + if properties is not None: + for key in required: + if key in value: + continue + # A missing key's issue is at the key, worded by the messages for that field, with its title. + mpath = [*at.lookup.mpath, key] + scopes = own_scopes(properties.get(key), len(mpath), resolve, list(at.lookup.scopes)) + report(run, at, "required", {"key": key}, [*at.path, key], + Lookup(mpath, scopes, title_of(properties.get(key), resolve))) + for key, child in value.items(): + if key in compiled: + compiled[key](child, run, Position([*at.path, key], Lookup([*at.lookup.mpath, key], at.lookup.scopes))) + elif additional is True: + continue + elif compiled_additional is not None: + compiled_additional(child, run, Position([*at.path, key], Lookup([*at.lookup.mpath, "*"], at.lookup.scopes))) + elif properties is not None: + # An extra key has no field of its own, so the object that rejects it words its issue, without a title. + report(run, at, "additionalProperties", {"key": key}, [*at.path, key], Lookup(at.lookup.mpath, at.lookup.scopes)) + elif not is_primitive(child): + # Without properties or additionalProperties, an object is flat. + report(run, at, "type", {"type": "primitive", "received": kind_of(child)}, [*at.path, key], + Lookup(at.lookup.mpath, at.lookup.scopes)) + + return validate + + +_TYPE_CHECKS: dict[str, Callable[[Any], bool]] = { + "string": lambda value: isinstance(value, str), + "integer": is_integer, + "number": is_finite_number, + "boolean": lambda value: isinstance(value, bool), + "array": lambda value: isinstance(value, list), + "object": lambda value: isinstance(value, dict), +} + + +def _compile_rules(node: dict[str, Any], resolve: Resolver) -> Validator: + reference = node.get("schema") + if isinstance(reference, str): + def validate_reference(value: Any, run: Run, at: Position) -> None: + if run.depth >= MAX_REFERENCE_DEPTH: + resolve.reference_too_deep(run.schema) + report(run, at, "refineError", {}) + return + target = resolve.resolve(reference) + if target is None: + report(run, at, "schemaNotFound", {"schema": reference}) + return + run.depth += 1 + try: + target[1](value, run, at) + finally: + run.depth -= 1 + return validate_reference + if isinstance(node.get("oneOf"), list): + return _compile_one_of(node, resolve) + # A listed timestamp must still be one, so its typed rules run after the value matches. + typed = _compile_typed(node, resolve) if node.get("format") == "date-time" else None + if "const" in node: + constant = node["const"] + + def validate_const(value: Any, run: Run, at: Position) -> None: + if not same(value, constant): + report(run, at, "const", {"const": constant}) + elif typed is not None: + typed(value, run, at) + return validate_const + if isinstance(node.get("enum"), list): + options = node["enum"] + + def validate_enum(value: Any, run: Run, at: Position) -> None: + if any(same(value, option) for option in options): + if typed is not None: + typed(value, run, at) + return + params: dict[str, Any] = {"options": list(options)} + _put_titles(params, [option_entry(node, option) for option in options]) + report(run, at, "enum", params) + return validate_enum + return _compile_typed(node, resolve) + + +def _compile_typed(node: dict[str, Any], resolve: Resolver) -> Validator: + """A node's rules by its type: the type itself, then the keywords that type takes.""" + kind = node.get("type") if isinstance(node.get("type"), str) else None + check = _TYPE_CHECKS.get(kind) if kind else None + # With a type, only its own keywords can apply, so only they are compiled. + string = _compile_string(node, resolve) if kind in (None, "string") else None + number = _compile_number(node) if kind in (None, "integer", "number") else None + array = _compile_array(node, resolve) if kind in (None, "array") else None + object_ = _compile_object(node, resolve) if kind in (None, "object") else None + + def validate(value: Any, run: Run, at: Position) -> None: + if check is not None and not check(value): + report(run, at, "type", {"type": kind, "received": kind_of(value)}) + return + if isinstance(value, str): + if string is not None: + string(value, run, at) + elif is_number(value): + if number is not None: + number(value, run, at) + elif isinstance(value, list): + if array is not None: + array(value, run, at) + elif isinstance(value, dict): + if object_ is not None: + object_(value, run, at) + + return validate + + +def read_input(value: Any, path: str) -> Any: + """The value at a dot path inside a value, through own keys only, for input leaves, or ABSENT.""" + current = value + for part in path.split("."): + if isinstance(current, dict): + if part not in current: + return ABSENT + current = current[part] + elif isinstance(current, list): + # A list's own keys are its indexes and its length, as JavaScript reads items.0.name. + if part == "length": + current = len(current) + elif part.isdigit() and (part == "0" or not part.startswith("0")) and int(part) < len(current): + current = current[int(part)] + else: + return ABSENT + else: + return ABSENT + return current + + +def _rule_of(rules: Any, path: Sequence[Any], code: str) -> tuple[list[Any], bool]: + """Where the rule an issue reports sits in a node's rules, such as + properties.taxId.pattern, and whether the walk reached it, which it does not + through a reference or a oneOf.""" + # A missing or an extra key is a rule of the object around it. + parent = code in ("required", "additionalProperties") + steps = path[:-1] if parent else path + at: list[Any] = [] + current = rules + for step in steps: + node = current if isinstance(current, dict) else {} + properties = node.get("properties") + if isinstance(step, str) and isinstance(properties, dict) and step in properties: + at += ["properties", step] + current = properties[step] + elif isinstance(step, int) and isinstance(node.get("items"), dict): + at.append("items") + current = node["items"] + elif isinstance(node.get("additionalProperties"), dict): + at.append("additionalProperties") + current = node["additionalProperties"] + else: + return at, False + if code == "required": + at.append("required") + elif code == "additionalProperties": + at += ["properties", path[-1]] + else: + at.append(code) + return at, True + + +def _reaches(operation: Sequence[Any], rule: Sequence[Any], whole: bool) -> bool: + """Whether an operation's path reaches a rule, as a prefix of it or, when the rule was reached, beyond it.""" + for part, step in zip(operation, rule): + # A selector picks an item by its fields, as any item can. + if isinstance(part, dict): + continue + if type(part) is not type(step) or part != step: + return False + return len(operation) <= len(rule) or whole + + +def has_mutations(node: Any) -> bool: + return isinstance(node, dict) and isinstance(node.get("mutations"), list) and bool(node["mutations"]) + + +def matching_mutations(node: dict[str, Any], value: Any, context: dict[str, Any], resolve: Resolver, schema: str) -> str: + """Which of a node's mutations match the value at it, as an id such as "0,2,".""" + # input reads the value at this node, so a mutation in address reads the address's own fields. + reader = lambda path: read_input(value, path) # noqa: E731 + return "".join( + f"{index}," + for index, mutation in enumerate(node["mutations"]) + if resolve.match(mutation.get("conditions") if isinstance(mutation, dict) else None, context, reader, schema) + ) + + +def mutated_rules(node: dict[str, Any], mutation_id: str) -> dict[str, Any]: + """A node's rules with the mutations an id names applied in order, without mutations.""" + rules: Any = {key: value for key, value in node.items() if key != "mutations"} + for index in mutation_id.split(","): + if index: + rules = apply_variable_operations(rules, node["mutations"][int(index)].get("operations")) + if not isinstance(rules, dict): + raise ValueError("Mutations of a schema node must keep it an object") + return rules + + +def _compile_mutations(node: dict[str, Any], resolve: Resolver) -> Validator: + """A node whose rules change under conditions: each value is validated against + the node with every mutation whose conditions match applied, in order. Each + combination of matches compiles once and is kept for the node. An issue whose + rule a matching mutation set or changed names the last such mutation.""" + mutations = node["mutations"] + variants: dict[str, tuple[Validator | None, dict[str, Any], list[int], Exception | None]] = {} + lock = threading.Lock() + + def validate(value: Any, run: Run, at: Position) -> None: + mutation_id = matching_mutations(node, value, run.sources.info.context, resolve, run.schema) + with lock: + variant = variants.get(mutation_id) + if variant is None: + matched = [int(index) for index in mutation_id.split(",") if index] + try: + rules = mutated_rules(node, mutation_id) + variant = (compile_node(rules, resolve), rules, matched, None) + except Exception as refused: # noqa: BLE001 + variant = (None, {}, [], refused) + with lock: + variants[mutation_id] = variant + compiled, rules, matched, failure = variant + if compiled is None: + # Operations the interpreter refuses fail closed: no value can be shown to meet rules nobody can read. + if failure is not None: + resolve.mutation_failed(run.schema, failure) + report(run, at, "refineError", {}) + return + start = len(run.issues) + compiled(value, run, at) + if not matched: + return + for position in range(start, len(run.issues)): + issue = run.issues[position] + # A mutation inside the node applies last, so its claim stands. + if issue.mutation is not None: + continue + rule, whole = _rule_of(rules, issue.path[len(at.path):], issue.code) + for index in reversed(matched): + mutation = mutations[index] + paths = [operation.get("path", []) for operation in mutation.get("operations", []) if isinstance(operation, dict)] + if issue.code == "refine": + sets = any("issues" in path for path in paths) + else: + sets = any(_reaches(path, rule, whole) for path in paths) + if sets: + run.issues[position] = replace(issue, mutation=mutation.get("key")) + break + + return validate + + +def _compile_issues(node: dict[str, Any], rules: Validator, resolve: Resolver) -> Validator: + """An object's issues: after its own rules, unless an issue of shape sits + anywhere inside it, each entry whose conditions match reports its issue at its + path, with that field's title and the messages around it.""" + entries = node["issues"] + + def validate(value: Any, run: Run, at: Position) -> None: + shape = run.shape + rules(value, run, at) + if run.shape != shape or not isinstance(value, dict): + return + reader = lambda path: read_input(value, path) # noqa: E731 + for entry in entries: + if not isinstance(entry, dict) or not resolve.match(entry.get("conditions"), run.sources.info.context, reader, run.schema): + continue + parts = entry["path"].split(".") if entry.get("path") else [] + scopes = list(at.lookup.scopes) + field_node: Any = node + for index, part in enumerate(parts): + properties = (resolve_node(field_node, resolve) or {}).get("properties") + field_node = properties.get(part) if isinstance(properties, dict) else None + own_scopes(field_node, len(at.lookup.mpath) + index + 1, resolve, scopes) + title = title_of(field_node, resolve) if parts else at.lookup.title + report(run, at, "refine", {"refine": entry.get("key")}, [*at.path, *parts], + Lookup([*at.lookup.mpath, *parts], scopes, title, entry.get("message"))) + + return validate + + +def compile_node(node: Any, resolve: Resolver) -> Validator: + """Compiles a schema node into a validator, with its messages and title in scope.""" + if not isinstance(node, dict): + return lambda value, run, at: None + if has_mutations(node): + return _compile_mutations(node, resolve) + own = _compile_rules(node, resolve) + rules = _compile_issues(node, own, resolve) if isinstance(node.get("issues"), list) and node["issues"] else own + messages = node.get("messages") if isinstance(node.get("messages"), dict) else None + annotations = node.get("annotations") + title = annotations.get("title") if isinstance(annotations, dict) and isinstance(annotations.get("title"), str) else None + if messages is None and title is None: + return rules + + def validate(value: Any, run: Run, at: Position) -> None: + scopes = [*at.lookup.scopes, Scope(messages, len(at.lookup.mpath))] if messages is not None else at.lookup.scopes + # A reference's own title wins over the title of the schema it references. + lookup = Lookup(at.lookup.mpath, scopes, at.lookup.title if at.lookup.title is not None else title, at.lookup.own) + rules(value, run, Position(at.path, lookup)) + + return validate diff --git a/src/featurevisor/schemas/_handle.py b/src/featurevisor/schemas/_handle.py new file mode 100644 index 0000000..e703163 --- /dev/null +++ b/src/featurevisor/schemas/_handle.py @@ -0,0 +1,515 @@ +"""A schema's handle, or a field's.""" + +from __future__ import annotations + +import asyncio +import inspect +import threading +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Callable, Mapping, Sequence + +from ._derived import (constraints_of, field_constraints_of, field_keys_of, field_options_of, kind_of_field, + options_of) +from ._engine import Position, Run, Validator, annotations_of, compile_node, report, title_of +from ._json import plain, same +from ._messages import Lookup, Sources, form_messages +from ._paths import ITEMS, Step, format_steps, is_at_or_inside, matches_steps, parse_path, steps_of +from ._store import Walk, locate +from ._types import (CheckInfo, Constraints, Message, MessageInfo, OptionSource, Refinement, SchemaIssue, + SchemaOption, SchemaValidationError, ValidationResult, make_option) +from ._views import adjuster, place, reads_of, resolve_tree + +if TYPE_CHECKING: + from . import Schemas + + +@dataclass(frozen=True) +class _View: + values: Any + context: dict[str, Any] | None + start: int + + +@dataclass(frozen=True) +class _Check: + key: str + message: str | None + kind: str + steps: Sequence[Step] + reads: Sequence[Sequence[Step]] + run: Callable[[Any, CheckInfo], Any] + + +def _reaches(step: Step, own: Step) -> bool: + """Whether a source's step reaches a handle's: [] every index, * every key.""" + if step.kind == "items": + return own.kind in ("items", "index") + if step.kind == "values": + return own.kind in ("values", "key") + if step.kind == "key": + return own.kind == "key" and own.key == step.key + return own.kind == "index" and own.index == step.index + + +def _expand(value: Any, steps: Sequence[Step], path: list[Any], found: list[tuple[list[Any], Any]]) -> list[tuple[list[Any], Any]]: + """The concrete paths a check's steps reach in a value, with the value at each.""" + if not steps: + found.append((path, value)) + return found + step, rest = steps[0], steps[1:] + if step.kind == "items": + if isinstance(value, list): + for index, item in enumerate(value): + _expand(item, rest, [*path, index], found) + elif step.kind == "values": + if isinstance(value, dict): + for key, item in value.items(): + _expand(item, rest, [*path, key], found) + elif step.kind == "index": + if isinstance(value, list) and step.index < len(value): + _expand(value[step.index], rest, [*path, step.index], found) + elif isinstance(value, dict) and step.key in value: + _expand(value[step.key], rest, [*path, step.key], found) + return found + + +def _found(answer: Any) -> bool: + """Whether a lookup found a choice: anything but None and False.""" + return answer is not None and answer is not False + + +class SchemaHandle: + """A schema's handle, or a field's. Everything it does reads the current datafile + when it is used, so one handle stays right for the life of an application.""" + + def __init__(self, schemas: Schemas, key: str, options: Mapping[str, Any] | None = None, + steps: Sequence[Step] = (), view: _View | None = None) -> None: + self._schemas = schemas + self.key = key + """The schema's key, such as "signUp".""" + self._steps = list(steps) + self.path = format_steps(self._steps) + """The field's path in its schema, such as "address.city" or "items[].name", or empty for the schema.""" + self._options = dict(options or {}) + self._form = form_messages(self._options.get("messages")) + self._view = view + self._lock = threading.Lock() + self._handles: dict[str, SchemaHandle] = {} + self._compiled: tuple[Any, Validator, Any, Lookup] | None = None + self._memo: tuple[Any, str, dict[str, Any]] | None = None + + @property + def _store(self): + return self._schemas._store + + @property + def name(self) -> str: + """Its own key in the object it sits in, such as "city", or empty for the schema itself.""" + return self._steps[-1].part if self._steps else "" + + # Validation + + def validate(self, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: + """Validates a value with the rules and the checks in code that answer at + once. A check that is a coroutine function reports refineError here, so + await avalidate where the handle has one.""" + input_ = plain(value) + run = self._run(context) + located = self._apply_rules(input_, run) + checks = self._checks() if located else [] + if not checks: + return ValidationResult(value, tuple(run.issues)) + rule_issues, input_value, info, read_issues = self._check_input(input_, context, run) + issues = list(rule_issues) + for check in checks: + for path, target in _expand(input_, check.steps, [], []): + if self._blocked(path, check, rule_issues, read_issues): + continue + try: + if inspect.iscoroutinefunction(check.run): + raise RuntimeError("A check that answers later cannot be waited for here") + answer = check.run(target, info) + if inspect.isawaitable(answer): + if hasattr(answer, "close"): + answer.close() + raise RuntimeError("A check that answers later cannot be waited for here") + except Exception: # noqa: BLE001 + issues += self._report_check(run, located, "refineError", check, path) + continue + if not self._passes(check, answer): + issues += self._report_check(run, located, "refine" if check.kind == "refine" else "enum", check, path) + return ValidationResult(value, tuple(issues)) + + async def avalidate(self, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: + """Validates a value, awaiting every check in code, which run concurrently. A + cancelled task cancels them.""" + input_ = plain(value) + run = self._run(context) + located = self._apply_rules(input_, run) + checks = self._checks() if located else [] + if not checks: + return ValidationResult(value, tuple(run.issues)) + rule_issues, input_value, info, read_issues = self._check_input(input_, context, run) + jobs: list[tuple[_Check, list[Any], Any]] = [] + for check in checks: + for path, target in _expand(input_, check.steps, [], []): + if not self._blocked(path, check, rule_issues, read_issues): + jobs.append((check, path, target)) + + async def answer(check: _Check, target: Any) -> Any: + result = check.run(target, info) + return await result if inspect.isawaitable(result) else result + + outcomes = await asyncio.gather(*(answer(check, target) for check, _, target in jobs), return_exceptions=True) + issues = list(rule_issues) + for (check, path, _), outcome in zip(jobs, outcomes): + if isinstance(outcome, asyncio.CancelledError): + raise outcome + if isinstance(outcome, BaseException): + issues += self._report_check(run, located, "refineError", check, path) + elif not self._passes(check, outcome): + issues += self._report_check(run, located, "refine" if check.kind == "refine" else "enum", check, path) + return ValidationResult(value, tuple(issues)) + + def validate_rules(self, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: + """The schema's own rules, without checks in code.""" + run = self._run(context) + self._apply_rules(plain(value), run) + return ValidationResult(value, tuple(run.issues)) + + def is_valid(self, value: Any, context: Mapping[str, Any] | None = None) -> bool: + return self.validate(value, context).valid + + def parse(self, value: Any, context: Mapping[str, Any] | None = None) -> Any: + """The value, or a SchemaValidationError with the issues found.""" + result = self.validate(value, context) + if not result.valid: + raise SchemaValidationError(self.key, result.issues) + return value + + async def aparse(self, value: Any, context: Mapping[str, Any] | None = None) -> Any: + result = await self.avalidate(value, context) + if not result.valid: + raise SchemaValidationError(self.key, result.issues) + return value + + @property + def has_checks(self) -> bool: + """Whether the handle has checks in code, which can make validation wait for an answer.""" + return bool(self._checks()) + + @staticmethod + def _passes(check: _Check, answer: Any) -> bool: + return answer is True if check.kind == "refine" else _found(answer) + + def _run(self, given: Mapping[str, Any] | None) -> Run: + # A view's context, with one given to the call merged over it. + merged = dict(given) if given else None + if self._view is not None and self._view.context: + merged = {**self._view.context, **(given or {})} + f = self._store.f + info = MessageInfo(lambda: f.get_context(merged)) + sources = Sources(self._form, self._schemas._messages, info) + return Run(self.key, sources, self._schemas._translate) + + def _locate(self, value: Any, run: Run) -> tuple[Validator, Any, Lookup] | None: + """Where this handle's field sits in its schema, or None when the datafile lacks + it. In a view, the fields around it read the view's values, with the value + being validated in the field's place.""" + store = self._store + root = store.resolve(self.key) + if root is None: + return None + node, validate = root + if not self._steps and self._view is None: + return validate, node, Lookup([]) + if self._view is None: + # A field's node is kept until its schema changes. + version = store.version(self.key) + with self._lock: + compiled = self._compiled + if compiled is not None and compiled[0] == version: + return compiled[1], compiled[2], compiled[3] + field = locate(store, node, self._steps) + if field is None: + return None + entry = (version, compile_node(field.node, store), field.node, Lookup(field.mpath, field.scopes)) + with self._lock: + self._compiled = entry + return entry[1], entry[2], entry[3] + view = self._view + walk = Walk(place(view.values, self._steps[view.start:], value), view.start, + adjuster(store, run.sources.info.context, self.key)) + field = locate(store, node, self._steps, walk=walk) + if field is None: + return None + return compile_node(field.node, store), field.node, Lookup(field.mpath, field.scopes) + + def _apply_rules(self, value: Any, run: Run) -> tuple[Validator, Any, Lookup] | None: + located = self._locate(value, run) + if located is None: + self._store.report_missing(self.key) + params: dict[str, Any] = {"schema": self.key} + if self._steps: + params["field"] = self.path + report(run, Position([], Lookup([])), "schemaNotFound", params) + return None + located[0](value, run, Position([], located[2])) + return located + + def _in_root_view(self) -> bool: + return bool(self._steps) and self._view is not None and self._view.start == 0 + + def _checks(self) -> list[_Check]: + """The checks in code this handle runs, its sources' lookups first, then its refinements, its own or a field's share.""" + checks: list[_Check] = [] + + def add(key: str, message: str | None, kind: str, path: str, reads: Sequence[str], run: Callable[..., Any]) -> None: + owner_steps = parse_path(path) + parsed_reads = [parse_path(read) for read in reads] + if not self._steps: + checks.append(_Check(key, message, kind, owner_steps, parsed_reads, run)) + return + # A field's handle carries the checks at or inside it. One that reads other + # fields needs the whole input, which only a view from the schema's root holds. + if (parsed_reads and not self._in_root_view()) or len(owner_steps) < len(self._steps): + return + if all(_reaches(owner_steps[index], own) for index, own in enumerate(self._steps)): + checks.append(_Check(key, message, kind, owner_steps[len(self._steps):], parsed_reads, run)) + + for source in self._options.get("option_sources") or (): + if source.lookup is not None: + add(source.key, source.message, "lookup", source.path, source.reads, source.lookup) + for refinement in self._options.get("refine") or (): + add(refinement.key, refinement.message, "refine", refinement.path, refinement.reads, refinement.check) + return checks + + def _check_input(self, value: Any, given: Mapping[str, Any] | None, run: Run): + rule_issues = list(run.issues) + # In a view from the root, a field's checks see the whole input with the value in its place, + # as they would validating the schema, and the issues of the fields they read hold them back. + if self._in_root_view(): + input_value = place(self._view.values, self._steps, value) # type: ignore[union-attr] + read_issues = self._root_rule_issues(input_value, given) + else: + input_value = value + read_issues = rule_issues + return rule_issues, input_value, CheckInfo(input_value, run.sources.info.context), read_issues + + @staticmethod + def _blocked(path: list[Any], check: _Check, rule_issues: Sequence[SchemaIssue], read_issues: Sequence[SchemaIssue]) -> bool: + if any(is_at_or_inside(issue.path, path) for issue in rule_issues): + return True + return any(matches_steps(issue.path, read) for read in check.reads for issue in read_issues) + + def _root_rule_issues(self, input_value: Any, given: Mapping[str, Any] | None) -> list[SchemaIssue]: + root = self._store.resolve(self.key) + if root is None: + return [] + run = self._run(given) + run.translate = None + root[1](input_value, run, Position([], Lookup([]))) + return run.issues + + def _report_check(self, run: Run, located, code: str, check: _Check, path: list[Any]) -> list[SchemaIssue]: + _, node, lookup = located + field = locate(self._store, node, steps_of(path), lookup.mpath, lookup.scopes) + if field is not None: + found = Lookup(field.mpath, field.scopes, title_of(field.node, self._store)) + else: + found = Lookup([*lookup.mpath, *(str(part) for part in path)], list(lookup.scopes)) + params = {"refine": check.key} if check.kind == "refine" else {"optionSource": check.key} + reporting = Run(run.schema, run.sources, run.translate) + report(reporting, Position(path, found), code, params, path, found, None if code == "refineError" else check.message) + return reporting.issues + + # Fields + + def at(self, path: str) -> SchemaHandle: + """The handle for a field at a path, such as "address.city", "items[].name" or "labels.*".""" + return self._handle(path, lambda: parse_path(path)) + + def child(self, key: str) -> SchemaHandle: + """The handle for one of an object's fields by its key, the same handle at gives + when the key reads as itself, and its own for a key such as "a.b", "*" or "2024".""" + if key and key[0] not in ".[]*" and not key[0].isdigit() and not any(c in key for c in ".[]"): + return self.at(key) + return self._handle("\x00" + key, lambda: [Step("key", key=key)]) + + def _handle(self, handle_id: str, more: Callable[[], list[Step]]) -> SchemaHandle: + with self._lock: + field = self._handles.get(handle_id) + if field is None: + field = SchemaHandle(self._schemas, self.key, self._options, [*self._steps, *more()], self._view) + self._handles[handle_id] = field + return field + + def with_input(self, input_value: Any, context: Mapping[str, Any] | None = None) -> SchemaHandle: + """The same handle with an input, such as the values a form has so far: its + members describe the rules with every mutation whose conditions match that + input, and the context, applied at every depth.""" + return SchemaHandle(self._schemas, self.key, self._options, self._steps, + _View(plain(input_value), dict(context) if context else None, len(self._steps))) + + # What the rules describe + + def _describe(self, view: _View | None) -> tuple[Any, bool] | None: + store = self._store + root = store.resolve(self.key) + if root is None: + return None + if view is None: + field = locate(store, root[0], self._steps) + return (field.node, field.required) if field is not None else None + adjust = adjuster(store, store.f.get_context(view.context), self.key) + field = locate(store, root[0], self._steps, walk=Walk(view.values, view.start, adjust)) + if field is None: + return None + return resolve_tree(field.node, field.value, adjust, store), field.required + + def _derive(self, kind: str, make: Callable[[Any, bool], Any], otherwise: Any) -> Any: + store = self._store + if store.entry(self.key) is None: + return otherwise + version = store.version(self.key) + revision = store.api["get_revision"]() + with self._lock: + memo = self._memo + if memo is not None and memo[0] == version and memo[1] == revision and kind in memo[2]: + return memo[2][kind] + described = self._describe(self._view) + made = make(described[0] if described else None, described[1] if described else False) + with self._lock: + if self._memo is None or self._memo[0] != version or self._memo[1] != revision: + self._memo = (version, revision, {}) + self._memo[2][kind] = made + return made + + @property + def reads(self) -> list[str]: + """The fields, relative to this handle, that its mutations' and issues' conditions read.""" + return self._derive("reads", lambda node, required: reads_of((self._describe(None) or (None,))[0], self._store), []) + + @property + def annotations(self) -> dict[str, Any]: + """Its annotations, over those of a schema its field references.""" + return self._derive("annotations", lambda node, required: dict(annotations_of(node, self._store) or {}), {}) + + @property + def field_keys(self) -> list[str]: + """The keys of an object's fields, in its order.""" + return self._derive("field_keys", lambda node, required: field_keys_of(node, self._store), []) + + @property + def fields(self) -> list[SchemaHandle]: + """An object's fields' handles, in its order, or none for any other value.""" + return [self.child(key) for key in self.field_keys] + + @property + def constraints(self) -> Constraints: + """The HTML validation attributes its rules imply, with required from the object it sits in.""" + return self._derive("constraints", lambda node, required: constraints_of(node, required, self._store), Constraints()) + + @property + def field_constraints(self) -> dict[str, Constraints]: + """An object's fields' constraints by dot path, such as "address.city".""" + return self._derive("field_constraints", lambda node, required: field_constraints_of(node, self._store), {}) + + @property + def options(self) -> list[SchemaOption]: + """The choices the field allows, in the order its rules list them, empty when it lists none.""" + return self._derive("options", lambda node, required: options_of(node, self._store), []) + + @property + def field_options(self) -> dict[str, list[SchemaOption]]: + """An object's fields' choices by dot path, for the fields that list some.""" + return self._derive("field_options", lambda node, required: field_options_of(node, self._store), {}) + + def option(self, value: Any) -> SchemaOption | None: + """The schema's own choice for a value, or None.""" + value = plain(value) + return next((option for option in self.options if same(option.value, value)), None) + + @property + def kind(self) -> str | None: + """What the rules make the field, such as "text", "select" or "date-time", or None for a oneOf of shapes.""" + return self._derive("kind", lambda node, required: kind_of_field(node, self._store), None) + + # Option sources + + def _source(self, search: bool) -> OptionSource | None: + for source in self._options.get("option_sources") or (): + if (source.search if search else source.lookup) is None: + continue + steps = parse_path(source.path) + exact = len(steps) == len(self._steps) + holder = len(steps) == len(self._steps) + 1 and steps[len(self._steps)] == ITEMS + if (exact or holder) and all(_reaches(steps[index], own) for index, own in enumerate(self._steps)): + return source + return None + + @property + def can_search(self) -> bool: + """Whether an option source suggests choices for this field.""" + return self._source(True) is not None + + async def search(self, query: str, context: Mapping[str, Any] | None = None) -> list[SchemaOption]: + """Suggestions from the field's option source for a query, empty without a source that searches.""" + source = self._source(True) + if source is None: + return [] + answer = source.search(query, self._source_info(context)) # type: ignore[misc] + if inspect.isawaitable(answer): + answer = await answer + if not isinstance(answer, (list, tuple)): + raise TypeError(f"The search of option source {source.key!r} must return a list.") + suggestions = [] + for item in answer: + item = plain(item) + if isinstance(item, dict): + if "value" not in item: + # A dict without a value, such as {id, name}, would vanish from the list unseen. + raise TypeError(f"The search of option source {source.key!r} must return values, or dicts with a value.") + suggestions.append(make_option(item["value"], item)) + else: + suggestions.append(make_option(item, None)) + return suggestions + + async def lookup(self, value: Any, context: Mapping[str, Any] | None = None) -> SchemaOption | None: + """The choice for a value: the schema's own, or else the one the field's option source finds, or None.""" + own = self.option(value) + if own is not None: + return own + source = self._source(False) + if source is None: + return None + value = plain(value) + answer = source.lookup(value, self._source_info(context)) # type: ignore[misc] + if inspect.isawaitable(answer): + answer = await answer + if not _found(answer): + return None + answer = plain(answer) + return make_option(value, answer if isinstance(answer, dict) else None) + + def _source_info(self, given: Mapping[str, Any] | None) -> CheckInfo: + return CheckInfo(self._view.values if self._view else None, self._run(given).sources.info.context) + + # Changes + + def subscribe(self, listener: Callable[[], None]) -> Callable[[], None]: + """Calls back when the datafile changes this handle's schema, until the returned function is called.""" + store = self._store + state = {"version": store.version(self.key)} + + def changed() -> None: + version = store.version(self.key) + if version == state["version"]: + return + state["version"] = version + listener() + + return self._schemas._listen(changed) + + def __repr__(self) -> str: + return f"SchemaHandle({self.key!r}{', ' + repr(self.path) if self.path else ''})" diff --git a/src/featurevisor/schemas/_json.py b/src/featurevisor/schemas/_json.py new file mode 100644 index 0000000..008d502 --- /dev/null +++ b/src/featurevisor/schemas/_json.py @@ -0,0 +1,152 @@ +"""Values as JSON has them, the way the JavaScript package reads them.""" + +from __future__ import annotations + +import dataclasses +import json +import math +from collections.abc import Mapping, Sequence +from typing import Any + +from ..conditions import MISSING + +ABSENT = MISSING + + +def is_number(value: Any) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) + + +def is_finite_number(value: Any) -> bool: + return is_number(value) and math.isfinite(value) + + +def is_integer(value: Any) -> bool: + """A finite number with no fraction, so 2.0 is an integer, as in JavaScript.""" + if not is_finite_number(value): + return False + return isinstance(value, int) or float(value).is_integer() + + +def is_primitive(value: Any) -> bool: + return value is None or isinstance(value, (str, bool)) or is_finite_number(value) + + +def same(first: Any, second: Any) -> bool: + """Deep equality of JSON values: lists item by item, objects key by key in any order, numbers as doubles.""" + if first is None or second is None: + return first is None and second is None + if isinstance(first, bool) or isinstance(second, bool): + return isinstance(first, bool) and isinstance(second, bool) and first == second + if is_number(first) and is_number(second): + return float(first) == float(second) + if isinstance(first, str) and isinstance(second, str): + return first == second + if isinstance(first, list) and isinstance(second, list): + return len(first) == len(second) and all(same(a, b) for a, b in zip(first, second)) + if isinstance(first, dict) and isinstance(second, dict): + return len(first) == len(second) and all(key in second and same(value, second[key]) for key, value in first.items()) + return False + + +def kind_of(value: Any) -> str: + """The kind of a value, as an issue names what it received.""" + if value is None: + return "null" + if isinstance(value, bool): + return "boolean" + if isinstance(value, list): + return "array" + if isinstance(value, dict): + return "object" + if isinstance(value, str): + return "string" + if is_number(value): + number = float(value) + if math.isnan(number): + return "NaN" + if math.isinf(number): + return "Infinity" if number > 0 else "-Infinity" + return "number" + return type(value).__name__.lower() + + +def plain(value: Any, depth: int = 0) -> Any: + """A value as JSON decodes it: dicts with string keys, lists, strings, numbers, + booleans and None. Tuples, other sequences and mappings, dataclasses and + pydantic models are converted, and anything else kept, so an issue names its kind.""" + if value is None or isinstance(value, (str, bool, int, float)): + return value + if depth > 256: + return value + if isinstance(value, dict): + if all(isinstance(key, str) for key in value) and all(_is_plain(item) for item in value.values()): + return value + return {str(key): plain(item, depth + 1) for key, item in value.items()} + if isinstance(value, list): + if all(_is_plain(item) for item in value): + return value + return [plain(item, depth + 1) for item in value] + if dataclasses.is_dataclass(value) and not isinstance(value, type): + return plain(dataclasses.asdict(value), depth + 1) + dump = getattr(value, "model_dump", None) + if callable(dump): + return plain(dump(mode="json"), depth + 1) + if isinstance(value, Mapping): + return {str(key): plain(item, depth + 1) for key, item in value.items()} + if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray)): + return [plain(item, depth + 1) for item in value] + return value + + +def _is_plain(value: Any) -> bool: + if value is None or isinstance(value, (str, bool, int, float)): + return True + if isinstance(value, dict): + return all(isinstance(key, str) for key in value) and all(_is_plain(item) for item in value.values()) + if isinstance(value, list): + return all(_is_plain(item) for item in value) + return False + + +def number_text(value: Any) -> str: + """A number as JavaScript writes it: 2 for 2.0, 0.0001, 1e+21.""" + number = float(value) + if math.isnan(number): + return "NaN" + if math.isinf(number): + return "Infinity" if number > 0 else "-Infinity" + if number == 0: + return "0" + if isinstance(value, int) and abs(value) < 1e21: + return str(value) + magnitude = abs(number) + if magnitude >= 1e21 or magnitude < 1e-6: + mantissa, exponent = repr(number).split("e") if "e" in repr(number) else (f"{number:e}".split("e")) + if mantissa.endswith(".0"): + mantissa = mantissa[:-2] + sign = "-" if exponent.startswith("-") else "+" + return f"{mantissa}e{sign}{int(exponent.lstrip('+-') or '0')}" + if number.is_integer(): + return str(int(number)) + text = repr(number) + if "e" in text: + text = f"{number:.17f}".rstrip("0").rstrip(".") + return text + + +def stringify(value: Any) -> str: + """JSON text as JavaScript's JSON.stringify writes it, for messages.""" + if value is None: + return "null" + if isinstance(value, bool): + return "true" if value else "false" + if is_number(value): + return number_text(value) if math.isfinite(value) else "null" + if isinstance(value, str): + return json.dumps(value, ensure_ascii=False) + if isinstance(value, list): + return "[" + ",".join(stringify(item) for item in value) + "]" + if isinstance(value, dict): + return "{" + ",".join(json.dumps(str(key), ensure_ascii=False) + ":" + stringify(item) for key, item in value.items()) + "}" + return json.dumps(str(value), ensure_ascii=False) diff --git a/src/featurevisor/schemas/_messages.py b/src/featurevisor/schemas/_messages.py new file mode 100644 index 0000000..8ebed86 --- /dev/null +++ b/src/featurevisor/schemas/_messages.py @@ -0,0 +1,205 @@ +"""How issues are worded: the form's messages, then the schema's, then the application's, then the default.""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from typing import Any, Mapping, Sequence + +from ._json import is_number, number_text, stringify +from ._paths import message_path +from ._types import Message, MessageInfo + + +@dataclass(frozen=True) +class Scope: + """A schema's messages, for issues below base, the depth of the node carrying them.""" + + messages: Mapping[str, Any] + base: int + + +@dataclass +class Lookup: + """Where an issue's message is looked for: the field's message path, with [] for + items and * for an open object's values, the schema messages around it, the + field's title and an issue entry's own message.""" + + mpath: list[str] + scopes: list[Scope] = field(default_factory=list) + title: str | None = None + own: str | None = None + + +@dataclass(frozen=True) +class Sources: + """What wording an instance and a form bring, for one validation.""" + + form: Mapping[str, Mapping[str, Message]] + app: Mapping[str, Message] + info: MessageInfo + + +SEPARATOR = "\x1f" + + +def form_messages(messages: Mapping[str, Mapping[str, Message]] | None) -> dict[str, dict[str, Message]]: + by_path: dict[str, dict[str, Message]] = {} + for field_path, codes in (messages or {}).items(): + by_path.setdefault(SEPARATOR.join(message_path(field_path)), {}).update(codes) + return by_path + + +def _navigate(messages: Mapping[str, Any], steps: Sequence[str], start: int) -> Mapping[str, Any] | None: + node: Any = messages + for step in steps[start:]: + if not isinstance(node, dict): + return None + node = node.get(step) + return node if isinstance(node, dict) else None + + +def format_param(value: Any) -> str: + if isinstance(value, list): + return ", ".join(format_param(item) for item in value) + if isinstance(value, str): + return value + if value is None: + return "null" + if isinstance(value, bool): + return "true" if value else "false" + if is_number(value): + return number_text(value) + return stringify(value) + + +_PLACEHOLDER = re.compile(r"\{\{|\}\}|\{([^{}]*)\}") + + +def fill_template(template: str, params: Mapping[str, Any]) -> str: + """Fills {name} from params. Lists are joined with commas, and {{ and }} write braces.""" + + def replace(match: re.Match[str]) -> str: + text = match.group(0) + if text == "{{": + return "{" + if text == "}}": + return "}" + name = match.group(1) + # A name the params lack fills nothing, as undefined does in JavaScript. + return format_param(params[name]) if name in params else "" + + return _PLACEHOLDER.sub(replace, template) + + +def _apply(message: Message, params: Mapping[str, Any], info: MessageInfo) -> str: + return fill_template(message, params) if isinstance(message, str) else message(params, info) + + +_TYPE_NAMES = { + "string": "a string", "integer": "an integer", "number": "a number", "boolean": "a boolean", + "object": "an object", "array": "an array", "primitive": "a string, number, boolean or null", +} + + +def _subject(path: Sequence[Any]) -> str: + return "Value" if not path else "Value at " + json.dumps(".".join(str(part) for part in path), ensure_ascii=False) + + +def _param(params: Mapping[str, Any], name: str) -> str: + return format_param(params[name]) if name in params else "undefined" + + +def _items(count: Any) -> str: + return "item" if is_number(count) and count == 1 else "items" + + +def default_message(code: str, params: Mapping[str, Any], path: Sequence[Any]) -> str: + """The default wording of each issue, in lint's English.""" + at = _subject(path) + if code == "type": + kind = params.get("type") + name = _TYPE_NAMES.get(kind, format_param(kind)) if isinstance(kind, str) else format_param(kind) + return f"{at} must be {name} (got {_param(params, 'received')})." + if code == "const": + return f"{at} must equal {stringify(params.get('const'))}." + if code == "enum": + listed = params.get("titles", params.get("options")) + # An option source's lookup knows no list to name. + if not isinstance(listed, list): + return f"{at} is not one of its choices." + names = [option if isinstance(option, str) else stringify(option) for option in listed] + return f"{at} must be one of {', '.join(names)}." + if code == "minimum": + return f"{at} must be at least {_param(params, 'minimum')} (got {_param(params, 'value')})." + if code == "maximum": + return f"{at} must be at most {_param(params, 'maximum')} (got {_param(params, 'value')})." + if code == "minLength": + return f"{at} must be at least {_param(params, 'minLength')} characters long (got {_param(params, 'length')})." + if code == "maxLength": + return f"{at} must be at most {_param(params, 'maxLength')} characters long (got {_param(params, 'length')})." + if code == "pattern": + return f"{at} does not match the expected pattern." + if code == "format": + if params.get("format") == "date-time": + return f"{at} must be a timestamp such as 2026-01-31T09:00:00Z." + return f"{at} must be a version such as 1.2.3." + if code == "minItems": + return f"{at} must have at least {_param(params, 'minItems')} {_items(params.get('minItems'))} (got {_param(params, 'count')})." + if code == "maxItems": + return f"{at} must have at most {_param(params, 'maxItems')} {_items(params.get('maxItems'))} (got {_param(params, 'count')})." + if code == "uniqueItems": + return f"{at} must not repeat items (item {_param(params, 'index')} repeats an earlier one)." + if code == "required": + return f"{at} is required." + if code == "additionalProperties": + return f"{at} is not allowed." + if code == "oneOf": + if params.get("matches") == 0: + return f"{at} does not match any of the allowed shapes." + return f"{at} must match exactly one of the allowed shapes (matched {_param(params, 'matches')})." + if code == "refine": + return f"{at} is not valid." + if code == "refineError": + return f"{at} could not be checked." + if code == "schemaNotFound": + if "field" in params: + return f"Field {stringify(params['field'])} was not found in schema {stringify(params.get('schema'))}." + return f"Schema {stringify(params.get('schema'))} was not found." + return f"{at} is not valid." + + +_LIST_PLACEHOLDER = re.compile(r"\{(options|titles)\}") + + +def _fits(message: Any, listless: bool) -> bool: + return not listless or not isinstance(message, str) or not _LIST_PLACEHOLDER.search(message) + + +def choose_message(code: str, params: Mapping[str, Any], path: Sequence[Any], lookup: Lookup, + sources: Sources, own_message: str | None = None) -> str: + """The message an issue carries, the first of: a check's own message, the form's + for the field, the schema's from the outside in, an issue entry's own, the + application's for the code, and the default. A message is for the field it + names, never for fields inside it.""" + if own_message is not None: + return fill_template(own_message, params) + # An option source's enum names no list, so a wording that fills one in is passed over. + listless = code == "enum" and "options" not in params and "titles" not in params + form = sources.form.get(SEPARATOR.join(lookup.mpath), {}).get(code) + if form is not None and _fits(form, listless): + return _apply(form, params, sources.info) + for scope in lookup.scopes: + if scope.base > len(lookup.mpath): + continue + messages = _navigate(scope.messages, lookup.mpath, scope.base) + template = messages.get(code) if messages else None + if isinstance(template, str) and _fits(template, listless): + return fill_template(template, params) + if lookup.own is not None and _fits(lookup.own, listless): + return fill_template(lookup.own, params) + app = sources.app.get(code) + if app is not None and _fits(app, listless): + return _apply(app, params, sources.info) + return default_message(code, params, path) diff --git a/src/featurevisor/schemas/_paths.py b/src/featurevisor/schemas/_paths.py new file mode 100644 index 0000000..236b909 --- /dev/null +++ b/src/featurevisor/schemas/_paths.py @@ -0,0 +1,103 @@ +"""Field paths as form libraries write them: address.city, items.0.name, items[].name, labels.*.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any, Sequence + +_INDEX = re.compile(r"(0|[1-9][0-9]{0,8})") + + +@dataclass(frozen=True) +class Step: + """One step of a field path: an object key, an array index, every item ([]), or every value of an open object (*).""" + + kind: str + key: str = "" + index: int = -1 + + @property + def part(self) -> str: + if self.kind == "key": + return self.key + if self.kind == "index": + return str(self.index) + return "[]" if self.kind == "items" else "*" + + +ITEMS = Step("items") +VALUES = Step("values") + + +def _step(text: str) -> Step: + if text == "*": + return VALUES + if _INDEX.fullmatch(text): + return Step("index", index=int(text)) + return Step("key", key=text) + + +def parse_path(path: str) -> list[Step]: + """A number after a dot or in brackets is an index, so items.0 and items[0] are the same.""" + steps: list[Step] = [] + key = "" + index = 0 + while index < len(path): + character = path[index] + if character == ".": + if key: + steps.append(_step(key)) + key = "" + index += 1 + elif character == "[": + if key: + steps.append(_step(key)) + key = "" + end = path.find("]", index) + inside = path[index + 1:] if end == -1 else path[index + 1:end] + if inside == "": + steps.append(ITEMS) + elif inside == "*": + steps.append(VALUES) + elif _INDEX.fullmatch(inside): + steps.append(Step("index", index=int(inside))) + else: + steps.append(Step("key", key=inside.strip("\"'"))) + index = len(path) if end == -1 else end + 1 + else: + key += character + index += 1 + if key: + steps.append(_step(key)) + return steps + + +def format_steps(steps: Sequence[Step]) -> str: + """A handle's path, such as items[].name.""" + return ".".join(step.part for step in steps).replace(".[]", "[]") + + +def message_path(field: str) -> list[str]: + """A field's message path: keys, [] for items and * for an open object's values.""" + return [step.key if step.kind == "key" else "*" if step.kind == "values" else "[]" for step in parse_path(field)] + + +def is_at_or_inside(inner: Sequence[Any], outer: Sequence[Any]) -> bool: + return len(inner) >= len(outer) and all(str(a) == str(b) for a, b in zip(inner, outer)) + + +def matches_steps(path: Sequence[Any], steps: Sequence[Step]) -> bool: + """Whether a concrete path matches a path with [] and * steps, at or inside it.""" + if len(path) < len(steps): + return False + for part, step in zip(path, steps): + if step.kind == "index" and str(part) != str(step.index): + return False + if step.kind == "key" and str(part) != step.key: + return False + return True + + +def steps_of(path: Sequence[Any]) -> list[Step]: + return [Step("index", index=part) if isinstance(part, int) else Step("key", key=str(part)) for part in path] diff --git a/src/featurevisor/schemas/_patterns.py b/src/featurevisor/schemas/_patterns.py new file mode 100644 index 0000000..c6f7fae --- /dev/null +++ b/src/featurevisor/schemas/_patterns.py @@ -0,0 +1,167 @@ +"""Schema patterns, written for JavaScript's RegExp without flags, compiled to mean the same in Python's re. + +Patterns compile with re.ASCII, so \\w, \\d and \\b keep to ASCII as in +JavaScript. Without the rewrites, Python's $ matches before a final line break, +its \\s takes U+001C to U+001F and misses the BOM, its . takes \\r, U+2028 and +U+2029, and it refuses unknown letter escapes such as \\p, which JavaScript reads +as the letter. + +One difference stays: JavaScript without flags reads a string in UTF-16 units, +so ^.$ refuses an emoji there and accepts it here. +""" + +from __future__ import annotations + +import re +import threading + +_SPACES = "\\t\\n\\x0b\\f\\r \\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff" +_NOT_SPACES = ("\\x00-\\x08\\x0e-\\x1f\\x21-\\x9f\\xa1-\\u167f\\u1681-\\u1fff\\u200b-\\u2027\\u202a-\\u202e" + "\\u2030-\\u205e\\u2060-\\u2fff\\u3001-\\ufefe\\uff00-\\U0010ffff") +_NOT_DIGITS = "\\x00-\\x2f\\x3a-\\U0010ffff" +_NOT_WORD = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\U0010ffff" + +_lock = threading.Lock() +_cache: dict[str, re.Pattern[str] | None] = {} + + +def compile_pattern(source: str) -> re.Pattern[str] | None: + """The pattern compiled, or None when Python cannot compile it.""" + with _lock: + if source in _cache: + return _cache[source] + try: + compiled: re.Pattern[str] | None = re.compile(translate(source), re.ASCII) + except (re.error, OverflowError, ValueError): + compiled = None + with _lock: + if len(_cache) < 4096: + _cache[source] = compiled + return compiled + + +def _quantifier_end(source: str, start: int) -> int: + index = start + 1 + digits = 0 + while index < len(source) and source[index].isascii() and source[index].isdigit(): + index += 1 + digits += 1 + if digits == 0 or index >= len(source): + return -1 + if source[index] == "}": + return index + if source[index] != ",": + return -1 + index += 1 + while index < len(source) and source[index].isascii() and source[index].isdigit(): + index += 1 + return index if index < len(source) and source[index] == "}" else -1 + + +def translate(source: str) -> str: + """JavaScript's pattern in Python's syntax.""" + out: list[str] = [] + in_class = False + index = 0 + length = len(source) + while index < length: + current = source[index] + if current == "\\" and index + 1 < length: + code = source[index + 1] + index += 2 + if code == "d": + out.append("0-9" if in_class else "[0-9]") + elif code == "D": + out.append(_NOT_DIGITS if in_class else "[^0-9]") + elif code == "w": + out.append("A-Za-z0-9_" if in_class else "[A-Za-z0-9_]") + elif code == "W": + out.append(_NOT_WORD if in_class else "[^A-Za-z0-9_]") + elif code == "s": + out.append(_SPACES if in_class else f"[{_SPACES}]") + elif code == "S": + out.append(_NOT_SPACES if in_class else f"[^{_SPACES}]") + elif code == "v": + out.append("\\x0b") + elif code == "b": + out.append("\\x08" if in_class else "\\b") + elif code == "B": + out.append("B" if in_class else "\\B") + elif code in "nrtf": + out.append("\\" + code) + elif code == "u": + hexadecimal = source[index:index + 4] + if len(hexadecimal) == 4 and all(c in "0123456789abcdefABCDEF" for c in hexadecimal): + out.append("\\u" + hexadecimal) + index += 4 + else: + out.append("u") + elif code == "x": + hexadecimal = source[index:index + 2] + if len(hexadecimal) == 2 and all(c in "0123456789abcdefABCDEF" for c in hexadecimal): + out.append("\\x" + hexadecimal) + index += 2 + else: + out.append("x") + elif code == "c": + letter = source[index] if index < length else "" + if letter.isascii() and letter.isalpha(): + out.append(f"\\x{ord(letter) % 32:02x}") + index += 1 + else: + out.append("\\\\c") + elif code == "0": + out.append("\\x00") + elif code.isdigit(): + # A back reference, which lint refuses in delivered schemas. + out.append("\\" + code) + elif code.isalpha(): + # Without flags JavaScript reads an unknown escape, such as \p, as the letter. + out.append(code) + else: + out.append(re.escape(code)) + continue + if in_class: + if current == "]": + in_class = False + out.append("]") + elif current in "[&~|" or (current == "-" and index + 1 < length and source[index + 1] == "-"): + # Python warns of set operations on these, where JavaScript reads the characters. + out.append("\\" + current) + else: + out.append(current) + index += 1 + continue + if current == "[": + if source.startswith("[^]", index): + # Any character, as JavaScript reads an empty negated class. + out.append("[\\x00-\\U0010ffff]") + index += 3 + continue + if source.startswith("[]", index): + # Nothing, as JavaScript reads an empty class. + out.append("(?!)") + index += 2 + continue + in_class = True + out.append("[") + if index + 1 < length and source[index + 1] == "^": + out.append("^") + index += 1 + elif current == ".": + out.append("[^\\n\\r\\u2028\\u2029]") + elif current == "$": + out.append("\\Z") + elif current == "{": + end = _quantifier_end(source, index) + if end == -1: + out.append("\\{") + else: + out.append(source[index:end + 1]) + index = end + elif current == "}": + out.append("\\}") + else: + out.append(current) + index += 1 + return "".join(out) diff --git a/src/featurevisor/schemas/_store.py b/src/featurevisor/schemas/_store.py new file mode 100644 index 0000000..c3a3bdc --- /dev/null +++ b/src/featurevisor/schemas/_store.py @@ -0,0 +1,229 @@ +"""What a Schemas instance reads through its Featurevisor instance.""" + +from __future__ import annotations + +import json +import threading +import weakref +from dataclasses import dataclass, field +from typing import Any, Callable, Sequence + +from ..modules import FeaturevisorModule +from ._engine import Resolver, Validator, compile_node +from ._messages import Scope +from ._paths import Step + +SECTION = "schemas" +NAME = "@featurevisor/schemas" + +# Featurevisor instances whose schemas module holds the package's name, which only one module on an instance can. +_named: "weakref.WeakSet[Any]" = weakref.WeakSet() +_named_lock = threading.Lock() + + +class Store(Resolver): + """The module API, and schemas compiled by the entry the datafile holds, so a + datafile that changes one compiles it again and references resolve at call time.""" + + def __init__(self, f: Any) -> None: + if not hasattr(f, "add_module"): + raise TypeError("featurevisor.schemas takes the instance create_featurevisor returns, not a child. " + "Pass a child's context to validate instead.") + self.f = f + self._lock = threading.Lock() + self._compiled: dict[str, tuple[Any, Validator]] = {} + self._reported: set[str] = set() + api: dict[str, Any] = {} + with _named_lock: + takes_name = f not in _named + if takes_name: + _named.add(f) + # A module without evaluation hooks costs evaluations nothing. + remove = f.add_module(FeaturevisorModule({"name": NAME if takes_name else None, "setup": api.update})) + if remove is None and takes_name: + # A module of the same name was added by hand. + with _named_lock: + _named.discard(f) + takes_name = False + remove = f.add_module(FeaturevisorModule({"setup": api.update})) + self._holds_name = takes_name + self._remove = remove + if "get_entry" not in api or "match_conditions" not in api: + self.close() + raise RuntimeError("featurevisor.schemas needs a featurevisor whose modules can read datafile sections.") + self.api = api + + def close(self) -> None: + if self._remove is not None: + self._remove() + self._remove = None + if self._holds_name: + with _named_lock: + _named.discard(self.f) + self._holds_name = False + + def entry(self, key: str) -> dict[str, Any] | None: + value = self.api["get_entry"](SECTION, key) + return value if isinstance(value, dict) else None + + def keys(self) -> list[str]: + return sorted(self.api["get_entry_keys"](SECTION)) + + def version(self, key: str) -> Any: + """What changes when the schema does, through the schemas it references too, since its hash covers them.""" + node = self.entry(key) + if node is None: + return None + return node.get("hash", id(node)) + + def node(self, key: str) -> dict[str, Any] | None: + """A schema's node, without compiling it, for what reads a node: references, annotations and messages.""" + return self.entry(key) + + def resolve(self, key: str) -> tuple[dict[str, Any], Validator] | None: + """The schema's node and validator, compiled once per entry. Compiling reads only the nodes of + the schemas it references, so a schema that references itself compiles.""" + node = self.entry(key) + if node is None: + return None + with self._lock: + cached = self._compiled.get(key) + if cached is not None and cached[0] is node: + return node, cached[1] + validate = compile_node(node, self) + with self._lock: + self._compiled[key] = (node, validate) + return node, validate + + def match(self, conditions: Any, context: dict[str, Any], input_reader: Callable[[str], Any], schema: str) -> bool: + # Conditions read through the SDK, so a segment means in a schema what it means in a flag. + return self.api["match_conditions"](conditions, context, {"type": "schema", "key": schema, "readers": {"input": input_reader}}) + + def _once(self, key: str) -> bool: + with self._lock: + if key in self._reported: + return False + self._reported.add(key) + return True + + def unsupported_pattern(self, pattern: str) -> None: + if self._once("pattern " + pattern): + self.api["report_diagnostic"]({ + "level": "error", "code": "schema_pattern_unsupported", + "message": f"Pattern {json.dumps(pattern)} does not compile in Python, so it fails every value.", + "details": {"pattern": pattern}, + }) + + def mutation_failed(self, schema: str, error: Exception) -> None: + if self._once("mutation " + schema): + self.api["report_diagnostic"]({ + "level": "error", "code": "schema_mutation_error", + "message": f"A mutation of schema {json.dumps(schema)} cannot be applied, so the rules it changes fail every value.", + "originalError": error, "details": {"schemaKey": schema}, + }) + + def reference_too_deep(self, schema: str) -> None: + if self._once("depth " + schema): + self.api["report_diagnostic"]({ + "level": "error", "code": "schema_reference_depth", + "message": f"Schema {json.dumps(schema)} follows references more than 128 deep, so it fails the value. " + "A schema that references itself must read deeper into the value each time.", + "details": {"schemaKey": schema}, + }) + + def report_missing(self, key: str) -> None: + """Reports schema_not_found once per key.""" + if self._once("missing " + key): + self.api["report_diagnostic"]({ + "level": "warn", "code": "schema_not_found", + "message": f'Schema "{key}" is not in the datafile. Check that a target delivers it.', + "details": {"schemaKey": key}, + }) + + +@dataclass +class Location: + """A field inside a schema: its node, and the message path and messages around it.""" + + node: Any + mpath: list[str] + scopes: list[Scope] + value: Any = None + """The field's value in a view's values.""" + required: bool = False + """Whether the object the field sits in requires it, after that object's mutations in a view.""" + + +@dataclass +class Walk: + """How a view walks: its values, from which step they apply, and what applies a node's matching mutations.""" + + value: Any + start: int + adjust: Callable[[Any, Any], Any] + + +def locate(resolve: Resolver, root: Any, steps: Sequence[Step], mpath: Sequence[str] = (), + scopes: Sequence[Scope] = (), walk: Walk | None = None) -> Location | None: + """Follows a path from a node, through references, properties, array items and + the values an open object allows. It stops at oneOf, and gives None for a path + the schema does not describe. In a view, each node on the way, and each schema + it references, has its matching mutations applied for the value there.""" + node = root + value = walk.value if walk else None + required = False + mpath = list(mpath) + scopes = list(scopes) + for index, step in enumerate(steps): + adjust = walk.adjust if walk and index >= walk.start else None + # The node's messages, then those of each schema it references, at the same depth. + seen: set[str] = set() + resolved = adjust(node, value) if adjust else node + while True: + if not isinstance(resolved, dict): + return None + if isinstance(resolved.get("messages"), dict): + scopes.append(Scope(resolved["messages"], len(mpath))) + key = resolved.get("schema") + if not isinstance(key, str): + break + if key in seen: + return None + seen.add(key) + target_node = resolve.node(key) + resolved = adjust(target_node, value) if adjust else target_node + if isinstance(resolved.get("oneOf"), list): + return None + in_view = walk is not None and index >= walk.start + required = False + if step.kind == "key": + properties = resolved.get("properties") + if isinstance(properties, dict) and step.key in properties: + node = properties[step.key] + mpath.append(step.key) + required = isinstance(resolved.get("required"), list) and step.key in resolved["required"] + elif isinstance(resolved.get("additionalProperties"), dict): + node = resolved["additionalProperties"] + mpath.append("*") + else: + return None + if in_view: + value = value.get(step.key) if isinstance(value, dict) else None + continue + if step.kind == "values": + if not isinstance(resolved.get("additionalProperties"), dict): + return None + node = resolved["additionalProperties"] + mpath.append("*") + # * names no one value. + if in_view: + value = None + continue + # An index or []: every item of an array is described alike. + if resolved.get("type") != "array": + return None + node = resolved["items"] if "items" in resolved else {"type": "string"} + mpath.append("[]") + if in_view: + value = value[step.index] if step.kind == "index" and isinstance(value, list) and step.index < len(value) else None + return Location(node, mpath, scopes, value, required) diff --git a/src/featurevisor/schemas/_types.py b/src/featurevisor/schemas/_types.py new file mode 100644 index 0000000..1af2864 --- /dev/null +++ b/src/featurevisor/schemas/_types.py @@ -0,0 +1,219 @@ +"""Public types of featurevisor.schemas.""" + +from __future__ import annotations + +import threading +from dataclasses import dataclass, field +from typing import Any, Awaitable, Callable, Mapping, Sequence, Union + +from ._paths import parse_path + +Message = Union[str, Callable[[Mapping[str, Any], "MessageInfo"], str]] +"""A template such as "Use at least {minLength} characters", or a function of the params and info.""" + + +@dataclass(frozen=True) +class SchemaIssue: + """One problem with a value, with what an application needs to word it.""" + + message: str + """From the form's, the schema's or the application's messages, or the default.""" + path: tuple[str | int, ...] + """Where the issue is in the value: keys as strings and list indexes as ints. Empty for the value itself.""" + code: str + """What went wrong, such as "required", "minLength" or "refine".""" + params: Mapping[str, Any] + """What a message can name, such as minLength and length, and the field's title.""" + schema: str + """The key of the schema validated, such as "signUp".""" + mutation: str | None = None + """The key of the mutation that set or changed the rule, or None when none did.""" + + @property + def field(self) -> str: + """The path as a field name with dots, such as "items.0.name".""" + return ".".join(str(part) for part in self.path) + + def __str__(self) -> str: + return (f"{self.field}: " if self.path else "") + f"{self.message} ({self.code})" + + +@dataclass(frozen=True) +class FlattenedIssues: + """Issues' messages grouped by field, in the shape of Zod's flattenError.""" + + form_errors: list[str] + field_errors: dict[str, list[str]] + + +def flatten_issues(issues: Sequence[SchemaIssue]) -> FlattenedIssues: + form: list[str] = [] + fields: dict[str, list[str]] = {} + for issue in issues: + if issue.path: + fields.setdefault(issue.field, []).append(issue.message) + else: + form.append(issue.message) + return FlattenedIssues(form, fields) + + +@dataclass(frozen=True) +class ValidationResult: + """What validating a value found.""" + + value: Any + """The value as it was given, whether or not it passed.""" + issues: tuple[SchemaIssue, ...] = () + """Empty when the value passes.""" + + @property + def valid(self) -> bool: + return not self.issues + + def __bool__(self) -> bool: + return self.valid + + def flatten(self) -> FlattenedIssues: + """The issues by field, for showing them next to inputs or in an error response.""" + return flatten_issues(self.issues) + + +class SchemaValidationError(ValueError): + """Raised by parse when a value fails, with the issues found.""" + + def __init__(self, schema: str, issues: Sequence[SchemaIssue]) -> None: + count = "1 issue" if len(issues) == 1 else f"{len(issues)} issues" + super().__init__(f"{schema}: {count}. {issues[0].message if issues else ''}".strip()) + self.schema = schema + self.issues = tuple(issues) + + def flatten(self) -> FlattenedIssues: + return flatten_issues(self.issues) + + +class MessageInfo: + """What a message function and a translator get besides the issue: the context validation uses.""" + + def __init__(self, make: Callable[[], dict[str, Any]]) -> None: + self._make = make + self._context: dict[str, Any] | None = None + self._lock = threading.Lock() + + @property + def context(self) -> dict[str, Any]: + """The instance's context, with any given to the validation merged over it, merged only when read.""" + with self._lock: + if self._context is None: + self._context = self._make() + return self._context + + +@dataclass(frozen=True) +class CheckInfo: + """What a check in code gets besides the value at its path.""" + + input: Any + """The whole value being validated. For a search or a lookup outside validation, the values with_input gave, or None.""" + context: dict[str, Any] + """The instance's context, with any given to the call merged over it.""" + + def read(self, path: str) -> Any: + """The value at a path in the input, such as "password" or "items.0.name", or None.""" + current = self.input + for step in parse_path(path): + if step.kind == "key" and isinstance(current, dict): + current = current.get(step.key) + elif step.kind == "index" and isinstance(current, list) and step.index < len(current): + current = current[step.index] + else: + return None + return current + + +@dataclass(frozen=True) +class Refinement: + """A check in code that rules cannot express, such as whether a username is taken. + + check gets the value at its path and the CheckInfo, and passes with True. It + can be a coroutine function, which only avalidate awaits. It runs after the + rules, and only where they found no issue at or inside its path, nor in a + field it reads. A check that raises reports refineError. + """ + + key: str + check: Callable[[Any, CheckInfo], bool | Awaitable[bool]] + path: str = "" + reads: Sequence[str] = () + message: str | None = None + + +@dataclass(frozen=True) +class OptionSource: + """Choices for a field that come from the application, such as cities from a service. + + search suggests them as a person types: values, or dicts with a "value" and + what to show, such as a "title". lookup checks a value when validating: None + or False for none, a dict for what it says about the choice. A lookup that + finds nothing reports enum. Either can be a coroutine function. + """ + + key: str + path: str + search: Callable[[str, CheckInfo], Sequence[Any] | Awaitable[Sequence[Any]]] | None = None + lookup: Callable[[Any, CheckInfo], Any] | None = None + reads: Sequence[str] = () + message: str | None = None + + +@dataclass(frozen=True) +class Constraints: + """The HTML validation attributes a field's rules imply, such as required and maxlength. None where the rules set none.""" + + required: bool = False + min_length: int | None = None + max_length: int | None = None + min: float | None = None + max: float | None = None + step: float | None = None + """1 for an integer.""" + multiple: bool = False + + def attributes(self) -> dict[str, Any]: + """The constraints as HTML attributes, only those set.""" + attributes: dict[str, Any] = {} + if self.required: + attributes["required"] = True + for name, value in (("minlength", self.min_length), ("maxlength", self.max_length), + ("min", self.min), ("max", self.max), ("step", self.step)): + if value is not None: + attributes[name] = value + if self.multiple: + attributes["multiple"] = True + return attributes + + +@dataclass(frozen=True) +class SchemaOption: + """A choice a field allows, as its value with what the schema says about it, such as its title.""" + + value: Any + fields: Mapping[str, Any] = field(default_factory=dict) + """What the schema or the source says about the choice, "value" included.""" + + @property + def title(self) -> str | None: + title = self.fields.get("title") + return title if isinstance(title, str) else None + + def __getitem__(self, name: str) -> Any: + return self.fields[name] + + +def make_option(value: Any, entry: Mapping[str, Any] | None) -> SchemaOption: + fields = dict(entry or {}) + fields["value"] = value + return SchemaOption(value, fields) + + +KINDS = ("text", "date-time", "version", "number", "boolean", "select", "multiselect", "object", "list") +"""What a field's rules can make it, for choosing an input.""" diff --git a/src/featurevisor/schemas/_views.py b/src/featurevisor/schemas/_views.py new file mode 100644 index 0000000..a927020 --- /dev/null +++ b/src/featurevisor/schemas/_views.py @@ -0,0 +1,135 @@ +"""What a handle's members describe with an input: rules with every matching mutation applied, at every depth.""" + +from __future__ import annotations + +import json +from typing import Any, Callable, Sequence + +from ._engine import Resolver, has_mutations, matching_mutations, mutated_rules +from ._paths import Step + + +def adjuster(resolve: Resolver, context: dict[str, Any], schema: str) -> Callable[[Any, Any], Any]: + """Applies a node's mutations whose conditions match the value at it and the context.""" + + def adjust(node: Any, value: Any) -> Any: + if not has_mutations(node): + return node + try: + return mutated_rules(node, matching_mutations(node, value, context, resolve, schema)) + except Exception: # noqa: BLE001 + return node + + return adjust + + +def _map_children(node: dict[str, Any], map_child: Callable[[Any, str | None, str | None], Any]) -> dict[str, Any]: + """A copy of a node with each child mapped: a property with its key, items and an open object's values with [] or *.""" + copy = dict(node) + if isinstance(node.get("properties"), dict): + copy["properties"] = {key: map_child(child, key, None) for key, child in node["properties"].items()} + if isinstance(node.get("items"), dict): + copy["items"] = map_child(node["items"], None, "[]") + if isinstance(node.get("additionalProperties"), dict): + copy["additionalProperties"] = map_child(node["additionalProperties"], None, "*") + if isinstance(node.get("oneOf"), list): + copy["oneOf"] = [map_child(branch, None, None) for branch in node["oneOf"]] + return copy + + +def resolve_tree(node: Any, value: Any, adjust: Callable[[Any, Any], Any], resolve: Resolver, seen: Sequence[str] = ()) -> Any: + """A node's subtree for a value, with the matching mutations applied at every node + for the value there. References are inlined, so each use of a schema, such as a + billing and a shipping address, resolves for its own value. Items and the + values of an open object resolve for no value, since each is its own.""" + current = adjust(node, value) + if not isinstance(current, dict): + return current + key = current.get("schema") + if not isinstance(key, str): + return _map_children(current, lambda child, name, many: resolve_tree( + child, None if many else (value.get(name) if isinstance(value, dict) else None) if name else value, + adjust, resolve, seen)) + target = resolve.node(key) if key not in seen else None + if target is None: + return current + inner = resolve_tree(target, value, adjust, resolve, [*seen, key]) + # The reference's own annotations win over the referenced schema's, as they do outside a view. + return {**inner, "annotations": {**(inner.get("annotations") or {}), **(current.get("annotations") or {})}} + + +def place(values: Any, steps: Sequence[Step], value: Any) -> Any: + """A copy of values with a value at a path, so the fields around it read as they will. [] and * name no one place.""" + if not steps: + return value + step, rest = steps[0], steps[1:] + if step.kind == "key": + copy = dict(values) if isinstance(values, dict) else {} + copy[step.key] = place(copy.get(step.key), rest, value) + return copy + if step.kind == "index": + items = list(values) if isinstance(values, list) else [] + while len(items) <= step.index: + items.append(None) + items[step.index] = place(items[step.index], rest, value) + return items + return values + + +def _inputs_of(conditions: Any, found: Callable[[Any], None]) -> None: + """Calls back with the input paths conditions read, in input and valueFrom, through every group.""" + # Datafiles can carry conditions as JSON text, as features' are. + if isinstance(conditions, str): + text = conditions.strip() + if not text[:1] in ("{", "[", '"'): + return + try: + conditions = json.loads(text) + except ValueError: + return + if isinstance(conditions, list): + for item in conditions: + _inputs_of(item, found) + return + if not isinstance(conditions, dict): + return + found(conditions.get("input")) + if isinstance(conditions.get("valueFrom"), dict): + found(conditions["valueFrom"].get("input")) + for group in ("and", "or", "not"): + _inputs_of(conditions.get(group), found) + + +def reads_of(node: Any, resolve: Resolver) -> list[str]: + """The fields, relative to a node, that the conditions of its mutations and issues + read, at any depth and through references, as at takes paths: accountType, + address.country or items[].room.""" + reads: list[str] = [] + + def join(at: str, path: str) -> str: + return f"{at}.{path}" if at else path + + def visit(current: Any, at: str, seen: Sequence[str]) -> None: + if not isinstance(current, dict): + return + for name in ("mutations", "issues"): + for entry in current.get(name) or []: + def add(path: Any) -> None: + if isinstance(path, str) and join(at, path) not in reads: + reads.append(join(at, path)) + _inputs_of(entry.get("conditions") if isinstance(entry, dict) else None, add) + key = current.get("schema") + if isinstance(key, str) and key not in seen: + visit(resolve.node(key), at, [*seen, key]) + if isinstance(current.get("properties"), dict): + for name, child in current["properties"].items(): + visit(child, join(at, name), seen) + if "items" in current: + visit(current["items"], at + "[]", seen) + if "additionalProperties" in current: + visit(current["additionalProperties"], join(at, "*"), seen) + for branch in current.get("oneOf") or []: + visit(branch, at, seen) + + visit(node, "", []) + return reads diff --git a/tests/fixtures/schemas/built-datafile-expected.json b/tests/fixtures/schemas/built-datafile-expected.json new file mode 100644 index 0000000..80f4847 --- /dev/null +++ b/tests/fixtures/schemas/built-datafile-expected.json @@ -0,0 +1,548 @@ +{ + "cases": [ + { + "schema": "signUp", + "value": {}, + "context": {}, + "issues": [ + { + "message": "Value at \"accountType\" is required.", + "path": [ + "accountType" + ], + "code": "required", + "params": { + "key": "accountType", + "title": "Account type" + }, + "schema": "signUp" + }, + { + "message": "Value at \"displayName\" is required.", + "path": [ + "displayName" + ], + "code": "required", + "params": { + "key": "displayName", + "title": "Display name" + }, + "schema": "signUp" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "business", + "displayName": "A" + }, + "context": {}, + "issues": [ + { + "message": "Value at \"taxId\" is required.", + "path": [ + "taxId" + ], + "code": "required", + "params": { + "key": "taxId", + "title": "VAT number" + }, + "schema": "signUp", + "mutation": "business" + }, + { + "message": "Use at least 2 characters", + "path": [ + "displayName" + ], + "code": "minLength", + "params": { + "minLength": 2, + "length": 1, + "title": "Display name" + }, + "schema": "signUp" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "business", + "displayName": "Ada", + "taxId": "x" + }, + "context": {}, + "issues": [ + { + "message": "Enter your VAT number, such as DE123456789", + "path": [ + "taxId" + ], + "code": "pattern", + "params": { + "pattern": "^[A-Z]{2}[0-9]{9}$", + "title": "VAT number" + }, + "schema": "signUp", + "mutation": "business" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "business", + "displayName": "Ada", + "taxId": "DE123456789" + }, + "context": {}, + "issues": [] + }, + { + "schema": "signUp", + "value": { + "accountType": "personal", + "displayName": "Ada", + "extra": 1 + }, + "context": {}, + "issues": [ + { + "message": "Value at \"extra\" is not allowed.", + "path": [ + "extra" + ], + "code": "additionalProperties", + "params": { + "key": "extra" + }, + "schema": "signUp" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "other", + "displayName": 5 + }, + "context": {}, + "issues": [ + { + "message": "Value at \"accountType\" must be one of Personal, Business.", + "path": [ + "accountType" + ], + "code": "enum", + "params": { + "options": [ + "personal", + "business" + ], + "titles": [ + "Personal", + "Business" + ], + "title": "Account type" + }, + "schema": "signUp" + }, + { + "message": "Value at \"displayName\" must be a string (got number).", + "path": [ + "displayName" + ], + "code": "type", + "params": { + "type": "string", + "received": "number", + "title": "Display name" + }, + "schema": "signUp" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "personal", + "displayName": "😀😀" + }, + "context": {}, + "issues": [] + }, + { + "schema": "checkout", + "value": { + "billingCountry": "nl", + "shippingCountry": "de" + }, + "context": { + "plan": "paid" + }, + "issues": [ + { + "message": "Value at \"customsDescription\" is required.", + "path": [ + "customsDescription" + ], + "code": "required", + "params": { + "key": "customsDescription" + }, + "schema": "checkout", + "mutation": "shipsAbroad" + } + ] + }, + { + "schema": "checkout", + "value": { + "billingCountry": "nl", + "shippingCountry": "de" + }, + "context": { + "plan": "free" + }, + "issues": [] + }, + { + "schema": "checkout", + "value": { + "billingCountry": "nl", + "shippingCountry": "nl" + }, + "context": { + "plan": "paid" + }, + "issues": [] + }, + { + "schema": "register", + "value": { + "password": "short", + "confirmPassword": "x" + }, + "context": {}, + "issues": [ + { + "message": "Value at \"password\" must be at least 8 characters long (got 5).", + "path": [ + "password" + ], + "code": "minLength", + "params": { + "minLength": 8, + "length": 5 + }, + "schema": "register" + }, + { + "message": "Confirmation does not match the password", + "path": [ + "confirmPassword" + ], + "code": "refine", + "params": { + "refine": "passwordsDiffer", + "title": "Confirmation" + }, + "schema": "register" + } + ] + }, + { + "schema": "register", + "value": { + "password": "long enough", + "confirmPassword": "long enough", + "billingCountry": "nl", + "shippingCountry": "de" + }, + "context": { + "country": "nl" + }, + "issues": [ + { + "message": "We ship Dutch orders to the billing country only", + "path": [ + "shippingCountry" + ], + "code": "refine", + "params": { + "refine": "dutchShippingCountry" + }, + "schema": "register" + } + ] + }, + { + "schema": "register", + "value": { + "password": "long enough", + "confirmPassword": "long enough", + "billingCountry": "nl", + "shippingCountry": "de" + }, + "context": { + "country": "de" + }, + "issues": [] + }, + { + "schema": "register", + "value": { + "confirmPassword": "x" + }, + "context": {}, + "issues": [ + { + "message": "Value at \"password\" is required.", + "path": [ + "password" + ], + "code": "required", + "params": { + "key": "password" + }, + "schema": "register" + } + ] + }, + { + "schema": "missing", + "value": {}, + "context": {}, + "issues": [ + { + "message": "Schema \"missing\" was not found.", + "path": [], + "code": "schemaNotFound", + "params": { + "schema": "missing" + }, + "schema": "missing" + } + ] + } + ], + "members": { + "signUp": { + "path": "", + "fieldKeys": [ + "accountType", + "displayName", + "taxId" + ], + "constraints": { + "accountType": { + "required": true + }, + "displayName": { + "required": true, + "minLength": 2, + "maxLength": 40 + }, + "taxId": {} + }, + "options": { + "accountType": [ + { + "value": "personal", + "title": "Personal" + }, + { + "value": "business", + "title": "Business" + } + ] + }, + "kind": "object", + "reads": [ + "accountType" + ], + "annotations": { + "title": "Create your account", + "order": [ + "accountType", + "displayName", + "taxId" + ] + } + }, + "accountType": { + "path": "accountType", + "fieldKeys": [], + "constraints": { + "required": true + }, + "options": [ + { + "value": "personal", + "title": "Personal" + }, + { + "value": "business", + "title": "Business" + } + ], + "kind": "select", + "reads": [], + "annotations": { + "title": "Account type", + "options": { + "personal": { + "title": "Personal" + }, + "business": { + "title": "Business" + } + } + } + }, + "displayName": { + "path": "displayName", + "fieldKeys": [], + "constraints": { + "required": true, + "minLength": 2, + "maxLength": 40 + }, + "options": [], + "kind": "text", + "reads": [], + "annotations": { + "title": "Display name", + "examples": [ + "Ada", + "Grace Hopper" + ] + } + }, + "taxId": { + "path": "taxId", + "fieldKeys": [], + "constraints": {}, + "options": [], + "kind": "text", + "reads": [], + "annotations": { + "title": "VAT number" + } + }, + "businessTaxId": { + "path": "taxId", + "fieldKeys": [], + "constraints": { + "required": true + }, + "options": [], + "kind": "text", + "reads": [], + "annotations": { + "title": "VAT number" + } + }, + "business": { + "path": "", + "fieldKeys": [ + "accountType", + "displayName", + "taxId" + ], + "constraints": { + "accountType": { + "required": true + }, + "displayName": { + "required": true, + "minLength": 2, + "maxLength": 40 + }, + "taxId": { + "required": true + } + }, + "options": { + "accountType": [ + { + "value": "personal", + "title": "Personal" + }, + { + "value": "business", + "title": "Business" + } + ] + }, + "kind": "object", + "reads": [ + "accountType" + ], + "annotations": { + "title": "Create your account", + "order": [ + "accountType", + "displayName", + "taxId" + ] + } + }, + "checkout": { + "path": "", + "fieldKeys": [ + "billingCountry", + "shippingCountry", + "customsDescription", + "password", + "confirmPassword" + ], + "constraints": { + "billingCountry": { + "required": true + }, + "shippingCountry": {}, + "customsDescription": {}, + "password": {}, + "confirmPassword": {} + }, + "options": {}, + "kind": "object", + "reads": [ + "shippingCountry", + "billingCountry" + ], + "annotations": {} + }, + "register": { + "path": "", + "fieldKeys": [ + "password", + "confirmPassword", + "shippingCountry", + "billingCountry" + ], + "constraints": { + "password": { + "required": true, + "minLength": 8 + }, + "confirmPassword": {}, + "shippingCountry": {}, + "billingCountry": {} + }, + "options": {}, + "kind": "object", + "reads": [ + "confirmPassword", + "password", + "shippingCountry", + "billingCountry" + ], + "annotations": {} + } + } +} diff --git a/tests/fixtures/schemas/built-datafile.json b/tests/fixtures/schemas/built-datafile.json new file mode 100644 index 0000000..5bb7417 --- /dev/null +++ b/tests/fixtures/schemas/built-datafile.json @@ -0,0 +1 @@ +{"schemaVersion":"4","featurevisorVersion":"4.13.0","revision":"2","segments":{"netherlands":{"conditions":"{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}"},"paying":{"conditions":"{\"attribute\":\"plan\",\"operator\":\"equals\",\"value\":\"paid\"}"}},"features":{},"variables":{},"schemas":{"checkout":{"hash":"gSboXrZWcM","type":"object","properties":{"billingCountry":{"type":"string"},"shippingCountry":{"type":"string"},"customsDescription":{"type":"string"},"password":{"type":"string"},"confirmPassword":{"type":"string"}},"required":["billingCountry"],"mutations":[{"key":"shipsAbroad","conditions":"[{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}},\"paying\"]","operations":[{"op":"appendUnique","path":["required"],"value":"customsDescription"}]}]},"register":{"hash":"XlDf9sip1o","type":"object","properties":{"password":{"type":"string","minLength":8},"confirmPassword":{"type":"string","annotations":{"title":"Confirmation"}},"shippingCountry":{"type":"string"},"billingCountry":{"type":"string"}},"required":["password"],"issues":[{"key":"passwordsDiffer","conditions":"{\"input\":\"confirmPassword\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"password\"}}","path":"confirmPassword","message":"{title} does not match the password"},{"key":"dutchShippingCountry","conditions":"[\"netherlands\",{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}}]","path":"shippingCountry","message":"We ship Dutch orders to the billing country only"}]},"signUp":{"hash":"wLXjboTQnZ","type":"object","properties":{"accountType":{"type":"string","enum":["personal","business"],"annotations":{"title":"Account type","options":{"personal":{"title":"Personal"},"business":{"title":"Business"}}}},"displayName":{"type":"string","minLength":2,"maxLength":40,"annotations":{"title":"Display name","examples":["Ada","Grace Hopper"]}},"taxId":{"type":"string","annotations":{"title":"VAT number"}}},"required":["accountType","displayName"],"messages":{"displayName":{"minLength":"Use at least {minLength} characters"}},"annotations":{"title":"Create your account","order":["accountType","displayName","taxId"]},"mutations":[{"key":"business","conditions":"{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}","operations":[{"op":"appendUnique","path":["required"],"value":"taxId"},{"op":"set","path":["properties","taxId","pattern"],"value":"^[A-Z]{2}[0-9]{9}$"},{"op":"set","path":["properties","taxId","messages"],"value":{"pattern":"Enter your VAT number, such as DE123456789"}}]}]}}} \ No newline at end of file diff --git a/tests/test_module_conditions.py b/tests/test_module_conditions.py new file mode 100644 index 0000000..d938664 --- /dev/null +++ b/tests/test_module_conditions.py @@ -0,0 +1,98 @@ +import unittest + +from featurevisor import create_featurevisor +from featurevisor.conditions import MISSING + + +DATAFILE = { + "schemaVersion": "4", + "revision": "1", + "segments": { + "dutch": {"hash": "d1", "conditions": [{"attribute": "country", "operator": "equals", "value": "nl"}]}, + "payingDutch": {"hash": "p1", "conditions": {"and": ["dutch", {"feature": "paid"}]}}, + }, + "features": {"paid": {"hash": "f1", "bucketBy": "userId", "traffic": [{"key": "everyone", "conditions": "*", "percentage": 100000}]}}, + "variables": {}, +} + + +class ModuleConditionsTests(unittest.TestCase): + """match_conditions on the module API, as the JavaScript SDK's moduleConditions.spec.ts pins it.""" + + def setup_api(self, modules=()): + diagnostics = [] + f = create_featurevisor({ + "datafile": DATAFILE, + "logLevel": "error", + "context": {"country": "nl"}, + "onDiagnostic": lambda diagnostic: diagnostics.append(diagnostic["code"]), + }) + for module in modules: + f.add_module(module) + api = {} + f.add_module({"name": "@featurevisor/schemas", "setup": lambda module_api: api.update(module_api)}) + return api, diagnostics + + def test_answers_attributes_segments_and_feature_leaves(self) -> None: + api, diagnostics = self.setup_api() + match = api["match_conditions"] + self.assertTrue(match("*", {})) + self.assertTrue(match([{"attribute": "country", "operator": "equals", "value": "nl"}], {})) + self.assertFalse(match("dutch", {"country": "de"})) + self.assertTrue(match("payingDutch", {})) + self.assertFalse(match({"not": [{"feature": "paid"}]}, {})) + # Conditions as JSON text, as Core writes them by default. + self.assertTrue(match('["dutch"]', {})) + self.assertEqual(diagnostics, []) + + def test_reads_leaves_only_the_package_knows(self) -> None: + api, _ = self.setup_api() + match = api["matchConditions"] + value = {"accountType": "business", "password": "a", "confirm": "a"} + readers = {"readers": {"input": lambda path: value.get(path, MISSING)}} + self.assertTrue(match({"and": ["dutch", {"input": "accountType", "operator": "equals", "value": "business"}]}, {}, readers)) + same = {"input": "confirm", "operator": "equals", "valueFrom": {"input": "password"}} + self.assertTrue(match(same, {}, readers)) + value["confirm"] = "b" + self.assertFalse(match(same, {}, readers)) + # "value" is always a value, even an object naming a reader. + value["confirm"] = "a" + self.assertFalse(match({"input": "confirm", "operator": "equals", "value": {"input": "password"}}, {}, readers)) + # A pattern read from a value never runs, nor a source no reader answers. + self.assertFalse(match({"input": "confirm", "operator": "matches", "valueFrom": {"input": "password"}}, {}, readers)) + self.assertFalse(match({"input": "confirm", "operator": "equals", "valueFrom": {"attribute": "country"}}, {}, readers)) + # Without a reader for its kind, a leaf does not match. + self.assertFalse(match({"input": "accountType", "operator": "equals", "value": "business"}, {})) + # Absent differs from null. + self.assertTrue(match({"input": "missing", "operator": "notExists"}, {}, readers)) + self.assertFalse(match({"input": "missing", "operator": "isNull"}, {}, readers)) + # Without a value to compare, JavaScript compares with undefined, which only an absent read equals. + value["nothing"] = None + self.assertTrue(match({"input": "missing", "operator": "equals"}, {}, readers)) + self.assertFalse(match({"input": "nothing", "operator": "equals"}, {}, readers)) + self.assertTrue(match({"input": "nothing", "operator": "notEquals"}, {}, readers)) + self.assertFalse(match({"input": "nothing", "operator": "equals", "valueFrom": {"input": "missing"}}, {}, readers)) + + def test_feature_leaves_reach_modules_as_dependencies_of_the_entry(self) -> None: + seen = [] + + def after(evaluation, options): + seen.append({"featureKey": evaluation.get("featureKey"), "dependencyOf": options.get("dependencyOf")}) + return evaluation + + api, _ = self.setup_api([{"name": "observer", "afterEvaluation": after}]) + self.assertTrue(api["match_conditions"]([{"feature": "paid"}], {}, {"type": "schema", "key": "signUp"})) + self.assertEqual(seen, [{"featureKey": "paid", "dependencyOf": {"type": "schema", "key": "signUp"}}]) + + def test_a_condition_that_cannot_be_answered_reports_evaluation_error(self) -> None: + api, diagnostics = self.setup_api() + + def broken(path): + raise RuntimeError("broken reader") + + self.assertFalse(api["match_conditions"]({"input": "x", "operator": "equals", "value": 1}, {}, {"readers": {"input": broken}})) + self.assertEqual(diagnostics, ["evaluation_error"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_schemas.py b/tests/test_schemas.py new file mode 100644 index 0000000..4497baa --- /dev/null +++ b/tests/test_schemas.py @@ -0,0 +1,215 @@ +import asyncio +import json +import threading +import unittest +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass + +from featurevisor import create_featurevisor +from featurevisor.schemas import OptionSource, Refinement, SchemaValidationError, create_schemas + +SCHEMAS = { + "signUp": {"hash": "s1", "type": "object", + "properties": { + "username": {"type": "string", "minLength": 3, "annotations": {"title": "Username"}}, + "password": {"type": "string", "minLength": 8}, + "confirm": {"type": "string"}, + "city": {"type": "string"}, + "country": {"type": "string", "enum": ["nl", "de"]}, + "code": {"type": "string", "pattern": "^[A-Z]{2}$"}, + "tags": {"type": "array", "items": {"type": "string"}}, + }, + "required": ["username", "password"]}, + "spaced": {"hash": "p1", "type": "string", "pattern": "^a\\sb$"}, + "braces": {"hash": "b1", "type": "string", "pattern": "^a{$"}, + "dots": {"hash": "d1", "type": "string", "pattern": "^a.b$"}, + "digits": {"hash": "n1", "type": "string", "pattern": "^\\d+$"}, + "broken": {"hash": "x1", "type": "string", "pattern": "(?x)"}, +} + +VALID = {"username": "ada", "password": "long enough", "confirm": "long enough"} + + +def datafile(revision, schemas): + return {"schemaVersion": "4", "revision": revision, "segments": {}, "features": {}, "variables": {}, "schemas": schemas} + + +@dataclass +class Request: + username: str + password: str + + +class SchemasTests(unittest.TestCase): + def setUp(self) -> None: + self.diagnostics = [] + self.f = create_featurevisor({"datafile": datafile("1", SCHEMAS), "logLevel": "warn", + "onDiagnostic": lambda diagnostic: self.diagnostics.append(diagnostic["code"])}) + + def test_validates_dicts_dataclasses_and_tuples(self) -> None: + s = create_schemas(self.f) + self.assertTrue(s.validate("signUp", VALID).valid) + result = s.validate("signUp", Request("ad", "short")) + self.assertEqual([issue.code for issue in result.issues], ["minLength", "minLength"]) + self.assertTrue(s.is_valid("signUp", {**VALID, "tags": ("a", "b")})) + # A bool is never a number, though Python makes it an int. + self.assertEqual(s.validate("signUp", {**VALID, "username": True}).issues[0].params["received"], "boolean") + + def test_parse_raises_with_the_issues_and_flattens_them(self) -> None: + s = create_schemas(self.f) + self.assertIs(s.parse("signUp", VALID), VALID) + with self.assertRaises(SchemaValidationError) as raised: + s.parse("signUp", {"password": "x"}) + self.assertEqual(raised.exception.schema, "signUp") + self.assertEqual(str(raised.exception), 'signUp: 2 issues. Value at "username" is required.') + self.assertEqual(raised.exception.flatten().field_errors["password"], + ['Value at "password" must be at least 8 characters long (got 1).']) + + def test_words_issues_from_the_form_the_application_and_the_translator(self) -> None: + s = create_schemas(self.f, messages={"required": "{title} is needed", + "minLength": lambda params, info: f"At least {params['minLength']}"}) + self.assertEqual(sorted(issue.message for issue in s.validate("signUp", {"password": "x"}).issues), + ["At least 8", "Username is needed"]) + form = s.get("signUp", messages={"password": {"minLength": "Use {minLength} characters or more"}}) + self.assertEqual(sorted(issue.message for issue in form.validate({"password": "x"}).issues), + ["Use 8 characters or more", "Username is needed"]) + translated = create_schemas(self.f, translate=lambda issue, info: "Vereist" if issue.code == "required" else None) + self.assertEqual(translated.validate("signUp", {"password": "long enough"}).issues[0].message, "Vereist") + + def test_refinements_run_after_the_rules_where_they_found_nothing(self) -> None: + async def free(value, info): + await asyncio.sleep(0.001) + return value != "taken" + + def down(value, info): + raise RuntimeError("down") + + sign_up = create_schemas(self.f).get("signUp", refine=[ + Refinement("passwordsMatch", lambda value, info: value == info.read("password"), path="confirm", + reads=["password"], message="Passwords must match"), + Refinement("usernameFree", free, path="username"), + Refinement("broken", down, path="city"), + ]) + self.assertTrue(sign_up.has_checks) + self.assertTrue(asyncio.run(sign_up.avalidate(VALID)).valid) + result = asyncio.run(sign_up.avalidate({"username": "taken", "password": "long enough", "confirm": "other", "city": "Utrecht"})) + self.assertEqual([issue.code for issue in result.issues], ["refine", "refine", "refineError"]) + self.assertEqual(result.issues[0].message, "Passwords must match") + self.assertEqual(dict(result.issues[1].params), {"refine": "usernameFree", "title": "Username"}) + self.assertEqual(result.issues[2].message, 'Value at "city" could not be checked.') + # Without awaiting, a check that answers later cannot pass. + self.assertEqual([issue.code for issue in sign_up.validate(VALID).issues], ["refineError"]) + # A rule's issue at the field, or in a field a check reads, holds the check back. + held = asyncio.run(sign_up.avalidate({"username": "ab", "password": "short", "confirm": "other"})) + self.assertEqual([issue.code for issue in held.issues], ["minLength", "minLength"]) + self.assertTrue(sign_up.validate_rules({"username": "taken", "password": "long enough"}).valid) + + def test_option_sources_look_up_values_and_suggest_choices(self) -> None: + cities = {"utrecht": "Utrecht", "rotterdam": "Rotterdam", "amsterdam": "Amsterdam"} + + async def search(query, info): + return [{"value": value, "title": title} for value, title in cities.items() if title.lower().startswith(query.lower())] + + source = OptionSource("cities", "city", search=search, + lookup=lambda value, info: {"title": cities[value]} if value in cities else None) + sign_up = create_schemas(self.f).get("signUp", option_sources=[source]) + city = sign_up.at("city") + self.assertTrue(city.can_search) + self.assertFalse(sign_up.at("username").can_search) + suggestions = asyncio.run(city.search("ut")) + self.assertEqual([option.value for option in suggestions], ["utrecht"]) + self.assertEqual(suggestions[0].title, "Utrecht") + self.assertEqual(asyncio.run(city.lookup("rotterdam")).title, "Rotterdam") + self.assertIsNone(asyncio.run(city.lookup("amstelveen"))) + # The schema's own choices come first. + self.assertEqual(asyncio.run(sign_up.at("country").lookup("nl")).value, "nl") + result = sign_up.validate({"username": "ada", "password": "long enough", "city": "amstelveen"}) + self.assertEqual([issue.code for issue in result.issues], ["enum"]) + self.assertEqual(dict(result.issues[0].params), {"optionSource": "cities"}) + self.assertEqual(result.issues[0].message, 'Value at "city" is not one of its choices.') + + def test_patterns_mean_what_they_mean_in_javascript(self) -> None: + s = create_schemas(self.f) + # A dollar sign is the end of the value, never a final line break. + self.assertTrue(s.is_valid("signUp", {**VALID, "code": "DE"})) + self.assertFalse(s.is_valid("signUp", {**VALID, "code": "DE\n"})) + # A whitespace class takes JavaScript's whitespace, the BOM included and U+001C not. + self.assertTrue(s.is_valid("spaced", "a b")) + self.assertTrue(s.is_valid("spaced", "ab")) + self.assertFalse(s.is_valid("spaced", "a\u001cb")) + # A brace that starts no quantifier is a brace. + self.assertTrue(s.is_valid("braces", "a{")) + # A dot refuses a carriage return, as JavaScript's does. + self.assertTrue(s.is_valid("dots", "a\u0085b")) + self.assertFalse(s.is_valid("dots", "a\rb")) + # A digit is an ASCII digit. + self.assertTrue(s.is_valid("digits", "123")) + self.assertFalse(s.is_valid("digits", "١٢")) + # A pattern Python cannot compile fails every value, and says so once. + self.assertEqual([issue.code for issue in s.validate("broken", "x").issues], ["pattern"]) + s.validate("broken", "y") + self.assertEqual(self.diagnostics.count("schema_pattern_unsupported"), 1) + + def test_a_missing_schema_or_field_is_an_issue_reported_once(self) -> None: + s = create_schemas(self.f) + missing = s.validate("nothing", {}) + self.assertEqual([issue.code for issue in missing.issues], ["schemaNotFound"]) + self.assertEqual(missing.issues[0].message, 'Schema "nothing" was not found.') + s.validate("nothing", {}) + self.assertEqual(self.diagnostics.count("schema_not_found"), 1) + self.assertEqual(dict(s.get("signUp").at("address.city").validate("x").issues[0].params), + {"schema": "signUp", "field": "address.city"}) + self.assertEqual(s.keys(), ["braces", "broken", "digits", "dots", "signUp", "spaced"]) + self.assertTrue(s.has("signUp")) + self.assertFalse(s.has("nothing")) + + def test_handles_read_the_current_datafile_and_tell_when_their_schema_changes(self) -> None: + s = create_schemas(self.f) + sign_up = s.get("signUp") + self.assertIs(sign_up, s.get("signUp")) + self.assertIs(sign_up.at("username"), sign_up.at("username")) + changes = [] + stop = sign_up.subscribe(lambda: changes.append(1)) + self.assertEqual(sign_up.at("username").constraints.min_length, 3) + # A datafile that leaves the schema alone changes nothing. + self.f.set_datafile(datafile("2", {})) + self.assertEqual(changes, []) + self.f.set_datafile(datafile("3", {"signUp": {"hash": "s2", "type": "object", "properties": {"username": {"type": "string", "minLength": 5}}}})) + self.assertEqual(len(changes), 1) + self.assertEqual(sign_up.at("username").constraints.min_length, 5) + self.assertEqual([issue.code for issue in sign_up.validate({"username": "ada"}).issues], ["minLength"]) + stop() + self.f.set_datafile(datafile("4", {"signUp": {"hash": "s3", "type": "object"}})) + self.assertEqual(len(changes), 1) + + def test_a_schema_that_references_itself_follows_the_value_and_fails_closed_in_a_loop(self) -> None: + self.f.set_datafile(datafile("2", { + "list": {"hash": "l1", "type": "array", "items": {"oneOf": [{"schema": "list"}, {"type": "string"}]}}, + "tree": {"hash": "t1", "oneOf": [{"schema": "tree"}, {"type": "string"}]}, + }), True) + s = create_schemas(self.f) + self.assertTrue(s.is_valid("list", ["a", ["b", ["c"]]])) + self.assertEqual([issue.code for issue in s.validate("list", [1]).issues], ["oneOf"]) + self.assertTrue(s.is_valid("tree", "a")) + self.assertEqual([issue.code for issue in s.validate("tree", 1).issues], ["oneOf"]) + self.assertEqual(self.diagnostics.count("schema_reference_depth"), 1) + + def test_instances_share_a_featurevisor_instance_and_close_cleanly(self) -> None: + first, second = create_schemas(self.f), create_schemas(self.f) + self.assertTrue(first.is_valid("signUp", VALID) and second.is_valid("signUp", VALID)) + first.close() + self.assertTrue(second.is_valid("signUp", VALID)) + with create_schemas(self.f) as third: + self.assertTrue(third.is_valid("signUp", VALID)) + self.assertNotIn("duplicate_module", self.diagnostics) + + def test_validates_from_many_threads_at_once(self) -> None: + sign_up = create_schemas(self.f).get("signUp") + with ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map(lambda index: sign_up.is_valid(VALID) if index % 2 == 0 + else not sign_up.is_valid({"username": "a", "password": "b"}), range(400))) + self.assertTrue(all(results)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_schemas_conformance.py b/tests/test_schemas_conformance.py new file mode 100644 index 0000000..7be8ea4 --- /dev/null +++ b/tests/test_schemas_conformance.py @@ -0,0 +1,112 @@ +import json +import unittest +from pathlib import Path + +from featurevisor import create_featurevisor +from featurevisor.schemas import create_schemas +from featurevisor.schemas._json import stringify + +ROOT = Path(__file__).resolve().parents[1] +FIXTURE = json.loads((ROOT / "conformance" / "schemas-validation.json").read_text()) +BUILT = ROOT / "tests" / "fixtures" / "schemas" + + +def canonical(value): + """JSON text with keys sorted and numbers by value, so values compare by what they mean.""" + if isinstance(value, dict): + return "{" + ",".join(json.dumps(key) + ":" + canonical(value[key]) for key in sorted(value)) + "}" + if isinstance(value, (list, tuple)): + return "[" + ",".join(canonical(item) for item in value) + "]" + if isinstance(value, (int, float)) and not isinstance(value, bool): + return repr(float(value)) + return stringify(value) + + +def portable(issue): + fields = {"code": issue.code, "path": list(issue.path), "params": dict(issue.params)} + if issue.mutation is not None: + fields["mutation"] = issue.mutation + return canonical(fields) + + +class SchemasValidationConformanceTests(unittest.TestCase): + """Runs conformance/schemas-validation.json, the cases every schemas package passes.""" + + def test_fixture_version(self) -> None: + self.assertEqual(FIXTURE["kind"], "featurevisor.schemas-validation") + self.assertEqual(FIXTURE["schemaVersion"], 2) + self.assertTrue(FIXTURE["cases"]) + + def test_every_case(self) -> None: + for case in FIXTURE["cases"]: + with self.subTest(case=case["name"]): + f = create_featurevisor({ + "datafile": {"schemaVersion": "4", "revision": "1", "segments": case.get("segments", {}), + "features": {}, "variables": {}, "schemas": case["schemas"]}, + "context": case.get("context", {}), "logLevel": "fatal", + }) + s = create_schemas(f) + expected = sorted(canonical({key: issue[key] for key in ("code", "path", "params", "mutation") if key in issue}) + for issue in case["issues"]) + # Twice, so a compiled schema answers as a fresh one does. + for _ in range(2): + actual = sorted(portable(issue) for issue in s.validate(case["schema"], case["value"]).issues) + self.assertEqual(actual, expected) + + +class BuiltDatafileTests(unittest.TestCase): + """A datafile the CLI built, with conditions as JSON text, against what the JavaScript + package answers for it, messages included. Regenerate built-datafile-expected.json + with the JavaScript package when the datafile changes.""" + + datafile = json.loads((BUILT / "built-datafile.json").read_text()) + expected = json.loads((BUILT / "built-datafile-expected.json").read_text()) + + def schemas(self, context=None): + return create_schemas(create_featurevisor({"datafile": self.datafile, "context": context or {}, "logLevel": "fatal"})) + + def test_validates_as_javascript_does(self) -> None: + for case in self.expected["cases"]: + with self.subTest(schema=case["schema"], value=case["value"]): + result = self.schemas(case["context"]).validate(case["schema"], case["value"]) + actual = sorted(canonical({"message": issue.message, "path": list(issue.path), "code": issue.code, + "params": dict(issue.params), "schema": issue.schema, + **({"mutation": issue.mutation} if issue.mutation else {})}) + for issue in result.issues) + self.assertEqual(actual, sorted(canonical(issue) for issue in case["issues"])) + + def test_describes_fields_as_javascript_does(self) -> None: + s = self.schemas() + sign_up = s.get("signUp") + business = sign_up.with_input({"accountType": "business"}) + handles = { + "signUp": sign_up, "accountType": sign_up.at("accountType"), "displayName": sign_up.at("displayName"), + "taxId": sign_up.at("taxId"), "businessTaxId": business.at("taxId"), "business": business, + "checkout": s.get("checkout"), "register": s.get("register"), + } + + def constraints(value): + names = (("required", value.required or None), ("minLength", value.min_length), ("maxLength", value.max_length), + ("min", value.min), ("max", value.max), ("step", value.step), ("multiple", value.multiple or None)) + return {name: item for name, item in names if item is not None} + + for name, handle in handles.items(): + with self.subTest(handle=name): + wanted = self.expected["members"][name] + self.assertEqual(handle.path, wanted["path"]) + self.assertEqual(handle.field_keys, wanted["fieldKeys"]) + self.assertEqual(handle.kind, wanted["kind"]) + self.assertEqual(handle.reads, wanted["reads"]) + self.assertEqual(canonical(handle.annotations), canonical(wanted["annotations"])) + if handle.kind == "object": + actual_constraints = {key: constraints(value) for key, value in handle.field_constraints.items()} + actual_options = {key: [dict(option.fields) for option in options] for key, options in handle.field_options.items()} + else: + actual_constraints = constraints(handle.constraints) + actual_options = [dict(option.fields) for option in handle.options] + self.assertEqual(canonical(actual_constraints), canonical(wanted["constraints"])) + self.assertEqual(canonical(actual_options), canonical(wanted["options"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sdk_sections.py b/tests/test_sdk_sections.py new file mode 100644 index 0000000..138b5ae --- /dev/null +++ b/tests/test_sdk_sections.py @@ -0,0 +1,76 @@ +import json +import unittest +from pathlib import Path + +from featurevisor import create_featurevisor + + +FIXTURE = json.loads((Path(__file__).resolve().parents[1] / "conformance" / "sdk-sections.json").read_text()) + + +def datafile_of(value): + return value if isinstance(value, str) else json.dumps(value) + + +class SDKSectionsConformanceTests(unittest.TestCase): + """Runs conformance/sdk-sections.json: sections change no evaluation, and modules read them by entry.""" + + def test_fixture_version(self) -> None: + self.assertEqual(FIXTURE["kind"], "featurevisor.sdk-sections") + self.assertEqual(FIXTURE["schemaVersion"], 1) + + def test_sections_change_no_evaluation(self) -> None: + for case in FIXTURE["evaluationCases"]: + with self.subTest(case=case["name"]): + f = create_featurevisor({"datafile": datafile_of(case["datafile"]), "context": case.get("context", {}), "logLevel": "fatal"}) + for _ in range(2): + for result in case["results"]: + method, args = result["method"], result["args"] + if method == "isEnabled": + actual = f.is_enabled(args[0]) + elif method == "getVariation": + actual = f.get_variation(args[0]) + else: + actual = f.get_variable(*args) + self.assertEqual(actual, result["value"], f"{method} {args}") + + def test_sections_carry_through_merge_and_replace(self) -> None: + for case in FIXTURE["carriageCases"]: + with self.subTest(case=case["name"]): + f = create_featurevisor({"datafile": datafile_of(case["initial"]["datafile"]), "logLevel": "fatal"}) + api = {} + f.add_module({"name": "sections", "setup": lambda module_api: api.update(module_api)}) + events = [] + f.on("datafile_set", lambda details: events.append(details)) + self._expect(api, case["expectInitial"], None) + for operation in case["operations"]: + self.assertEqual(operation["action"], "setDatafile") + f.set_datafile(datafile_of(operation["datafile"]), operation["replace"]) + self._expect(api, operation["expect"], events[-1]) + + def _expect(self, api, expected, details) -> None: + if "sections" in expected: + self.assertEqual(set(details["sections"]), set(expected["sections"])) + for name, keys in expected["sections"].items(): + self.assertEqual(sorted(details["sections"][name]), sorted(keys), name) + for section, keys in expected.get("entryKeys", {}).items(): + self.assertEqual(sorted(api["get_entry_keys"](section)), sorted(keys), section) + for entry in expected.get("entries", []): + self.assertEqual(api["get_entry"](entry["section"], entry["key"]), entry["value"], entry) + + def test_a_datafile_given_as_a_dict_keeps_sections_and_returns_them(self) -> None: + datafile = {"schemaVersion": "4", "revision": "1", "segments": {}, "features": {}, "variables": {}, + "schemas": {"signUp": {"hash": "s1", "type": "object"}}, "note": "kept"} + f = create_featurevisor({"datafile": datafile, "logLevel": "fatal"}) + api = {} + f.add_module({"name": "sections", "setup": lambda module_api: api.update(module_api)}) + self.assertEqual(api["getEntryKeys"]("schemas"), ["signUp"]) + self.assertEqual(api["getEntryKeys"]("note"), []) + self.assertEqual(api["getEntryKeys"]("features"), []) + stored = f.datafile.get_datafile() + self.assertEqual(stored["note"], "kept") + self.assertIn("signUp", stored["schemas"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sdk_stateful.py b/tests/test_sdk_stateful.py index 927cfa3..2971f10 100644 --- a/tests/test_sdk_stateful.py +++ b/tests/test_sdk_stateful.py @@ -18,6 +18,8 @@ def _normalize_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]: normalized = [] for event in events: copy = {**event, "details": dict(event["details"])} + # "sections" in datafile_set is not yet part of the portable fixtures, as in JavaScript. + copy["details"].pop("sections", None) for key in ("features", "variables"): if key in copy["details"]: copy["details"][key] = sorted(copy["details"][key]) diff --git a/tests/test_set_datafile_result.py b/tests/test_set_datafile_result.py index 0e350cd..8feb9ea 100644 --- a/tests/test_set_datafile_result.py +++ b/tests/test_set_datafile_result.py @@ -58,12 +58,14 @@ def test_accepts_native_and_json_merge_replacement_and_unchanged_for_both_names( "revision": "2", "previousRevision": "1", "revisionChanged": True, "features": ["original", "next"] if replace else ["next"], "variables": ["original", "next"] if replace else ["next"], "replaced": replace, + "sections": {}, }) self.assertIs(setter(encode(incoming), replace), True) self.assertEqual(len(events), 2) self.assertEqual(events[1], { "revision": "2", "previousRevision": "2", "revisionChanged": False, "features": [], "variables": [], "replaced": replace, + "sections": {}, }) def test_rejection_preserves_state_and_reports_once_at_each_log_level(self): From 7cfd4a81062e79947a75699b9f2f895ec95b5b08 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Fri, 27 Nov 2026 22:17:10 +0100 Subject: [PATCH 02/21] fix: read $, \s, the dot and large numbers in conditions as JavaScript does Without the m flag, $ now matches only at the end of a value, never before a final line break. \s and \S follow JavaScript's whitespace, with the BOM and without U+001C to U+001F, and without the s flag a dot refuses only JavaScript's line terminators. Numbers compare as doubles, so integers above 2^53 that JavaScript cannot tell apart are equal. sdk-conditions.json pins each, and sdk-package-conditions.json now runs match_conditions with readers. --- conformance/sdk-conditions.json | 768 +++++++++++++++++++ conformance/sdk-package-conditions.json | 380 +++++++++ src/featurevisor/conditions.py | 57 +- src/featurevisor/evaluation_data_provider.py | 2 +- tests/test_package_conditions_conformance.py | 38 + 5 files changed, 1233 insertions(+), 12 deletions(-) create mode 100644 conformance/sdk-package-conditions.json create mode 100644 tests/test_package_conditions_conformance.py diff --git a/conformance/sdk-conditions.json b/conformance/sdk-conditions.json index 339a41b..f62fff4 100644 --- a/conformance/sdk-conditions.json +++ b/conformance/sdk-conditions.json @@ -10985,6 +10985,774 @@ "value": "matched" } } + }, + { + "name": "matches: $ matches at the end", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^[A-Z]{2}$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "DE" + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "matches: $ is the end only, never before a final line break", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^[A-Z]{2}$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "DE\n" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^[A-Z]{2}$" + } + } + }, + { + "name": "matches: ^ is the start only, never after a line break", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\d{5}$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "abc\n12345" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\d{5}$" + } + } + }, + { + "name": "matches: with the m flag ^ and $ match at every line", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\d{5}$", + "regexFlags": "m" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "abc\n12345" + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "matches: \\s matches a no-break space and the byte order mark", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^a\\sb\\sc$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "a\u00a0b\ufeffc" + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "matches: \\s does not match U+0085 or U+001C", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "\\s" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "a\u0085\u001cb" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "\\s" + } + } + }, + { + "name": "matches: \\S does not match a no-break space", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\S$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "\u00a0" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\S$" + } + } + }, + { + "name": "matches: a dot matches U+0085 and a vertical tab", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^..$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "\u0085\u000b" + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "matches: a dot does not match a line separator", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^.$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "\u2028" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^.$" + } + } + }, + { + "name": "matches: a dot does not match a carriage return", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^.$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "\r" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^.$" + } + } + }, + { + "name": "equals: integers above 2^53 compare as doubles", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "id", + "operator": "equals", + "value": 9007199254740993 + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "id": 9007199254740992 + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "greaterThan: integers above 2^53 compare as doubles", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "id", + "operator": "greaterThan", + "value": 9007199254740992 + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "id": 9007199254740993 + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "id", + "operator": "greaterThan", + "value": 9007199254740992 + } + } } ] } diff --git a/conformance/sdk-package-conditions.json b/conformance/sdk-package-conditions.json new file mode 100644 index 0000000..127a87a --- /dev/null +++ b/conformance/sdk-package-conditions.json @@ -0,0 +1,380 @@ +{ + "kind": "featurevisor.sdk-package-conditions", + "schemaVersion": 1, + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "dutch": { + "hash": "d1", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ] + }, + "payingDutch": { + "hash": "p1", + "conditions": { + "and": [ + "dutch", + { + "feature": "paid" + } + ] + } + } + }, + "features": { + "paid": { + "hash": "f1", + "bucketBy": "userId", + "traffic": [ + { + "key": "everyone", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": {} + }, + "context": { + "country": "nl" + }, + "cases": [ + { + "name": "a wildcard matches", + "conditions": "*", + "expected": true + }, + { + "name": "an attribute leaf reads the instance's context", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ], + "expected": true + }, + { + "name": "a call's context is merged over the instance's", + "conditions": "dutch", + "context": { + "country": "de" + }, + "expected": false + }, + { + "name": "a segment reads a feature through the instance", + "conditions": "payingDutch", + "expected": true + }, + { + "name": "a feature leaf is evaluated", + "conditions": { + "not": [ + { + "feature": "paid" + } + ] + }, + "expected": false + }, + { + "name": "conditions can be JSON text", + "conditions": "[\"dutch\"]", + "expected": true + }, + { + "name": "an input leaf reads through the reader beside a segment", + "conditions": { + "and": [ + "dutch", + { + "input": "accountType", + "operator": "equals", + "value": "business" + } + ] + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": true + }, + { + "name": "valueFrom compares two reads that agree", + "conditions": { + "input": "confirm", + "operator": "equals", + "valueFrom": { + "input": "password" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": true + }, + { + "name": "valueFrom compares two reads that differ", + "conditions": { + "input": "confirm", + "operator": "equals", + "valueFrom": { + "input": "password" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "b" + }, + "expected": false + }, + { + "name": "value is always a value, even an object naming a reader", + "conditions": { + "input": "confirm", + "operator": "equals", + "value": { + "input": "password" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": false + }, + { + "name": "a pattern read from a value never runs", + "conditions": { + "input": "confirm", + "operator": "matches", + "valueFrom": { + "input": "password" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": false + }, + { + "name": "a source no reader answers does not match", + "conditions": { + "input": "confirm", + "operator": "equals", + "valueFrom": { + "attribute": "country" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": false + }, + { + "name": "without a reader for its kind, a leaf does not match", + "conditions": { + "input": "accountType", + "operator": "equals", + "value": "business" + }, + "expected": false + }, + { + "name": "an absent read does not exist", + "conditions": { + "input": "missing", + "operator": "notExists" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "an absent read is not null", + "conditions": { + "input": "missing", + "operator": "isNull" + }, + "input": { + "nothing": null + }, + "expected": false + }, + { + "name": "a null read is null", + "conditions": { + "input": "nothing", + "operator": "isNull" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "a null read exists", + "conditions": { + "input": "nothing", + "operator": "exists" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "without a value to compare, an absent read equals", + "conditions": { + "input": "missing", + "operator": "equals" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "without a value to compare, a null read does not equal", + "conditions": { + "input": "nothing", + "operator": "equals" + }, + "input": { + "nothing": null + }, + "expected": false + }, + { + "name": "without a value to compare, a null read is not equal", + "conditions": { + "input": "nothing", + "operator": "notEquals" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "an absent valueFrom does not equal a null read", + "conditions": { + "input": "nothing", + "operator": "equals", + "valueFrom": { + "input": "missing" + } + }, + "input": { + "nothing": null + }, + "expected": false + }, + { + "name": "valueFrom compares numbers", + "conditions": { + "input": "guests", + "operator": "greaterThan", + "valueFrom": { + "input": "rooms" + } + }, + "input": { + "guests": 3, + "rooms": 2 + }, + "expected": true + }, + { + "name": "valueFrom compares timestamps", + "conditions": { + "input": "checkOut", + "operator": "after", + "valueFrom": { + "input": "checkIn" + } + }, + "input": { + "checkIn": "2026-12-01T14:00:00Z", + "checkOut": "2026-12-02T10:00:00Z" + }, + "expected": true + }, + { + "name": "a text that is not a timestamp is never after one", + "conditions": { + "input": "checkOut", + "operator": "after", + "valueFrom": { + "input": "checkIn" + } + }, + "input": { + "checkIn": "2026-12-01T14:00:00Z", + "checkOut": "tomorrow" + }, + "expected": false + }, + { + "name": "reads above 2^53 compare as doubles", + "conditions": { + "input": "first", + "operator": "equals", + "valueFrom": { + "input": "second" + } + }, + "input": { + "first": 9007199254740993, + "second": 9007199254740992 + }, + "expected": true + }, + { + "name": "an input leaf in a group with an attribute leaf", + "conditions": { + "or": [ + { + "attribute": "country", + "operator": "equals", + "value": "de" + }, + { + "input": "accountType", + "operator": "in", + "value": [ + "business", + "charity" + ] + } + ] + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": true + } + ] +} diff --git a/src/featurevisor/conditions.py b/src/featurevisor/conditions.py index be7e9e5..fc95860 100644 --- a/src/featurevisor/conditions.py +++ b/src/featurevisor/conditions.py @@ -1,6 +1,7 @@ from __future__ import annotations import datetime as dt +import math import re from dataclasses import dataclass from typing import Any, Callable @@ -14,13 +15,29 @@ MAX_PORTABLE_DATE = dt.datetime(9999, 12, 31, 23, 59, 59, 999000, tzinfo=dt.timezone.utc) -def normalize_portable_regex(pattern: str) -> str: - """Use JS ASCII digit and word shorthands without altering Unicode whitespace.""" +_PORTABLE_SPACES = "\\t\\n\\x0b\\f\\r \\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff" +_PORTABLE_NOT_SPACES = ("\\x00-\\x08\\x0e-\\x1f\\x21-\\x9f\\xa1-\\u167f\\u1681-\\u1fff\\u200b-\\u2027\\u202a-\\u202e" + "\\u2030-\\u205e\\u2060-\\u2fff\\u3001-\\ufefe\\uff00-\\U0010ffff") + + +def normalize_portable_regex(pattern: str, flags: str = "") -> str: + """A portable pattern in Python's syntax, meaning what it means in JavaScript with the same flags. + + \\d and \\w are ASCII, \\s is JavaScript's whitespace, a dot refuses only + JavaScript's line terminators, and without m a $ matches at the very end, + never before a final line break as Python's does. + """ + multiline = "m" in flags + dot_all = "s" in flags inside = { "d": "0-9", "D": r"\x00-\x2F\x3A-\U0010FFFF", "w": "A-Za-z0-9_", "W": r"\x00-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\U0010FFFF", + "s": _PORTABLE_SPACES, "S": _PORTABLE_NOT_SPACES, + } + outside = { + "d": "[0-9]", "D": "[^0-9]", "w": "(?-i:[A-Za-z0-9_])", "W": "(?-i:[^A-Za-z0-9_])", + "s": f"[{_PORTABLE_SPACES}]", "S": f"[^{_PORTABLE_SPACES}]", } - outside = {"d": "[0-9]", "D": "[^0-9]", "w": "(?-i:[A-Za-z0-9_])", "W": "(?-i:[^A-Za-z0-9_])"} result: list[str] = [] in_class = False index = 0 @@ -31,10 +48,19 @@ def normalize_portable_regex(pattern: str) -> str: result.append((inside if in_class else outside).get(escaped, pattern[index:index + 2])) index += 2 continue - if char == "[" and not in_class: + if in_class: + if char == "]": + in_class = False + elif char == "[": in_class = True - elif char == "]" and in_class: - in_class = False + elif char == "$" and not multiline: + result.append("\\Z") + index += 1 + continue + elif char == "." and not dot_all: + result.append("[^\\n\\r\\u2028\\u2029]") + index += 1 + continue result.append(char) index += 1 return "".join(result) @@ -79,11 +105,19 @@ def prepare_conditions(conditions: Any) -> Any: return conditions +def _binary64(number: int | float) -> float: + """A number as JavaScript reads it, a double, so integers above 2^53 compare as JavaScript compares them.""" + try: + return float(number) + except OverflowError: + return math.inf if number > 0 else -math.inf + + def _strict_equal(left: Any, right: Any) -> bool: if isinstance(left, bool) or isinstance(right, bool): return isinstance(left, bool) and isinstance(right, bool) and left == right if isinstance(left, (int, float)) and isinstance(right, (int, float)): - return left == right + return _binary64(left) == _binary64(right) if left is None or right is None: return left is None and right is None if isinstance(left, str) and isinstance(right, str): @@ -250,14 +284,15 @@ def _value_is_matched( if operator == "notMatches": return not get_regex(value, regex_flags).search(context_value) if not isinstance(context_value, bool) and not isinstance(value, bool) and isinstance(context_value, (int, float)) and isinstance(value, (int, float)): + left, right = _binary64(context_value), _binary64(value) if operator == "greaterThan": - return context_value > value + return left > right if operator == "greaterThanOrEquals": - return context_value >= value + return left >= right if operator == "lessThan": - return context_value < value + return left < right if operator == "lessThanOrEquals": - return context_value <= value + return left <= right if operator == "exists": return context_value is not MISSING if operator == "notExists": diff --git a/src/featurevisor/evaluation_data_provider.py b/src/featurevisor/evaluation_data_provider.py index 16aa39a..23e0af9 100644 --- a/src/featurevisor/evaluation_data_provider.py +++ b/src/featurevisor/evaluation_data_provider.py @@ -200,7 +200,7 @@ def get_regex(self, regex_string: str, regex_flags: str = "") -> re.Pattern[str] flags |= re.MULTILINE if "s" in regex_flags: flags |= re.DOTALL - self.regex_cache[key] = re.compile(normalize_portable_regex(regex_string), flags) + self.regex_cache[key] = re.compile(normalize_portable_regex(regex_string, regex_flags), flags) return self.regex_cache[key] def all_conditions_are_matched(self, conditions: Any, context: Context) -> bool: diff --git a/tests/test_package_conditions_conformance.py b/tests/test_package_conditions_conformance.py new file mode 100644 index 0000000..6598039 --- /dev/null +++ b/tests/test_package_conditions_conformance.py @@ -0,0 +1,38 @@ +import json +import unittest +from pathlib import Path + +from featurevisor import create_featurevisor +from featurevisor.conditions import MISSING + +ROOT = Path(__file__).resolve().parents[1] +FIXTURE = json.loads((ROOT / "conformance" / "sdk-package-conditions.json").read_text()) + + +class PackageConditionsConformanceTests(unittest.TestCase): + """Runs conformance/sdk-package-conditions.json: match_conditions with readers, as packages call it.""" + + def test_fixture_version(self) -> None: + self.assertEqual(FIXTURE["kind"], "featurevisor.sdk-package-conditions") + self.assertEqual(FIXTURE["schemaVersion"], 1) + self.assertTrue(FIXTURE["cases"]) + + def test_every_case(self) -> None: + for case in FIXTURE["cases"]: + with self.subTest(case=case["name"]): + f = create_featurevisor({"datafile": FIXTURE["datafile"], "context": FIXTURE["context"], "logLevel": "fatal"}) + api = {} + f.add_module({"name": "package", "setup": lambda module_api: api.update(module_api)}) + options = None + if "input" in case: + values = case["input"] + # An absent key reads as nothing, which differs from null. + options = {"readers": {"input": lambda path, values=values: values.get(path, MISSING)}} + # Twice, so a cached answer is the answer. + for _ in range(2): + matched = api["match_conditions"](case["conditions"], case.get("context", {}), options) + self.assertEqual(matched, case["expected"]) + + +if __name__ == "__main__": + unittest.main() From 16e6234b88678937f8d1aa1b672d5f388bea02bd Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Fri, 27 Nov 2026 22:17:10 +0100 Subject: [PATCH 03/21] feat(schemas): read patterns with the u flag and fail closed as JavaScript does Patterns now mean what JavaScript means with the u flag, so what u rejects, such as an escape without a meaning or a lone brace, fails every value, and \u{...} escapes compile. format holds issue entries back, and additionalProperties other than true or a schema takes no extra key. The conformance runner checks diagnostics, and the differential test reads the shared schemas-datafile.json instead of its own copies. --- README.md | 4 + .../schemas-datafile.json | 191 ++ conformance/schemas-validation.json | 1552 +++++++++++++++++ src/featurevisor/schemas/_engine.py | 11 +- src/featurevisor/schemas/_patterns.py | 120 +- tests/fixtures/schemas/built-datafile.json | 1 - tests/test_schemas.py | 8 +- tests/test_schemas_conformance.py | 24 +- 8 files changed, 1859 insertions(+), 52 deletions(-) rename tests/fixtures/schemas/built-datafile-expected.json => conformance/schemas-datafile.json (69%) delete mode 100644 tests/fixtures/schemas/built-datafile.json diff --git a/README.md b/README.md index f7c4bc3..74672af 100644 --- a/README.md +++ b/README.md @@ -807,6 +807,10 @@ result = await sign_up.avalidate(request) Handles are safe to use from many threads. `close()` on the instance, or leaving a `with create_schemas(f) as s:` block, stops its subscriptions and removes its module from the Featurevisor instance. +### Patterns + +Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value with one `schema_pattern_unsupported` diagnostic. A mutation whose operations cannot be applied fails the value with `refineError` and one `schema_mutation_error` diagnostic, and so does a schema that follows references more than 128 deep without reading deeper into the value, with `schema_reference_depth`. + ## CLI usage Install the package in your Python environment: diff --git a/tests/fixtures/schemas/built-datafile-expected.json b/conformance/schemas-datafile.json similarity index 69% rename from tests/fixtures/schemas/built-datafile-expected.json rename to conformance/schemas-datafile.json index 80f4847..1cd37f0 100644 --- a/tests/fixtures/schemas/built-datafile-expected.json +++ b/conformance/schemas-datafile.json @@ -1,4 +1,195 @@ { + "kind": "featurevisor.schemas-datafile", + "schemaVersion": 1, + "datafile": { + "schemaVersion": "4", + "featurevisorVersion": "4.13.0", + "revision": "lKLik9RrAm", + "segments": { + "netherlands": { + "conditions": "{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}" + }, + "paying": { + "conditions": "{\"attribute\":\"plan\",\"operator\":\"equals\",\"value\":\"paid\"}" + } + }, + "features": {}, + "variables": {}, + "schemas": { + "checkout": { + "hash": "gSboXrZWcM", + "type": "object", + "properties": { + "billingCountry": { + "type": "string" + }, + "shippingCountry": { + "type": "string" + }, + "customsDescription": { + "type": "string" + }, + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "billingCountry" + ], + "mutations": [ + { + "key": "shipsAbroad", + "conditions": "[{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}},\"paying\"]", + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "customsDescription" + } + ] + } + ] + }, + "register": { + "hash": "XlDf9sip1o", + "type": "object", + "properties": { + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string", + "annotations": { + "title": "Confirmation" + } + }, + "shippingCountry": { + "type": "string" + }, + "billingCountry": { + "type": "string" + } + }, + "required": [ + "password" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": "{\"input\":\"confirmPassword\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"password\"}}", + "path": "confirmPassword", + "message": "{title} does not match the password" + }, + { + "key": "dutchShippingCountry", + "conditions": "[\"netherlands\",{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}}]", + "path": "shippingCountry", + "message": "We ship Dutch orders to the billing country only" + } + ] + }, + "signUp": { + "hash": "wLXjboTQnZ", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ], + "annotations": { + "title": "Account type", + "options": { + "personal": { + "title": "Personal" + }, + "business": { + "title": "Business" + } + } + } + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 40, + "annotations": { + "title": "Display name", + "examples": [ + "Ada", + "Grace Hopper" + ] + } + }, + "taxId": { + "type": "string", + "annotations": { + "title": "VAT number" + } + } + }, + "required": [ + "accountType", + "displayName" + ], + "messages": { + "displayName": { + "minLength": "Use at least {minLength} characters" + } + }, + "annotations": { + "title": "Create your account", + "order": [ + "accountType", + "displayName", + "taxId" + ] + }, + "mutations": [ + { + "key": "business", + "conditions": "{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}", + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + }, + { + "op": "set", + "path": [ + "properties", + "taxId", + "pattern" + ], + "value": "^[A-Z]{2}[0-9]{9}$" + }, + { + "op": "set", + "path": [ + "properties", + "taxId", + "messages" + ], + "value": { + "pattern": "Enter your VAT number, such as DE123456789" + } + } + ] + } + ] + } + } + }, "cases": [ { "schema": "signUp", diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index d1d6b64..e5f79a7 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -2593,6 +2593,1558 @@ } } ] + }, + { + "name": "a format issue holds every issue entry back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "checkIn": { + "type": "string", + "format": "date-time" + }, + "checkOut": { + "type": "string", + "format": "date-time" + } + }, + "issues": [ + { + "key": "checkOutAfterCheckIn", + "conditions": [ + { + "not": [ + { + "input": "checkOut", + "operator": "after", + "valueFrom": { + "input": "checkIn" + } + } + ] + } + ], + "path": "checkOut", + "message": "Check out after check in" + } + ] + } + }, + "schema": "subject", + "value": { + "checkIn": "2026-12-01T14:00:00Z", + "checkOut": "tomorrow" + }, + "issues": [ + { + "code": "format", + "path": [ + "checkOut" + ], + "params": { + "format": "date-time" + } + } + ] + }, + { + "name": "an issue entry compares valid timestamps", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "checkIn": { + "type": "string", + "format": "date-time" + }, + "checkOut": { + "type": "string", + "format": "date-time" + } + }, + "issues": [ + { + "key": "checkOutAfterCheckIn", + "conditions": [ + { + "not": [ + { + "input": "checkOut", + "operator": "after", + "valueFrom": { + "input": "checkIn" + } + } + ] + } + ], + "path": "checkOut", + "message": "Check out after check in" + } + ] + } + }, + "schema": "subject", + "value": { + "checkIn": "2026-12-02T10:00:00Z", + "checkOut": "2026-12-01T10:00:00Z" + }, + "issues": [ + { + "code": "refine", + "path": [ + "checkOut" + ], + "params": { + "refine": "checkOutAfterCheckIn" + } + } + ] + }, + { + "name": "-0 equals 0 in const", + "schemas": { + "subject": { + "hash": "subject-1", + "const": 0 + } + }, + "schema": "subject", + "value": -0, + "issues": [] + }, + { + "name": "0 equals -0 in enum", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + -0 + ] + } + }, + "schema": "subject", + "value": 0, + "issues": [] + }, + { + "name": "uniqueItems counts -0 and 0 as one value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "number" + }, + "uniqueItems": true + } + }, + "schema": "subject", + "value": [ + 0, + -0 + ], + "issues": [ + { + "code": "uniqueItems", + "path": [], + "params": { + "index": 1 + } + } + ] + }, + { + "name": "a boolean never equals a number in const", + "schemas": { + "subject": { + "hash": "subject-1", + "const": 0 + } + }, + "schema": "subject", + "value": false, + "issues": [ + { + "code": "const", + "path": [], + "params": { + "const": 0 + } + } + ] + }, + { + "name": "a boolean never equals a number in enum", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + 1, + "a" + ] + } + }, + "schema": "subject", + "value": true, + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + 1, + "a" + ] + } + } + ] + }, + { + "name": "integers above 2^53 compare as doubles in const", + "schemas": { + "subject": { + "hash": "subject-1", + "const": 9007199254740993 + } + }, + "schema": "subject", + "value": 9007199254740992, + "issues": [] + }, + { + "name": "integers above 2^53 compare as doubles in enum", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + 9007199254740993 + ] + } + }, + "schema": "subject", + "value": 9007199254740992, + "issues": [] + }, + { + "name": "integers above 2^53 compare as doubles in maximum", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer", + "maximum": 9007199254740992 + } + }, + "schema": "subject", + "value": 9007199254740993, + "issues": [] + }, + { + "name": "a dot takes an emoji as one character", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^.$" + } + }, + "schema": "subject", + "value": "😀", + "issues": [] + }, + { + "name": "a negated class takes an emoji as one character", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^[^a]$" + } + }, + "schema": "subject", + "value": "😀", + "issues": [] + }, + { + "name": "a pattern counts an emoji as one character, as lengths do", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^.{2}$" + } + }, + "schema": "subject", + "value": "😀", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^.{2}$" + } + } + ] + }, + { + "name": "$ matches at the end only, never before a final line break", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^[A-Z]{2}$" + } + }, + "schema": "subject", + "value": "DE\n", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^[A-Z]{2}$" + } + } + ] + }, + { + "name": "^ matches at the start only, never after a line break", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^a" + } + }, + "schema": "subject", + "value": "b\na", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^a" + } + } + ] + }, + { + "name": "\\s matches a no-break space and the byte order mark", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\s\\s$" + } + }, + "schema": "subject", + "value": "\u00a0\ufeff", + "issues": [] + }, + { + "name": "\\s matches a vertical tab, a line separator and an ideographic space", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\s{3}$" + } + }, + "schema": "subject", + "value": "\u000b\u2028\u3000", + "issues": [] + }, + { + "name": "\\s does not match U+0085 or U+001C", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "\\s" + } + }, + "schema": "subject", + "value": "a\u0085\u001cb", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "\\s" + } + } + ] + }, + { + "name": "\\S does not match a no-break space", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\S$" + } + }, + "schema": "subject", + "value": "\u00a0", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\S$" + } + } + ] + }, + { + "name": "a dot matches U+0085 and a vertical tab", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^..$" + } + }, + "schema": "subject", + "value": "\u0085\u000b", + "issues": [] + }, + { + "name": "a dot does not match a line separator", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^.$" + } + }, + "schema": "subject", + "value": "\u2028", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^.$" + } + } + ] + }, + { + "name": "a dot does not match a carriage return", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^.$" + } + }, + "schema": "subject", + "value": "\r", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^.$" + } + } + ] + }, + { + "name": "\\d is ASCII", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\d$" + } + }, + "schema": "subject", + "value": "\u0663", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\d$" + } + } + ] + }, + { + "name": "\\w is ASCII", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\w$" + } + }, + "schema": "subject", + "value": "é", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\w$" + } + } + ] + }, + { + "name": "an escaped slash is a slash", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\/$" + } + }, + "schema": "subject", + "value": "/", + "issues": [] + }, + { + "name": "an escaped hyphen inside a class is a hyphen", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^[a\\-]$" + } + }, + "schema": "subject", + "value": "-", + "issues": [] + }, + { + "name": "a pattern that does not compile fails every value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "(" + } + }, + "schema": "subject", + "value": "(", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "(" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "a lone brace does not compile with u", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "a{" + } + }, + "schema": "subject", + "value": "a{", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "a{" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "a lone closing bracket does not compile with u", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "a]" + } + }, + "schema": "subject", + "value": "a]", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "a]" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "an escaped hyphen outside a class does not compile with u", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\-$" + } + }, + "schema": "subject", + "value": "-", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\-$" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "an escaped letter without a meaning does not compile with u", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\a$" + } + }, + "schema": "subject", + "value": "a", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\a$" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "a mutation with an unknown operation fails the value closed", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "mutations": [ + { + "key": "broken", + "conditions": "*", + "operations": [ + { + "op": "explode", + "path": [ + "properties", + "name", + "minLength" + ], + "value": 1 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "name": "Ada" + }, + "issues": [ + { + "code": "refineError", + "path": [], + "params": {} + } + ], + "diagnostics": [ + "schema_mutation_error" + ] + }, + { + "name": "a mutation through an unsafe key fails the value closed", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "mutations": [ + { + "key": "broken", + "conditions": "*", + "operations": [ + { + "op": "set", + "path": [ + "properties", + "constructor", + "maxLength" + ], + "value": 1 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "name": "Ada" + }, + "issues": [ + { + "code": "refineError", + "path": [], + "params": {} + } + ], + "diagnostics": [ + "schema_mutation_error" + ] + }, + { + "name": "additionalProperties false takes no key beyond properties", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "a": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "schema": "subject", + "value": { + "a": "x", + "b": 1 + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "b" + ], + "params": { + "key": "b" + } + } + ] + }, + { + "name": "additionalProperties false without properties takes no key", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "additionalProperties": false + } + }, + "schema": "subject", + "value": { + "b": "x" + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "b" + ], + "params": { + "key": "b" + } + } + ] + }, + { + "name": "additionalProperties other than true or a schema takes no extra key", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "additionalProperties": null + } + }, + "schema": "subject", + "value": { + "b": "x" + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "b" + ], + "params": { + "key": "b" + } + } + ] + }, + { + "name": "a schema that references itself reads deeper into the value each time", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "oneOf": [ + { + "schema": "subject" + }, + { + "type": "string" + } + ] + } + } + }, + "schema": "subject", + "value": [ + "a", + [ + "b", + [ + "c" + ] + ] + ], + "issues": [] + }, + { + "name": "a schema that references itself reports the item that fails", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "oneOf": [ + { + "schema": "subject" + }, + { + "type": "string" + } + ] + } + } + }, + "schema": "subject", + "value": [ + "a", + [ + 1 + ] + ], + "issues": [ + { + "code": "oneOf", + "path": [ + 1, + 0 + ], + "params": { + "matches": 0 + } + } + ] + }, + { + "name": "a reference loop fails closed at 128 references", + "schemas": { + "subject": { + "hash": "subject-1", + "schema": "other" + }, + "other": { + "hash": "other-1", + "schema": "subject" + } + }, + "schema": "subject", + "value": "x", + "issues": [ + { + "code": "refineError", + "path": [], + "params": {} + } + ], + "diagnostics": [ + "schema_reference_depth" + ] + }, + { + "name": "a schema that references itself at the same value fails closed at 128 references", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "schema": "subject" + }, + { + "type": "string" + } + ] + } + }, + "schema": "subject", + "value": 1, + "issues": [ + { + "code": "oneOf", + "path": [], + "params": { + "matches": 0 + } + } + ], + "diagnostics": [ + "schema_reference_depth" + ] + }, + { + "name": "references at the same value count to exactly 128", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "schema": "subject" + }, + { + "type": "string" + } + ] + } + }, + "schema": "subject", + "value": "a", + "issues": [], + "diagnostics": [ + "schema_reference_depth" + ] + }, + { + "name": "a mutation's conditions can be JSON text", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ] + }, + "taxId": { + "type": "string" + } + }, + "required": [ + "accountType" + ], + "mutations": [ + { + "key": "business", + "conditions": "[{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}]", + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "accountType": "business" + }, + "issues": [ + { + "code": "required", + "path": [ + "taxId" + ], + "params": { + "key": "taxId" + }, + "mutation": "business" + } + ] + }, + { + "name": "an issue entry's conditions can be JSON text", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "issues": [ + { + "key": "passwordsDiffer", + "conditions": "[{\"input\":\"confirmPassword\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"password\"}}]", + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "password": "lovelace", + "confirmPassword": "lovelaced" + }, + "issues": [ + { + "code": "refine", + "path": [ + "confirmPassword" + ], + "params": { + "refine": "passwordsDiffer" + } + } + ] + }, + { + "name": "JSON text conditions read segments and the context", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ] + }, + "taxId": { + "type": "string" + } + }, + "required": [ + "accountType" + ], + "mutations": [ + { + "key": "business", + "conditions": "{\"and\":[\"dutch\",{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}]}", + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + } + ] + } + ] + } + }, + "segments": { + "dutch": { + "hash": "dutch-1", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ] + } + }, + "context": { + "country": "nl" + }, + "schema": "subject", + "value": { + "accountType": "business" + }, + "issues": [ + { + "code": "required", + "path": [ + "taxId" + ], + "params": { + "key": "taxId" + }, + "mutation": "business" + } + ] + }, + { + "name": "a missing field's title is in its issue's params", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "annotations": { + "title": "Name" + } + } + }, + "required": [ + "name" + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "required", + "path": [ + "name" + ], + "params": { + "key": "name", + "title": "Name" + } + } + ] + }, + { + "name": "a field's title is in its issue's params", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "annotations": { + "title": "Name" + }, + "minLength": 3 + } + }, + "required": [ + "name" + ] + } + }, + "schema": "subject", + "value": { + "name": "A" + }, + "issues": [ + { + "code": "minLength", + "path": [ + "name" + ], + "params": { + "minLength": 3, + "length": 1, + "title": "Name" + } + } + ] + }, + { + "name": "an enum gives its choices' titles when every choice has one", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "enum": [ + "a", + "b" + ], + "annotations": { + "options": { + "a": { + "title": "A" + }, + "b": { + "title": "B" + } + } + } + } + }, + "schema": "subject", + "value": "c", + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + "a", + "b" + ], + "titles": [ + "A", + "B" + ] + } + } + ] + }, + { + "name": "a oneOf of consts gives its branches' titles", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "const": "a", + "annotations": { + "title": "A" + } + }, + { + "const": "b", + "annotations": { + "title": "B" + } + } + ] + } + }, + "schema": "subject", + "value": "c", + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + "a", + "b" + ], + "titles": [ + "A", + "B" + ] + } + } + ] + }, + { + "name": "a reference's own title wins over the referenced schema's", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "city": { + "schema": "city", + "annotations": { + "title": "Town" + } + } + } + }, + "city": { + "hash": "city-1", + "type": "string", + "minLength": 2, + "annotations": { + "title": "City" + } + } + }, + "schema": "subject", + "value": { + "city": "A" + }, + "issues": [ + { + "code": "minLength", + "path": [ + "city" + ], + "params": { + "minLength": 2, + "length": 1, + "title": "Town" + } + } + ] + }, + { + "name": "rules beside a reference are ignored", + "schemas": { + "subject": { + "hash": "subject-1", + "schema": "text", + "minLength": 100 + }, + "text": { + "hash": "text-1", + "type": "string" + } + }, + "schema": "subject", + "value": "x", + "issues": [] + }, + { + "name": "a type beside oneOf is ignored", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number", + "oneOf": [ + { + "type": "string" + }, + { + "type": "boolean" + } + ] + } + }, + "schema": "subject", + "value": "x", + "issues": [] + }, + { + "name": "required without properties is ignored", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "required": [ + "a" + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [] + }, + { + "name": "const skips the typed rules", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "const": "a", + "minLength": 5 + } + }, + "schema": "subject", + "value": "a", + "issues": [] + }, + { + "name": "enum skips the typed rules", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "enum": [ + "a" + ], + "pattern": "^b" + } + }, + "schema": "subject", + "value": "a", + "issues": [] + }, + { + "name": "a node without a type skips the rules of other kinds", + "schemas": { + "subject": { + "hash": "subject-1", + "minLength": 3 + } + }, + "schema": "subject", + "value": 5, + "issues": [] + }, + { + "name": "a node without a type applies the rules of the value's kind", + "schemas": { + "subject": { + "hash": "subject-1", + "minLength": 3 + } + }, + "schema": "subject", + "value": "ab", + "issues": [ + { + "code": "minLength", + "path": [], + "params": { + "minLength": 3, + "length": 2 + } + } + ] + }, + { + "name": "a mutation under items reads each item", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "code": { + "type": "string" + } + }, + "required": [ + "kind" + ], + "mutations": [ + { + "key": "coded", + "conditions": [ + { + "input": "kind", + "operator": "equals", + "value": "coded" + } + ], + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "code" + } + ] + } + ] + } + } + }, + "schema": "subject", + "value": [ + { + "kind": "plain" + }, + { + "kind": "coded" + } + ], + "issues": [ + { + "code": "required", + "path": [ + 1, + "code" + ], + "params": { + "key": "code" + }, + "mutation": "coded" + } + ] + }, + { + "name": "a mutation can change a node's type", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "mutations": [ + { + "key": "numeric", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "paid" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "type" + ], + "value": "number" + } + ] + } + ] + } + }, + "context": { + "plan": "paid" + }, + "schema": "subject", + "value": "x", + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "number", + "received": "string" + }, + "mutation": "numeric" + } + ] } ] } diff --git a/src/featurevisor/schemas/_engine.py b/src/featurevisor/schemas/_engine.py index 4043e04..53e93f9 100644 --- a/src/featurevisor/schemas/_engine.py +++ b/src/featurevisor/schemas/_engine.py @@ -59,7 +59,10 @@ def mutation_failed(self, schema: str, error: Exception) -> None: ... # without reading deeper into the value gets this far, so the walk fails closed there. MAX_REFERENCE_DEPTH = 128 -SHAPE_CODES = frozenset({"type", "required", "enum", "const", "additionalProperties", "oneOf", "schemaNotFound"}) +# Issues after which an object's issues could not trust the values they compare, format among them, +# since the operators that read timestamps and versions cannot compare a value that is neither. +SHAPE_CODES = frozenset({"type", "required", "enum", "const", "additionalProperties", "oneOf", "schemaNotFound", + "format"}) def report(run: Run, at: Position, code: str, params: dict[str, Any], path: list[Any] | None = None, @@ -299,7 +302,9 @@ def _compile_object(node: dict[str, Any], resolve: Resolver) -> Validator: required = [key for key in node.get("required", []) if isinstance(key, str)] if isinstance(node.get("required"), list) else [] has_additional = "additionalProperties" in node additional = node.get("additionalProperties") - compiled_additional = compile_node(additional, resolve) if has_additional and additional is not True else None + compiled_additional = compile_node(additional, resolve) if isinstance(additional, dict) else None + # Anything but true or a schema, false included, takes no key beyond properties. + closed = has_additional and additional is not True and compiled_additional is None def validate(value: Any, run: Run, at: Position) -> None: if properties is not None: @@ -318,7 +323,7 @@ def validate(value: Any, run: Run, at: Position) -> None: continue elif compiled_additional is not None: compiled_additional(child, run, Position([*at.path, key], Lookup([*at.lookup.mpath, "*"], at.lookup.scopes))) - elif properties is not None: + elif properties is not None or closed: # An extra key has no field of its own, so the object that rejects it words its issue, without a title. report(run, at, "additionalProperties", {"key": key}, [*at.path, key], Lookup(at.lookup.mpath, at.lookup.scopes)) elif not is_primitive(child): diff --git a/src/featurevisor/schemas/_patterns.py b/src/featurevisor/schemas/_patterns.py index c6f7fae..cf2af66 100644 --- a/src/featurevisor/schemas/_patterns.py +++ b/src/featurevisor/schemas/_patterns.py @@ -1,13 +1,11 @@ -"""Schema patterns, written for JavaScript's RegExp without flags, compiled to mean the same in Python's re. +"""Schema patterns, written for JavaScript's RegExp with the u flag, compiled to mean the same in Python's re. -Patterns compile with re.ASCII, so \\w, \\d and \\b keep to ASCII as in -JavaScript. Without the rewrites, Python's $ matches before a final line break, -its \\s takes U+001C to U+001F and misses the BOM, its . takes \\r, U+2028 and -U+2029, and it refuses unknown letter escapes such as \\p, which JavaScript reads -as the letter. - -One difference stays: JavaScript without flags reads a string in UTF-16 units, -so ^.$ refuses an emoji there and accepts it here. +Both read code points, so ^.$ takes an emoji in each. Patterns compile with +re.ASCII, so \\w, \\d and \\b keep to ASCII as in JavaScript. Without the +rewrites, Python's $ matches before a final line break, its \\s takes U+001C to +U+001F and misses the BOM, and its . takes \\r, U+2028 and U+2029. What the u +flag rejects, such as an escaped letter without a meaning or a lone brace, does +not compile here either, so it fails every value as it does in JavaScript. """ from __future__ import annotations @@ -30,8 +28,9 @@ def compile_pattern(source: str) -> re.Pattern[str] | None: with _lock: if source in _cache: return _cache[source] + translated = translate(source) try: - compiled: re.Pattern[str] | None = re.compile(translate(source), re.ASCII) + compiled: re.Pattern[str] | None = None if translated is None else re.compile(translated, re.ASCII) except (re.error, OverflowError, ValueError): compiled = None with _lock: @@ -58,17 +57,45 @@ def _quantifier_end(source: str, start: int) -> int: return index if index < len(source) and source[index] == "}" else -1 -def translate(source: str) -> str: - """JavaScript's pattern in Python's syntax.""" +_HEX = "0123456789abcdefABCDEF" +# Characters the u flag lets an escape name as themselves, besides - in a class. +_SYNTAX = "^$\\.*+?()[]{}|/" +_NO_ATOM, _CHARACTER, _CLASS_ESCAPE = 0, 1, 2 + + +def translate(source: str) -> str | None: + """JavaScript's pattern in Python's syntax, or None for one the u flag rejects.""" out: list[str] = [] in_class = False + # The class's last item, which a dash can make the low end of a range, and whether one waits for its high end. + last_atom = _NO_ATOM + range_pending = False index = 0 length = len(source) + + def class_item(atom: int) -> bool: + nonlocal last_atom, range_pending + if not in_class: + return True + if range_pending: + # The u flag lets no class, such as \\d, bound a range. + if atom == _CLASS_ESCAPE or last_atom == _CLASS_ESCAPE: + return False + last_atom = _NO_ATOM + range_pending = False + else: + last_atom = atom + return True + while index < length: current = source[index] - if current == "\\" and index + 1 < length: + if current == "\\": + if index + 1 >= length: + return None code = source[index + 1] index += 2 + if not class_item(_CLASS_ESCAPE if code in "dDwWsS" else _CHARACTER): + return None if code == "d": out.append("0-9" if in_class else "[0-9]") elif code == "D": @@ -86,46 +113,62 @@ def translate(source: str) -> str: elif code == "b": out.append("\\x08" if in_class else "\\b") elif code == "B": - out.append("B" if in_class else "\\B") + if in_class: + return None + out.append("\\B") elif code in "nrtf": out.append("\\" + code) elif code == "u": hexadecimal = source[index:index + 4] - if len(hexadecimal) == 4 and all(c in "0123456789abcdefABCDEF" for c in hexadecimal): + if len(hexadecimal) == 4 and all(c in _HEX for c in hexadecimal): out.append("\\u" + hexadecimal) index += 4 + elif index < length and source[index] == "{": + end = source.find("}", index + 1) + digits = source[index + 1:end] if end != -1 else "" + if not digits or not all(c in _HEX for c in digits) or int(digits, 16) > 0x10FFFF: + return None + out.append(f"\\U{int(digits, 16):08x}") + index = end + 1 else: - out.append("u") + return None elif code == "x": hexadecimal = source[index:index + 2] - if len(hexadecimal) == 2 and all(c in "0123456789abcdefABCDEF" for c in hexadecimal): - out.append("\\x" + hexadecimal) - index += 2 - else: - out.append("x") + if len(hexadecimal) != 2 or not all(c in _HEX for c in hexadecimal): + return None + out.append("\\x" + hexadecimal) + index += 2 elif code == "c": letter = source[index] if index < length else "" - if letter.isascii() and letter.isalpha(): - out.append(f"\\x{ord(letter) % 32:02x}") - index += 1 - else: - out.append("\\\\c") + if not (letter.isascii() and letter.isalpha()): + return None + out.append(f"\\x{ord(letter) % 32:02x}") + index += 1 elif code == "0": + if index < length and source[index] in "0123456789": + return None out.append("\\x00") - elif code.isdigit(): + elif code in "123456789": # A back reference, which lint refuses in delivered schemas. out.append("\\" + code) - elif code.isalpha(): - # Without flags JavaScript reads an unknown escape, such as \p, as the letter. - out.append(code) - else: + elif code in _SYNTAX or (in_class and code == "-"): out.append(re.escape(code)) + else: + # The u flag rejects an escape without a meaning, such as \\a or \\- outside a class. + return None continue if in_class: if current == "]": in_class = False out.append("]") - elif current in "[&~|" or (current == "-" and index + 1 < length and source[index + 1] == "-"): + index += 1 + continue + if current == "-" and last_atom != _NO_ATOM and not range_pending and index + 1 < length \ + and source[index + 1] != "]": + range_pending = True + elif not class_item(_CHARACTER): + return None + if current in "[&~|" or (current == "-" and index + 1 < length and source[index + 1] == "-"): # Python warns of set operations on these, where JavaScript reads the characters. out.append("\\" + current) else: @@ -144,6 +187,8 @@ def translate(source: str) -> str: index += 2 continue in_class = True + last_atom = _NO_ATOM + range_pending = False out.append("[") if index + 1 < length and source[index + 1] == "^": out.append("^") @@ -155,12 +200,11 @@ def translate(source: str) -> str: elif current == "{": end = _quantifier_end(source, index) if end == -1: - out.append("\\{") - else: - out.append(source[index:end + 1]) - index = end - elif current == "}": - out.append("\\}") + return None + out.append(source[index:end + 1]) + index = end + elif current in "}]": + return None else: out.append(current) index += 1 diff --git a/tests/fixtures/schemas/built-datafile.json b/tests/fixtures/schemas/built-datafile.json deleted file mode 100644 index 5bb7417..0000000 --- a/tests/fixtures/schemas/built-datafile.json +++ /dev/null @@ -1 +0,0 @@ -{"schemaVersion":"4","featurevisorVersion":"4.13.0","revision":"2","segments":{"netherlands":{"conditions":"{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}"},"paying":{"conditions":"{\"attribute\":\"plan\",\"operator\":\"equals\",\"value\":\"paid\"}"}},"features":{},"variables":{},"schemas":{"checkout":{"hash":"gSboXrZWcM","type":"object","properties":{"billingCountry":{"type":"string"},"shippingCountry":{"type":"string"},"customsDescription":{"type":"string"},"password":{"type":"string"},"confirmPassword":{"type":"string"}},"required":["billingCountry"],"mutations":[{"key":"shipsAbroad","conditions":"[{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}},\"paying\"]","operations":[{"op":"appendUnique","path":["required"],"value":"customsDescription"}]}]},"register":{"hash":"XlDf9sip1o","type":"object","properties":{"password":{"type":"string","minLength":8},"confirmPassword":{"type":"string","annotations":{"title":"Confirmation"}},"shippingCountry":{"type":"string"},"billingCountry":{"type":"string"}},"required":["password"],"issues":[{"key":"passwordsDiffer","conditions":"{\"input\":\"confirmPassword\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"password\"}}","path":"confirmPassword","message":"{title} does not match the password"},{"key":"dutchShippingCountry","conditions":"[\"netherlands\",{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}}]","path":"shippingCountry","message":"We ship Dutch orders to the billing country only"}]},"signUp":{"hash":"wLXjboTQnZ","type":"object","properties":{"accountType":{"type":"string","enum":["personal","business"],"annotations":{"title":"Account type","options":{"personal":{"title":"Personal"},"business":{"title":"Business"}}}},"displayName":{"type":"string","minLength":2,"maxLength":40,"annotations":{"title":"Display name","examples":["Ada","Grace Hopper"]}},"taxId":{"type":"string","annotations":{"title":"VAT number"}}},"required":["accountType","displayName"],"messages":{"displayName":{"minLength":"Use at least {minLength} characters"}},"annotations":{"title":"Create your account","order":["accountType","displayName","taxId"]},"mutations":[{"key":"business","conditions":"{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}","operations":[{"op":"appendUnique","path":["required"],"value":"taxId"},{"op":"set","path":["properties","taxId","pattern"],"value":"^[A-Z]{2}[0-9]{9}$"},{"op":"set","path":["properties","taxId","messages"],"value":{"pattern":"Enter your VAT number, such as DE123456789"}}]}]}}} \ No newline at end of file diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 4497baa..6c4ffea 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -137,8 +137,10 @@ def test_patterns_mean_what_they_mean_in_javascript(self) -> None: self.assertTrue(s.is_valid("spaced", "a b")) self.assertTrue(s.is_valid("spaced", "ab")) self.assertFalse(s.is_valid("spaced", "a\u001cb")) - # A brace that starts no quantifier is a brace. - self.assertTrue(s.is_valid("braces", "a{")) + # A brace that starts no quantifier does not compile with the u flag, so it fails every value, as in JavaScript. + self.assertFalse(s.is_valid("braces", "a{")) + # The u flag reads code points, so a dot takes an emoji whole. + self.assertTrue(s.is_valid("dots", "a\U0001F600b")) # A dot refuses a carriage return, as JavaScript's does. self.assertTrue(s.is_valid("dots", "a\u0085b")) self.assertFalse(s.is_valid("dots", "a\rb")) @@ -148,7 +150,7 @@ def test_patterns_mean_what_they_mean_in_javascript(self) -> None: # A pattern Python cannot compile fails every value, and says so once. self.assertEqual([issue.code for issue in s.validate("broken", "x").issues], ["pattern"]) s.validate("broken", "y") - self.assertEqual(self.diagnostics.count("schema_pattern_unsupported"), 1) + self.assertEqual(self.diagnostics.count("schema_pattern_unsupported"), 2) def test_a_missing_schema_or_field_is_an_issue_reported_once(self) -> None: s = create_schemas(self.f) diff --git a/tests/test_schemas_conformance.py b/tests/test_schemas_conformance.py index 7be8ea4..8698521 100644 --- a/tests/test_schemas_conformance.py +++ b/tests/test_schemas_conformance.py @@ -8,7 +8,7 @@ ROOT = Path(__file__).resolve().parents[1] FIXTURE = json.loads((ROOT / "conformance" / "schemas-validation.json").read_text()) -BUILT = ROOT / "tests" / "fixtures" / "schemas" +BUILT = json.loads((ROOT / "conformance" / "schemas-datafile.json").read_text()) def canonical(value): @@ -40,10 +40,13 @@ def test_fixture_version(self) -> None: def test_every_case(self) -> None: for case in FIXTURE["cases"]: with self.subTest(case=case["name"]): + diagnostics: list[str] = [] f = create_featurevisor({ "datafile": {"schemaVersion": "4", "revision": "1", "segments": case.get("segments", {}), "features": {}, "variables": {}, "schemas": case["schemas"]}, - "context": case.get("context", {}), "logLevel": "fatal", + # Errors reach onDiagnostic only at their own level or below. + "context": case.get("context", {}), "logLevel": "error", + "onDiagnostic": lambda diagnostic: diagnostics.append(diagnostic["code"]), }) s = create_schemas(f) expected = sorted(canonical({key: issue[key] for key in ("code", "path", "params", "mutation") if key in issue}) @@ -52,15 +55,22 @@ def test_every_case(self) -> None: for _ in range(2): actual = sorted(portable(issue) for issue in s.validate(case["schema"], case["value"]).issues) self.assertEqual(actual, expected) + # The error diagnostics the case reports, each once, when it gives them. + if "diagnostics" in case: + self.assertEqual(sorted(diagnostics), sorted(case["diagnostics"])) class BuiltDatafileTests(unittest.TestCase): - """A datafile the CLI built, with conditions as JSON text, against what the JavaScript - package answers for it, messages included. Regenerate built-datafile-expected.json - with the JavaScript package when the datafile changes.""" + """conformance/schemas-datafile.json: a datafile the CLI built, with conditions as JSON + text, against what the JavaScript package answers for it, messages and handle members + included.""" - datafile = json.loads((BUILT / "built-datafile.json").read_text()) - expected = json.loads((BUILT / "built-datafile-expected.json").read_text()) + datafile = BUILT["datafile"] + expected = BUILT + + def test_fixture_version(self) -> None: + self.assertEqual(BUILT["kind"], "featurevisor.schemas-datafile") + self.assertEqual(BUILT["schemaVersion"], 1) def schemas(self, context=None): return create_schemas(create_featurevisor({"datafile": self.datafile, "context": context or {}, "logLevel": "fatal"})) From 130db02420c56ca64285781348f8785068bde776 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 00:13:08 +0100 Subject: [PATCH 04/21] feat: evaluate package entries with module phases, as getters do The module API's evaluate runs every module's beforeEvaluation for a package's own entry, with the entry's type and key, and answers the conditions its callback matches with the context the modules leave, in one dependency session. Schemas validate and describe views inside it, so context a module adds reaches mutations and issue entries as it reaches flags. Nested feature and variable reads never carry the package's key. The shared fixtures gain package condition cases with a module that adds context, and drop the case that counted references at one value to exactly 128. --- README.md | 4 +- conformance/schemas-validation.json | 22 ------ conformance/sdk-package-conditions.json | 80 ++++++++++++++++++++ src/featurevisor/instance.py | 51 ++++++++++++- src/featurevisor/modules.py | 17 +++++ src/featurevisor/schemas/_engine.py | 17 +++-- src/featurevisor/schemas/_handle.py | 63 +++++++++------ src/featurevisor/schemas/_store.py | 13 +++- src/featurevisor/schemas/_views.py | 8 +- tests/test_module_conditions.py | 30 ++++++++ tests/test_package_conditions_conformance.py | 20 +++-- tests/test_schemas.py | 35 +++++++++ 12 files changed, 290 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 74672af..8382194 100644 --- a/README.md +++ b/README.md @@ -593,7 +593,7 @@ remove_module() f.remove_module("my-module") ``` -The API `setup` receives also reads a datafile's sections, the top level keys besides Featurevisor's own whose values are objects, such as `schemas`. `get_entry(section, key)` returns an entry as stored, so treat it as read only, and `get_entry_keys(section)` lists a section's keys. `match_conditions(conditions, context, options)` answers a package's own conditions with the instance's engine, segments and feature leaves included, and `options["readers"]` answer leaves only the package knows, such as `input`, returning `featurevisor.conditions.MISSING` for no value. Feature and variable leaves reach modules as dependencies, with `dependencyOf` naming the package's entry by `type` and `key`. This is how [schemas](#schemas) read their schemas. +The API `setup` receives also reads a datafile's sections, the top level keys besides Featurevisor's own whose values are objects, such as `schemas`. `get_entry(section, key)` returns an entry as stored, so treat it as read only, and `get_entry_keys(section)` lists a section's keys. `match_conditions(conditions, context, options)` answers a package's own conditions with the instance's engine, segments and feature leaves included, and `options["readers"]` answer leaves only the package knows, such as `input`, returning `featurevisor.conditions.MISSING` for no value. `evaluate({"type": ..., "key": ..., "context": ...}, callback)` evaluates a package's own entry as a getter evaluates a feature: every module's `beforeEvaluation` runs first, with `type` and `key` naming the entry, and the conditions the callback answers with `scope.match_conditions(conditions, readers)` read the context the modules leave, in one dependency session. The callback's result is returned. Feature and variable leaves reach modules as dependencies, with `dependencyOf` naming the package's entry by `type` and `key`. This is how [schemas](#schemas) read their schemas. ## Child instance @@ -753,7 +753,7 @@ if not result.valid: A value can be dicts, lists, strings, numbers, booleans and `None`, or a dataclass, a pydantic model, a tuple or another mapping or sequence, which is converted first. A `bool` is never a number, although Python makes it an `int`. `parse` returns the value when it passes and raises a `SchemaValidationError` with the issues when it does not. `flatten()` on a result or an error groups the messages by field name, such as `displayName` or `items.0.name`, for an error response. -Every call reads the current datafile, so a new datafile takes effect at the next validation. A context passed to `validate` is merged over the instance's, for rules that change by segment. +Every call reads the current datafile, so a new datafile takes effect at the next validation. A context passed to `validate` is merged over the instance's, for rules that change by segment. Validation runs as the schema's evaluation, so a module's `beforeEvaluation` sees `type` `schema` and the schema's `key`, and context it adds reaches every condition, as it does for flags. ### Handles diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index e5f79a7..abf81ab 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -3536,28 +3536,6 @@ "schema_reference_depth" ] }, - { - "name": "references at the same value count to exactly 128", - "schemas": { - "subject": { - "hash": "subject-1", - "oneOf": [ - { - "schema": "subject" - }, - { - "type": "string" - } - ] - } - }, - "schema": "subject", - "value": "a", - "issues": [], - "diagnostics": [ - "schema_reference_depth" - ] - }, { "name": "a mutation's conditions can be JSON text", "schemas": { diff --git a/conformance/sdk-package-conditions.json b/conformance/sdk-package-conditions.json index 127a87a..30da8ee 100644 --- a/conformance/sdk-package-conditions.json +++ b/conformance/sdk-package-conditions.json @@ -38,6 +38,17 @@ "percentage": 100000 } ] + }, + "dutchOnly": { + "hash": "f2", + "bucketBy": "userId", + "traffic": [ + { + "key": "dutch", + "conditions": "dutch", + "percentage": 100000 + } + ] } }, "variables": {} @@ -350,6 +361,75 @@ }, "expected": true }, + { + "name": "without a module, an attribute the context lacks does not match", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "pro" + } + ], + "expected": false + }, + { + "name": "a module's context reaches attribute leaves", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "pro" + } + ], + "module": { + "context": { + "plan": "pro" + } + }, + "expected": true + }, + { + "name": "a module's context goes over the call's, as for flags", + "conditions": "dutch", + "context": { + "country": "de" + }, + "module": { + "context": { + "country": "nl" + } + }, + "expected": true + }, + { + "name": "without a module, a feature gated by the context is off", + "conditions": [ + { + "feature": "dutchOnly" + } + ], + "context": { + "country": "de" + }, + "expected": false + }, + { + "name": "a module's context reaches feature leaves", + "conditions": [ + { + "feature": "dutchOnly" + } + ], + "context": { + "country": "de" + }, + "module": { + "context": { + "country": "nl" + } + }, + "expected": true + }, { "name": "an input leaf in a group with an attribute leaf", "conditions": { diff --git a/src/featurevisor/instance.py b/src/featurevisor/instance.py index 8bb5102..73a0fff 100644 --- a/src/featurevisor/instance.py +++ b/src/featurevisor/instance.py @@ -18,7 +18,7 @@ from .normalize import normalize_datafile, InvalidConditions, ConditionsParseFailure from .diagnostics import DEFAULT_LOG_LEVEL, LOG_LEVELS, _EvaluationDiagnostics, should_report, write_diagnostic_to_console from .mutations import _array_index, apply_variable_operations -from .modules import FeaturevisorModule, ModulesManager +from .modules import FeaturevisorModule, ModulesManager, PackageEvaluationScope from .types import DatafileContent, LogLevel empty_datafile: DatafileContent = {"schemaVersion": "2", "revision": "unknown", "segments": {}, "features": {}, "variables": {}} @@ -376,7 +376,7 @@ def _evaluate_dependency(self, reference, dependencies, type_, purpose="conditio session = dependencies["_evaluationSession"] nested = {key: value for key, value in dependencies.items() if key not in {"type", "featureKey", "variableKey", "defaultVariableValue", - "defaultVariationValue", "dependencyOf", "dependencyPurpose"}} + "defaultVariationValue", "dependencyOf", "dependencyPurpose", "key"}} if reference.get("feature") is None and type_ == "variable": result = self._evaluate_global_variable(reference["variable"], dependencies["context"], { "__featurevisor_session": session, "__dependency_of": session.parent(), @@ -720,6 +720,7 @@ def unsubscribe() -> None: "get_entry_keys": self._get_entry_keys, "matchConditions": lambda conditions, context=None, options=None: self._match_package_conditions(conditions, context, options, module), "match_conditions": lambda conditions, context=None, options=None: self._match_package_conditions(conditions, context, options, module), + "evaluate": lambda request, callback: self._evaluate_package(request, callback, module), } def _get_entry(self, section: str, key: str) -> Any: @@ -751,6 +752,52 @@ def _match_package_conditions(self, conditions, context, options, module: Featur }, module) return False + def _evaluate_package(self, request, callback, module: FeaturevisorModule): + """A package's own entry, evaluated as a getter evaluates a feature: the + request's context is merged over the instance's, and every module's + beforeEvaluation runs in registration order with options whose "type" is + the request's, such as "schema", and whose "key" is its key. The callback + reads with the context that results, and every condition it matches + answers in this one dependency session, with the entry as the requester + of feature and variable leaves. A module that raises reports + evaluation_error, and the evaluation goes on with the options before the + modules. The callback's result is returned as it is.""" + type_ = request.get("type") + key = request.get("key") + identity = {"type": type_, **({"key": key} if key is not None else {})} + details = dict(identity) + dependencies = self._get_evaluation_dependencies(request.get("context") or {}) + session = dependencies["_evaluationSession"] + # One session for every condition the package answers in this evaluation. + with session.frame({"type": type_, "featureKey": None, "variableKey": key}, parent=identity): + session.retain(dependencies) + evaluated = {**dependencies, "type": type_, "key": key} + if self.modules_manager.modules: + private = {name: value for name, value in evaluated.items() + if name == "_evaluationSession" or name.startswith("__featurevisor_")} + public = {name: value for name, value in evaluated.items() if name not in private} + try: + evaluated = {**self.modules_manager.run_before_evaluation_modules(public, session.retain), **private} + session.retain(evaluated) + except Exception as error: + self.report_diagnostic({ + "level": "error", "code": "evaluation_error", "message": "beforeEvaluation failed", + "originalError": error, "details": details, + }, module) + refresh_evaluation_state(evaluated) + + def match(conditions, readers=None) -> bool: + try: + return self._package_conditions_are_matched(conditions, evaluated, readers or {}) + except Exception as error: + self.report_diagnostic({ + "level": "error", "code": "evaluation_error", "message": "matchConditions failed", + "originalError": error, "details": details, + }, module) + return False + + return callback(PackageEvaluationScope(evaluated["context"], match)) + def _package_conditions_are_matched(self, conditions, dependencies, readers) -> bool: """A package's conditions, such as a schema mutation's: groups, JSON text and leaves only the package knows, such as "input", are answered here, and every diff --git a/src/featurevisor/modules.py b/src/featurevisor/modules.py index 714b8b0..df96196 100644 --- a/src/featurevisor/modules.py +++ b/src/featurevisor/modules.py @@ -6,6 +6,23 @@ DiagnosticHandler = Callable[[dict[str, Any]], None] +class PackageEvaluationScope: + """What a package evaluation's callback reads with: the context after every + module's beforeEvaluation, as a getter's conditions see it, and conditions + answered with it in the evaluation's one dependency session.""" + + def __init__(self, context: dict[str, Any], match: Callable[..., bool]) -> None: + self.context = context + self._match = match + + def match_conditions(self, conditions: Any, readers: dict[str, Callable[[str], Any]] | None = None) -> bool: + """Answers conditions as the module API's match_conditions does, with + readers for leaves only the package knows, such as "input".""" + return self._match(conditions, readers) + + matchConditions = match_conditions + + class FeaturevisorModule: def __init__(self, options: dict[str, Any] | None = None) -> None: options = options or {} diff --git a/src/featurevisor/schemas/_engine.py b/src/featurevisor/schemas/_engine.py index 53e93f9..313edd3 100644 --- a/src/featurevisor/schemas/_engine.py +++ b/src/featurevisor/schemas/_engine.py @@ -15,6 +15,10 @@ from ._types import SchemaIssue +Matcher = Callable[[Any, Callable[[str], Any]], bool] +"""Answers a schema's conditions in its package evaluation, with input leaves reading the value at the node.""" + + @dataclass class Run: """One validation: where issues go and how they are worded.""" @@ -30,9 +34,11 @@ class Run: """How many issues of shape were found, which hold back the issues of every object around them.""" depth: int = 0 """How many references the walk follows at this point, which only a value nested as deep can need.""" + match: Matcher | None = None + """Answers conditions in the schema's package evaluation, with the context its modules leave.""" def trial_run(self) -> Run: - return Run(self.schema, self.sources, self.translate, trial=True, shape=self.shape, depth=self.depth) + return Run(self.schema, self.sources, self.translate, trial=True, shape=self.shape, depth=self.depth, match=self.match) @dataclass @@ -50,7 +56,6 @@ class Resolver(Protocol): def resolve(self, key: str) -> tuple[dict[str, Any], Validator] | None: ... def node(self, key: str) -> dict[str, Any] | None: ... def reference_too_deep(self, schema: str) -> None: ... - def match(self, conditions: Any, context: dict[str, Any], input_reader: Callable[[str], Any], schema: str) -> bool: ... def unsupported_pattern(self, pattern: str) -> None: ... def mutation_failed(self, schema: str, error: Exception) -> None: ... @@ -488,14 +493,14 @@ def has_mutations(node: Any) -> bool: return isinstance(node, dict) and isinstance(node.get("mutations"), list) and bool(node["mutations"]) -def matching_mutations(node: dict[str, Any], value: Any, context: dict[str, Any], resolve: Resolver, schema: str) -> str: +def matching_mutations(node: dict[str, Any], value: Any, match: Matcher) -> str: """Which of a node's mutations match the value at it, as an id such as "0,2,".""" # input reads the value at this node, so a mutation in address reads the address's own fields. reader = lambda path: read_input(value, path) # noqa: E731 return "".join( f"{index}," for index, mutation in enumerate(node["mutations"]) - if resolve.match(mutation.get("conditions") if isinstance(mutation, dict) else None, context, reader, schema) + if match(mutation.get("conditions") if isinstance(mutation, dict) else None, reader) ) @@ -520,7 +525,7 @@ def _compile_mutations(node: dict[str, Any], resolve: Resolver) -> Validator: lock = threading.Lock() def validate(value: Any, run: Run, at: Position) -> None: - mutation_id = matching_mutations(node, value, run.sources.info.context, resolve, run.schema) + mutation_id = matching_mutations(node, value, run.match) with lock: variant = variants.get(mutation_id) if variant is None: @@ -576,7 +581,7 @@ def validate(value: Any, run: Run, at: Position) -> None: return reader = lambda path: read_input(value, path) # noqa: E731 for entry in entries: - if not isinstance(entry, dict) or not resolve.match(entry.get("conditions"), run.sources.info.context, reader, run.schema): + if not isinstance(entry, dict) or not run.match(entry.get("conditions"), reader): continue parts = entry["path"].split(".") if entry.get("path") else [] scopes = list(at.lookup.scopes) diff --git a/src/featurevisor/schemas/_handle.py b/src/featurevisor/schemas/_handle.py index e703163..628e882 100644 --- a/src/featurevisor/schemas/_handle.py +++ b/src/featurevisor/schemas/_handle.py @@ -114,8 +114,8 @@ def validate(self, value: Any, context: Mapping[str, Any] | None = None) -> Vali once. A check that is a coroutine function reports refineError here, so await avalidate where the handle has one.""" input_ = plain(value) - run = self._run(context) - located = self._apply_rules(input_, run) + # The rules run in the schema's evaluation, and checks in code after it. + run, located = self._evaluated(context, lambda run: (run, self._apply_rules(input_, run))) checks = self._checks() if located else [] if not checks: return ValidationResult(value, tuple(run.issues)) @@ -144,8 +144,8 @@ async def avalidate(self, value: Any, context: Mapping[str, Any] | None = None) """Validates a value, awaiting every check in code, which run concurrently. A cancelled task cancels them.""" input_ = plain(value) - run = self._run(context) - located = self._apply_rules(input_, run) + # The rules run in the schema's evaluation, and checks in code after it. + run, located = self._evaluated(context, lambda run: (run, self._apply_rules(input_, run))) checks = self._checks() if located else [] if not checks: return ValidationResult(value, tuple(run.issues)) @@ -173,9 +173,11 @@ async def answer(check: _Check, target: Any) -> Any: def validate_rules(self, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: """The schema's own rules, without checks in code.""" - run = self._run(context) - self._apply_rules(plain(value), run) - return ValidationResult(value, tuple(run.issues)) + def rules(run: Run) -> ValidationResult: + self._apply_rules(plain(value), run) + return ValidationResult(value, tuple(run.issues)) + + return self._evaluated(context, rules) def is_valid(self, value: Any, context: Mapping[str, Any] | None = None) -> bool: return self.validate(value, context).valid @@ -202,15 +204,20 @@ def has_checks(self) -> bool: def _passes(check: _Check, answer: Any) -> bool: return answer is True if check.kind == "refine" else _found(answer) - def _run(self, given: Mapping[str, Any] | None) -> Run: - # A view's context, with one given to the call merged over it. + def _evaluated(self, given: Mapping[str, Any] | None, callback: Callable[[Run], Any]) -> Any: + """Runs the callback with a run in the schema's package evaluation, so modules see it + and its conditions read the context they leave. A view's context comes first, with + one given to the call merged over it.""" merged = dict(given) if given else None if self._view is not None and self._view.context: merged = {**self._view.context, **(given or {})} - f = self._store.f - info = MessageInfo(lambda: f.get_context(merged)) - sources = Sources(self._form, self._schemas._messages, info) - return Run(self.key, sources, self._schemas._translate) + + def run(context: dict[str, Any], match: Any) -> Any: + info = MessageInfo(lambda: context) + sources = Sources(self._form, self._schemas._messages, info) + return callback(Run(self.key, sources, self._schemas._translate, match=match)) + + return self._store.evaluate(self.key, merged, run) def _locate(self, value: Any, run: Run) -> tuple[Validator, Any, Lookup] | None: """Where this handle's field sits in its schema, or None when the datafile lacks @@ -239,7 +246,7 @@ def _locate(self, value: Any, run: Run) -> tuple[Validator, Any, Lookup] | None: return entry[1], entry[2], entry[3] view = self._view walk = Walk(place(view.values, self._steps[view.start:], value), view.start, - adjuster(store, run.sources.info.context, self.key)) + adjuster(run.match)) field = locate(store, node, self._steps, walk=walk) if field is None: return None @@ -306,10 +313,12 @@ def _root_rule_issues(self, input_value: Any, given: Mapping[str, Any] | None) - root = self._store.resolve(self.key) if root is None: return [] - run = self._run(given) - run.translate = None - root[1](input_value, run, Position([], Lookup([]))) - return run.issues + def rules(run: Run) -> list[SchemaIssue]: + run.translate = None + root[1](input_value, run, Position([], Lookup([]))) + return run.issues + + return self._evaluated(given, rules) def _report_check(self, run: Run, located, code: str, check: _Check, path: list[Any]) -> list[SchemaIssue]: _, node, lookup = located @@ -319,7 +328,7 @@ def _report_check(self, run: Run, located, code: str, check: _Check, path: list[ else: found = Lookup([*lookup.mpath, *(str(part) for part in path)], list(lookup.scopes)) params = {"refine": check.key} if check.kind == "refine" else {"optionSource": check.key} - reporting = Run(run.schema, run.sources, run.translate) + reporting = Run(run.schema, run.sources, run.translate, match=run.match) report(reporting, Position(path, found), code, params, path, found, None if code == "refineError" else check.message) return reporting.issues @@ -361,11 +370,15 @@ def _describe(self, view: _View | None) -> tuple[Any, bool] | None: if view is None: field = locate(store, root[0], self._steps) return (field.node, field.required) if field is not None else None - adjust = adjuster(store, store.f.get_context(view.context), self.key) - field = locate(store, root[0], self._steps, walk=Walk(view.values, view.start, adjust)) - if field is None: - return None - return resolve_tree(field.node, field.value, adjust, store), field.required + # A view's mutations match in the schema's evaluation, with the view's context. + def described(_context: dict[str, Any], match: Any) -> tuple[Any, bool] | None: + adjust = adjuster(match) + field = locate(store, root[0], self._steps, walk=Walk(view.values, view.start, adjust)) + if field is None: + return None + return resolve_tree(field.node, field.value, adjust, store), field.required + + return store.evaluate(self.key, view.context, described) def _derive(self, kind: str, make: Callable[[Any, bool], Any], otherwise: Any) -> Any: store = self._store @@ -493,7 +506,7 @@ async def lookup(self, value: Any, context: Mapping[str, Any] | None = None) -> return make_option(value, answer if isinstance(answer, dict) else None) def _source_info(self, given: Mapping[str, Any] | None) -> CheckInfo: - return CheckInfo(self._view.values if self._view else None, self._run(given).sources.info.context) + return CheckInfo(self._view.values if self._view else None, self._evaluated(given, lambda run: run.sources.info.context)) # Changes diff --git a/src/featurevisor/schemas/_store.py b/src/featurevisor/schemas/_store.py index c3a3bdc..9bcb0c0 100644 --- a/src/featurevisor/schemas/_store.py +++ b/src/featurevisor/schemas/_store.py @@ -48,7 +48,7 @@ def __init__(self, f: Any) -> None: remove = f.add_module(FeaturevisorModule({"setup": api.update})) self._holds_name = takes_name self._remove = remove - if "get_entry" not in api or "match_conditions" not in api: + if "get_entry" not in api or "evaluate" not in api: self.close() raise RuntimeError("featurevisor.schemas needs a featurevisor whose modules can read datafile sections.") self.api = api @@ -95,9 +95,14 @@ def resolve(self, key: str) -> tuple[dict[str, Any], Validator] | None: self._compiled[key] = (node, validate) return node, validate - def match(self, conditions: Any, context: dict[str, Any], input_reader: Callable[[str], Any], schema: str) -> bool: - # Conditions read through the SDK, so a segment means in a schema what it means in a flag. - return self.api["match_conditions"](conditions, context, {"type": "schema", "key": schema, "readers": {"input": input_reader}}) + def evaluate(self, schema: str, context: dict[str, Any] | None, callback: Callable[[dict[str, Any], Any], Any]) -> Any: + """Runs the callback in the schema's package evaluation, so modules see it as they + see a getter, and its conditions read the context they leave. Conditions read + through the SDK, so a segment means in a schema what it means in a flag.""" + return self.api["evaluate"]( + {"type": "schema", "key": schema, "context": context or {}}, + lambda scope: callback(scope.context, lambda conditions, reader: scope.match_conditions(conditions, {"input": reader})), + ) def _once(self, key: str) -> bool: with self._lock: diff --git a/src/featurevisor/schemas/_views.py b/src/featurevisor/schemas/_views.py index a927020..c28db4b 100644 --- a/src/featurevisor/schemas/_views.py +++ b/src/featurevisor/schemas/_views.py @@ -5,18 +5,18 @@ import json from typing import Any, Callable, Sequence -from ._engine import Resolver, has_mutations, matching_mutations, mutated_rules +from ._engine import Matcher, Resolver, has_mutations, matching_mutations, mutated_rules from ._paths import Step -def adjuster(resolve: Resolver, context: dict[str, Any], schema: str) -> Callable[[Any, Any], Any]: - """Applies a node's mutations whose conditions match the value at it and the context.""" +def adjuster(match: Matcher) -> Callable[[Any, Any], Any]: + """Applies a node's mutations whose conditions match the value at it, in the schema's package evaluation.""" def adjust(node: Any, value: Any) -> Any: if not has_mutations(node): return node try: - return mutated_rules(node, matching_mutations(node, value, context, resolve, schema)) + return mutated_rules(node, matching_mutations(node, value, match)) except Exception: # noqa: BLE001 return node diff --git a/tests/test_module_conditions.py b/tests/test_module_conditions.py index d938664..6d84f02 100644 --- a/tests/test_module_conditions.py +++ b/tests/test_module_conditions.py @@ -84,6 +84,36 @@ def after(evaluation, options): self.assertTrue(api["match_conditions"]([{"feature": "paid"}], {}, {"type": "schema", "key": "signUp"})) self.assertEqual(seen, [{"featureKey": "paid", "dependencyOf": {"type": "schema", "key": "signUp"}}]) + def test_evaluate_runs_the_modules_for_the_entry_as_a_getter_does_and_answers_in_one_session(self) -> None: + before = [] + after = [] + + def geo_before(options): + if options.get("key"): + before.append({"type": options["type"], "key": options["key"], "country": options["context"].get("country")}) + # A module that adds context, as one reading a request's country would. + return {**options, "context": {**options["context"], "country": "nl"}} + + def geo_after(evaluation, options): + after.append({"featureKey": evaluation.get("featureKey"), "dependencyOf": options.get("dependencyOf")}) + return evaluation + + api, _ = self.setup_api([{"name": "geo", "beforeEvaluation": geo_before, "afterEvaluation": geo_after}]) + result = api["evaluate"]( + {"type": "schema", "key": "signUp", "context": {"country": "de"}}, + lambda scope: { + "country": scope.context["country"], + "dutch": scope.match_conditions("dutch"), + "paid": scope.match_conditions([{"feature": "paid"}]), + "payingDutch": scope.match_conditions("payingDutch"), + }, + ) + + self.assertEqual(result, {"country": "nl", "dutch": True, "paid": True, "payingDutch": True}) + self.assertEqual(before, [{"type": "schema", "key": "signUp", "country": "de"}]) + # The feature is read once in the evaluation's session, for the entry. + self.assertEqual(after, [{"featureKey": "paid", "dependencyOf": {"type": "schema", "key": "signUp"}}]) + def test_a_condition_that_cannot_be_answered_reports_evaluation_error(self) -> None: api, diagnostics = self.setup_api() diff --git a/tests/test_package_conditions_conformance.py b/tests/test_package_conditions_conformance.py index 6598039..a3d2172 100644 --- a/tests/test_package_conditions_conformance.py +++ b/tests/test_package_conditions_conformance.py @@ -10,7 +10,7 @@ class PackageConditionsConformanceTests(unittest.TestCase): - """Runs conformance/sdk-package-conditions.json: match_conditions with readers, as packages call it.""" + """Runs conformance/sdk-package-conditions.json: conditions in a package evaluation, as packages answer them.""" def test_fixture_version(self) -> None: self.assertEqual(FIXTURE["kind"], "featurevisor.sdk-package-conditions") @@ -21,16 +21,26 @@ def test_every_case(self) -> None: for case in FIXTURE["cases"]: with self.subTest(case=case["name"]): f = create_featurevisor({"datafile": FIXTURE["datafile"], "context": FIXTURE["context"], "logLevel": "fatal"}) + if "module" in case: + added = case["module"]["context"] + # A module whose beforeEvaluation merges this context over every evaluation's. + f.add_module({ + "name": "context", + "beforeEvaluation": lambda options, added=added: {**options, "context": {**options["context"], **added}}, + }) api = {} f.add_module({"name": "package", "setup": lambda module_api: api.update(module_api)}) - options = None + readers = {} if "input" in case: values = case["input"] # An absent key reads as nothing, which differs from null. - options = {"readers": {"input": lambda path, values=values: values.get(path, MISSING)}} - # Twice, so a cached answer is the answer. + readers["input"] = lambda path, values=values: values.get(path, MISSING) + # Twice, so a cached answer is the answer, each in a package evaluation as a package makes one. for _ in range(2): - matched = api["match_conditions"](case["conditions"], case.get("context", {}), options) + matched = api["evaluate"]( + {"type": "schema", "key": "subject", "context": case.get("context", {})}, + lambda scope: scope.match_conditions(case["conditions"], readers), + ) self.assertEqual(matched, case["expected"]) diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 6c4ffea..4e03a9c 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -46,6 +46,41 @@ def setUp(self) -> None: self.f = create_featurevisor({"datafile": datafile("1", SCHEMAS), "logLevel": "warn", "onDiagnostic": lambda diagnostic: self.diagnostics.append(diagnostic["code"])}) + def test_context_a_module_adds_reaches_mutations_issue_entries_and_views_as_it_reaches_flags(self) -> None: + seen = [] + + def geo(options): + seen.append((options.get("type"), options.get("key"))) + return {**options, "context": {**options["context"], "country": "nl"}} + + dutch = [{"attribute": "country", "operator": "equals", "value": "nl"}] + f = create_featurevisor({ + "datafile": { + **datafile("1", {"signUp": { + "hash": "s1", "type": "object", + "properties": {"taxId": {"type": "string"}, "name": {"type": "string"}}, + "mutations": [{"key": "dutch", "conditions": dutch, + "operations": [{"op": "appendUnique", "path": ["required"], "value": "taxId"}]}], + "issues": [{"key": "noAda", "conditions": ["dutch", {"input": "name", "operator": "equals", "value": "Ada"}], + "path": "name", "message": "Pick another name"}], + }}), + "segments": {"dutch": {"conditions": dutch}}, + }, + "logLevel": "fatal", + "modules": [{"name": "geo", "beforeEvaluation": geo}], + }) + s = create_schemas(f) + + def codes(result): + return [(issue.code, ".".join(str(part) for part in issue.path)) for issue in result.issues] + + self.assertEqual(codes(s.validate("signUp", {"name": "Ada"})), [("required", "taxId")]) + self.assertEqual(codes(s.validate("signUp", {"name": "Ada", "taxId": "x"})), [("refine", "name")]) + self.assertTrue(s.get("signUp").with_input({}).at("taxId").constraints.required) + # One evaluation per validation and per view, each the schema's own. + self.assertTrue(seen) + self.assertEqual(set(seen), {("schema", "signUp")}) + def test_validates_dicts_dataclasses_and_tuples(self) -> None: s = create_schemas(self.f) self.assertTrue(s.validate("signUp", VALID).valid) From 37ccb148219cebd0069fba28b7cc10972af0b40b Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 00:13:08 +0100 Subject: [PATCH 05/21] feat(cli): run schema specs with featurevisor.schemas The test runner asks for schema specs and validates each assertion's value as the JavaScript CLI does, against the datafile of its environment and Target, under its context. A Node.js CLI from before schema specs rejects the option, so the runner asks again without it. --- README.md | 2 +- src/featurevisor/cli.py | 2 +- src/featurevisor/project.py | 11 +++ src/featurevisor/tester.py | 124 ++++++++++++++++++++++++++++- tests/test_cli.py | 6 +- tests/test_schema_specs_listing.py | 31 ++++++++ 6 files changed, 169 insertions(+), 7 deletions(-) create mode 100644 tests/test_schema_specs_listing.py diff --git a/README.md b/README.md index 8382194..e041854 100644 --- a/README.md +++ b/README.md @@ -844,7 +844,7 @@ See [Testing](https://featurevisor.com/docs/testing/) for authoring specs and [C Useful test options: - `--key-pattern=` and `--assertion-pattern=` filter tests. -- `--entity-type=scenario` selects scenarios. `--set=` selects one project set. Omitting `--set` runs all sets. +- `--entity-type=scenario` selects scenarios, and `--entity-type=schema` schema specs, which validate their values with `featurevisor.schemas` as the JavaScript CLI does. `--set=` selects one project set. Omitting `--set` runs all sets. - `--case=` reruns one expanded case. Copy the opaque ID or rerun command from a failure report. - `--json --pretty` produces an indented JSON report. - `--coverage` reports observed rule and override selections. `--uncovered` lists features and global variables without associated specs. diff --git a/src/featurevisor/cli.py b/src/featurevisor/cli.py index 39df195..1a199d8 100644 --- a/src/featurevisor/cli.py +++ b/src/featurevisor/cli.py @@ -60,7 +60,7 @@ def build_parser() -> argparse.ArgumentParser: common.add_argument("--target", type=nonempty_value, action="append", default=[]) common.add_argument("--set") test_parser = subparsers.add_parser("test", parents=[common], allow_abbrev=False) - test_parser.add_argument("--entity-type", "--entityType", dest="entityType", choices=("feature", "segment", "variable", "scenario")) + test_parser.add_argument("--entity-type", "--entityType", dest="entityType", choices=("feature", "segment", "variable", "scenario", "schema")) test_parser.add_argument("--json", action="store_true") test_parser.add_argument("--pretty", action="store_true") test_parser.add_argument("--case", dest="case_id") diff --git a/src/featurevisor/project.py b/src/featurevisor/project.py index 43f12e8..3db543b 100644 --- a/src/featurevisor/project.py +++ b/src/featurevisor/project.py @@ -32,6 +32,9 @@ def __init__(self, message: str, *, code: str | None = None) -> None: class FeaturevisorProject: + lists_schema_specs = True + """Whether the Node.js CLI lists schema specs, which one from before them does not.""" + def __init__(self, project_directory_path: str | None = None, set_name: str | None = None) -> None: self.project_directory_path = pathlib.Path(project_directory_path or os.getcwd()) self.set_name = set_name @@ -54,7 +57,10 @@ def get_config(self) -> dict[str, Any]: return self.run_json("config", "--json", include_set=False) def list_tests(self, key_pattern: str | None = None, assertion_pattern: str | None = None, entity_type: str | None = None, case_id: str | None = None) -> list[dict[str, Any]]: + # Schema specs come too, validated with featurevisor.schemas. args = ["list", "--tests", "--execution-protocol", "--json"] + if FeaturevisorProject.lists_schema_specs: + args.append("--with-schemas") if key_pattern: args.append(f"--keyPattern={key_pattern}") if assertion_pattern: @@ -64,6 +70,11 @@ def list_tests(self, key_pattern: str | None = None, assertion_pattern: str | No if case_id: args.append(f"--case={case_id}") result = self.run(*args, check=False) + output = (result.stdout or "") + (result.stderr or "") + if result.returncode != 0 and "--with-schemas" in args and "Unknown argument" in output and "with-schemas" in output: + # A CLI from before schema specs rejects the option, and has none to list. + FeaturevisorProject.lists_schema_specs = False + result = self.run(*[arg for arg in args if arg != "--with-schemas"], check=False) if result.returncode != 0: try: payload = json.loads(result.stderr) diff --git a/src/featurevisor/tester.py b/src/featurevisor/tester.py index 24c5fa4..3842783 100644 --- a/src/featurevisor/tester.py +++ b/src/featurevisor/tester.py @@ -260,6 +260,108 @@ def _assert_scenario(sdk, assertion: dict[str, Any], datafile: dict[str, Any], d child.close() +def _run_schema_assertion(schema: str, assertion: dict[str, Any], datafile: dict[str, Any] | None) -> dict[str, Any]: + """A schema spec's assertion: validates its value with featurevisor.schemas against the + datafile its environment and Target build, under its context, as the JavaScript CLI + does, so a test proves what applications see.""" + from .schemas import create_schemas + + started = time.perf_counter() + errors: list[dict[str, Any]] = [] + + def fail(message: str, expected: Any, actual: Any) -> None: + errors.append({"type": "schema", "message": message, "expected": expected, "actual": actual}) + + environment, target = assertion.get("environment"), assertion.get("target") + if datafile is None: + if not environment: + message = (f'datafile not found for target "{target}"' if target else + "No datafile without an environment. When the project configures environments, add environment to the assertion.") + else: + message = f'datafile not found for environment "{environment}"' + (f' and target "{target}"' if target else "") + fail(message, "datafile", None) + elif schema not in (datafile.get("schemas") or {}): + fail(f'Target "{target}" does not deliver schema "{schema}". Tag the schema for it, or list it in its includeSchemas.', schema, None) + else: + sdk = create_featurevisor({"datafile": datafile, "context": assertion.get("context", {}), "logLevel": "fatal"}) + schemas = create_schemas(sdk) + try: + issues = [_describe_issue(issue) for issue in schemas.validate(schema, assertion.get("value")).issues] + finally: + schemas.close() + sdk.close() + valid = not issues + expected_valid = assertion.get("expectedToBeValid") + if isinstance(expected_valid, bool) and expected_valid != valid: + if valid: + message = "Expected the value to be invalid, and it is valid." + else: + count = "an issue" if len(issues) == 1 else f"{len(issues)} issues" + lines = "\n".join(f" {_compact_json(issue)}" for issue in issues) + message = f"Expected the value to be valid, and it has {count}:\n{lines}" + fail(message, expected_valid, valid) + if isinstance(assertion.get("expectedIssues"), list): + # Each expected issue pairs with one issue found, and every issue found must be expected. + left = list(issues) + missing = [] + for expected in assertion["expectedIssues"]: + index = next((at for at, actual in enumerate(left) if _matches_issue(expected, actual)), None) + if index is None: + missing.append(expected) + else: + left.pop(index) + if missing or left: + lines = [f" missing: {_compact_json(issue)}" for issue in missing] + lines += [f" unexpected: {_compact_json(issue)}" for issue in left] + fail("The issues differ from expectedIssues:\n" + "\n".join(lines), assertion["expectedIssues"], issues) + return { + "description": assertion.get("description", ""), + "duration": int((time.perf_counter() - started) * 1000), + "passed": not errors, + "errors": errors, + } + + +def _describe_issue(issue: Any) -> dict[str, Any]: + """An issue as a test result shows it, without the schema key every issue repeats.""" + described: dict[str, Any] = {"path": list(issue.path), "code": issue.code} + if issue.mutation is not None: + described["mutation"] = issue.mutation + described["message"] = issue.message + described["params"] = dict(issue.params) + return described + + +def _matches_issue(expected: Any, actual: dict[str, Any]) -> bool: + """Whether an issue has every field an expected issue gives, params by JSON equality.""" + if not isinstance(expected, dict): + return False + if "path" in expected and _compact_json(expected["path"]) != _compact_json(actual["path"]): + return False + for field in ("code", "mutation", "message"): + if field in expected and expected[field] != actual.get(field): + return False + params = actual.get("params") or {} + for name, value in (expected.get("params") or {}).items(): + if name not in params or _compact_json(value) != _compact_json(params[name]): + return False + return True + + +def _compact_json(value: Any) -> str: + """JSON as JavaScript's JSON.stringify writes it, whole numbers without a fraction.""" + def plain(item: Any) -> Any: + if isinstance(item, float) and item.is_integer(): + return int(item) + if isinstance(item, dict): + return {key: plain(entry) for key, entry in item.items()} + if isinstance(item, (list, tuple)): + return [plain(entry) for entry in item] + return item + + return json.dumps(plain(value), separators=(",", ":"), ensure_ascii=False) + + def _missing_datafile_assertion(assertion: dict[str, Any]) -> dict[str, Any]: environment = assertion.get("environment") or "none" target = f' and target "{assertion["target"]}"' if assertion.get("target") else "" @@ -443,6 +545,8 @@ def _case_result( for leaf in details["evaluated"] ] item["details"] = details + elif item.get("type") == "schema": + item["path"] = ["assertions", case_metadata.get("assertionIndex", 0)] elif item.get("type") in {"flag", "variation", "variable", "evaluation", "segment"}: raw_details = item.get("details") details = raw_details if isinstance(raw_details, dict) else {} @@ -698,13 +802,29 @@ def _run_test_project_set(project: FeaturevisorProject, *, key_pattern: str | No passed = True for test in tests: executed_assertions = list(test.get("assertions") or []) - discriminators = [key for key in ("feature", "variable", "segment", "scenario") if key in test] + discriminators = [key for key in ("feature", "variable", "segment", "scenario", "schema") if key in test] if len(discriminators) != 1: executed_assertions = [{"description": "malformed test spec"}] result = { "type": "test", "key": test.get("key", "malformed"), "notFound": False, "passed": False, "duration": 0, - "assertions": [{"description": "malformed test spec", "duration": 0, "passed": False, "errors": [{"type": "check", "message": "test spec requires exactly one of feature, variable, segment or scenario"}]}], + "assertions": [{"description": "malformed test spec", "duration": 0, "passed": False, "errors": [{"type": "check", "message": "test spec requires exactly one of feature, variable, segment, scenario or schema"}]}], } + elif test.get("schema"): + assertions = [ + assertion for assertion in test["assertions"] + if not selected_targets or not assertion.get("target") or assertion.get("target") in selected_targets + ] + if not assertions: + continue + executed_assertions = assertions + schema_start = time.perf_counter() + result = {"type": "schema", "key": test["schema"], "notFound": False, "passed": True, "duration": 0, "assertions": []} + for assertion in assertions: + assertion_result = _run_schema_assertion(test["schema"], assertion, _get_datafile_for_assertion(assertion, datafile_cache)) + if not assertion_result["passed"]: + result["passed"] = False + result["assertions"].append(assertion_result) + result["duration"] = int((time.perf_counter() - schema_start) * 1000) elif "scenario" in test and not test.get("assertions"): executed_assertions = [{"description": "malformed scenario spec"}] result = { diff --git a/tests/test_cli.py b/tests/test_cli.py index 282203a..afa6e71 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -259,7 +259,7 @@ def test_execution_protocol_envelope_is_strictly_validated(self) -> None: self.assertEqual(project.list_tests(key_pattern="ready"), valid["tests"]) self.assertEqual( run.call_args.args, - ("list", "--tests", "--execution-protocol", "--json", "--keyPattern=ready"), + ("list", "--tests", "--execution-protocol", "--json", "--with-schemas", "--keyPattern=ready"), ) def test_target_datafile_cache_key(self) -> None: @@ -930,7 +930,7 @@ def test_json_report_exact_rerun_coverage_and_uncovered(self) -> None: }]) with open(log_path, encoding="utf-8") as handle: self.assertIn( - "list --tests --execution-protocol --json --case=opaque case", + "list --tests --execution-protocol --json --with-schemas --case=opaque case", handle.read(), ) @@ -1097,7 +1097,7 @@ def test_native_executable_runs_scenario_children_filter_and_failure_exit(self) ) self.assertEqual(malformed_result.returncode, 1, malformed_result.stdout + malformed_result.stderr) self.assertIn("scenario spec requires assertions", malformed_result.stdout) - self.assertIn("requires exactly one of feature, variable, segment or scenario", malformed_result.stdout) + self.assertIn("requires exactly one of feature, variable, segment, scenario or schema", malformed_result.stdout) with open(log_path, "w", encoding="utf-8"): pass diff --git a/tests/test_schema_specs_listing.py b/tests/test_schema_specs_listing.py new file mode 100644 index 0000000..90f7450 --- /dev/null +++ b/tests/test_schema_specs_listing.py @@ -0,0 +1,31 @@ +import subprocess +import unittest +from unittest import mock + +from featurevisor.project import FeaturevisorProject + +EMPTY = '{"kind":"featurevisor.test-execution","schemaVersion":1,"tests":[]}' +REJECTED = '{"error":{"code":"invalid_cli_arguments","message":"Unknown arguments: with-schemas, withSchemas","details":{}}}' + + +class SchemaSpecsListingTests(unittest.TestCase): + def setUp(self) -> None: + FeaturevisorProject.lists_schema_specs = True + + def tearDown(self) -> None: + FeaturevisorProject.lists_schema_specs = True + + def test_asks_again_without_schema_specs_when_the_node_cli_predates_them(self) -> None: + listings = [] + + def run(project, *args, check=True, include_set=True): + listings.append(args) + if "--with-schemas" in args: + return subprocess.CompletedProcess(args, 1, stdout=REJECTED, stderr="") + return subprocess.CompletedProcess(args, 0, stdout=EMPTY, stderr="") + + with mock.patch.object(FeaturevisorProject, "run", run): + for _ in range(2): + self.assertEqual(FeaturevisorProject("project").list_tests(), []) + # Asked with the option once, then without it for the rest of the run. + self.assertEqual(["--with-schemas" in args for args in listings], [True, False, False]) From fab827d323975f54e44e501dbfc8e56fab7efe4b Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 04:12:47 +0100 Subject: [PATCH 06/21] perf: skip module phases no module has, and parse package conditions once The modules manager records which phases its modules take part in, so evaluations skip before and after evaluation, bucket key and bucket value when no module has them. A module that only reads the datafile, such as the schemas package's, no longer makes flags slower. Package conditions given as JSON text are parsed once per datafile, with conditions_parse_error reported for text that does not parse, and the cache is cleared when it reaches 1000 entries. Two mypy errors from the last round are fixed: a schemas run always has a matcher, and the tester no longer reuses a name for another type. --- src/featurevisor/evaluate.py | 20 +++++++------ src/featurevisor/instance.py | 31 +++++++++++++++----- src/featurevisor/modules.py | 22 +++++++++++++-- src/featurevisor/schemas/_engine.py | 5 ++-- src/featurevisor/tester.py | 6 ++-- tests/test_module_conditions.py | 44 +++++++++++++++++++++++++++++ 6 files changed, 104 insertions(+), 24 deletions(-) diff --git a/src/featurevisor/evaluate.py b/src/featurevisor/evaluate.py index 1d28604..c31bfe3 100644 --- a/src/featurevisor/evaluate.py +++ b/src/featurevisor/evaluate.py @@ -45,7 +45,7 @@ def evaluate_with_modules(options: dict[str, Any]) -> dict[str, Any]: modules_manager = options["modulesManager"] module_options = None current_options = options - if modules_manager.modules: + if modules_manager.has_before_evaluation: private = {key: value for key, value in options.items() if key == "_evaluationSession" or key.startswith("__featurevisor_")} module_options = {key: value for key, value in options.items() if key not in private} @@ -71,8 +71,8 @@ def evaluate_with_modules(options: dict[str, Any]) -> dict[str, Any]: ): evaluation["variableValue"] = current_options["defaultVariableValue"] # Evaluation callbacks may install a module after the initial - # empty-list check. Its after hook must still see public options. - if modules_manager.modules: + # check. Its after hook must still see public options. + if modules_manager.has_after_evaluation: if module_options is None: module_options = {key: value for key, value in options.items() if key != "_evaluationSession" and not key.startswith("__featurevisor_")} @@ -243,13 +243,15 @@ def evaluate(options: dict[str, Any]) -> dict[str, Any]: return evaluation bucket_key = get_bucket_key(featureKey=feature_key, bucketBy=feature["bucketBy"], context=context, diagnostics=diagnostics) - bucket_key = modules_manager.run_bucket_key_modules( - {"featureKey": feature_key, "context": context, "bucketBy": feature["bucketBy"], "bucketKey": bucket_key} - ) + if modules_manager.has_bucket_key: + bucket_key = modules_manager.run_bucket_key_modules( + {"featureKey": feature_key, "context": context, "bucketBy": feature["bucketBy"], "bucketKey": bucket_key} + ) bucket_value = get_bucketed_number(bucket_key) - bucket_value = modules_manager.run_bucket_value_modules( - {"featureKey": feature_key, "bucketKey": bucket_key, "context": context, "bucketValue": bucket_value} - ) + if modules_manager.has_bucket_value: + bucket_value = modules_manager.run_bucket_value_modules( + {"featureKey": feature_key, "bucketKey": bucket_key, "context": context, "bucketValue": bucket_value} + ) matched_traffic = datafile.get_matched_traffic(feature["traffic"], context, options) matched_allocation = datafile.get_matched_allocation(matched_traffic, bucket_value) if type_ != "flag" and matched_traffic else None diff --git a/src/featurevisor/instance.py b/src/featurevisor/instance.py index 73a0fff..4180880 100644 --- a/src/featurevisor/instance.py +++ b/src/featurevisor/instance.py @@ -35,6 +35,9 @@ def __init__(self, options: dict[str, Any] | None = None) -> None: self.sticky_variables = options.get("stickyVariables") self.closed = False self._state_version = 0 + # A package's conditions as Core writes them, JSON text, parsed once per + # text for the current datafile. + self._package_conditions: dict[str, Any] = {} self._datafile_lock = Lock() self.module_diagnostic_subscriptions: list[dict[str, Any]] = [] self.evaluation_diagnostics = _EvaluationDiagnostics( @@ -100,6 +103,7 @@ def set_datafile(self, datafile, replace: bool = False) -> bool: details = get_params_for_datafile_set_event(previous_datafile, new_datafile, replace, parsed) details["sections"] = get_changed_sections(previous_datafile, new_datafile) self.datafile = new_datafile + self._package_conditions.clear() self._state_version += 1 for diagnostic in errors: self.report_diagnostic(diagnostic) @@ -521,7 +525,7 @@ def _evaluate_global_variable_impl(self, variable_key: str, context: dict[str, A return cached input_options = evaluation_options try: - had_modules = bool(self.modules_manager.modules) + had_modules = self.modules_manager.has_before_evaluation if had_modules: evaluation_options = self.modules_manager.run_before_evaluation_modules( {key: value for key, value in evaluation_options.items() if not key.startswith("__featurevisor_")}, @@ -613,7 +617,7 @@ def _evaluate_global_variable_impl(self, variable_key: str, context: dict[str, A if "variableValue" not in evaluation and "defaultVariableValue" in evaluation_options: evaluation["variableValue"] = evaluation_options["defaultVariableValue"] - if self.modules_manager.modules: + if self.modules_manager.has_after_evaluation: public_options = (evaluation_options if had_modules else { key: value for key, value in evaluation_options.items() if not key.startswith("__featurevisor_") @@ -772,7 +776,7 @@ def _evaluate_package(self, request, callback, module: FeaturevisorModule): with session.frame({"type": type_, "featureKey": None, "variableKey": key}, parent=identity): session.retain(dependencies) evaluated = {**dependencies, "type": type_, "key": key} - if self.modules_manager.modules: + if self.modules_manager.has_before_evaluation: private = {name: value for name, value in evaluated.items() if name == "_evaluationSession" or name.startswith("__featurevisor_")} public = {name: value for name, value in evaluated.items() if name not in private} @@ -808,10 +812,23 @@ def _package_conditions_are_matched(self, conditions, dependencies, readers) -> text = conditions.lstrip() # Conditions written as JSON text, as Core writes them by default. A bare segment key stays a key. if text[:1] in ("{", "[", '"'): - try: - return self._package_conditions_are_matched(strict_json_loads(text), dependencies, readers) - except ValueError: - return False + parsed = self._package_conditions.get(conditions, MISSING) + if parsed is MISSING: + try: + parsed = strict_json_loads(text) + except ValueError as error: + # Reported on every call, as JavaScript does, and never kept. + self.report_diagnostic({ + "level": "error", "code": "conditions_parse_error", + "message": "Error parsing conditions", "originalError": error, + "details": {"conditions": conditions}, + }) + return False + # Text a package makes up at run time cannot grow the cache without bound. + if len(self._package_conditions) >= 1000: + self._package_conditions.clear() + self._package_conditions[conditions] = parsed + return self._package_conditions_are_matched(parsed, dependencies, readers) return self._conditions_are_matched(conditions, dependencies) if isinstance(conditions, list): return bool(conditions) and all(self._package_conditions_are_matched(item, dependencies, readers) for item in conditions) diff --git a/src/featurevisor/modules.py b/src/featurevisor/modules.py index df96196..e239f3f 100644 --- a/src/featurevisor/modules.py +++ b/src/featurevisor/modules.py @@ -74,6 +74,8 @@ def __init__( clear_module_diagnostic_subscriptions: Callable[[FeaturevisorModule], None] | None = None, ) -> None: self.modules: list[FeaturevisorModule] = [] + self.has_before_evaluation = self.has_after_evaluation = False + self.has_bucket_key = self.has_bucket_value = False self.report_diagnostic = report_diagnostic self.module_api_factory = module_api_factory self.clear_module_diagnostic_subscriptions = clear_module_diagnostic_subscriptions @@ -81,6 +83,20 @@ def __init__( for module in modules or []: self.add(module) + def _set_modules(self, modules: list[FeaturevisorModule]) -> None: + # The list is replaced whole on every change, so which phases any module + # takes part in is known up front, and a getter skips the others. A + # module without hooks, such as a package's, costs evaluations nothing. + self.modules = modules + if not modules: + self.has_before_evaluation = self.has_after_evaluation = False + self.has_bucket_key = self.has_bucket_value = False + return + self.has_before_evaluation = any(module.before_evaluation for module in modules) + self.has_after_evaluation = any(module.after_evaluation for module in modules) + self.has_bucket_key = any(module.bucket_key for module in modules) + self.has_bucket_value = any(module.bucket_value for module in modules) + def add(self, module: dict[str, Any] | FeaturevisorModule): module = FeaturevisorModule(module) if isinstance(module, dict) else module if module is None: @@ -118,7 +134,7 @@ def add(self, module: dict[str, Any] | FeaturevisorModule): return None # Replace membership so an active phase keeps its starting list. - self.modules = [*self.modules, module] + self._set_modules([*self.modules, module]) def remove() -> None: self.remove(module) @@ -134,7 +150,7 @@ def remove(self, name_or_module: str | FeaturevisorModule) -> None: removed.append(module) else: kept.append(module) - self.modules = kept + self._set_modules(kept) for module in removed: if self.clear_module_diagnostic_subscriptions: @@ -177,7 +193,7 @@ def close_all(self) -> None: if self.clear_module_diagnostic_subscriptions: self.clear_module_diagnostic_subscriptions(module) self._close_module(module) - self.modules = [] + self._set_modules([]) def _close_module(self, module: FeaturevisorModule) -> None: try: diff --git a/src/featurevisor/schemas/_engine.py b/src/featurevisor/schemas/_engine.py index 313edd3..f1a2fed 100644 --- a/src/featurevisor/schemas/_engine.py +++ b/src/featurevisor/schemas/_engine.py @@ -34,8 +34,9 @@ class Run: """How many issues of shape were found, which hold back the issues of every object around them.""" depth: int = 0 """How many references the walk follows at this point, which only a value nested as deep can need.""" - match: Matcher | None = None - """Answers conditions in the schema's package evaluation, with the context its modules leave.""" + match: Matcher = field(default=lambda conditions, reader: False) + """Answers conditions in the schema's package evaluation, with the context its modules leave. + Every run is made with one, and a run without one matches nothing.""" def trial_run(self) -> Run: return Run(self.schema, self.sources, self.translate, trial=True, shape=self.shape, depth=self.depth, match=self.match) diff --git a/src/featurevisor/tester.py b/src/featurevisor/tester.py index 3842783..f96467f 100644 --- a/src/featurevisor/tester.py +++ b/src/featurevisor/tester.py @@ -311,9 +311,9 @@ def fail(message: str, expected: Any, actual: Any) -> None: else: left.pop(index) if missing or left: - lines = [f" missing: {_compact_json(issue)}" for issue in missing] - lines += [f" unexpected: {_compact_json(issue)}" for issue in left] - fail("The issues differ from expectedIssues:\n" + "\n".join(lines), assertion["expectedIssues"], issues) + differences = [f" missing: {_compact_json(issue)}" for issue in missing] + differences += [f" unexpected: {_compact_json(issue)}" for issue in left] + fail("The issues differ from expectedIssues:\n" + "\n".join(differences), assertion["expectedIssues"], issues) return { "description": assertion.get("description", ""), "duration": int((time.perf_counter() - started) * 1000), diff --git a/tests/test_module_conditions.py b/tests/test_module_conditions.py index 6d84f02..00870db 100644 --- a/tests/test_module_conditions.py +++ b/tests/test_module_conditions.py @@ -123,6 +123,50 @@ def broken(path): self.assertFalse(api["match_conditions"]({"input": "x", "operator": "equals", "value": 1}, {}, {"readers": {"input": broken}})) self.assertEqual(diagnostics, ["evaluation_error"]) + def test_evaluate_without_a_before_evaluation_module_answers_in_one_session(self) -> None: + after = [] + api, diagnostics = self.setup_api([{ + "name": "reads", + "after_evaluation": lambda evaluation, options: ( + after.append({"featureKey": evaluation.get("featureKey"), "dependencyOf": options.get("dependencyOf")}) or evaluation + ), + }]) + + result = api["evaluate"]({"type": "schema", "key": "signUp"}, lambda scope: [ + scope.match_conditions([{"feature": "paid"}]), + scope.match_conditions("payingDutch"), + ]) + + self.assertEqual(result, [True, True]) + self.assertEqual(after, [{"featureKey": "paid", "dependencyOf": {"type": "schema", "key": "signUp"}}]) + + def test_json_text_is_parsed_once_per_datafile(self) -> None: + import featurevisor.instance as instance_module + + f = create_featurevisor({"datafile": DATAFILE, "logLevel": "fatal", "context": {"country": "nl"}}) + api = {} + f.add_module({"name": "@featurevisor/schemas", "setup": lambda module_api: api.update(module_api)}) + text = '{"attribute": "country", "operator": "equals", "value": "nl"}' + calls = [] + original = instance_module.strict_json_loads + instance_module.strict_json_loads = lambda value: calls.append(value) or original(value) + try: + self.assertTrue(api["match_conditions"](text, {})) + self.assertFalse(api["match_conditions"](text, {"country": "de"})) + self.assertEqual(calls.count(text), 1) + f.set_datafile({**DATAFILE, "revision": "2"}) + self.assertTrue(api["match_conditions"](text, {})) + self.assertEqual(calls.count(text), 2) + finally: + instance_module.strict_json_loads = original + + def test_json_text_that_does_not_parse_is_reported_on_every_call(self) -> None: + api, diagnostics = self.setup_api() + + self.assertFalse(api["match_conditions"]('{"attribute":', {})) + self.assertFalse(api["match_conditions"]('{"attribute":', {})) + self.assertEqual(diagnostics.count("conditions_parse_error"), 2) + if __name__ == "__main__": unittest.main() From 7a64a586c3f65722c5bf639db5b74c48fd0d0b44 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 04:12:47 +0100 Subject: [PATCH 07/21] docs: follow the JavaScript SDK page in the README The README now has the JavaScript SDK page's sections in its order: install, create an instance with an options table, context, flags, variations and variables with typed methods and composition, default values, evaluating everything at once, sticky values, datafile updates with merging and an interval refresh, child instances, events, diagnostics, evaluation details with the reasons table, modules, and schemas from creating an instance to patterns. Examples use the docs' running example, checkout, pricing, buyButton and supportEmail for user-4 in the Netherlands, and the signUp schema, so each page reads like the others in its own language. The README test reads the example under its new heading. --- README.md | 993 ++++++++++++++++++---------- tests/test_readme_initialization.py | 6 +- 2 files changed, 638 insertions(+), 361 deletions(-) diff --git a/README.md b/README.md index e041854..8ad4e10 100644 --- a/README.md +++ b/README.md @@ -1,63 +1,68 @@ # Featurevisor Python SDK -Use the Featurevisor Python SDK to evaluate flags, variations and variables in Python applications. - -The package name is `featurevisor`, and it targets Python 3.10+. +The Featurevisor Python SDK evaluates flags, variations and variables in Python applications, from a datafile it holds in memory. The package is `featurevisor`, for Python 3.10 and later. ## Table of contents -- [Installation](#installation) -- [Initialization](#initialization) - - [Public API](#public-api) - - [Evaluation types](#evaluation-types) +- [Install](#install) +- [Create an instance](#create-an-instance) + - [Concurrency](#concurrency) - [Context](#context) - - [Setting initial context](#setting-initial-context) - - [Setting after initialization](#setting-after-initialization) - - [Replacing existing context](#replacing-existing-context) - - [Manually passing context](#manually-passing-context) -- [Check if enabled](#check-if-enabled) -- [Getting variation](#getting-variation) -- [Getting variables](#getting-variables) - - [Getting feature variables](#getting-feature-variables) - - [Getting global variables](#getting-global-variables) - - [Conditions and composition](#conditions-and-composition) - - [Type specific methods](#type-specific-methods) -- [Getting evaluations](#getting-evaluations) -- [Sticky](#sticky) - - [Initialize with sticky](#initialize-with-sticky) - - [Set sticky afterwards](#set-sticky-afterwards) -- [Setting datafile](#setting-datafile) - - [Merging by default](#merging-by-default) - - [Replacing](#replacing) - - [Loading datafiles on demand](#loading-datafiles-on-demand) - - [Updating datafile](#updating-datafile) - - [Interval-based update](#interval-based-update) -- [Diagnostics](#diagnostics) - - [Levels](#levels) - - [Handler](#handler) +- [Check a flag](#check-a-flag) +- [Get a variation](#get-a-variation) +- [Get a variable](#get-a-variable) + - [Typed methods](#typed-methods) + - [Composed variables](#composed-variables) +- [Default values](#default-values) +- [Evaluate everything at once](#evaluate-everything-at-once) + - [Hand results from server to client](#hand-results-from-server-to-client) +- [Sticky values](#sticky-values) +- [Update the datafile](#update-the-datafile) + - [Merge or replace](#merge-or-replace) + - [Refresh on an interval](#refresh-on-an-interval) +- [Child instances](#child-instances) - [Events](#events) - - [`datafile_set`](#datafile_set) + - [`datafile_set`](#datafile-set) - [`context_set`](#context_set) - - [`sticky_features_set` and `sticky_variables_set`](#sticky_features_set-and-sticky_variables_set) + - [`sticky_features_set`](#sticky_features_set) + - [`sticky_variables_set`](#sticky_variables_set) - [`error`](#error) +- [Diagnostics](#diagnostics) + - [Evaluation errors](#evaluation-errors) - [Evaluation details](#evaluation-details) + - [Evaluation reasons](#evaluation-reasons) - [Modules](#modules) - - [Defining a module](#defining-a-module) - - [Registering modules](#registering-modules) -- [Child instance](#child-instance) + - [Dependency evaluations](#dependency-evaluations) + - [Register a module](#register-a-module) + - [Read the datafile from a module](#read-the-datafile-from-a-module) +- [Schemas](#schemas) + - [Create a schemas instance](#create-a-schemas-instance) + - [Validate a value](#validate-a-value) + - [Read the issues](#read-the-issues) + - [Get a handle](#get-a-handle) + - [Read constraints and choices](#read-constraints-and-choices) + - [Read annotations](#read-annotations) + - [Choose the messages](#choose-the-messages) + - [Check in code](#check-in-code) + - [Options from your application](#options-from-your-application) + - [Follow the values typed so far](#follow-the-values-typed-so-far) + - [Validate on the server](#validate-on-the-server) + - [Listen for changes](#listen-for-changes) + - [Patterns](#patterns) - [Close](#close) - [OpenFeature](#openfeature) -- [Schemas](#schemas) - - [Handles](#handles) - - [Messages](#messages) - - [Checks in code](#checks-in-code) - - [Installation](#installation-1) + - [Installation](#installation) - [Provider setup](#provider-setup) - [Flag key mapping](#flag-key-mapping) - [Context mapping](#context-mapping) - [Resolution details](#resolution-details) - [Tracking](#tracking) - [Using an existing Featurevisor instance](#using-an-existing-featurevisor-instance) +- [Schemas](#schemas) + - [Handles](#handles) + - [Messages](#messages) + - [Checks in code](#checks-in-code) + - [Patterns](#patterns) - [CLI usage](#cli-usage) - [Test](#test) - [Benchmark](#benchmark) @@ -69,17 +74,17 @@ The package name is `featurevisor`, and it targets Python 3.10+. -## Installation - -Upgrading an existing application? Follow the [Python migration guide](https://featurevisor.com/docs/migrations/v4/python/). +## Install ```bash pip install "featurevisor>=4.0.0,<5" ``` -## Initialization +The SDK supports Python 3.10 and later. Upgrading an existing application? Follow the [Python migration guide](https://featurevisor.com/docs/migrations/v4/python/). + +## Create an instance -Initialize the SDK with Featurevisor datafile content: +Fetch a [datafile](https://featurevisor.com/docs/building-datafiles/) and create an instance with it: ```python from urllib.request import urlopen @@ -87,7 +92,7 @@ import json from featurevisor import create_featurevisor -datafile_url = "https://cdn.yoursite.com/featurevisor-all.json" +datafile_url = "https://cdn.example.com/featurevisor-all.json" with urlopen(datafile_url) as response: datafile_content = json.load(response) @@ -96,311 +101,272 @@ f = create_featurevisor({ "datafile": datafile_content, }) try: - print(f.is_enabled("checkout", {"userId": "123"})) + print(f.is_enabled("checkout", {"userId": "user-4"})) finally: f.close() ``` -This example closes the instance after evaluation. In a long running application, keep it alive for subsequent evaluations and close it during shutdown. HTTP failures and invalid JSON propagate to the caller before initialization. - -### Public API - -The main runtime API is `create_featurevisor()`: +This example closes the instance at once. In a long running application, keep it for every evaluation and close it at shutdown. `datafile` takes parsed content or a JSON string. Every option is optional, so an instance can start without a datafile and [receive one later](#update-the-datafile): -```python -from featurevisor import Featurevisor, create_featurevisor - -f: Featurevisor = create_featurevisor({ - "datafile": datafile_content, -}) -``` - -Most applications only need `create_featurevisor` and the `Featurevisor` instance type. Public extension and observability APIs include `FeaturevisorModule`, diagnostics, events, and the datafile dictionaries accepted by the factory. +| Option | Sets | +| ----------------------------------- | -------------------------------- | +| `datafile` | The datafile to evaluate | +| `context` | The [instance context](#context) | +| `stickyFeatures`, `stickyVariables` | [Sticky values](#sticky-values) | +| `logLevel`, `onDiagnostic` | [Diagnostics](#diagnostics) | +| `modules` | [Modules](#modules) | -Concurrent evaluations are safe after an instance is configured. Do not mutate or close the same instance concurrently with evaluations. Serialize calls to `set_datafile`, `set_context`, `set_sticky_features`, `set_sticky_variables`, `add_module`, `remove_module`, and `close`. Module, event, and diagnostic callbacks must synchronize mutable state that they capture. +Create one instance and reuse it. On a server that handles many users, give each request a [child instance](#child-instances). -### Evaluation types +### Concurrency -Featurevisor evaluates four kinds of values: +Evaluations are safe from many threads once an instance is set up. Apply changes, such as `set_datafile`, `set_context`, `set_sticky_features`, `set_sticky_variables`, `add_module`, `remove_module` and `close`, from one thread at a time, never during evaluations. Module, event and diagnostic callbacks synchronize any state of their own. -- [**Flag**](#check-if-enabled) (`bool`): whether the feature is enabled or not -- [**Variation**](#getting-variation) (`str`): the variation of the feature (if any) -- [**Feature variable**](#getting-feature-variables): a configuration value owned by a feature -- [**Global variable**](#getting-global-variables): a configuration value evaluated independently of a feature +Every method also has a camelCase name, such as `isEnabled` and `getVariable`. ## Context -Context is a plain dictionary of attribute values used during evaluation: - -Conditions compare these attributes using the [operators](https://featurevisor.com/docs/operators/), including `empty` and `notEmpty`. - -Date comparisons accept portable timestamp strings and aware `datetime` values with a usable UTC offset. Plain `date` and naive `datetime` values are not accepted. Offsets must stay within 14 hours and the UTC year within 0001 to 9999. Fractions are truncated to milliseconds after conversion to UTC. +Context is a plain dictionary of [attribute](https://featurevisor.com/docs/attributes/) values. The instance keeps a context of its own, and each evaluation can add to it. -```python -context = { - "userId": "123", - "country": "nl", -} -``` - -### Setting initial context - -Set context when you create the instance: +Set it when creating the instance: ```python f = create_featurevisor({ + "datafile": datafile_content, "context": { - "deviceId": "123", "country": "nl", }, }) ``` -### Setting after initialization - -Merge more context later: +Add to it later with `set_context`, or replace it by passing `True` as the second argument: ```python f.set_context({ - "userId": "234", + "userId": "user-4", }) -``` - -### Replacing existing context - -Or replace the existing context: -```python f.set_context( { - "deviceId": "123", - "userId": "234", + "userId": "user-2", "country": "nl", - "browser": "chrome", }, True, ) ``` -### Manually passing context - -Pass additional context to one evaluation: +Context passed to an evaluation is merged over the instance context for that call only: ```python -is_enabled = f.is_enabled("checkout", {"country": "nl"}) -variation = f.get_variation("checkout", {"country": "nl"}) -feature_variable = f.get_variable("checkout", "bgColor", {"country": "nl"}) -global_variable = f.get_variable("supportEmail", {"country": "nl"}) +context = { + "userId": "user-4", + "country": "nl", +} + +f.is_enabled("checkout", context) ``` -## Check if enabled +`get_context()` returns the instance context, and `get_context({"country": "de"})` shows it merged with extra values without storing them. -```python -if f.is_enabled("checkout"): - pass -``` +Dates compare as portable timestamp strings or aware `datetime` values with a UTC offset. A plain `date` or a naive `datetime` is not accepted. Offsets stay within 14 hours, years within 0001 and 9999 in UTC, and fractions are truncated to milliseconds. -## Getting variation +## Check a flag + +`is_enabled` reads a [flag](https://featurevisor.com/docs/flags/). Dutch users have the new `checkout`: ```python -variation = f.get_variation("checkout") +context = { + "userId": "user-4", + "country": "nl", +} -if variation == "treatment": - pass +if f.is_enabled("checkout", context): + ... # show the new checkout ``` -## Getting variables +## Get a variation -### Getting feature variables +`get_variation` returns the [variation](https://featurevisor.com/docs/variations/) of a feature, or `None` if the feature is disabled or has none: ```python -bg_color = f.get_variable("checkout", "bgColor") +variation = f.get_variation("pricing", context) + +if variation == "treatment": + ... # show the new pricing ``` -### Getting global variables +For `user-4` it returns `"control"`, and for `user-2` it returns `"treatment"`. + +## Get a variable -Global variables use the same methods without a feature key: +`get_variable` reads a [feature variable](https://featurevisor.com/docs/variables/#feature-variables) with a feature key and a variable key. For `user-4`, the `netherlands` rule sets the buy button's label to `"Nu kopen"`: ```python -support_email = f.get_variable("supportEmail", {"country": "nl"}) -evaluation = f.evaluate_variable("supportEmail", {"country": "nl"}) +label = f.get_variable("buyButton", "label", context) ``` -Conditions, composition and overrides are applied for you. See [Variables](https://featurevisor.com/docs/variables/#global-variables) and [Conditions](https://featurevisor.com/docs/conditions/) for authoring guidance. - -To see which overrides changed a value, inspect `variableOverridePaths` in the detailed evaluation: +With a context as its second argument, it reads a [global variable](https://featurevisor.com/docs/variables/#global-variables) instead. `supportEmail` returns `"support-nl@example.com"` for `user-4`: ```python -evaluation = f.evaluate_variable("runtimePolicy", {"country": "nl"}) -value = evaluation.get("variableValue") -matched_paths = evaluation.get("variableOverridePaths") +email = f.get_variable("supportEmail", context) ``` -Modules should return the same result for the same input during one evaluation. Pass values that change through context. +A string second argument means a feature variable, and a dictionary means context for a global variable. The typed methods below follow the same rule. -### Conditions and composition +Treat returned dictionaries and lists as read only. The SDK can share them with its datafile rather than copy them on every evaluation, so copy a value before changing it, and never change a datafile after passing it to the instance. -Schema version `"4"` uses one condition language for segments, root gates, force entries, traffic and variable overrides. Leaves compare attributes, reference a segment by its literal key, check a feature's enabled state and optional variation, or compare an ordinary variable getter result. A variable condition can specify its feature owner and a compiled path such as `["items", 0, "enabled"]`. +### Typed methods -Arrays imply AND. Groups use `and`, `or` and `not`. NOT negates the AND of its direct children. Empty expressions are false. Conditions preserve order and short circuiting. Missing paths remain distinct from explicit null. +Each typed method returns `None` when the value has a different type, and never converts it. `get_variable_integer` returns `None` for the string `"1"`, and `get_variable_boolean` returns `None` for `"true"`. A `bool` is never a number, although Python makes it an `int`. -Feature evaluation checks sticky state, force entries, the root gate, then traffic and variable overrides. A failed feature or global variable root gate reports `conditions_unmet` and records the normalized expression in `evaluation.conditions`. Variation and feature variable disabled reasons are unchanged. +`get_variable_number` reads a variable of [type `number`](https://featurevisor.com/docs/variables/#number) as a float, and also `double` in datafiles built before v4. -A global variable can compose ordinary getter results: +| Method | Returns | +| ---------------------- | ---------------------------- | +| `get_variable_boolean` | `bool` | +| `get_variable_string` | `str` | +| `get_variable_integer` | `int` | +| `get_variable_number` | `float`, whole or fractional | +| `get_variable_array` | `list` | +| `get_variable_object` | `dict` | +| `get_variable_json` | Any JSON value | ```python -datafile_content = { - "schemaVersion": "4", - "revision": "example", - "segments": {}, - "features": {}, - "variables": { - "policy": {"type": "object", "defaultValue": {"limit": 50}}, - "screen": {"type": "object", "compose": [ - {"key": "policy", "variable": "policy"}, - ]}, - "policyAlias": {"type": "object", "compose": "policy"}, - }, -} -f = create_featurevisor({"datafile": datafile_content}) -try: - screen = f.get_variable("screen") - policy = f.get_variable("policyAlias") -finally: - f.close() +settings = f.get_variable_object("checkoutSettings", context) +# {"currency": "EUR", "paymentMethods": ["card"]} ``` -The compiled list creates a fresh outer dictionary with literal property names. Entries may read global variables, feature variables, enabled flags or variations. A string `compose` is an alias of one literal global variable key and returns its value directly. False, zero, empty strings, arrays and null remain ordinary source values. JSON is decoded exactly once, including alias chains. +### Composed variables -Compositions have no `defaultValue` or `useDefaultWhenDisabled`. They may have root conditions and `disabledValue`. An unmet gate skips every source and override, returning the disabled value or null. Whole sticky state bypasses source reads. Otherwise all sources are read before the existing override program runs. Detailed evaluations report `variable_composed`, or `variable_override_rule` when an override matches. +Read a [composed global variable](https://featurevisor.com/docs/variables/#compose-values) like any other global variable. For a string `compose` alias, choose the getter for the source's type, such as `get_variable_string` for an alias of `supportEmail`. It returns what the source's own getter returns, including decoded JSON and `None`, with no wrapper or copy. -Sources use effective context, modules and child sticky state without inheriting an outer explicit default. SDK mutations copy changed paths and never change source, sibling or sticky values. Treat supplied datafiles and returned dictionaries and lists as read only. Copy them before application mutations. Cycles and more than 256 dependency handoffs fail the entire evaluation, with no partial composition returned. Python's interpreter recursion limit can stop a very deep chain sooner. With the default recursion limit of 1000, a chain of about 120 feature handoffs fits. This depends on the host and the caller's own stack. Lint warns about chains deeper than 32, which fit comfortably. The logical bound counts active dependency frames rather than every entity name or terminal attribute predicate. The SDK preserves the host application's recursion setting. Exhaustion returns an error evaluation, and later independent evaluations remain usable. +A composition is evaluated in this order: -Schema version `"2"` selectors are normalized eagerly before merging, without changing caller objects or their informational version metadata. Schema version `"4"` entities normalize lazily on their first read. Partial updates invalidate only incoming entities. Replacement clears all normalized entity caches. Concurrent evaluations and background datafile refreshes are supported. Diagnostic handlers may evaluate the same entity again. +1. A sticky value for the whole variable, which skips everything after it. +2. Root `conditions`. When they miss, no source is read and no override runs. The result is `disabledValue` when supplied, otherwise `None`, with reason `conditions_unmet`. +3. The sources, with their own sticky values, the context and modules taking part as usual. +4. The [overrides](https://featurevisor.com/docs/variables/#override-composed-values), which run as they do for any global variable. -Malformed stringified selector JSON fails that entire selector, even through NOT or a segment alias, while other entities remain usable. An error diagnostic with code `conditions_parse_error` is reported once per selector per incoming entity load, eagerly for schema version `"2"` and on first read for schema version `"4"`. Its details contain exactly `conditions`, `entityType` and `entityKey`. Accepted data is stored before eager callbacks, and lazy results are cached before callbacks, so diagnostic handlers can safely reenter evaluation. +Compositions have no `defaultValue` or `useDefaultWhenDisabled`. With no override match, the reason is `variable_composed`, and a match reports `variable_override_rule`, with `variableOverridePaths` listing every override that changed the value. Only the outer dictionary of a composition is fresh, so treat what it holds as read only. -### Type specific methods +Cycles, and chains of more than 256 dependencies, fail the whole evaluation. Python's recursion limit can stop a deep chain sooner: with the default limit of 1000, about 120 feature handoffs fit, depending on your own stack. Lint warns about chains deeper than 32, which fit comfortably. -Typed convenience methods are also available: +## Default values + +Pass `defaultVariationValue` or `defaultVariableValue` in the options for when an evaluation produces no value, such as a feature missing from the datafile: ```python -f.get_variable_boolean(feature_key, variable_key, context={}) -f.get_variable_string(feature_key, variable_key, context={}) -f.get_variable_integer(feature_key, variable_key, context={}) -f.get_variable_number(feature_key, variable_key, context={}) -f.get_variable_array(feature_key, variable_key, context={}) -f.get_variable_object(feature_key, variable_key, context={}) -f.get_variable_json(feature_key, variable_key, context={}) +label = f.get_variable( + "buyButton", + "label", + context, + {"defaultVariableValue": "Buy"}, +) ``` -The same helpers evaluate global variables when the feature key is omitted: +A default counts as given whenever the key is present, so `""`, `0`, `False` and `None` are all valid defaults. -```python -f.get_variable_string("supportEmail", context={}) -f.get_variable_object("checkoutSettings", context={}) -``` +## Evaluate everything at once -Type specific methods do not coerce values. `get_variable_integer()` returns `None` for the string `"1"`, and boolean getters return `None` for non-boolean values. +`get_feature_evaluations` evaluates every loaded feature, or only the keys you pass: -`get_variable_number()` reads a variable of type `number` as a float, whether it holds `3` or `4.5`. Datafiles built before v4 call that type `double`, and it reads the same way. The v3 name `get_variable_double()` was removed in v4. Each method also has a camelCase name, such as `getVariableNumber()`. +```python +f.get_feature_evaluations(context, [ + "checkout", + "pricing", + "buyButton", +]) +# { +# "checkout": {"enabled": True}, +# "pricing": {"enabled": True, "variation": "control"}, +# "buyButton": { +# "enabled": True, +# "variation": "treatment", +# "variables": {"label": "Nu kopen", "colour": "#2563eb"}, +# }, +# } +``` -## Getting evaluations +`get_variable_evaluations` does the same for global variables: ```python -features = f.get_feature_evaluations() -variables = f.get_variable_evaluations() +f.get_variable_evaluations(context, [ + "supportEmail", + "checkoutSettings", +]) ``` -## Sticky +To see what is loaded without evaluating anything: -### Initialize with sticky +- `get_feature_keys()` lists every feature in the datafile, enabled or not. +- `get_variable_keys()` lists global variables, and `get_variable_keys("buyButton")` lists that feature's variables. +- `has_variations("pricing")` is `True` when a feature has variations, and `False` for an unknown feature. -Pin feature evaluations with sticky values: +### Hand results from server to client -Sticky values belong to an SDK or child instance. Evaluation options do not accept sticky overrides. Pass `stickyFeatures` or `stickyVariables` when a child needs its own state. +Both results have the shape [sticky values](#sticky-values) take. A server can evaluate once per request and pass the results to the browser, so the first render matches what the server saw. The JavaScript SDK's [sticky values](https://featurevisor.com/docs/sdks/javascript/#hand-results-from-server-to-client) read them there. -Treat supplied sticky maps and their nested values as read only after handoff. Use the instance or child sticky setters to change them. Mutating a supplied map in place is not supported. +## Sticky values + +Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests: ```python f = create_featurevisor({ "stickyFeatures": { - "checkout": { + "checkout": {"enabled": True}, + "pricing": { "enabled": True, "variation": "treatment", - "variables": { - "myVariableKey": "myVariableValue", - }, }, }, "stickyVariables": { - "supportEmail": "sticky@example.com", + "supportEmail": "support@example.com", }, }) ``` -### Set sticky afterwards - -Or update them later: +A sticky feature can also set `variables`. Change sticky values later with `set_sticky_features` and `set_sticky_variables`. Both merge by default, and replace the whole map with `replace=True`: ```python -f.set_sticky_features({ - "checkout": { - "enabled": False, - } -}) - -f.set_sticky_variables({"supportEmail": "new@example.com"}) +f.set_sticky_features( + { + "checkout": {"enabled": False}, + }, + replace=True, +) ``` -## Setting datafile +Treat sticky maps as read only once given to an instance, and change them only through these methods. + +## Update the datafile -You may initialize the SDK without passing `datafile`, and set it later on. The SDK accepts either parsed JSON content or a JSON string: +`set_datafile` gives the instance a newer datafile, parsed or as a JSON string: ```python f.set_datafile(datafile_content) -f.set_datafile(json.dumps(datafile_content)) ``` -`set_datafile` returns `True` when the datafile is accepted, including unchanged content. It returns `False` when the datafile is rejected or the instance is closed. Rejected datafiles leave the last accepted datafile in place. Diagnostics and events keep their existing behaviour. The `setDatafile` alias returns the same boolean. - -### Merging by default - -By default, `set_datafile(datafile)` merges incoming content into the SDK's current datafile: +It returns `True` when the datafile is accepted, even if nothing changed, and `False` when it is rejected or the instance is closed. A rejected datafile leaves the previous one in place and is reported through [diagnostics](#diagnostics). -- top-level metadata such as `schemaVersion`, `revision`, and `featurevisorVersion` comes from the incoming datafile -- `segments` are merged, with incoming entries overriding existing ones -- `features` are merged, with incoming entries overriding existing ones -- global `variables` are merged, with incoming entries overriding existing ones +### Merge or replace -Call `set_datafile` with different datafiles to merge their features, segments, and global variables. Use this to [load datafiles on demand](#loading-datafiles-on-demand). +By default, the new datafile is merged into the current one: -### Replacing +- Its features, segments and global variables replace those with the same keys. +- Definitions it does not contain are kept. +- Its `revision` and `schemaVersion` are taken. -To fully replace the stored datafile, pass `replace=True`: +Pass `replace=True` to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger: ```python f.set_datafile(datafile_content, replace=True) ``` -### Loading datafiles on demand - -Merge datafiles for different [targets](https://featurevisor.com/docs/targets/) into the same instance. Here, the two datafile values have already been loaded and validated by your application from the same published release: - -```python -f.set_datafile(products_datafile) -f.set_datafile(checkout_datafile) -``` - -Use immutable release URLs, check HTTP responses and keep shared dependencies consistent. See [Loading datafiles on demand](https://featurevisor.com/docs/use-cases/on-demand-datafiles/) for the complete loading and refresh flow. - -### Updating datafile +Merging is what lets one instance hold datafiles for several [targets](https://featurevisor.com/docs/targets/), loaded as each part of the application needs them. See [Loading datafiles on demand](https://featurevisor.com/docs/use-cases/on-demand-datafiles/). -Each accepted datafile update emits a [`datafile_set`](#datafile-set) event. Subscribe to react to updates. +### Refresh on an interval -### Interval-based update - -Replace the complete datafile on each refresh so definitions removed upstream are removed from the SDK too. Use merging only when loading partial datafiles intentionally. Schedule the next attempt even if fetching or decoding fails. +Fetch the datafile again every few minutes, scheduling the next attempt even when one fails: ```python import json @@ -408,208 +374,517 @@ import logging import threading from urllib.request import urlopen -def update_datafile(): +def refresh_datafile(): try: with urlopen(datafile_url, timeout=30) as response: f.set_datafile(json.load(response), replace=True) except Exception: - logging.exception("Failed to update datafile") + logging.exception("Could not refresh datafile") finally: - threading.Timer(5 * 60, update_datafile).start() + threading.Timer(5 * 60, refresh_datafile).start() -update_datafile() +refresh_datafile() ``` -## Diagnostics - -By default, Featurevisor reports diagnostics to the console for `info` level and above with a `[Featurevisor]` prefix. - -### Levels - -Available diagnostic levels are `fatal`, `error`, `warn`, `info`, and `debug`. - -Set the level during initialization or update it afterwards: +A failed fetch keeps the previous datafile. `set_datafile` does not raise for an invalid datafile, it reports it through diagnostics. Cancel the timer when you stop, since `close()` does not cancel your timers or requests. Each accepted update emits [`datafile_set`](#datafile-set). -```python -f = create_featurevisor({"logLevel": "debug"}) -f.set_log_level("info") -``` +## Child instances -### Handler - -Use `onDiagnostic` to send structured diagnostics to your observability system: +A server handles many users at once, so give each request a child with its own context: ```python -f = create_featurevisor({ - "logLevel": "info", - "onDiagnostic": lambda diagnostic: print( - diagnostic["level"], - diagnostic["code"], - diagnostic["message"], - ), +child = f.spawn({ + "userId": "user-4", + "country": "nl", }) -``` -Every diagnostic has `level`, `code`, `message`, and an object-shaped `details` dictionary. Optional `module`, `moduleName`, and `originalError` fields describe provenance. Evaluation metadata belongs in `details`. +child.is_enabled("checkout") +``` -Diagnostic handlers are isolated from SDK behaviour. An exception in a handler does not stop other handlers or evaluations. +- The child copies the parent's context keys when it is spawned, and its own values win. Keys the parent adds later still reach it. +- Sticky values are not inherited. Pass `{"stickyFeatures": ...}` as the second argument when the child needs some. +- A child has the parent's evaluation methods, plus `get_context`, `set_context`, `set_sticky_features`, `set_sticky_variables`, `on` and `close`. +- `close()` removes the child's listeners, including the ones it registered on its parent. ## Events -Subscribe to SDK events to respond to context, sticky state and datafile changes. +`on` subscribes to an event and returns a function that unsubscribes. ### `datafile_set` +Emitted for every accepted datafile: + ```python -def handle_datafile_set(event): +def on_datafile_set(event): revision = event["revision"] previous_revision = event["previousRevision"] - revision_changed = event["revisionChanged"] - features = event["features"] replaced = event["replaced"] + features = event["features"] + variables = event["variables"] + # evaluate the listed features and variables again -unsubscribe = f.on("datafile_set", handle_datafile_set) +unsubscribe = f.on("datafile_set", on_datafile_set) unsubscribe() ``` -The `features` list will contain keys of features that have either been added, updated, or removed compared to the previous datafile content. +`replaced` says whether the datafile replaced the previous one or merged into it. `features` and `variables` list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. `sections` lists the changed entries of each [datafile section](#read-the-datafile-from-a-module), such as `schemas`. ### `context_set` +Emitted by `set_context`, with the new `context` and `replaced`: + ```python -unsubscribe = f.on("context_set", lambda event: print(event["context"])) -unsubscribe() +f.on("context_set", lambda event: print(event["context"])) ``` -### `sticky_features_set` and `sticky_variables_set` +### `sticky_features_set` + +Emitted by `set_sticky_features`, with `features`, every feature that had a sticky value before the call or has one after it, and `replaced`: ```python -unsubscribe = f.on("sticky_features_set", lambda event: print(event["features"])) -unsubscribe() +f.on("sticky_features_set", lambda event: print(event["features"])) +``` -unsubscribe = f.on("sticky_variables_set", lambda event: print(event["variables"])) -unsubscribe() +### `sticky_variables_set` + +Emitted by `set_sticky_variables`, with `variables` and `replaced`: + +```python +f.on("sticky_variables_set", lambda event: print(event["variables"])) ``` ### `error` +Emitted for every diagnostic at `error`: + ```python -unsubscribe = f.on("error", lambda event: print(event["diagnostic"]["message"])) -unsubscribe() +f.on("error", lambda event: print(event["diagnostic"]["message"])) ``` -The `error` event is emitted for diagnostics reported with `level` set to `error`. +## Diagnostics -## Evaluation details +The SDK reports what happens during evaluation as diagnostics, at one of five levels: `fatal`, `error`, `warn`, `info` and `debug`. By default, those at `info` and above go to the console with a `[Featurevisor]` prefix. -Inspect how variations and variables are evaluated against a context: +`debug` shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later: ```python -# flag -evaluation = f.evaluate_flag(feature_key, context={}) +f = create_featurevisor({ + "logLevel": "debug", +}) + +f.set_log_level("warn") +``` -# variation -evaluation = f.evaluate_variation(feature_key, context={}) +To send diagnostics somewhere other than the console, pass a handler: -# variable -evaluation = f.evaluate_variable(feature_key, variable_key, context={}) +```python +def on_diagnostic(diagnostic): + level, code, message = diagnostic["level"], diagnostic["code"], diagnostic["message"] + # send to your observability system + +f = create_featurevisor({ + "onDiagnostic": on_diagnostic, +}) ``` -The returned object will always contain the following properties: +Every diagnostic has `level`, `code`, `message` and a `details` dictionary. Values about an evaluation, such as `featureKey`, `variableKey`, `reason` and `evaluation`, are in `details`. `module`, `moduleName` and `originalError` say where an error came from, when known. A handler that raises stops neither other handlers nor evaluations. -- `type`: flag, variation or variable -- `reason`: why the value was evaluated +### Evaluation errors -Feature evaluations also contain `featureKey`. Global variable evaluations contain `variableKey`. +`conditions_parse_error` is an `error` diagnostic for malformed stringified conditions. It fires once per selector per datafile load, on first read for v4 datafiles and during `set_datafile` for v3 datafiles. Its `details` contain `conditions` with the raw string, `entityType` and `entityKey`. -And optionally these properties depending on whether you are evaluating a feature variation or a variable: +The whole malformed selector evaluates to `False`, even under `not`, while other entities keep working and `set_datafile` returns `True` for an otherwise valid datafile. A malformed root gate is unmet and reports `conditions_unmet`. Handlers may evaluate the same entity again, since results are cached before they run. -- `bucketValue`: the bucket value between 0 and 100,000 -- `ruleKey`: the rule key -- `error`: the error object -- `enabled`: if feature itself is enabled or not -- `variation`: the variation object -- `variationValue`: the variation value -- `variableKey`: the variable key -- `variableValue`: the variable value -- `variableSchema`: the variable schema -- `variableOverrideIndex`: index of matched variable override when applicable -- `variableOverrideKey`: key of the matched variable override when available -- `variableOverridePath`: nested authoring path of the matched global variable override -- `variableOverridePaths`: all matched paths from an accumulating global variable override -- `conditions`: the normalized root expression when its gate prevents evaluation -- `variable`: the global variable definition when available +Dependency cycles fail the whole evaluation with reason `error`. SDK evaluation errors return the ordinary false or `None` result, and other entities keep working. -## Modules +## Evaluation details -The before evaluation and after evaluation phases each use the module membership at the start of that phase. Where an evaluation uses bucketing, the bucket key and bucket value phases each use their own starting membership. Adding or removing a module during a phase does not change the iteration already in progress. The next phase uses the membership then installed. A module added before the after phase can receive after callbacks for evaluations already in progress, even if it did not receive their before callbacks. A module removed before the after phase receives no after callback. +The `evaluate` methods return how a value was reached, not only the value: -Modules can intercept evaluation and participate in SDK lifecycle: +```python +f.evaluate_flag("checkout", context) +f.evaluate_variation("pricing", context) +f.evaluate_variable("buyButton", "label", context) +f.evaluate_variable("supportEmail", context) +``` -- `setup` -- `bucketKey` -- `bucketValue` -- `beforeEvaluation` -- `afterEvaluation` -- `close` +For `user-4`, `evaluate_flag` returns: -### Defining a module +```python +{ + "type": "flag", + "featureKey": "checkout", + "reason": "rule", + "bucketKey": "user-4.checkout", + "bucketValue": 89312, + "ruleKey": "netherlands", + "enabled": True, +} +``` + +Every evaluation has a `type` and a `reason`. Others appear when they apply: + +- `featureKey`, absent for global variables, so check for it before using it +- `bucketKey` and `bucketValue`, from 0 to 100,000, and the `ruleKey` that matched +- `enabled`, `variation` and `variationValue` +- `variableKey`, `variableValue`, `variableSchema` and `variable`, the global variable's definition +- `variableOverrideKey` and `variableOverrideIndex` when a keyed override matched, and `variableOverridePath` for a nested one +- `variableOverridePaths`, every override path matched in order, for [accumulating overrides](https://featurevisor.com/docs/mutations/#accumulate-overrides). The singular fields describe the last match +- `conditions` when a [root gate](https://featurevisor.com/docs/conditions/) stopped the evaluation +- `error` when evaluation failed + +### Evaluation reasons + +[Test specs](https://featurevisor.com/docs/testing/) can assert them. + +| Reason | Meaning | +| ----------------------------- | -------------------------------------------------------------------------------- | +| `feature_not_found` | The feature is not in the datafile | +| `disabled` | The feature is disabled | +| `no_variations` | A variation was requested from a feature without variations | +| `variation_disabled` | A disabled feature returned its `disabledVariationValue` | +| `variable_not_found` | The feature variable or global variable is not in the datafile | +| `variable_default` | The variable returned its default value | +| `variable_composed` | A global variable read its composition sources with no override match | +| `variable_disabled` | A disabled feature returned the variable's disabled value | +| `variable_override_variation` | A feature variable override matched inside a variation | +| `variable_override_rule` | A feature variable override or global variable override matched | +| `conditions_unmet` | Root conditions did not match. See `conditions` | +| `no_match` | No rule, allocation or variation matched, or the bucket fell outside the rollout | +| `forced` | A `force` entry supplied the result | +| `sticky` | A sticky value supplied the result | +| `rule` | A matching rule supplied the result | +| `allocated` | Bucketing allocated the result | +| `error` | Evaluation failed. See `error` | + +## Modules + +A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Every part is optional: ```python -my_module = { - "name": "my-module", - "setup": lambda api: api["onDiagnostic"](lambda diagnostic: print(diagnostic)), - "beforeEvaluation": lambda options: {**options, "context": {**options["context"], "country": "nl"}}, +def setup(api): + api["onDiagnostic"](lambda diagnostic: ..., {"logLevel": "warn"}) + api["reportDiagnostic"]({ + "level": "info", + "code": "module_ready", + "message": f"Ready for revision {api['getRevision']()}", + }) + +audit_module = { + "name": "audit", + "setup": setup, + # type, featureKey, variableKey and context + "beforeEvaluation": lambda options: { + **options, + "context": {**options["context"], "plan": "paid"}, + }, + "afterEvaluation": lambda evaluation, options: evaluation, "bucketKey": lambda options: options["bucketKey"], + # between 0 and 100,000 "bucketValue": lambda options: options["bucketValue"], - "afterEvaluation": lambda evaluation, options: evaluation, "close": lambda: None, } ``` -`beforeEvaluation` and `afterEvaluation` run for feature and global variable evaluations. Required feature and variable checks use the same module pipeline, while an accumulating override publishes only its final result to `afterEvaluation`. +`beforeEvaluation` and `afterEvaluation` run for flags, variations and both kinds of variable, every module in registration order, and must return the options and the evaluation, changed or not. A variable evaluation without a `featureKey` is a global one. Snake case keys, such as `before_evaluation`, work too. -For an internal prerequisite read, both callbacks receive `options["dependencyOf"]` identifying the immediate requester, for example `{"type": "variable", "variableKey": "checkoutPolicy"}`. Feature variable requesters also include `featureKey`. Ordinary application calls have no `dependencyOf` entry. Callbacks can inspect this metadata without adding it to application options. +The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress. -The module API passed to `setup` exposes `getRevision`, `onDiagnostic`, and `reportDiagnostic`. +If `setup` raises, the module is not registered. The SDK removes the diagnostic subscriptions it made, reports `module_setup_error`, and calls its `close` if it has one. -If `setup` raises an exception, the module is not registered. Featurevisor removes subscriptions created during setup, reports `module_setup_error`, and calls `close` when present. +### Dependency evaluations -Internal reads carry `dependencyOf` identifying the immediate requester and `dependencyPurpose` set to `condition` or `composition`. Direct application calls carry neither. Conditions use owned comparison snapshots. Composition follows ordinary getter ownership. Memoization separates these purposes and is scoped to one public call. Tracking modules should normally skip condition reads, but composition reads consume real values. Private request state is never exposed to callbacks. +[Conditions](https://featurevisor.com/docs/conditions/) and [composition members](https://featurevisor.com/docs/variables/#compose-values) are evaluated through modules too. Their options include `dependencyOf`, naming the requesting evaluation by `type`, `featureKey` and `variableKey`. `dependencyPurpose` is `"condition"` for an eligibility check and `"composition"` for a consumed member value. Direct calls have neither. -### Registering modules +When tracking consumed evaluations, skip eligibility checks, not every read with `dependencyOf`, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context. -Modules can be registered at initialization or afterwards: +### Register a module -```python +Pass modules when creating the instance, or add them later: +```python f = create_featurevisor({ - "modules": [my_module], + "modules": [audit_module], }) -remove_module = f.add_module(my_module) -remove_module() +remove = f.add_module(tracking_module) -f.remove_module("my-module") +# later +remove() +f.remove_module("audit") ``` -The API `setup` receives also reads a datafile's sections, the top level keys besides Featurevisor's own whose values are objects, such as `schemas`. `get_entry(section, key)` returns an entry as stored, so treat it as read only, and `get_entry_keys(section)` lists a section's keys. `match_conditions(conditions, context, options)` answers a package's own conditions with the instance's engine, segments and feature leaves included, and `options["readers"]` answer leaves only the package knows, such as `input`, returning `featurevisor.conditions.MISSING` for no value. `evaluate({"type": ..., "key": ..., "context": ...}, callback)` evaluates a package's own entry as a getter evaluates a feature: every module's `beforeEvaluation` runs first, with `type` and `key` naming the entry, and the conditions the callback answers with `scope.match_conditions(conditions, readers)` read the context the modules leave, in one dependency session. The callback's result is returned. Feature and variable leaves reach modules as dependencies, with `dependencyOf` naming the package's entry by `type` and `key`. This is how [schemas](#schemas) read their schemas. +### Read the datafile from a module + +A package, such as [schemas](#schemas), reads the datafile through the API `setup` receives: + +- `get_entry(section, key)` returns an entry of a section, a top level key besides Featurevisor's own whose value is an object, such as `schemas`. Treat it as read only. `get_entry_keys(section)` lists a section's keys. +- `match_conditions(conditions, context, options)` answers the package's own conditions with the instance's engine, segments and feature leaves included. `options["readers"]` answer leaves only the package knows, such as `input`, returning `featurevisor.conditions.MISSING` for no value. +- `evaluate({"type": ..., "key": ..., "context": ...}, callback)` evaluates the package's own entry as a getter evaluates a flag. Every module's `beforeEvaluation` runs first, with `type` and `key` naming the entry, and the conditions the callback answers with `scope.match_conditions(conditions, readers)` read the context the modules leave, in one dependency session. The callback's result is returned. + +Feature and variable leaves reach modules as dependencies, with `dependencyOf` naming the package's entry. A module with no evaluation callbacks, such as a package's, costs evaluations nothing. -## Child instance +## Schemas + +Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/#validate-application-data) your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript. -A child snapshots the parent keys that exist when it is spawned. Child values win for those keys. Parent keys introduced later are still inherited. Calling `close()` removes both child-owned listeners and subscriptions delegated to the parent. +### Create a schemas instance + +They are the `featurevisor.schemas` subpackage, installed with the SDK. Create it from the SDK instance. Call it `s`, as the SDK instance is `f`: ```python -child = f.spawn({"country": "de"}) -child.is_enabled("checkout") -child.evaluate_flag("checkout") -child.evaluate_variation("checkout") -child.evaluate_variable("checkout", "bgColor") -child.evaluate_variable("supportEmail") +from featurevisor.schemas import create_schemas + +s = create_schemas(f) +``` + +It holds no copy of the schemas. Every call reads the datafile `f` has now, so a [new datafile](#update-the-datafile) applies at the next validation. Compiled schemas are kept until a datafile changes them, and handles are safe to use from many threads. + +### Validate a value + +```python +sign_up = { + "email": "user-1@example.com", + "displayName": "A", + "country": "nl", +} + +result = s.validate("signUp", sign_up) + +if not result.valid: + ... # show result.issues beside the form's fields ``` +- `s.validate(key, value)` returns a `ValidationResult` with the value itself and its `issues`. It never coerces, fills defaults or strips keys. +- `s.is_valid(key, value)` returns a boolean. +- `s.parse(key, value)` returns the value, or raises a `SchemaValidationError`, for a server or a script that wants a value or a stop. +- All three take a context as a third argument, merged over the instance's, for the [conditions](https://featurevisor.com/docs/schemas/#read-the-context) a schema's rules read. +- A validation runs as the schema's own evaluation, so a [module](#modules)'s `beforeEvaluation` sees it, with `type` `schema` and the schema's `key`, and context the module adds reaches every condition, as it does for flags. +- `s.keys()` lists the schemas the datafile has, and `s.has(key)` says whether it has one. + +A value can be dictionaries, lists, strings, numbers, booleans and `None`, or a dataclass, a pydantic model, a tuple or another mapping or sequence, converted first. + +A key the datafile does not have fails closed, with one `schemaNotFound` issue, and a `schema_not_found` [diagnostic](#diagnostics) at `warn`, once per key. + +### Read the issues + +Every issue has a `message`, a `path` of object keys and list indices, the `code` of the rule that failed, its `params`, and the `schema` validated. `issue.field` gives its path as a form names a field, such as `items.0.name`. + +Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a [title](https://featurevisor.com/docs/schemas/#title-the-fields) carries it in `params["title"]`, and one whose rule a [mutation](https://featurevisor.com/docs/schemas/#mutations) set names it in `mutation`. + +| Code | Raised when | +| ---------------------------------- | --------------------------------------------------------------------- | +| `type` | The value has another type | +| `const`, `enum` | The value is not one allowed | +| `minimum`, `maximum` | A number is out of range | +| `minLength`, `maxLength` | A string is too short or too long | +| `pattern`, `format` | A string has the wrong shape | +| `minItems`, `maxItems` | A list has too few or too many items | +| `uniqueItems` | A list repeats an item | +| `required`, `additionalProperties` | A key is missing, or there is one it does not allow | +| `oneOf` | No branch matches, or more than one does | +| `refine` | An `issues` entry matches, or a [check in code](#check-in-code) fails | +| `refineError` | A check in code raises, or the schema itself cannot be applied | +| `schemaNotFound` | The datafile has no such schema or field | + +`result.flatten()` groups the messages by field, in the shape of Zod's `flattenError`, and so does `flatten()` on a `SchemaValidationError`, for an error response. + +### Get a handle + +`s.get(key)` gives the schema's handle: + +```python +sign_up = s.get("signUp") +``` + +A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application. + +| Member | What it is | +| ------------------------------------------- | -------------------------------------------------------------------- | +| `validate`, `is_valid`, `parse` | As on `s`, without the key | +| `avalidate`, `aparse` | The same, awaiting your [checks in code](#check-in-code) | +| `at(path)` | The handle of one field, such as `at("displayName")` | +| `fields`, `field_keys` | An object's fields' handles and names, in [order](#read-annotations) | +| `constraints`, `field_constraints` | HTML validation attributes, [below](#read-constraints-and-choices) | +| `options`, `field_options`, `option(value)` | Its choices, and one of them by value | +| `kind` | What its rules make the field, such as `"select"` | +| `annotations` | Its [annotations](#read-annotations) | +| `with_input(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | +| `reads` | The fields its rules' conditions read | +| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | +| `key`, `path`, `name` | The schema's key, and the field's path and own name | + +`at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. + +### Read constraints and choices + +`constraints` are named after HTML attributes: + +```python +sign_up.at("displayName").constraints +# Constraints(required=True, min_length=2, max_length=40) + +sign_up.at("displayName").constraints.attributes() +# {"required": True, "minlength": 2, "maxlength": 40}, for a template +``` + +- `required`, when the key is required, so an input left empty fails +- `min_length` and `max_length`, from the same rules on a string +- `min` and `max`, from `minimum` and `maximum` on a number +- `step` of 1, for an `integer` +- `multiple`, for a list, such as a multiple select + +`options` lists a field's choices in the order of its rules, each with what its [annotations](https://featurevisor.com/docs/schemas/#label-the-choices) say, and `option(value)` finds one, for showing a value saved earlier: + +```python +country = sign_up.at("country") + +country.options # nl, de and be, each a SchemaOption +country.option("nl").title # "Netherlands" +country.option("fr") # None +``` + +A schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. `kind` answers the switch every generic form writes, from the field's rules alone: `"text"`, `"date-time"`, `"version"`, `"number"`, `"boolean"`, `"select"`, `"multiselect"`, `"object"` or `"list"`. Your own annotation, such as `input: select`, still wins over it. + +### Read annotations + +A handle's `annotations` are its node's own, and `fields` gives an object's fields in its `order`: + +```python +sign_up.annotations["title"] # "Create your account" + +[field.path for field in sign_up.fields] +# ["displayName", "email", "country"] +``` + +Fields an `order` annotation leaves out come after it, in key order. A field or schema the datafile lacks has no annotations, `{}`. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. + +### Choose the messages + +`messages` on `create_schemas` words every schema's issues, per code, as a template or a function of the params: + +```python +s = create_schemas( + f, + messages={ + "required": "This field is required", + "maxLength": lambda params, info: f"{params['length']} of {params['maxLength']} characters", + }, +) +``` + +`messages` on `s.get` words one form, by field and code, such as `{"displayName": {"maxLength": "Names fit {maxLength} characters"}}`. For each issue, the first of these that words it wins: + +1. A check in code's own message, then the form's. +2. The schema's own, and then the `message` of its [issues](https://featurevisor.com/docs/schemas/#issues) entry. +3. The application's, from `messages` on `create_schemas`. +4. The default, in English. + +`translate` on `create_schemas` gets each issue, with the message chosen, and returns what the issue says, or `None` to keep it. Keep the text in your translation system, and let schemas and `messages` hold keys, such as `errors.required`, which `translate` turns into text. + +### Check in code + +Some checks need your application, such as whether a display name is taken. Give them to a handle in `refine`, each a `Refinement` with a `key`, a `check`, a `path` and a `message`: + +```python +from featurevisor.schemas import Refinement + +async def name_available(display_name, info): + return await names.available(display_name) + +sign_up = s.get("signUp", refine=[ + Refinement("nameAvailable", name_available, path="displayName", + message="That display name is taken"), +]) + +result = await sign_up.avalidate(value) +``` + +- `check` gets the value at its path, and `info` with the whole `input` and the `context`. It returns `True` when the value passes, or a coroutine of it. +- It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database. +- Its issue has code `refine` and `params["refine"]` `"nameAvailable"`, with the field's title. A check that raises gives `refineError`, and validation fails closed. +- `avalidate` awaits every check, running them concurrently, and `aparse` is its `parse`. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. + +### Options from your application + +Some lists only your application can answer for, such as cities for a `city` field. Give a handle an `OptionSource` in `option_sources`, with a `key`, a `path`, and a `search`, a `lookup` or both: + +```python +from featurevisor.schemas import OptionSource + +cities = OptionSource( + "cities", + "city", + reads=["country"], + search=lambda query, info: city_index.search(info.input["country"], query), + lookup=lambda city, info: city_index.find(info.input["country"], city), + message="Choose a city from the list", +) + +sign_up = s.get("signUp", option_sources=[cities]) +city = sign_up.with_input({"country": "nl"}).at("city") + +await city.search("am") +# [SchemaOption(value="Amsterdam"), SchemaOption(value="Amersfoort")] +``` + +- `search` returns choices shaped like `options`, or values alone, now or as a coroutine. A handle's `search` passes it the values given to `with_input`, so the cities follow the country. `can_search` says whether a field has one. +- `lookup` returns the choice for a value, `True` when it carries nothing more, or `None` when there is none. A handle's `await lookup(value)` returns the schema's own choice first, then the source's. +- Validation runs `lookup` as a [check in code](#check-in-code), after the schema's rules, only for a value that is there, and not while a field `reads` names has an issue. A value it cannot find has code `enum`, worded by `message`. + +### Follow the values typed so far + +A handle's constraints and choices describe the schema's own rules, which no condition changes. `with_input(input)` gives the same handle with an input, such as a form's values, with the [mutations](https://featurevisor.com/docs/schemas/#mutations) that match it applied, so a tax ID shows as required once a business account is chosen: + +```python +values = { + "accountType": "business", + "country": "nl", +} + +sign_up.at("taxId").constraints.required # False +sign_up.with_input(values).at("taxId").constraints.required # True +``` + +Every member follows the input, at every depth. `reads` lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes. + +### Validate on the server + +`parse` answers a request with a value or a `SchemaValidationError`, whose `flatten()` gives the issues by field: + +```python +from featurevisor.schemas import SchemaValidationError + +@app.post("/sign-up") +def sign_up_endpoint(body: dict): + try: + value = s.parse("signUp", body) + except SchemaValidationError as error: + raise HTTPException(status_code=400, detail=error.flatten()) + + return create_account(value) +``` + +A rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree. + +### Listen for changes + +`subscribe` calls back when a new datafile changes the schema, through a schema it references too, and returns a function that stops it: + +```python +stop = s.get("signUp").at("country").subscribe(lambda: render_choices()) +``` + +A datafile whose schema is unchanged calls nothing. `s.close()`, or leaving a `with create_schemas(f) as s:` block, stops every listener the instance started and removes its module from the Featurevisor instance. + +### Patterns + +Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value with one `schema_pattern_unsupported` diagnostic. A mutation whose operations cannot be applied fails the value with `refineError` and one `schema_mutation_error` diagnostic, and so does a schema that follows references more than 128 deep without reading deeper into the value, with `schema_reference_depth`. + ## Close +`close()` removes event listeners and closes modules, on the instance and on a child: + ```python f.close() ``` @@ -640,7 +915,7 @@ client = api.get_client() enabled = client.get_boolean_value( "checkout", False, - EvaluationContext(targeting_key="user-123", attributes={"country": "nl"}), + EvaluationContext(targeting_key="user-4", attributes={"country": "nl"}), ) ``` @@ -648,12 +923,12 @@ Call `api.shutdown()` during application shutdown. This closes a Featurevisor in ### Flag key mapping -| OpenFeature key | Featurevisor evaluation | -| --- | --- | -| `checkout` | Boolean flag for `checkout` | -| `checkout:variation` | Variation value for `checkout` | -| `checkout:title` | Variable `title` for `checkout` | -| `variable:supportEmail` | Global variable `supportEmail` | +| OpenFeature key | Featurevisor evaluation | +| ----------------------- | -------------------------------- | +| `checkout` | Boolean flag for `checkout` | +| `checkout:variation` | Variation value for `checkout` | +| `buyButton:label` | Variable `label` for `buyButton` | +| `variable:supportEmail` | Global variable `supportEmail` | Boolean variables use the boolean resolver. Integer and double variables use their matching numeric resolvers. Arrays, objects, and JSON variables use the object resolver. @@ -668,7 +943,7 @@ provider = FeaturevisorOpenFeatureProvider( ) ``` -This makes `checkout/$variation` the variation key, `checkout/title` a feature variable key, and `$variable/supportEmail` a global variable key. The global prefix defaults to `variable` and cannot contain the separator. +This makes `checkout/$variation` the variation key, `buyButton/label` a feature variable key, and `$variable/supportEmail` a global variable key. The global prefix defaults to `variable` and cannot contain the separator. ### Context mapping @@ -689,16 +964,16 @@ OpenFeature context attributes are copied without mutating the incoming context. The provider maps Featurevisor evaluation results to OpenFeature details: -| Featurevisor result | OpenFeature result | -| --- | --- | -| Forced, sticky, rule match or composed variable | `TARGETING_MATCH` | -| Traffic allocation | `SPLIT` | -| Unmet root conditions, disabled variation or disabled variable | `DISABLED` | -| No match or variable default | `DEFAULT` | -| Missing feature, variable, or variations | `ERROR` with `FLAG_NOT_FOUND` | -| Wrong resolver type | `ERROR` with `TYPE_MISMATCH` | -| Invalid datafile | `ERROR` with `PARSE_ERROR` | -| Evaluation failure | `ERROR` with `GENERAL` | +| Featurevisor result | OpenFeature result | +| -------------------------------------------------------------- | ----------------------------- | +| Forced, sticky, rule match or composed variable | `TARGETING_MATCH` | +| Traffic allocation | `SPLIT` | +| Unmet root conditions, disabled variation or disabled variable | `DISABLED` | +| No match or variable default | `DEFAULT` | +| Missing feature, variable, or variations | `ERROR` with `FLAG_NOT_FOUND` | +| Wrong resolver type | `ERROR` with `TYPE_MISMATCH` | +| Invalid datafile | `ERROR` with `PARSE_ERROR` | +| Evaluation failure | `ERROR` with `GENERAL` | Errors return the default value supplied to OpenFeature. A malformed datafile uses the stable message `Could not parse datafile`. A later successful `set_datafile` call clears the parse error. @@ -884,12 +1159,14 @@ Repeat `--populate-uuid=` to generate UUID values for multiple context attr + -The aggregate evaluation reference has moved to [Getting evaluations](#getting-evaluations). +The aggregate evaluation reference has moved to [Evaluate everything at once](#evaluate-everything-at-once). + -The sticky state reference has moved to [Sticky](#sticky). +The sticky state reference has moved to [Sticky values](#sticky-values). ## Development @@ -908,7 +1185,7 @@ make check `make check` runs the base SDK tests, OpenFeature provider tests, and static type checking. Run them separately with `make test`, `make test-openfeature`, and `make typecheck`. -Run `PYTHONPATH=src python3 -m unittest discover -s tests -p test_readme_initialization.py -v` to execute the actual initialization snippet with simulated HTTP responses. The check covers evaluation, cleanup and failures without network access, and also runs in the ordinary SDK suite and CI. +Run `PYTHONPATH=src python3 -m unittest discover -s tests -p test_readme_initialization.py -v` to run the README's "Create an instance" snippet with simulated HTTP responses. The check covers evaluation, cleanup and failures without network access, and also runs in the ordinary SDK suite and CI. Run the example project integration directly: diff --git a/tests/test_readme_initialization.py b/tests/test_readme_initialization.py index 46bcdea..efca8ba 100644 --- a/tests/test_readme_initialization.py +++ b/tests/test_readme_initialization.py @@ -13,8 +13,8 @@ class ReadmeInitializationTests(unittest.TestCase): def setUp(self): readme = Path(__file__).resolve().parents[1] / "README.md" - match = re.search(r"## Initialization\n.*?```python\n(.*?)\n```", readme.read_text(), re.S) - self.assertIsNotNone(match, "README initialization fence not found") + match = re.search(r"## Create an instance\n.*?```python\n(.*?)\n```", readme.read_text(), re.S) + self.assertIsNotNone(match, "README create an instance fence not found") self.code = compile(match[1], str(readme), "exec") def fixture(self, enabled): @@ -34,7 +34,7 @@ def test_evaluation_and_cleanup(self): with patch("urllib.request.urlopen", return_value=response) as fetch: with contextlib.redirect_stdout(output): exec(self.code, namespace) - fetch.assert_called_once_with("https://cdn.yoursite.com/featurevisor-all.json") + fetch.assert_called_once_with("https://cdn.example.com/featurevisor-all.json") self.assertIn(str(enabled), output.getvalue().splitlines()) self.assertTrue(response.closed) self.assertTrue(namespace["f"].closed) From 977dcabb4fc0fb996684a1d71cda64bb8df090c4 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 14:34:34 +0100 Subject: [PATCH 08/21] feat: changed keys in context_set and segments in datafile_set context_set details now carry keys, the top level keys whose values changed, compared by value: numbers by numeric value, though a bool is never a number, dicts key by key and lists item by item, with a dict or list given again as the same object counted as changed, and every key when the stored context itself comes back. A merge compares only the keys it carries, a replace every key of either context, and a child its own context. The keys are worked out only when a listener or a debug diagnostic receiver reads them. datafile_set details now carry segments, the segments whose definitions were added, changed or, on replace, removed, which the SDK already worked out to find the features and variables they affect. conformance/sdk-events.json pins both, as in JavaScript, and the README documents them as the JavaScript page does. Its contents list links datafile_set by GitHub's anchor. --- README.md | 39 +- conformance/sdk-events.json | 1104 +++++++++++++++++++++++++++++ src/featurevisor/child.py | 9 +- src/featurevisor/events.py | 64 ++ src/featurevisor/instance.py | 12 +- tests/test_sdk.py | 2 +- tests/test_sdk_events.py | 100 +++ tests/test_sdk_stateful.py | 4 +- tests/test_set_datafile_result.py | 5 +- 9 files changed, 1326 insertions(+), 13 deletions(-) create mode 100644 conformance/sdk-events.json create mode 100644 tests/test_sdk_events.py diff --git a/README.md b/README.md index 8ad4e10..ab3e507 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ The Featurevisor Python SDK evaluates flags, variations and variables in Python - [Refresh on an interval](#refresh-on-an-interval) - [Child instances](#child-instances) - [Events](#events) - - [`datafile_set`](#datafile-set) + - [`datafile_set`](#datafile_set) - [`context_set`](#context_set) - [`sticky_features_set`](#sticky_features_set) - [`sticky_variables_set`](#sticky_variables_set) @@ -418,25 +418,56 @@ Emitted for every accepted datafile: def on_datafile_set(event): revision = event["revision"] previous_revision = event["previousRevision"] + revision_changed = event["revisionChanged"] replaced = event["replaced"] features = event["features"] variables = event["variables"] + segments = event["segments"] # evaluate the listed features and variables again unsubscribe = f.on("datafile_set", on_datafile_set) unsubscribe() ``` -`replaced` says whether the datafile replaced the previous one or merged into it. `features` and `variables` list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. `sections` lists the changed entries of each [datafile section](#read-the-datafile-from-a-module), such as `schemas`. +`replaced` says whether the datafile replaced the previous one or merged into it. `features` and `variables` list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. Evaluate those again and you have everything that changed. + +`segments` lists the segments whose definitions were added, changed or, on a replace, removed. If a new datafile has the `netherlands` segment take Belgium too, `segments` is `["netherlands"]`, and `features` and `variables` include `checkout` and `supportEmail`, whose conditions read it. The first datafile lists every feature, global variable and segment. `sections` lists the changed entries of each [datafile section](#read-the-datafile-from-a-module), such as `schemas`. ### `context_set` -Emitted by `set_context`, with the new `context` and `replaced`: +Emitted by `set_context`: ```python -f.on("context_set", lambda event: print(event["context"])) +def on_context_set(event): + context = event["context"] # the new instance context + keys = event["keys"] # the top level keys whose values changed + +f.on("context_set", on_context_set) ``` +`keys` compares values, so a key set again to the value it already holds is not listed. Starting from the instance context `{"userId": "user-4", "country": "nl"}`: + +```python +f.set_context({ + "country": "de", +}) +# keys: ["country"] + +f.set_context({ + "country": "de", + "plan": "paid", +}) +# keys: ["plan"] + +f.set_context({ + "userId": "user-4", + "country": "de", +}, True) +# keys: ["plan"] +``` + +A replace also lists the keys it removed, as `plan` above. Dicts and lists compare item by item, and numbers by value, so `30` and `30.0` are the same while `True` and `1` are not, but a dict or list given again as the same object counts as changed, since it may have been changed in place. + ### `sticky_features_set` Emitted by `set_sticky_features`, with `features`, every feature that had a sticky value before the call or has one after it, and `replaced`: diff --git a/conformance/sdk-events.json b/conformance/sdk-events.json new file mode 100644 index 0000000..406fb5c --- /dev/null +++ b/conformance/sdk-events.json @@ -0,0 +1,1104 @@ +{ + "kind": "featurevisor.sdk-events", + "schemaVersion": 1, + "contextCases": [ + { + "name": "a merge lists the keys whose values changed", + "context": { + "userId": "user-4", + "country": "nl" + }, + "operations": [ + { + "target": "root", + "replace": false, + "context": { + "country": "de" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de" + }, + "replaced": false, + "keys": [ + "country" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "country": "de", + "plan": "pro" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "plan": "pro" + }, + "replaced": false, + "keys": [ + "plan" + ] + } + }, + { + "target": "root", + "replace": false, + "context": {}, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "plan": "pro" + }, + "replaced": false, + "keys": [] + } + } + ] + }, + { + "name": "a replace lists the keys it changed, added or removed", + "context": { + "userId": "user-4", + "country": "nl", + "plan": "pro" + }, + "operations": [ + { + "target": "root", + "replace": true, + "context": { + "userId": "user-4", + "country": "de", + "browser": "firefox" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "browser": "firefox" + }, + "replaced": true, + "keys": [ + "browser", + "country", + "plan" + ] + } + }, + { + "target": "root", + "replace": true, + "context": { + "userId": "user-4", + "country": "de", + "browser": "firefox" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "browser": "firefox" + }, + "replaced": true, + "keys": [] + } + }, + { + "target": "root", + "replace": true, + "context": {}, + "expect": { + "context": {}, + "replaced": true, + "keys": [ + "browser", + "country", + "userId" + ] + } + } + ] + }, + { + "name": "objects and arrays compare item by item", + "context": { + "userId": "user-4", + "account": { + "plan": "pro", + "seats": 5 + }, + "tags": [ + "beta", + "staff" + ] + }, + "operations": [ + { + "target": "root", + "replace": false, + "context": { + "account": { + "seats": 5, + "plan": "pro" + }, + "tags": [ + "beta", + "staff" + ] + }, + "expect": { + "context": { + "userId": "user-4", + "account": { + "seats": 5, + "plan": "pro" + }, + "tags": [ + "beta", + "staff" + ] + }, + "replaced": false, + "keys": [] + } + }, + { + "target": "root", + "replace": false, + "context": { + "tags": [ + "staff", + "beta" + ] + }, + "expect": { + "context": { + "userId": "user-4", + "account": { + "seats": 5, + "plan": "pro" + }, + "tags": [ + "staff", + "beta" + ] + }, + "replaced": false, + "keys": [ + "tags" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "account": { + "plan": "pro", + "seats": 6 + } + }, + "expect": { + "context": { + "userId": "user-4", + "account": { + "plan": "pro", + "seats": 6 + }, + "tags": [ + "staff", + "beta" + ] + }, + "replaced": false, + "keys": [ + "account" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "account": { + "plan": "pro", + "seats": 6, + "trial": false + } + }, + "expect": { + "context": { + "userId": "user-4", + "account": { + "plan": "pro", + "seats": 6, + "trial": false + }, + "tags": [ + "staff", + "beta" + ] + }, + "replaced": false, + "keys": [ + "account" + ] + } + } + ] + }, + { + "name": "null is a value of its own", + "context": { + "userId": "user-4" + }, + "operations": [ + { + "target": "root", + "replace": false, + "context": { + "plan": null + }, + "expect": { + "context": { + "userId": "user-4", + "plan": null + }, + "replaced": false, + "keys": [ + "plan" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "plan": null + }, + "expect": { + "context": { + "userId": "user-4", + "plan": null + }, + "replaced": false, + "keys": [] + } + }, + { + "target": "root", + "replace": true, + "context": { + "userId": "user-4" + }, + "expect": { + "context": { + "userId": "user-4" + }, + "replaced": true, + "keys": [ + "plan" + ] + } + } + ] + }, + { + "name": "numbers compare by value", + "context": { + "userId": "user-4", + "age": 30, + "score": 2.5 + }, + "operations": [ + { + "target": "root", + "replace": false, + "context": { + "age": 30.0, + "score": 2.5 + }, + "expect": { + "context": { + "userId": "user-4", + "age": 30.0, + "score": 2.5 + }, + "replaced": false, + "keys": [] + } + }, + { + "target": "root", + "replace": false, + "context": { + "age": 31 + }, + "expect": { + "context": { + "userId": "user-4", + "age": 31, + "score": 2.5 + }, + "replaced": false, + "keys": [ + "age" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "age": "31" + }, + "expect": { + "context": { + "userId": "user-4", + "age": "31", + "score": 2.5 + }, + "replaced": false, + "keys": [ + "age" + ] + } + } + ] + }, + { + "name": "a child starts from the parent's context and lists the keys of its own", + "context": { + "userId": "user-4", + "country": "nl" + }, + "childContext": { + "plan": "pro" + }, + "operations": [ + { + "target": "child", + "replace": false, + "context": { + "plan": "pro" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "nl", + "plan": "pro" + }, + "replaced": false, + "keys": [] + } + }, + { + "target": "child", + "replace": false, + "context": { + "country": "de" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "plan": "pro" + }, + "replaced": false, + "keys": [ + "country" + ] + } + }, + { + "target": "child", + "replace": true, + "context": { + "country": "de" + }, + "expect": { + "context": { + "country": "de" + }, + "replaced": true, + "keys": [ + "plan", + "userId" + ] + } + } + ] + } + ], + "datafileCases": [ + { + "name": "the first datafile lists every feature, global variable and segment", + "operations": [ + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + }, + "germany": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "de" + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "pricing": { + "hash": "pricing-1", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + }, + "expect": { + "revision": "1", + "previousRevision": "unknown", + "revisionChanged": true, + "features": [ + "buyButton", + "checkout", + "pricing" + ], + "variables": [ + "supportEmail" + ], + "segments": [ + "benelux", + "germany", + "netherlands" + ], + "sections": {}, + "replaced": false + } + } + ] + }, + { + "name": "a merge lists the segments whose definitions it changed", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + }, + "germany": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "de" + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "pricing": { + "hash": "pricing-1", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + } + }, + "operations": [ + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "in", + "value": [ + "nl", + "be" + ] + } + } + }, + "features": {}, + "variables": {} + }, + "expect": { + "revision": "2", + "previousRevision": "1", + "revisionChanged": true, + "features": [ + "buyButton", + "checkout" + ], + "variables": [ + "supportEmail" + ], + "segments": [ + "netherlands" + ], + "sections": {}, + "replaced": false + } + }, + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "3", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "in", + "value": [ + "nl", + "be" + ] + } + } + }, + "features": {}, + "variables": {} + }, + "expect": { + "revision": "3", + "previousRevision": "2", + "revisionChanged": true, + "features": [], + "variables": [], + "segments": [], + "sections": {}, + "replaced": false + } + }, + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "4", + "segments": { + "belgium": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "be" + } + } + }, + "features": {}, + "variables": {} + }, + "expect": { + "revision": "4", + "previousRevision": "3", + "revisionChanged": true, + "features": [], + "variables": [], + "segments": [ + "belgium" + ], + "sections": {}, + "replaced": false + } + } + ] + }, + { + "name": "a replace lists the segments it changed or removed", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + }, + "germany": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "de" + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "pricing": { + "hash": "pricing-1", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + } + }, + "operations": [ + { + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "in", + "value": [ + "nl", + "be" + ] + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + }, + "expect": { + "revision": "2", + "previousRevision": "1", + "revisionChanged": true, + "features": [ + "buyButton", + "checkout", + "pricing" + ], + "variables": [ + "supportEmail" + ], + "segments": [ + "germany", + "netherlands" + ], + "sections": {}, + "replaced": true + } + }, + { + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "in", + "value": [ + "nl", + "be" + ] + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + }, + "expect": { + "revision": "2", + "previousRevision": "2", + "revisionChanged": false, + "features": [], + "variables": [], + "segments": [], + "sections": {}, + "replaced": true + } + } + ] + }, + { + "name": "a changed feature or variable lists no segments", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + }, + "germany": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "de" + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "pricing": { + "hash": "pricing-1", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + } + }, + "operations": [ + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": {}, + "features": { + "pricing": { + "hash": "pricing-2", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-2", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + }, + "expect": { + "revision": "2", + "previousRevision": "1", + "revisionChanged": true, + "features": [ + "pricing" + ], + "variables": [ + "supportEmail" + ], + "segments": [], + "sections": {}, + "replaced": false + } + } + ] + } + ] +} diff --git a/src/featurevisor/child.py b/src/featurevisor/child.py index 22b3981..ed2335f 100644 --- a/src/featurevisor/child.py +++ b/src/featurevisor/child.py @@ -3,7 +3,7 @@ from typing import TYPE_CHECKING, Any from .emitter import Emitter -from .events import get_params_for_sticky_features_set_event, get_params_for_sticky_variables_set_event +from .events import get_changed_context_keys, get_params_for_sticky_features_set_event, get_params_for_sticky_variables_set_event if TYPE_CHECKING: from .instance import Featurevisor @@ -44,9 +44,14 @@ def close(self) -> None: self.emitter.clear_all() def set_context(self, context: dict[str, Any], replace: bool = False) -> None: + previous = self.context self.context = dict(context) if replace else {**self.context, **context} self._state_version += 1 - self.emitter.trigger("context_set", {"context": self.context, "replaced": replace}) + details: dict[str, Any] = {"context": self.context, "replaced": replace} + # Only a listener reads the changed keys, so only then are they worked out. + if self.emitter.listeners.get("context_set"): + details["keys"] = get_changed_context_keys(previous, self.context, None if replace else context) + self.emitter.trigger("context_set", details) def get_context(self, context: dict[str, Any] | None = None) -> dict[str, Any]: return self.parent.get_context({**self.context, **(context or {})}) diff --git a/src/featurevisor/events.py b/src/featurevisor/events.py index 390c7bb..82468dd 100644 --- a/src/featurevisor/events.py +++ b/src/featurevisor/events.py @@ -1,8 +1,69 @@ from __future__ import annotations +from datetime import date +from typing import Any + from .dependencies import add_datafile_dependency_changes, create_datafile_dependency_index from .evaluation_data_provider import _InstanceEvaluationDataProvider +# How deep two context values are compared. A value nested deeper, such as one +# that contains itself, counts as changed. +_ATTRIBUTE_VALUE_DEPTH = 64 + + +def get_changed_context_keys(previous: dict[str, Any], next_context: dict[str, Any], incoming: dict[str, Any] | None = None) -> list[str]: + """The top level keys whose values differ between two contexts, compared by + value. A merge can change only the keys it carries, given as ``incoming``, + and a replace any key of either context. None is a value, so a key set to + None where it was absent has changed.""" + if previous is next_context or previous is incoming: + # The stored context given back may have been changed in place, so + # every key in it may have changed. + return list(previous) + [key for key in next_context if key not in previous] + if incoming is not None: + return [ + key for key in incoming + if key not in previous or not _same_attribute_value(previous[key], next_context[key], 0) + ] + keys = [ + key for key, value in previous.items() + if key not in next_context or not _same_attribute_value(value, next_context[key], 0) + ] + return keys + [key for key in next_context if key not in previous] + + +def _same_attribute_value(before: Any, after: Any, depth: int) -> bool: + """Whether an attribute keeps its value. Numbers compare by numeric value, + though a bool is never a number, dicts key by key and lists item by item. + A dict or list given again as the same object counts as changed, since it + may have been changed in place.""" + if before is after: + return not isinstance(before, (dict, list)) + if depth > _ATTRIBUTE_VALUE_DEPTH: + return False + if isinstance(before, bool) or isinstance(after, bool): + return isinstance(before, bool) and isinstance(after, bool) and before == after + if isinstance(before, (int, float)) and isinstance(after, (int, float)): + return before == after + if isinstance(before, dict): + return ( + isinstance(after, dict) + and len(before) == len(after) + and all(key in after and _same_attribute_value(value, after[key], depth + 1) for key, value in before.items()) + ) + if isinstance(before, (list, tuple)): + return ( + isinstance(after, (list, tuple)) + and len(before) == len(after) + and all(_same_attribute_value(item, other, depth + 1) for item, other in zip(before, after)) + ) + if isinstance(before, (str, date)) or before is None: + return type(before) is type(after) and before == after + try: + return bool(before == after) + except Exception: + return False + def get_params_for_sticky_features_set_event(previous_sticky_features: dict | None = None, new_sticky_features: dict | None = None, replace: bool = False) -> dict: previous_sticky_features = previous_sticky_features or {} @@ -34,6 +95,7 @@ def get_params_for_datafile_set_event(previous_datafile: _InstanceEvaluationData "revisionChanged": previous_revision != new_revision, "features": new_feature_keys, "variables": new_datafile.get_variable_keys(), + "segments": new_datafile.get_segment_keys(), "replaced": replace, } removed_features = [key for key in previous_feature_keys if key not in new_datafile.features] @@ -82,6 +144,8 @@ def get_params_for_datafile_set_event(previous_datafile: _InstanceEvaluationData "revisionChanged": previous_revision != new_revision, "features": features, "variables": variables, + # The dependency changes add features and variables only, so these are the changed definitions. + "segments": changed_segments, "replaced": replace, } diff --git a/src/featurevisor/instance.py b/src/featurevisor/instance.py index 4180880..84bf3d7 100644 --- a/src/featurevisor/instance.py +++ b/src/featurevisor/instance.py @@ -9,7 +9,7 @@ from .evaluation_data_provider import _InstanceEvaluationDataProvider from .emitter import Emitter from .evaluate import evaluate_with_modules -from .events import get_params_for_datafile_set_event, get_params_for_sticky_features_set_event, get_params_for_sticky_variables_set_event +from .events import get_changed_context_keys, get_params_for_datafile_set_event, get_params_for_sticky_features_set_event, get_params_for_sticky_variables_set_event from .helpers import get_value_by_type from ._json import strict_json_loads from .conditions import MISSING, value_is_matched, _strict_equal @@ -187,14 +187,20 @@ def close(self) -> None: def set_context(self, context: dict[str, Any], replace: bool = False) -> None: if self.closed: return + previous = self.context self.context = dict(context) if replace else {**self.context, **context} self._state_version += 1 - self.emitter.trigger("context_set", {"context": self.context, "replaced": replace}) + details: dict[str, Any] = {"context": self.context, "replaced": replace} + # Only a listener or a debug diagnostic receiver reads the changed keys, + # so only then are they worked out. + if self.emitter.listeners.get("context_set") or self._diagnostic_is_observed("debug"): + details["keys"] = get_changed_context_keys(previous, self.context, None if replace else context) + self.emitter.trigger("context_set", details) self.report_diagnostic({ "level": "debug", "code": "context_set", "message": "Context replaced" if replace else "Context updated", - "details": {"context": self.context, "replaced": replace}, + "details": details, }) def get_context(self, context: dict[str, Any] | None = None) -> dict[str, Any]: diff --git a/tests/test_sdk.py b/tests/test_sdk.py index 15ab610..cdf9a06 100644 --- a/tests/test_sdk.py +++ b/tests/test_sdk.py @@ -345,7 +345,7 @@ def test_events_helpers(self) -> None: current = _InstanceEvaluationDataProvider(datafile={"schemaVersion": "2", "revision": "2", "segments": {}, "features": {"feature1": {"bucketBy": "userId", "hash": "hash2", "traffic": []}, "feature2": {"bucketBy": "userId", "hash": "hash3", "traffic": []}}}, diagnostics=diagnostics) self.assertEqual( get_params_for_datafile_set_event(previous, current), - {"revision": "2", "previousRevision": "1", "revisionChanged": True, "features": ["feature1", "feature2"], "variables": [], "replaced": False}, + {"revision": "2", "previousRevision": "1", "revisionChanged": True, "features": ["feature1", "feature2"], "variables": [], "segments": [], "replaced": False}, ) def test_emitter_subscribe_unsubscribe(self) -> None: diff --git a/tests/test_sdk_events.py b/tests/test_sdk_events.py new file mode 100644 index 0000000..2488676 --- /dev/null +++ b/tests/test_sdk_events.py @@ -0,0 +1,100 @@ +import json +import unittest +from pathlib import Path + +from featurevisor import create_featurevisor + + +FIXTURE = json.loads((Path(__file__).resolve().parents[1] / "conformance" / "sdk-events.json").read_text()) + + +def unordered(details): + """Event details with their lists sorted, since key order differs across platforms.""" + copy = json.loads(json.dumps(details)) + for field in ("keys", "features", "variables", "segments"): + if isinstance(copy.get(field), list): + copy[field] = sorted(copy[field]) + if isinstance(copy.get("sections"), dict): + copy["sections"] = {key: sorted(entries) for key, entries in copy["sections"].items()} + return copy + + +class SDKEventsConformanceTests(unittest.TestCase): + """Runs conformance/sdk-events.json: the keys of context_set and the segments of datafile_set.""" + + def test_fixture_version(self) -> None: + self.assertEqual(FIXTURE["kind"], "featurevisor.sdk-events") + self.assertEqual(FIXTURE["schemaVersion"], 1) + + def test_context_set_keys(self) -> None: + for case in FIXTURE["contextCases"]: + with self.subTest(case=case["name"]): + root = create_featurevisor({"context": case["context"], "logLevel": "fatal"}) + child = root.spawn(case.get("childContext") or {}) + events = [] + root.on("context_set", events.append) + child.on("context_set", events.append) + for index, operation in enumerate(case["operations"]): + events.clear() + target = child if operation["target"] == "child" else root + target.set_context(operation["context"], operation["replace"]) + self.assertEqual([unordered(event) for event in events], [unordered(operation["expect"])], f"operation {index}") + + def test_datafile_set_segments(self) -> None: + for case in FIXTURE["datafileCases"]: + with self.subTest(case=case["name"]): + options = {"logLevel": "fatal"} + if case.get("initial"): + options["datafile"] = json.dumps(case["initial"]["datafile"]) + f = create_featurevisor(options) + events = [] + f.on("datafile_set", events.append) + for index, operation in enumerate(case["operations"]): + events.clear() + self.assertTrue(f.set_datafile(json.dumps(operation["datafile"]), operation["replace"])) + self.assertEqual([unordered(event) for event in events], [unordered(operation["expect"])], f"operation {index}") + + +class ContextSetKeysTests(unittest.TestCase): + def test_python_values(self) -> None: + account = {"plan": "pro"} + f = create_featurevisor({"context": {"age": 30, "account": account, "beta": True}, "logLevel": "fatal"}) + keys = [] + f.on("context_set", lambda details: keys.append(details["keys"])) + + # An int and a float holding the same number, and an equal dict, keep their values. + f.set_context({"age": 30.0, "account": {"plan": "pro"}}) + # A bool is never a number. + f.set_context({"beta": 1}) + # The same dict given again may have been changed in place. + nested = {"plan": "pro"} + f.set_context({"account": nested}) + nested["plan"] = "basic" + f.set_context({"account": nested}) + # So may the stored context given back. + stored = f.get_context() + stored["country"] = "nl" + f.set_context(stored) + + self.assertEqual(keys[0], []) + self.assertEqual(keys[1], ["beta"]) + self.assertEqual(keys[3], ["account"]) + self.assertEqual(sorted(keys[4]), ["account", "age", "beta", "country"]) + + def test_keys_only_for_someone_who_reads_them(self) -> None: + diagnostics = [] + f = create_featurevisor({"logLevel": "debug", "onDiagnostic": diagnostics.append}) + f.set_context({"country": "nl"}) + context_set = [diagnostic for diagnostic in diagnostics if diagnostic["code"] == "context_set"] + self.assertEqual(context_set[0]["details"]["keys"], ["country"]) + + quiet = create_featurevisor({"logLevel": "fatal"}) + details = [] + quiet.set_context({"country": "nl"}) + quiet.on("context_set", details.append) + quiet.set_context({"country": "de"}) + self.assertEqual(details[0]["keys"], ["country"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sdk_stateful.py b/tests/test_sdk_stateful.py index 2971f10..90f3301 100644 --- a/tests/test_sdk_stateful.py +++ b/tests/test_sdk_stateful.py @@ -18,8 +18,10 @@ def _normalize_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]: normalized = [] for event in events: copy = {**event, "details": dict(event["details"])} - # "sections" in datafile_set is not yet part of the portable fixtures, as in JavaScript. + # The historical stateful cases predate "segments" and "sections" in + # datafile_set, which sdk-events.json and sdk-sections.json pin instead. copy["details"].pop("sections", None) + copy["details"].pop("segments", None) for key in ("features", "variables"): if key in copy["details"]: copy["details"][key] = sorted(copy["details"][key]) diff --git a/tests/test_set_datafile_result.py b/tests/test_set_datafile_result.py index 8feb9ea..42a8de0 100644 --- a/tests/test_set_datafile_result.py +++ b/tests/test_set_datafile_result.py @@ -57,14 +57,15 @@ def test_accepts_native_and_json_merge_replacement_and_unchanged_for_both_names( self.assertEqual(events[0], { "revision": "2", "previousRevision": "1", "revisionChanged": True, "features": ["original", "next"] if replace else ["next"], - "variables": ["original", "next"] if replace else ["next"], "replaced": replace, + "variables": ["original", "next"] if replace else ["next"], + "segments": ["original", "next"] if replace else ["next"], "replaced": replace, "sections": {}, }) self.assertIs(setter(encode(incoming), replace), True) self.assertEqual(len(events), 2) self.assertEqual(events[1], { "revision": "2", "previousRevision": "2", "revisionChanged": False, - "features": [], "variables": [], "replaced": replace, + "features": [], "variables": [], "segments": [], "replaced": replace, "sections": {}, }) From 7a217bfd195151124a1b7d8545ef32c47bff812c Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 16:47:46 +0100 Subject: [PATCH 09/21] perf: work out datafile_set details only for someone who reads them set_datafile worked out the changed features, variables, segments and sections, and their dependency closure, on every call, even when no listener and no diagnostic at info received them. It now does only when a datafile_set listener, a child's among them, or an info diagnostic receiver exists, and otherwise skips the details, the diagnostic and the event, and the new provider keeps no dependency index, which the next update that is read builds again from the datafile it has. What the SDK answers is unchanged, and so are the details whenever someone receives them. The incremental index tests subscribe a listener, since only then is there an index to inspect. --- src/featurevisor/instance.py | 15 +++- tests/test_datafile_set_details.py | 113 +++++++++++++++++++++++++ tests/test_incremental_dependencies.py | 10 ++- 3 files changed, 133 insertions(+), 5 deletions(-) create mode 100644 tests/test_datafile_set_details.py diff --git a/src/featurevisor/instance.py b/src/featurevisor/instance.py index 84bf3d7..b8662bb 100644 --- a/src/featurevisor/instance.py +++ b/src/featurevisor/instance.py @@ -100,15 +100,22 @@ def set_datafile(self, datafile, replace: bool = False) -> bool: incoming = {"feature": parsed.get("features", {}), "segment": parsed.get("segments", {}), "variable": parsed.get("variables") or {}} new_datafile.retain_entities(previous_datafile, incoming) - details = get_params_for_datafile_set_event(previous_datafile, new_datafile, replace, parsed) - details["sections"] = get_changed_sections(previous_datafile, new_datafile) + # Only a datafile_set listener or an info diagnostic receiver reads the + # details, so only then are they and the dependency closure worked out. + # Without them the new provider keeps no index, and the next update that + # is read builds it again from the datafile it has. + details: dict[str, Any] | None = None + if self.emitter.listeners.get("datafile_set") or self._diagnostic_is_observed("info"): + details = get_params_for_datafile_set_event(previous_datafile, new_datafile, replace, parsed) + details["sections"] = get_changed_sections(previous_datafile, new_datafile) self.datafile = new_datafile self._package_conditions.clear() self._state_version += 1 for diagnostic in errors: self.report_diagnostic(diagnostic) - self.report_diagnostic({"level": "info", "code": "datafile_set", "message": "Datafile set", "details": details}) - self.emitter.trigger("datafile_set", details) + if details is not None: + self.report_diagnostic({"level": "info", "code": "datafile_set", "message": "Datafile set", "details": details}) + self.emitter.trigger("datafile_set", details) return True except Exception as exc: self.report_diagnostic({"level": "error", "code": "invalid_datafile", "message": "Could not parse datafile", "originalError": exc}) diff --git a/tests/test_datafile_set_details.py b/tests/test_datafile_set_details.py new file mode 100644 index 0000000..9388ce5 --- /dev/null +++ b/tests/test_datafile_set_details.py @@ -0,0 +1,113 @@ +import json +import unittest + +from featurevisor import create_featurevisor + + +def datafile(revision, country="nl", **extra): + value = { + "schemaVersion": "4", + "revision": revision, + "segments": { + "netherlands": {"conditions": {"attribute": "country", "operator": "equals", "value": country}}, + "benelux": {"conditions": ["netherlands"]}, + }, + "features": { + "checkout": {"hash": "checkout-1", "bucketBy": "userId", "conditions": "benelux", + "traffic": [{"key": "all", "conditions": "*", "percentage": 100000}]}, + "payments": {"hash": "payments-1", "bucketBy": "userId", "conditions": {"feature": "checkout"}, + "traffic": [{"key": "all", "conditions": "*", "percentage": 100000}]}, + "simple": {"hash": "simple-1", "bucketBy": "userId", + "traffic": [{"key": "all", "conditions": "*", "percentage": 100000}]}, + }, + "variables": {}, + } + value.update(extra) + return json.dumps(value) + + +def keeps_index(f): + """Whether the instance kept a dependency index, the work a skipped update leaves out.""" + return f.datafile.dependency_index is not None + + +def sorted_details(details): + return {**details, **{key: sorted(details[key]) for key in ("features", "variables", "segments")}} + + +class DatafileSetDetailsTests(unittest.TestCase): + """datafile_set details are worked out only when a listener or an info diagnostic receiver reads them.""" + + def test_an_update_nobody_reads_still_applies_and_reports_nothing(self) -> None: + diagnostics = [] + f = create_featurevisor({"datafile": datafile("1"), "logLevel": "warn", "onDiagnostic": diagnostics.append}) + context = {"userId": "user-4", "country": "be"} + self.assertFalse(f.is_enabled("payments", context)) + self.assertTrue(f.set_datafile(datafile("2", "be"))) + self.assertTrue(f.set_datafile(datafile("3", "be", features={}))) + self.assertTrue(f.is_enabled("payments", context)) + self.assertEqual(f.get_revision(), "3") + self.assertEqual(diagnostics, []) + self.assertFalse(keeps_index(f)) + + def test_a_late_listener_receives_what_a_fresh_instance_would(self) -> None: + quiet = create_featurevisor({"datafile": datafile("1"), "logLevel": "fatal"}) + listening = create_featurevisor({"datafile": datafile("1"), "logLevel": "fatal"}) + always = [] + listening.on("datafile_set", always.append) + for f in (quiet, listening): + f.set_datafile(datafile("2", "de")) + f.set_datafile(datafile("3", "be"), True) + f.set_datafile(datafile("4", "be", segments={}, features={})) + late = [] + quiet.on("datafile_set", late.append) + for f in (quiet, listening): + f.set_datafile(datafile("5", "lu")) + self.assertEqual(len(late), 1) + self.assertEqual(sorted_details(late[0]), sorted_details(always[-1])) + self.assertEqual(sorted(late[0]["features"]), ["checkout", "payments"]) + self.assertEqual(late[0]["segments"], ["netherlands"]) + + def test_set_log_level_info_brings_the_diagnostic_back(self) -> None: + diagnostics = [] + f = create_featurevisor({"datafile": datafile("1"), "logLevel": "warn", "onDiagnostic": diagnostics.append}) + f.set_datafile(datafile("2", "de")) + f.set_log_level("info") + f.set_datafile(datafile("3", "be")) + self.assertEqual([diagnostic["code"] for diagnostic in diagnostics], ["datafile_set"]) + self.assertEqual(diagnostics[0]["details"]["previousRevision"], "2") + self.assertEqual(sorted(diagnostics[0]["details"]["features"]), ["checkout", "payments"]) + + def test_a_childs_listener_and_module_subscriptions_count(self) -> None: + f = create_featurevisor({"datafile": datafile("1"), "logLevel": "fatal"}) + child = f.spawn({"country": "be"}) + events = [] + stop = child.on("datafile_set", events.append) + f.set_datafile(datafile("2", "be")) + self.assertEqual(len(events), 1) + self.assertTrue(keeps_index(f)) + stop() + f.set_datafile(datafile("3", "de")) + self.assertEqual(len(events), 1) + self.assertFalse(keeps_index(f)) + + api = {} + f.add_module({"name": "details-test", "setup": api.update}) + warn, info = [], [] + stop_warn = api["on_diagnostic"](warn.append, {"logLevel": "warn"}) + f.set_datafile(datafile("4", "be")) + self.assertEqual(warn, []) + self.assertFalse(keeps_index(f)) + stop_info = api["on_diagnostic"](info.append, {"logLevel": "info"}) + f.set_datafile(datafile("5", "de")) + self.assertEqual([diagnostic["code"] for diagnostic in info], ["datafile_set"]) + self.assertTrue(keeps_index(f)) + stop_info() + stop_warn() + f.set_datafile(datafile("6", "be")) + self.assertEqual(len(info), 1) + self.assertFalse(keeps_index(f)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_incremental_dependencies.py b/tests/test_incremental_dependencies.py index 0b7652d..2d3b450 100644 --- a/tests/test_incremental_dependencies.py +++ b/tests/test_incremental_dependencies.py @@ -9,11 +9,19 @@ from concurrent.futures import ThreadPoolExecutor from unittest.mock import patch -from featurevisor import create_featurevisor +from featurevisor import create_featurevisor as create_instance from featurevisor.dependencies import extract_entity_dependencies from featurevisor._json import strict_json_loads +def create_featurevisor(options): + """The dependency index these tests inspect exists for datafile_set details, + which a listener reads, so every instance here has one.""" + sdk = create_instance(options) + sdk.on("datafile_set", lambda details: None) + return sdk + + def datafile(revision="initial", **values): return {"schemaVersion": "4", "revision": revision, "segments": {}, "features": {}, "variables": {}, **values} From 5b40e543de0c47db241e0bc7b0686b2abdaa98fc Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 00:22:06 +0100 Subject: [PATCH 10/21] refactor(schemas): keep child, field_keys, has_checks and validate_rules internal The JavaScript package exports none of them. fields gives the fields' handles, each with its name, and validate is the one way to validate. --- README.md | 36 ++++++++++++++--------------- src/featurevisor/schemas/_handle.py | 10 ++++---- tests/test_schemas.py | 4 ++-- tests/test_schemas_conformance.py | 2 +- 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index ab3e507..df7d165 100644 --- a/README.md +++ b/README.md @@ -730,20 +730,20 @@ sign_up = s.get("signUp") A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application. -| Member | What it is | -| ------------------------------------------- | -------------------------------------------------------------------- | -| `validate`, `is_valid`, `parse` | As on `s`, without the key | -| `avalidate`, `aparse` | The same, awaiting your [checks in code](#check-in-code) | -| `at(path)` | The handle of one field, such as `at("displayName")` | -| `fields`, `field_keys` | An object's fields' handles and names, in [order](#read-annotations) | -| `constraints`, `field_constraints` | HTML validation attributes, [below](#read-constraints-and-choices) | -| `options`, `field_options`, `option(value)` | Its choices, and one of them by value | -| `kind` | What its rules make the field, such as `"select"` | -| `annotations` | Its [annotations](#read-annotations) | -| `with_input(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | -| `reads` | The fields its rules' conditions read | -| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | -| `key`, `path`, `name` | The schema's key, and the field's path and own name | +| Member | What it is | +| ------------------------------------------- | -------------------------------------------------------------------------------- | +| `validate`, `is_valid`, `parse` | As on `s`, without the key | +| `avalidate`, `aparse` | The same, awaiting your [checks in code](#check-in-code) | +| `at(path)` | The handle of one field, such as `at("displayName")` | +| `fields` | An object's fields' handles, in [order](#read-annotations), each with its `name` | +| `constraints`, `field_constraints` | HTML validation attributes, [below](#read-constraints-and-choices) | +| `options`, `field_options`, `option(value)` | Its choices, and one of them by value | +| `kind` | What its rules make the field, such as `"select"` | +| `annotations` | Its [annotations](#read-annotations) | +| `with_input(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | +| `reads` | The fields its rules' conditions read | +| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | +| `key`, `path`, `name` | The schema's key, and the field's path and own name | `at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. @@ -1068,10 +1068,10 @@ Every call reads the current datafile, so a new datafile takes effect at the nex ```python sign_up = s.get("signUp") -sign_up.field_keys # ["accountType", "displayName", "taxId"], in the schema's order -sign_up.at("displayName").constraints # required, min_length and max_length -sign_up.at("accountType").options # personal and business, with their titles -sign_up.at("accountType").kind # "select" +[field.name for field in sign_up.fields] # ["accountType", "displayName", "taxId"], in the schema's order +sign_up.at("displayName").constraints # required, min_length and max_length +sign_up.at("accountType").options # personal and business, with their titles +sign_up.at("accountType").kind # "select" ``` `constraints.attributes()` gives them as HTML attributes, such as `required` and `maxlength`, for a template. `with_input(values)` returns the same handle for the values a form has so far, so its members describe the rules every matching mutation sets, such as a VAT number that becomes required for a business account. diff --git a/src/featurevisor/schemas/_handle.py b/src/featurevisor/schemas/_handle.py index 628e882..fbcea31 100644 --- a/src/featurevisor/schemas/_handle.py +++ b/src/featurevisor/schemas/_handle.py @@ -171,7 +171,7 @@ async def answer(check: _Check, target: Any) -> Any: issues += self._report_check(run, located, "refine" if check.kind == "refine" else "enum", check, path) return ValidationResult(value, tuple(issues)) - def validate_rules(self, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: + def _validate_rules(self, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: """The schema's own rules, without checks in code.""" def rules(run: Run) -> ValidationResult: self._apply_rules(plain(value), run) @@ -196,7 +196,7 @@ async def aparse(self, value: Any, context: Mapping[str, Any] | None = None) -> return value @property - def has_checks(self) -> bool: + def _has_checks(self) -> bool: """Whether the handle has checks in code, which can make validation wait for an answer.""" return bool(self._checks()) @@ -338,7 +338,7 @@ def at(self, path: str) -> SchemaHandle: """The handle for a field at a path, such as "address.city", "items[].name" or "labels.*".""" return self._handle(path, lambda: parse_path(path)) - def child(self, key: str) -> SchemaHandle: + def _child(self, key: str) -> SchemaHandle: """The handle for one of an object's fields by its key, the same handle at gives when the key reads as itself, and its own for a key such as "a.b", "*" or "2024".""" if key and key[0] not in ".[]*" and not key[0].isdigit() and not any(c in key for c in ".[]"): @@ -409,14 +409,14 @@ def annotations(self) -> dict[str, Any]: return self._derive("annotations", lambda node, required: dict(annotations_of(node, self._store) or {}), {}) @property - def field_keys(self) -> list[str]: + def _field_keys(self) -> list[str]: """The keys of an object's fields, in its order.""" return self._derive("field_keys", lambda node, required: field_keys_of(node, self._store), []) @property def fields(self) -> list[SchemaHandle]: """An object's fields' handles, in its order, or none for any other value.""" - return [self.child(key) for key in self.field_keys] + return [self._child(key) for key in self._field_keys] @property def constraints(self) -> Constraints: diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 4e03a9c..455a4a2 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -125,7 +125,7 @@ def down(value, info): Refinement("usernameFree", free, path="username"), Refinement("broken", down, path="city"), ]) - self.assertTrue(sign_up.has_checks) + self.assertTrue(sign_up._has_checks) self.assertTrue(asyncio.run(sign_up.avalidate(VALID)).valid) result = asyncio.run(sign_up.avalidate({"username": "taken", "password": "long enough", "confirm": "other", "city": "Utrecht"})) self.assertEqual([issue.code for issue in result.issues], ["refine", "refine", "refineError"]) @@ -137,7 +137,7 @@ def down(value, info): # A rule's issue at the field, or in a field a check reads, holds the check back. held = asyncio.run(sign_up.avalidate({"username": "ab", "password": "short", "confirm": "other"})) self.assertEqual([issue.code for issue in held.issues], ["minLength", "minLength"]) - self.assertTrue(sign_up.validate_rules({"username": "taken", "password": "long enough"}).valid) + self.assertTrue(sign_up._validate_rules({"username": "taken", "password": "long enough"}).valid) def test_option_sources_look_up_values_and_suggest_choices(self) -> None: cities = {"utrecht": "Utrecht", "rotterdam": "Rotterdam", "amsterdam": "Amsterdam"} diff --git a/tests/test_schemas_conformance.py b/tests/test_schemas_conformance.py index 8698521..12df028 100644 --- a/tests/test_schemas_conformance.py +++ b/tests/test_schemas_conformance.py @@ -104,7 +104,7 @@ def constraints(value): with self.subTest(handle=name): wanted = self.expected["members"][name] self.assertEqual(handle.path, wanted["path"]) - self.assertEqual(handle.field_keys, wanted["fieldKeys"]) + self.assertEqual([field.name for field in handle.fields], wanted["fieldKeys"]) self.assertEqual(handle.kind, wanted["kind"]) self.assertEqual(handle.reads, wanted["reads"]) self.assertEqual(canonical(handle.annotations), canonical(wanted["annotations"])) From e7469b7bb7208f7da4b8c93472ece27c3da82d5a Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 00:28:50 +0100 Subject: [PATCH 11/21] refactor(schemas): drop validate_rules and has_checks, which nothing called JavaScript keeps both for its React hooks, and Python has none. --- src/featurevisor/schemas/_handle.py | 13 ------------- tests/test_schemas.py | 2 -- 2 files changed, 15 deletions(-) diff --git a/src/featurevisor/schemas/_handle.py b/src/featurevisor/schemas/_handle.py index fbcea31..af0a233 100644 --- a/src/featurevisor/schemas/_handle.py +++ b/src/featurevisor/schemas/_handle.py @@ -171,14 +171,6 @@ async def answer(check: _Check, target: Any) -> Any: issues += self._report_check(run, located, "refine" if check.kind == "refine" else "enum", check, path) return ValidationResult(value, tuple(issues)) - def _validate_rules(self, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: - """The schema's own rules, without checks in code.""" - def rules(run: Run) -> ValidationResult: - self._apply_rules(plain(value), run) - return ValidationResult(value, tuple(run.issues)) - - return self._evaluated(context, rules) - def is_valid(self, value: Any, context: Mapping[str, Any] | None = None) -> bool: return self.validate(value, context).valid @@ -195,11 +187,6 @@ async def aparse(self, value: Any, context: Mapping[str, Any] | None = None) -> raise SchemaValidationError(self.key, result.issues) return value - @property - def _has_checks(self) -> bool: - """Whether the handle has checks in code, which can make validation wait for an answer.""" - return bool(self._checks()) - @staticmethod def _passes(check: _Check, answer: Any) -> bool: return answer is True if check.kind == "refine" else _found(answer) diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 455a4a2..85c9bc0 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -125,7 +125,6 @@ def down(value, info): Refinement("usernameFree", free, path="username"), Refinement("broken", down, path="city"), ]) - self.assertTrue(sign_up._has_checks) self.assertTrue(asyncio.run(sign_up.avalidate(VALID)).valid) result = asyncio.run(sign_up.avalidate({"username": "taken", "password": "long enough", "confirm": "other", "city": "Utrecht"})) self.assertEqual([issue.code for issue in result.issues], ["refine", "refine", "refineError"]) @@ -137,7 +136,6 @@ def down(value, info): # A rule's issue at the field, or in a field a check reads, holds the check back. held = asyncio.run(sign_up.avalidate({"username": "ab", "password": "short", "confirm": "other"})) self.assertEqual([issue.code for issue in held.issues], ["minLength", "minLength"]) - self.assertTrue(sign_up._validate_rules({"username": "taken", "password": "long enough"}).valid) def test_option_sources_look_up_values_and_suggest_choices(self) -> None: cities = {"utrecht": "Utrecht", "rotterdam": "Rotterdam", "amsterdam": "Amsterdam"} From 7c1858312256d33f2edcd8a0fd56805339000019 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 01:52:11 +0100 Subject: [PATCH 12/21] refactor(schemas): avalidate is the one asynchronous form, on handles only The instance's avalidate answered as validate does, since its handles have no checks, and aparse was a second asynchronous way to parse. --- README.md | 6 +++--- src/featurevisor/schemas/__init__.py | 3 --- src/featurevisor/schemas/_handle.py | 6 ------ 3 files changed, 3 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index df7d165..b48a20d 100644 --- a/README.md +++ b/README.md @@ -733,7 +733,7 @@ A handle is stable, and reads the current datafile whenever it is used, so keep | Member | What it is | | ------------------------------------------- | -------------------------------------------------------------------------------- | | `validate`, `is_valid`, `parse` | As on `s`, without the key | -| `avalidate`, `aparse` | The same, awaiting your [checks in code](#check-in-code) | +| `avalidate` | Validation awaiting your [checks in code](#check-in-code) | | `at(path)` | The handle of one field, such as `at("displayName")` | | `fields` | An object's fields' handles, in [order](#read-annotations), each with its `name` | | `constraints`, `field_constraints` | HTML validation attributes, [below](#read-constraints-and-choices) | @@ -834,7 +834,7 @@ result = await sign_up.avalidate(value) - `check` gets the value at its path, and `info` with the whole `input` and the `context`. It returns `True` when the value passes, or a coroutine of it. - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database. - Its issue has code `refine` and `params["refine"]` `"nameAvailable"`, with the field's title. A check that raises gives `refineError`, and validation fails closed. -- `avalidate` awaits every check, running them concurrently, and `aparse` is its `parse`. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. +- `avalidate` awaits every check, running them concurrently, and returns the result, whose issues say what failed. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. ### Options from your application @@ -1109,7 +1109,7 @@ sign_up = s.get( result = await sign_up.avalidate(request) ``` -`avalidate` awaits every check, running them concurrently, and `aparse` is its `parse`. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. A lookup that finds nothing reports `enum`, and a check that raises reports `refineError`. `await handle.search(query)` returns the source's suggestions. +`avalidate` awaits every check, running them concurrently, and returns the result, whose issues say what failed. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. A lookup that finds nothing reports `enum`, and a check that raises reports `refineError`. `await handle.search(query)` returns the source's suggestions. Handles are safe to use from many threads. `close()` on the instance, or leaving a `with create_schemas(f) as s:` block, stops its subscriptions and removes its module from the Featurevisor instance. diff --git a/src/featurevisor/schemas/__init__.py b/src/featurevisor/schemas/__init__.py index 8c482e1..83bda91 100644 --- a/src/featurevisor/schemas/__init__.py +++ b/src/featurevisor/schemas/__init__.py @@ -72,9 +72,6 @@ def get(self, key: str, *, messages: Mapping[str, Mapping[str, Message]] | None def validate(self, key: str, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: return self.get(key).validate(value, context) - async def avalidate(self, key: str, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: - return await self.get(key).avalidate(value, context) - def is_valid(self, key: str, value: Any, context: Mapping[str, Any] | None = None) -> bool: return self.get(key).is_valid(value, context) diff --git a/src/featurevisor/schemas/_handle.py b/src/featurevisor/schemas/_handle.py index af0a233..228fe03 100644 --- a/src/featurevisor/schemas/_handle.py +++ b/src/featurevisor/schemas/_handle.py @@ -181,12 +181,6 @@ def parse(self, value: Any, context: Mapping[str, Any] | None = None) -> Any: raise SchemaValidationError(self.key, result.issues) return value - async def aparse(self, value: Any, context: Mapping[str, Any] | None = None) -> Any: - result = await self.avalidate(value, context) - if not result.valid: - raise SchemaValidationError(self.key, result.issues) - return value - @staticmethod def _passes(check: _Check, answer: Any) -> bool: return answer is True if check.kind == "refine" else _found(answer) From b7e58223304c76acf398e8f2ea4f69e758642ac4 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 02:12:44 +0100 Subject: [PATCH 13/21] test(schemas): a default annotation, and one a mutation sets The shared fixture's sign up form gives accountType and a newsletter box a default, which the business mutation turns off, and the built datafile test reads both. --- conformance/schemas-datafile.json | 68 +++++++++++++++++++++++++++---- tests/test_schemas_conformance.py | 1 + 2 files changed, 60 insertions(+), 9 deletions(-) diff --git a/conformance/schemas-datafile.json b/conformance/schemas-datafile.json index 1cd37f0..b3e7ca5 100644 --- a/conformance/schemas-datafile.json +++ b/conformance/schemas-datafile.json @@ -4,7 +4,7 @@ "datafile": { "schemaVersion": "4", "featurevisorVersion": "4.13.0", - "revision": "lKLik9RrAm", + "revision": "Qw1wESNyKJ", "segments": { "netherlands": { "conditions": "{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}" @@ -95,7 +95,7 @@ ] }, "signUp": { - "hash": "wLXjboTQnZ", + "hash": "bKMCwKxTvT", "type": "object", "properties": { "accountType": { @@ -106,6 +106,7 @@ ], "annotations": { "title": "Account type", + "default": "personal", "options": { "personal": { "title": "Personal" @@ -133,6 +134,13 @@ "annotations": { "title": "VAT number" } + }, + "newsletter": { + "type": "boolean", + "annotations": { + "title": "Send me product news", + "default": true + } } }, "required": [ @@ -149,7 +157,8 @@ "order": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ] }, "mutations": [ @@ -183,6 +192,16 @@ "value": { "pattern": "Enter your VAT number, such as DE123456789" } + }, + { + "op": "set", + "path": [ + "properties", + "newsletter", + "annotations", + "default" + ], + "value": false } ] } @@ -526,7 +545,8 @@ "fieldKeys": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ], "constraints": { "accountType": { @@ -537,7 +557,8 @@ "minLength": 2, "maxLength": 40 }, - "taxId": {} + "taxId": {}, + "newsletter": {} }, "options": { "accountType": [ @@ -560,7 +581,8 @@ "order": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ] } }, @@ -584,6 +606,7 @@ "reads": [], "annotations": { "title": "Account type", + "default": "personal", "options": { "personal": { "title": "Personal" @@ -637,12 +660,37 @@ "title": "VAT number" } }, + "newsletter": { + "path": "newsletter", + "fieldKeys": [], + "constraints": {}, + "options": [], + "kind": "boolean", + "reads": [], + "annotations": { + "title": "Send me product news", + "default": true + } + }, + "businessNewsletter": { + "path": "newsletter", + "fieldKeys": [], + "constraints": {}, + "options": [], + "kind": "boolean", + "reads": [], + "annotations": { + "title": "Send me product news", + "default": false + } + }, "business": { "path": "", "fieldKeys": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ], "constraints": { "accountType": { @@ -655,7 +703,8 @@ }, "taxId": { "required": true - } + }, + "newsletter": {} }, "options": { "accountType": [ @@ -678,7 +727,8 @@ "order": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ] } }, diff --git a/tests/test_schemas_conformance.py b/tests/test_schemas_conformance.py index 12df028..52f2876 100644 --- a/tests/test_schemas_conformance.py +++ b/tests/test_schemas_conformance.py @@ -92,6 +92,7 @@ def test_describes_fields_as_javascript_does(self) -> None: handles = { "signUp": sign_up, "accountType": sign_up.at("accountType"), "displayName": sign_up.at("displayName"), "taxId": sign_up.at("taxId"), "businessTaxId": business.at("taxId"), "business": business, + "newsletter": sign_up.at("newsletter"), "businessNewsletter": business.at("newsletter"), "checkout": s.get("checkout"), "register": s.get("register"), } From 50b006dd329ca402119537d7a12f61b891056b23 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 02:28:33 +0100 Subject: [PATCH 14/21] docs(schemas): the default annotation in Read annotations The README says what default is and that a handle from with input has the one a mutation sets, as the JavaScript page does. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b48a20d..1c2f01f 100644 --- a/README.md +++ b/README.md @@ -788,7 +788,7 @@ sign_up.annotations["title"] # "Create your account" # ["displayName", "email", "country"] ``` -Fields an `order` annotation leaves out come after it, in key order. A field or schema the datafile lacks has no annotations, `{}`. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. +`default` is the value a form starts a field with, and a handle from `with_input` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). Fields an `order` annotation leaves out come after it, in key order. A field or schema the datafile lacks has no annotations, `{}`. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. ### Choose the messages From c86d3b04753e405256ef2a14ffaca67fdd9d06dd Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 02:58:39 +0100 Subject: [PATCH 15/21] feat(schemas): issues entries wait only for the fields they compare, and unlisted fields come in name order An issues entry waited for any issue of shape in its object. It now waits only while one sits at or inside its path, or anywhere in the object without a path, or in a field its conditions read, as JavaScript's does. Fields an order leaves out come in name order by Unicode code point, and the built datafile test compares field order exactly. The README says Schemas are experimental, as JavaScript's does, and that unlisted fields come in name order. --- README.md | 4 +- conformance/schemas-datafile.json | 54 +++++++- conformance/schemas-validation.json | 184 ++++++++++++++++++++++++++- src/featurevisor/schemas/_derived.py | 5 +- src/featurevisor/schemas/_engine.py | 61 +++++++-- src/featurevisor/schemas/_views.py | 29 +---- tests/test_schemas.py | 4 +- tests/test_schemas_conformance.py | 2 +- 8 files changed, 293 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 1c2f01f..b6c8e65 100644 --- a/README.md +++ b/README.md @@ -659,6 +659,8 @@ Feature and variable leaves reach modules as dependencies, with `dependencyOf` n Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/#validate-application-data) your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript. +Schemas are experimental, so their API may change in a minor release, as in JavaScript. + ### Create a schemas instance They are the `featurevisor.schemas` subpackage, installed with the SDK. Create it from the SDK instance. Call it `s`, as the SDK instance is `f`: @@ -788,7 +790,7 @@ sign_up.annotations["title"] # "Create your account" # ["displayName", "email", "country"] ``` -`default` is the value a form starts a field with, and a handle from `with_input` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). Fields an `order` annotation leaves out come after it, in key order. A field or schema the datafile lacks has no annotations, `{}`. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. +`default` is the value a form starts a field with, and a handle from `with_input` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). Fields an `order` annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations, `{}`. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. ### Choose the messages diff --git a/conformance/schemas-datafile.json b/conformance/schemas-datafile.json index b3e7ca5..affb9bc 100644 --- a/conformance/schemas-datafile.json +++ b/conformance/schemas-datafile.json @@ -4,7 +4,7 @@ "datafile": { "schemaVersion": "4", "featurevisorVersion": "4.13.0", - "revision": "Qw1wESNyKJ", + "revision": "Y2jhtKdlDE", "segments": { "netherlands": { "conditions": "{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}" @@ -55,6 +55,27 @@ } ] }, + "profile": { + "hash": "Diqw68LeIn", + "type": "object", + "properties": { + "zeta": { + "type": "string" + }, + "alpha": { + "type": "string" + }, + "Beta": { + "type": "string" + }, + "z": { + "type": "string" + }, + "😀": { + "type": "string" + } + } + }, "register": { "hash": "XlDf9sip1o", "type": "object", @@ -736,10 +757,10 @@ "path": "", "fieldKeys": [ "billingCountry", - "shippingCountry", + "confirmPassword", "customsDescription", "password", - "confirmPassword" + "shippingCountry" ], "constraints": { "billingCountry": { @@ -761,10 +782,10 @@ "register": { "path": "", "fieldKeys": [ - "password", + "billingCountry", "confirmPassword", - "shippingCountry", - "billingCountry" + "password", + "shippingCountry" ], "constraints": { "password": { @@ -784,6 +805,27 @@ "billingCountry" ], "annotations": {} + }, + "profile": { + "path": "", + "fieldKeys": [ + "Beta", + "alpha", + "zeta", + "z", + "😀" + ], + "constraints": { + "zeta": {}, + "alpha": {}, + "Beta": {}, + "z": {}, + "😀": {} + }, + "options": {}, + "kind": "object", + "reads": [], + "annotations": {} } } } diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index abf81ab..75222d5 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -2187,7 +2187,7 @@ "issues": [] }, { - "name": "an issue of shape holds every issue entry back", + "name": "an issue of shape elsewhere holds no issue entry back", "schemas": { "subject": { "hash": "subject-1", @@ -2230,6 +2230,186 @@ "password": "lovelace", "confirmPassword": "other" }, + "issues": [ + { + "code": "required", + "path": [ + "email" + ], + "params": { + "key": "email" + } + }, + { + "code": "refine", + "path": [ + "confirmPassword" + ], + "params": { + "refine": "passwordsDiffer" + } + } + ] + }, + { + "name": "an issue of shape in a field an entry reads holds it back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": 5, + "confirmPassword": "other" + }, + "issues": [ + { + "code": "type", + "path": [ + "password" + ], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "an issue of shape at an entry's path holds it back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": "lovelace", + "confirmPassword": 5 + }, + "issues": [ + { + "code": "type", + "path": [ + "confirmPassword" + ], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "an issue entry without a path waits for the whole object", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "password": "lovelace", + "confirmPassword": "other" + }, "issues": [ { "code": "required", @@ -2595,7 +2775,7 @@ ] }, { - "name": "a format issue holds every issue entry back", + "name": "a format issue in a field an issue entry reads holds it back", "schemas": { "subject": { "hash": "subject-1", diff --git a/src/featurevisor/schemas/_derived.py b/src/featurevisor/schemas/_derived.py index 447883d..e7e052d 100644 --- a/src/featurevisor/schemas/_derived.py +++ b/src/featurevisor/schemas/_derived.py @@ -152,7 +152,8 @@ def collect(current: dict[str, Any], prefix: str, depth: int) -> None: def field_keys_of(node: Any, resolve: Resolver) -> list[str]: - """The keys of an object's fields, the ones its order lists first, then the rest as written.""" + """The keys of an object's fields, the ones its order lists first, then the rest in name order, + by code point, as every SDK orders them.""" resolved = resolve_node(node, resolve) properties = resolved.get("properties") if resolved else None if not isinstance(properties, dict): @@ -163,7 +164,7 @@ def field_keys_of(node: Any, resolve: Resolver) -> list[str]: for key in order if isinstance(order, list) else []: if key in properties and key not in first: first.append(key) - return first + [key for key in keys if key not in first] + return first + sorted(key for key in keys if key not in first) def kind_of_field(node: Any, resolve: Resolver, depth: int = 0) -> str | None: diff --git a/src/featurevisor/schemas/_engine.py b/src/featurevisor/schemas/_engine.py index f1a2fed..b4e72c5 100644 --- a/src/featurevisor/schemas/_engine.py +++ b/src/featurevisor/schemas/_engine.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json import threading from dataclasses import dataclass, field, replace from typing import Any, Callable, Mapping, Protocol, Sequence @@ -30,8 +31,8 @@ class Run: trial: bool = False """Counting oneOf branches only notes whether a branch failed, without wording anything.""" failed: bool = False - shape: int = 0 - """How many issues of shape were found, which hold back the issues of every object around them.""" + shapes: list[list[Any]] = field(default_factory=list) + """The paths of the issues of shape found so far, which hold back the issues entries that read them.""" depth: int = 0 """How many references the walk follows at this point, which only a value nested as deep can need.""" match: Matcher = field(default=lambda conditions, reader: False) @@ -39,7 +40,7 @@ class Run: Every run is made with one, and a run without one matches nothing.""" def trial_run(self) -> Run: - return Run(self.schema, self.sources, self.translate, trial=True, shape=self.shape, depth=self.depth, match=self.match) + return Run(self.schema, self.sources, self.translate, trial=True, depth=self.depth, match=self.match) @dataclass @@ -75,7 +76,7 @@ def report(run: Run, at: Position, code: str, params: dict[str, Any], path: list lookup: Lookup | None = None, own: str | None = None) -> None: run.failed = True if code in SHAPE_CODES: - run.shape += 1 + run.shapes.append(list(path if path is not None else at.path)) if run.trial: return path = at.path if path is None else path @@ -569,19 +570,59 @@ def validate(value: Any, run: Run, at: Position) -> None: return validate +def inputs_of(conditions: Any, found: Callable[[Any], None]) -> None: + """Calls back with the input paths conditions read, in input and valueFrom, through every group.""" + # Datafiles can carry conditions as JSON text, as features' are. + if isinstance(conditions, str): + text = conditions.strip() + if not text[:1] in ("{", "[", '"'): + return + try: + conditions = json.loads(text) + except ValueError: + return + if isinstance(conditions, list): + for item in conditions: + inputs_of(item, found) + return + if not isinstance(conditions, dict): + return + found(conditions.get("input")) + if isinstance(conditions.get("valueFrom"), dict): + found(conditions["valueFrom"].get("input")) + for group in ("and", "or", "not"): + inputs_of(conditions.get(group), found) + + +def _at_or_inside(inner: list[Any], outer: list[str]) -> bool: + """Whether inner, a path relative to an object, is outer or a path inside it.""" + return len(inner) >= len(outer) and all(str(inner[index]) == part for index, part in enumerate(outer)) + + def _compile_issues(node: dict[str, Any], rules: Validator, resolve: Resolver) -> Validator: - """An object's issues: after its own rules, unless an issue of shape sits - anywhere inside it, each entry whose conditions match reports its issue at its - path, with that field's title and the messages around it.""" + """An object's issues: after its own rules, each entry whose conditions match + reports its issue at its path, with that field's title and the messages around + it. An entry waits while an issue of shape sits at or inside its path, or + anywhere in the object for an entry without one, as a check in code does, or + at or inside a field its conditions read.""" entries = node["issues"] + waits: list[list[list[str]]] = [] + for entry in entries: + own: list[list[str]] = [entry["path"].split(".") if isinstance(entry, dict) and entry.get("path") else []] + if isinstance(entry, dict): + inputs_of(entry.get("conditions"), lambda path: own.append(path.split(".")) if isinstance(path, str) else None) + waits.append(own) def validate(value: Any, run: Run, at: Position) -> None: - shape = run.shape + before = len(run.shapes) rules(value, run, at) - if run.shape != shape or not isinstance(value, dict): + if not isinstance(value, dict): return + found = [path[len(at.path):] for path in run.shapes[before:]] reader = lambda path: read_input(value, path) # noqa: E731 - for entry in entries: + for index, entry in enumerate(entries): + if any(_at_or_inside(path, wait) for path in found for wait in waits[index]): + continue if not isinstance(entry, dict) or not run.match(entry.get("conditions"), reader): continue parts = entry["path"].split(".") if entry.get("path") else [] diff --git a/src/featurevisor/schemas/_views.py b/src/featurevisor/schemas/_views.py index c28db4b..c54d791 100644 --- a/src/featurevisor/schemas/_views.py +++ b/src/featurevisor/schemas/_views.py @@ -2,10 +2,9 @@ from __future__ import annotations -import json from typing import Any, Callable, Sequence -from ._engine import Matcher, Resolver, has_mutations, matching_mutations, mutated_rules +from ._engine import Matcher, Resolver, has_mutations, inputs_of, matching_mutations, mutated_rules from ._paths import Step @@ -76,30 +75,6 @@ def place(values: Any, steps: Sequence[Step], value: Any) -> Any: return values -def _inputs_of(conditions: Any, found: Callable[[Any], None]) -> None: - """Calls back with the input paths conditions read, in input and valueFrom, through every group.""" - # Datafiles can carry conditions as JSON text, as features' are. - if isinstance(conditions, str): - text = conditions.strip() - if not text[:1] in ("{", "[", '"'): - return - try: - conditions = json.loads(text) - except ValueError: - return - if isinstance(conditions, list): - for item in conditions: - _inputs_of(item, found) - return - if not isinstance(conditions, dict): - return - found(conditions.get("input")) - if isinstance(conditions.get("valueFrom"), dict): - found(conditions["valueFrom"].get("input")) - for group in ("and", "or", "not"): - _inputs_of(conditions.get(group), found) - - def reads_of(node: Any, resolve: Resolver) -> list[str]: """The fields, relative to a node, that the conditions of its mutations and issues read, at any depth and through references, as at takes paths: accountType, @@ -117,7 +92,7 @@ def visit(current: Any, at: str, seen: Sequence[str]) -> None: def add(path: Any) -> None: if isinstance(path, str) and join(at, path) not in reads: reads.append(join(at, path)) - _inputs_of(entry.get("conditions") if isinstance(entry, dict) else None, add) + inputs_of(entry.get("conditions") if isinstance(entry, dict) else None, add) key = current.get("schema") if isinstance(key, str) and key not in seen: visit(resolve.node(key), at, [*seen, key]) diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 85c9bc0..32dd28e 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -74,7 +74,9 @@ def geo(options): def codes(result): return [(issue.code, ".".join(str(part) for part in issue.path)) for issue in result.issues] - self.assertEqual(codes(s.validate("signUp", {"name": "Ada"})), [("required", "taxId")]) + # The entry about the name reads no field, so a missing VAT number does not hold it back. + + self.assertEqual(codes(s.validate("signUp", {"name": "Ada"})), [("required", "taxId"), ("refine", "name")]) self.assertEqual(codes(s.validate("signUp", {"name": "Ada", "taxId": "x"})), [("refine", "name")]) self.assertTrue(s.get("signUp").with_input({}).at("taxId").constraints.required) # One evaluation per validation and per view, each the schema's own. diff --git a/tests/test_schemas_conformance.py b/tests/test_schemas_conformance.py index 52f2876..2785a3b 100644 --- a/tests/test_schemas_conformance.py +++ b/tests/test_schemas_conformance.py @@ -93,7 +93,7 @@ def test_describes_fields_as_javascript_does(self) -> None: "signUp": sign_up, "accountType": sign_up.at("accountType"), "displayName": sign_up.at("displayName"), "taxId": sign_up.at("taxId"), "businessTaxId": business.at("taxId"), "business": business, "newsletter": sign_up.at("newsletter"), "businessNewsletter": business.at("newsletter"), - "checkout": s.get("checkout"), "register": s.get("register"), + "checkout": s.get("checkout"), "register": s.get("register"), "profile": s.get("profile"), } def constraints(value): From 44bf11d4493feb32faa9293017525be6bb68dcc1 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 15:33:31 +0100 Subject: [PATCH 16/21] refactor(schemas): follow the simplified JavaScript package The JavaScript package was simplified for review with no change in behaviour, and this port follows it where it has the same structure: one position for report, an issue entry's path split once, inputsOf keeping only strings, a oneOf branch chosen from a map of kinds, attribution worked out once per issue, and one classifier for path steps. Compiled validators and mutated rules are kept per instance by node, in two generations, so an unchanged schema keeps its validator across a datafile change while memory holds two datafiles at most. An application or form message that is neither text nor a function is passed over, and child gives a key such as 2fa the handle at gives, each with a test. The shared schemas-validation.json gains two cases for a field a mutation adds by schema reference, which pass. The README follows the JavaScript page: the data is value beside the handle, Follow the values typed so far comes after Read annotations, Check in code names its optional fields, and the constraints and options rows say which member is keyed by field path. --- README.md | 73 ++++++------ conformance/schemas-validation.json | 134 ++++++++++++++++++++++ src/featurevisor/schemas/_derived.py | 41 +++---- src/featurevisor/schemas/_engine.py | 153 +++++++++++++++----------- src/featurevisor/schemas/_handle.py | 34 +++--- src/featurevisor/schemas/_messages.py | 11 +- src/featurevisor/schemas/_paths.py | 20 ++-- src/featurevisor/schemas/_store.py | 58 ++++++++-- src/featurevisor/schemas/_views.py | 13 ++- tests/test_schemas.py | 66 +++++++++++ 10 files changed, 436 insertions(+), 167 deletions(-) diff --git a/README.md b/README.md index b6c8e65..cccf999 100644 --- a/README.md +++ b/README.md @@ -42,10 +42,10 @@ The Featurevisor Python SDK evaluates flags, variations and variables in Python - [Get a handle](#get-a-handle) - [Read constraints and choices](#read-constraints-and-choices) - [Read annotations](#read-annotations) + - [Follow the values typed so far](#follow-the-values-typed-so-far) - [Choose the messages](#choose-the-messages) - [Check in code](#check-in-code) - [Options from your application](#options-from-your-application) - - [Follow the values typed so far](#follow-the-values-typed-so-far) - [Validate on the server](#validate-on-the-server) - [Listen for changes](#listen-for-changes) - [Patterns](#patterns) @@ -676,13 +676,13 @@ It holds no copy of the schemas. Every call reads the datafile `f` has now, so a ### Validate a value ```python -sign_up = { +value = { "email": "user-1@example.com", "displayName": "A", "country": "nl", } -result = s.validate("signUp", sign_up) +result = s.validate("signUp", value) if not result.valid: ... # show result.issues beside the form's fields @@ -724,7 +724,7 @@ Validation reports every issue it finds, so a form can mark every field at once. ### Get a handle -`s.get(key)` gives the schema's handle: +A handle is one schema as an object your code holds: it validates, and describes the schema's fields, constraints, choices and annotations for a form. `s.get(key)` gives one: ```python sign_up = s.get("signUp") @@ -732,20 +732,20 @@ sign_up = s.get("signUp") A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application. -| Member | What it is | -| ------------------------------------------- | -------------------------------------------------------------------------------- | -| `validate`, `is_valid`, `parse` | As on `s`, without the key | -| `avalidate` | Validation awaiting your [checks in code](#check-in-code) | -| `at(path)` | The handle of one field, such as `at("displayName")` | -| `fields` | An object's fields' handles, in [order](#read-annotations), each with its `name` | -| `constraints`, `field_constraints` | HTML validation attributes, [below](#read-constraints-and-choices) | -| `options`, `field_options`, `option(value)` | Its choices, and one of them by value | -| `kind` | What its rules make the field, such as `"select"` | -| `annotations` | Its [annotations](#read-annotations) | -| `with_input(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | -| `reads` | The fields its rules' conditions read | -| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | -| `key`, `path`, `name` | The schema's key, and the field's path and own name | +| Member | What it is | +| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | +| `validate`, `is_valid`, `parse` | As on `s`, without the key | +| `avalidate` | Validation awaiting your [checks in code](#check-in-code) | +| `at(path)` | The handle of one field, such as `at("displayName")` | +| `fields` | An object's fields' handles, in [order](#read-annotations), each with its `name` | +| `constraints`, `field_constraints` | HTML validation attributes, `field_constraints` by field path on an object, [below](#read-constraints-and-choices) | +| `options`, `field_options`, `option(value)` | Its choices, `field_options` by field path on an object, and one choice by value | +| `kind` | What its rules make the field, such as `"select"` | +| `annotations` | Its [annotations](#read-annotations) | +| `with_input(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | +| `reads` | The fields its rules' conditions read | +| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | +| `key`, `path`, `name` | The schema's key, and the field's path and own name | `at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. @@ -792,6 +792,22 @@ sign_up.annotations["title"] # "Create your account" `default` is the value a form starts a field with, and a handle from `with_input` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). Fields an `order` annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations, `{}`. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. +### Follow the values typed so far + +A handle's constraints and choices describe the schema's own rules, which no condition changes. `with_input(input)` gives the same handle with an input, such as a form's values, with the [mutations](https://featurevisor.com/docs/schemas/#mutations) that match it applied, so a tax ID shows as required once a business account is chosen: + +```python +values = { + "accountType": "business", + "country": "nl", +} + +sign_up.at("taxId").constraints.required # False +sign_up.with_input(values).at("taxId").constraints.required # True +``` + +Every member follows the input, at every depth. `reads` lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes. + ### Choose the messages `messages` on `create_schemas` words every schema's issues, per code, as a template or a function of the params: @@ -813,11 +829,11 @@ s = create_schemas( 3. The application's, from `messages` on `create_schemas`. 4. The default, in English. -`translate` on `create_schemas` gets each issue, with the message chosen, and returns what the issue says, or `None` to keep it. Keep the text in your translation system, and let schemas and `messages` hold keys, such as `errors.required`, which `translate` turns into text. +`translate` on `create_schemas` gets each issue, with the message chosen, and returns what the issue says, or `None` to keep it. With translations, `messages` holds keys, such as `errors.required`, and `translate` turns each into text. ### Check in code -Some checks need your application, such as whether a display name is taken. Give them to a handle in `refine`, each a `Refinement` with a `key`, a `check`, a `path` and a `message`: +Some checks need your application, such as whether a display name is taken. Give them to a handle in `refine`, each a `Refinement` with a `key` and a `check`, and the `path` it checks, a `message` and `reads` as it needs them: ```python from featurevisor.schemas import Refinement @@ -835,6 +851,7 @@ result = await sign_up.avalidate(value) - `check` gets the value at its path, and `info` with the whole `input` and the `context`. It returns `True` when the value passes, or a coroutine of it. - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database. +- Without a `path`, the check gets the whole value, and runs only when the value has no issue at all. `reads` names other fields whose issues hold it back too, such as `items` for a check of an order's total. - Its issue has code `refine` and `params["refine"]` `"nameAvailable"`, with the field's title. A check that raises gives `refineError`, and validation fails closed. - `avalidate` awaits every check, running them concurrently, and returns the result, whose issues say what failed. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. @@ -865,22 +882,6 @@ await city.search("am") - `lookup` returns the choice for a value, `True` when it carries nothing more, or `None` when there is none. A handle's `await lookup(value)` returns the schema's own choice first, then the source's. - Validation runs `lookup` as a [check in code](#check-in-code), after the schema's rules, only for a value that is there, and not while a field `reads` names has an issue. A value it cannot find has code `enum`, worded by `message`. -### Follow the values typed so far - -A handle's constraints and choices describe the schema's own rules, which no condition changes. `with_input(input)` gives the same handle with an input, such as a form's values, with the [mutations](https://featurevisor.com/docs/schemas/#mutations) that match it applied, so a tax ID shows as required once a business account is chosen: - -```python -values = { - "accountType": "business", - "country": "nl", -} - -sign_up.at("taxId").constraints.required # False -sign_up.with_input(values).at("taxId").constraints.required # True -``` - -Every member follows the input, at every depth. `reads` lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes. - ### Validate on the server `parse` answers a request with a value or a `SchemaValidationError`, whose `flatten()` gives the issues by field: diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index 75222d5..b5fbdcb 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -4303,6 +4303,140 @@ "mutation": "numeric" } ] + }, + { + "name": "a field a mutation adds by reference validates with the referenced schema", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "country": { + "type": "string" + } + }, + "mutations": [ + { + "key": "withAddress", + "conditions": [ + { + "input": "country", + "operator": "equals", + "value": "de" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "address" + ], + "value": { + "schema": "address" + } + } + ] + } + ] + }, + "address": { + "hash": "address-1", + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + }, + "schema": "subject", + "value": { + "country": "de", + "address": {} + }, + "issues": [ + { + "code": "required", + "path": [ + "address", + "city" + ], + "params": { + "key": "city" + }, + "mutation": "withAddress" + } + ] + }, + { + "name": "without the mutation, the field it adds by reference is not allowed", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "country": { + "type": "string" + } + }, + "mutations": [ + { + "key": "withAddress", + "conditions": [ + { + "input": "country", + "operator": "equals", + "value": "de" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "address" + ], + "value": { + "schema": "address" + } + } + ] + } + ] + }, + "address": { + "hash": "address-1", + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + }, + "schema": "subject", + "value": { + "country": "nl", + "address": {} + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "address" + ], + "params": { + "key": "address" + } + } + ] } ] } diff --git a/src/featurevisor/schemas/_derived.py b/src/featurevisor/schemas/_derived.py index e7e052d..13af0fe 100644 --- a/src/featurevisor/schemas/_derived.py +++ b/src/featurevisor/schemas/_derived.py @@ -2,13 +2,16 @@ from __future__ import annotations -from typing import Any +from typing import Any, Callable, TypeVar from ._engine import Resolver, annotations_of, is_const_list, option_entry, resolve_node from ._json import is_number, same from ._types import Constraints, SchemaOption, make_option +T = TypeVar("T") + + def non_null_branch(node: dict[str, Any], resolve: Resolver) -> dict[str, Any] | None: """The branch a nullable field's rules come from: a oneOf whose other branches only allow null.""" if not isinstance(node.get("oneOf"), list): @@ -70,9 +73,10 @@ def constraints_of(node: Any, required: bool, resolve: Resolver) -> Constraints: return Constraints(required=is_required, multiple=kind == "array") -def field_constraints_of(node: Any, resolve: Resolver) -> dict[str, Constraints]: - """An object's fields' constraints by dot path, nested objects included and lists left to their rows' handles.""" - result: dict[str, Constraints] = {} +def _by_path(node: Any, resolve: Resolver, read: Callable[[Any, bool], T | None]) -> dict[str, T]: + """What read says of each field of an object by dot path, nested objects included and lists left to their + rows' handles, for the fields it says something of.""" + result: dict[str, T] = {} def collect(current: dict[str, Any], prefix: str, depth: int) -> None: properties = current.get("properties") @@ -82,7 +86,9 @@ def collect(current: dict[str, Any], prefix: str, depth: int) -> None: required: list[Any] = listed if isinstance(listed, list) else [] for key, child in properties.items(): path = prefix + key - result[path] = constraints_of(child, key in required, resolve) + found = read(child, key in required) + if found is not None: + result[path] = found resolved = resolve_node(child, resolve) if is_object_node(resolved): collect(resolved, path + ".", depth + 1) # type: ignore[arg-type] @@ -93,6 +99,11 @@ def collect(current: dict[str, Any], prefix: str, depth: int) -> None: return result +def field_constraints_of(node: Any, resolve: Resolver) -> dict[str, Constraints]: + """An object's fields' constraints by dot path, nested objects included and lists left to their rows' handles.""" + return _by_path(node, resolve, lambda child, required: constraints_of(child, required, resolve)) + + def _choices_of(node: Any, resolve: Resolver, branch: bool = False, depth: int = 0) -> list[SchemaOption] | None: """A node's choices in the order its rules list them, each as its value with what the schema says about it.""" resolved = resolve_node(node, resolve) @@ -130,25 +141,7 @@ def options_of(node: Any, resolve: Resolver) -> list[SchemaOption]: def field_options_of(node: Any, resolve: Resolver) -> dict[str, list[SchemaOption]]: """An object's fields' choices by dot path, only for fields that list some.""" - result: dict[str, list[SchemaOption]] = {} - - def collect(current: dict[str, Any], prefix: str, depth: int) -> None: - properties = current.get("properties") - if not isinstance(properties, dict) or depth > 64: - return - for key, child in properties.items(): - path = prefix + key - choices = _choices_of(child, resolve) - if choices is not None: - result[path] = choices - resolved = resolve_node(child, resolve) - if is_object_node(resolved): - collect(resolved, path + ".", depth + 1) # type: ignore[arg-type] - - resolved = resolve_node(node, resolve) - if is_object_node(resolved): - collect(resolved, "", 0) # type: ignore[arg-type] - return result + return _by_path(node, resolve, lambda child, required: _choices_of(child, resolve)) def field_keys_of(node: Any, resolve: Resolver) -> list[str]: diff --git a/src/featurevisor/schemas/_engine.py b/src/featurevisor/schemas/_engine.py index b4e72c5..b1e3bf2 100644 --- a/src/featurevisor/schemas/_engine.py +++ b/src/featurevisor/schemas/_engine.py @@ -12,6 +12,7 @@ from ..mutations import apply_variable_operations from ._json import ABSENT, is_finite_number, is_integer, is_number, is_primitive, kind_of, same, stringify from ._messages import Lookup, Scope, Sources, choose_message +from ._paths import is_at_or_inside from ._patterns import compile_pattern from ._types import SchemaIssue @@ -27,6 +28,8 @@ class Run: schema: str sources: Sources translate: Callable[[SchemaIssue, Any], str | None] | None + match: Matcher + """Answers conditions in the schema's package evaluation, with the context its modules leave.""" issues: list[SchemaIssue] = field(default_factory=list) trial: bool = False """Counting oneOf branches only notes whether a branch failed, without wording anything.""" @@ -35,12 +38,9 @@ class Run: """The paths of the issues of shape found so far, which hold back the issues entries that read them.""" depth: int = 0 """How many references the walk follows at this point, which only a value nested as deep can need.""" - match: Matcher = field(default=lambda conditions, reader: False) - """Answers conditions in the schema's package evaluation, with the context its modules leave. - Every run is made with one, and a run without one matches nothing.""" def trial_run(self) -> Run: - return Run(self.schema, self.sources, self.translate, trial=True, depth=self.depth, match=self.match) + return Run(self.schema, self.sources, self.translate, self.match, trial=True, depth=self.depth) @dataclass @@ -72,20 +72,19 @@ def mutation_failed(self, schema: str, error: Exception) -> None: ... "format"}) -def report(run: Run, at: Position, code: str, params: dict[str, Any], path: list[Any] | None = None, - lookup: Lookup | None = None, own: str | None = None) -> None: +def report(run: Run, at: Position, code: str, params: dict[str, Any], own: str | None = None) -> None: + """Reports an issue at a position, which holds the issue's path and where its message is looked for.""" run.failed = True if code in SHAPE_CODES: - run.shapes.append(list(path if path is not None else at.path)) + run.shapes.append(list(at.path)) if run.trial: return - path = at.path if path is None else path - lookup = at.lookup if lookup is None else lookup + lookup = at.lookup # The field's title, so a message can say {title} is required. if lookup.title is not None: params = {**params, "title": lookup.title} - message = choose_message(code, params, path, lookup, run.sources, own) - issue = SchemaIssue(message, tuple(path), code, params, run.schema) + message = choose_message(code, params, at.path, lookup, run.sources, own) + issue = SchemaIssue(message, tuple(at.path), code, params, run.schema) if run.translate is not None: translated = run.translate(issue, run.sources.info) if isinstance(translated, str): @@ -146,13 +145,16 @@ def own_scopes(node: Any, base: int, resolve: Resolver, scopes: list[Scope], see def resolve_node(node: Any, resolve: Resolver) -> dict[str, Any] | None: """The node a reference resolves to, through any chain of references.""" - seen: set[str] = set() + seen: set[str] | None = None current = node while isinstance(current, dict): schema = current.get("schema") if not isinstance(schema, str): return current - if schema in seen: + # The set of references followed is made only for a node that is one. + if seen is None: + seen = set() + elif schema in seen: return None seen.add(schema) current = resolve.node(schema) @@ -198,23 +200,38 @@ def _compile_one_of(node: dict[str, Any], resolve: Resolver) -> Validator: return _compile_const_list(node, resolve) branch_nodes = node["oneOf"] branches = [compile_node(branch, resolve) for branch in branch_nodes] + # The nodes the branches resolved to when the kinds were last worked out, and the branch that takes each kind + # of value when no two branches take the same kind, otherwise None. + cached: tuple[list[dict[str, Any] | None], dict[str, int] | None] | None = None + + def kinds_now() -> dict[str, int] | None: + """Read each time, since a branch's reference can resolve to another schema, and kept until it does.""" + nonlocal cached + nodes = [resolve_node(branch, resolve) for branch in branch_nodes] + current = cached + if current is not None and all(a is b for a, b in zip(current[0], nodes)): + return current[1] + # Disjoint when every branch can say what it takes and no kind repeats across them. + select: dict[str, int] = {} + disjoint = True + for index, resolved in enumerate(nodes): + kinds = _branch_kinds(resolved) if resolved is not None else None + if kinds is None or any(kind in select for kind in kinds): + disjoint = False + break + select.update({kind: index for kind in kinds}) + cached = (nodes, select if disjoint else None) + return cached[1] def validate(value: Any, run: Run, at: Position) -> None: - # The kinds each branch takes, read each time, since a branch's reference can resolve to another schema. - kinds = [] - for branch in branch_nodes: - resolved = resolve_node(branch, resolve) - kinds.append(_branch_kinds(resolved) if resolved is not None else None) - disjoint = all(kind is not None for kind in kinds) and all( - not (kinds[a] & kinds[b]) for a in range(len(kinds)) for b in range(len(kinds)) if a != b) # type: ignore[operator] - if disjoint: + select = kinds_now() + if select is not None: # The value's type selects a branch, whose own issues are the ones reported. - kind = kind_of(value) - for index, kind_set in enumerate(kinds): - if kind in kind_set: # type: ignore[operator] - branches[index](value, run, at) - return - report(run, at, "oneOf", {"matches": 0}) + selected = select.get(kind_of(value)) + if selected is None: + report(run, at, "oneOf", {"matches": 0}) + else: + branches[selected](value, run, at) return matches = 0 for branch in branches: @@ -321,8 +338,8 @@ def validate(value: Any, run: Run, at: Position) -> None: # A missing key's issue is at the key, worded by the messages for that field, with its title. mpath = [*at.lookup.mpath, key] scopes = own_scopes(properties.get(key), len(mpath), resolve, list(at.lookup.scopes)) - report(run, at, "required", {"key": key}, [*at.path, key], - Lookup(mpath, scopes, title_of(properties.get(key), resolve))) + report(run, Position([*at.path, key], Lookup(mpath, scopes, title_of(properties.get(key), resolve))), + "required", {"key": key}) for key, child in value.items(): if key in compiled: compiled[key](child, run, Position([*at.path, key], Lookup([*at.lookup.mpath, key], at.lookup.scopes))) @@ -332,11 +349,12 @@ def validate(value: Any, run: Run, at: Position) -> None: compiled_additional(child, run, Position([*at.path, key], Lookup([*at.lookup.mpath, "*"], at.lookup.scopes))) elif properties is not None or closed: # An extra key has no field of its own, so the object that rejects it words its issue, without a title. - report(run, at, "additionalProperties", {"key": key}, [*at.path, key], Lookup(at.lookup.mpath, at.lookup.scopes)) + report(run, Position([*at.path, key], Lookup(at.lookup.mpath, at.lookup.scopes)), + "additionalProperties", {"key": key}) elif not is_primitive(child): # Without properties or additionalProperties, an object is flat. - report(run, at, "type", {"type": "primitive", "received": kind_of(child)}, [*at.path, key], - Lookup(at.lookup.mpath, at.lookup.scopes)) + report(run, Position([*at.path, key], Lookup(at.lookup.mpath, at.lookup.scopes)), + "type", {"type": "primitive", "received": kind_of(child)}) return validate @@ -495,10 +513,20 @@ def has_mutations(node: Any) -> bool: return isinstance(node, dict) and isinstance(node.get("mutations"), list) and bool(node["mutations"]) +def input_reader(value: Any) -> Callable[[str], Any]: + """The reader for input leaves, which read the value at the node whose conditions they answer.""" + return lambda path: read_input(value, path) + + +def matched_of(mutation_id: str) -> list[int]: + """The indexes of the mutations an id such as "0,2," names, in order.""" + return [int(index) for index in mutation_id.split(",") if index] + + def matching_mutations(node: dict[str, Any], value: Any, match: Matcher) -> str: """Which of a node's mutations match the value at it, as an id such as "0,2,".""" # input reads the value at this node, so a mutation in address reads the address's own fields. - reader = lambda path: read_input(value, path) # noqa: E731 + reader = input_reader(value) return "".join( f"{index}," for index, mutation in enumerate(node["mutations"]) @@ -509,9 +537,8 @@ def matching_mutations(node: dict[str, Any], value: Any, match: Matcher) -> str: def mutated_rules(node: dict[str, Any], mutation_id: str) -> dict[str, Any]: """A node's rules with the mutations an id names applied in order, without mutations.""" rules: Any = {key: value for key, value in node.items() if key != "mutations"} - for index in mutation_id.split(","): - if index: - rules = apply_variable_operations(rules, node["mutations"][int(index)].get("operations")) + for index in matched_of(mutation_id): + rules = apply_variable_operations(rules, node["mutations"][index].get("operations")) if not isinstance(rules, dict): raise ValueError("Mutations of a schema node must keep it an object") return rules @@ -523,6 +550,9 @@ def _compile_mutations(node: dict[str, Any], resolve: Resolver) -> Validator: combination of matches compiles once and is kept for the node. An issue whose rule a matching mutation set or changed names the last such mutation.""" mutations = node["mutations"] + # The paths of each mutation's operations, read once. + operation_paths = [[operation.get("path", []) for operation in mutation.get("operations", []) + if isinstance(operation, dict)] for mutation in mutations] variants: dict[str, tuple[Validator | None, dict[str, Any], list[int], Exception | None]] = {} lock = threading.Lock() @@ -531,7 +561,7 @@ def validate(value: Any, run: Run, at: Position) -> None: with lock: variant = variants.get(mutation_id) if variant is None: - matched = [int(index) for index in mutation_id.split(",") if index] + matched = matched_of(mutation_id) try: rules = mutated_rules(node, mutation_id) variant = (compile_node(rules, resolve), rules, matched, None) @@ -555,22 +585,21 @@ def validate(value: Any, run: Run, at: Position) -> None: # A mutation inside the node applies last, so its claim stands. if issue.mutation is not None: continue - rule, whole = _rule_of(rules, issue.path[len(at.path):], issue.code) + if issue.code == "refine": + # An issue entry's issue sits at its own path, so the mutation is one that changed issues. + sets: Callable[[Any], bool] = lambda path: "issues" in path # noqa: E731 + else: + rule, whole = _rule_of(rules, issue.path[len(at.path):], issue.code) + sets = lambda path, rule=rule, whole=whole: _reaches(path, rule, whole) # type: ignore[misc] # noqa: E731 for index in reversed(matched): - mutation = mutations[index] - paths = [operation.get("path", []) for operation in mutation.get("operations", []) if isinstance(operation, dict)] - if issue.code == "refine": - sets = any("issues" in path for path in paths) - else: - sets = any(_reaches(path, rule, whole) for path in paths) - if sets: - run.issues[position] = replace(issue, mutation=mutation.get("key")) + if any(sets(path) for path in operation_paths[index]): + run.issues[position] = replace(issue, mutation=mutations[index].get("key")) break return validate -def inputs_of(conditions: Any, found: Callable[[Any], None]) -> None: +def inputs_of(conditions: Any, found: Callable[[str], None]) -> None: """Calls back with the input paths conditions read, in input and valueFrom, through every group.""" # Datafiles can carry conditions as JSON text, as features' are. if isinstance(conditions, str): @@ -587,18 +616,15 @@ def inputs_of(conditions: Any, found: Callable[[Any], None]) -> None: return if not isinstance(conditions, dict): return - found(conditions.get("input")) - if isinstance(conditions.get("valueFrom"), dict): - found(conditions["valueFrom"].get("input")) + if isinstance(conditions.get("input"), str): + found(conditions["input"]) + value_from = conditions.get("valueFrom") + if isinstance(value_from, dict) and isinstance(value_from.get("input"), str): + found(value_from["input"]) for group in ("and", "or", "not"): inputs_of(conditions.get(group), found) -def _at_or_inside(inner: list[Any], outer: list[str]) -> bool: - """Whether inner, a path relative to an object, is outer or a path inside it.""" - return len(inner) >= len(outer) and all(str(inner[index]) == part for index, part in enumerate(outer)) - - def _compile_issues(node: dict[str, Any], rules: Validator, resolve: Resolver) -> Validator: """An object's issues: after its own rules, each entry whose conditions match reports its issue at its path, with that field's title and the messages around @@ -610,7 +636,7 @@ def _compile_issues(node: dict[str, Any], rules: Validator, resolve: Resolver) - for entry in entries: own: list[list[str]] = [entry["path"].split(".") if isinstance(entry, dict) and entry.get("path") else []] if isinstance(entry, dict): - inputs_of(entry.get("conditions"), lambda path: own.append(path.split(".")) if isinstance(path, str) else None) + inputs_of(entry.get("conditions"), lambda path: own.append(path.split("."))) waits.append(own) def validate(value: Any, run: Run, at: Position) -> None: @@ -619,22 +645,23 @@ def validate(value: Any, run: Run, at: Position) -> None: if not isinstance(value, dict): return found = [path[len(at.path):] for path in run.shapes[before:]] - reader = lambda path: read_input(value, path) # noqa: E731 + reader = input_reader(value) for index, entry in enumerate(entries): - if any(_at_or_inside(path, wait) for path in found for wait in waits[index]): + if any(is_at_or_inside(path, wait) for path in found for wait in waits[index]): continue if not isinstance(entry, dict) or not run.match(entry.get("conditions"), reader): continue - parts = entry["path"].split(".") if entry.get("path") else [] + # The entry's own path, read once with the fields it waits for. + parts = waits[index][0] scopes = list(at.lookup.scopes) field_node: Any = node - for index, part in enumerate(parts): + for depth, part in enumerate(parts): properties = (resolve_node(field_node, resolve) or {}).get("properties") field_node = properties.get(part) if isinstance(properties, dict) else None - own_scopes(field_node, len(at.lookup.mpath) + index + 1, resolve, scopes) + own_scopes(field_node, len(at.lookup.mpath) + depth + 1, resolve, scopes) title = title_of(field_node, resolve) if parts else at.lookup.title - report(run, at, "refine", {"refine": entry.get("key")}, [*at.path, *parts], - Lookup([*at.lookup.mpath, *parts], scopes, title, entry.get("message"))) + report(run, Position([*at.path, *parts], Lookup([*at.lookup.mpath, *parts], scopes, title, entry.get("message"))), + "refine", {"refine": entry.get("key")}) return validate diff --git a/src/featurevisor/schemas/_handle.py b/src/featurevisor/schemas/_handle.py index 228fe03..8ce4156 100644 --- a/src/featurevisor/schemas/_handle.py +++ b/src/featurevisor/schemas/_handle.py @@ -10,10 +10,10 @@ from ._derived import (constraints_of, field_constraints_of, field_keys_of, field_options_of, kind_of_field, options_of) -from ._engine import Position, Run, Validator, annotations_of, compile_node, report, title_of +from ._engine import Position, Run, Validator, annotations_of, report, title_of from ._json import plain, same from ._messages import Lookup, Sources, form_messages -from ._paths import ITEMS, Step, format_steps, is_at_or_inside, matches_steps, parse_path, steps_of +from ._paths import ITEMS, Step, format_steps, is_at_or_inside, matches_steps, parse_path, reads_as_key, steps_of from ._store import Walk, locate from ._types import (CheckInfo, Constraints, Message, MessageInfo, OptionSource, Refinement, SchemaIssue, SchemaOption, SchemaValidationError, ValidationResult, make_option) @@ -95,7 +95,7 @@ def __init__(self, schemas: Schemas, key: str, options: Mapping[str, Any] | None self._view = view self._lock = threading.Lock() self._handles: dict[str, SchemaHandle] = {} - self._compiled: tuple[Any, Validator, Any, Lookup] | None = None + self._located: tuple[Any, Any, Lookup] | None = None self._memo: tuple[Any, str, dict[str, Any]] | None = None @property @@ -196,7 +196,7 @@ def _evaluated(self, given: Mapping[str, Any] | None, callback: Callable[[Run], def run(context: dict[str, Any], match: Any) -> Any: info = MessageInfo(lambda: context) sources = Sources(self._form, self._schemas._messages, info) - return callback(Run(self.key, sources, self._schemas._translate, match=match)) + return callback(Run(self.key, sources, self._schemas._translate, match)) return self._store.evaluate(self.key, merged, run) @@ -212,26 +212,26 @@ def _locate(self, value: Any, run: Run) -> tuple[Validator, Any, Lookup] | None: if not self._steps and self._view is None: return validate, node, Lookup([]) if self._view is None: - # A field's node is kept until its schema changes. + # Where a field sits is kept until its schema changes, and its validator comes from the store. version = store.version(self.key) with self._lock: - compiled = self._compiled - if compiled is not None and compiled[0] == version: - return compiled[1], compiled[2], compiled[3] + known = self._located + if known is not None and known[0] == version: + return store.compile(known[1]), known[1], known[2] field = locate(store, node, self._steps) if field is None: return None - entry = (version, compile_node(field.node, store), field.node, Lookup(field.mpath, field.scopes)) + entry = (version, field.node, Lookup(field.mpath, field.scopes)) with self._lock: - self._compiled = entry - return entry[1], entry[2], entry[3] + self._located = entry + return store.compile(entry[1]), entry[1], entry[2] view = self._view walk = Walk(place(view.values, self._steps[view.start:], value), view.start, - adjuster(run.match)) + adjuster(run.match, store.mutated_rules)) field = locate(store, node, self._steps, walk=walk) if field is None: return None - return compile_node(field.node, store), field.node, Lookup(field.mpath, field.scopes) + return store.compile(field.node), field.node, Lookup(field.mpath, field.scopes) def _apply_rules(self, value: Any, run: Run) -> tuple[Validator, Any, Lookup] | None: located = self._locate(value, run) @@ -309,8 +309,8 @@ def _report_check(self, run: Run, located, code: str, check: _Check, path: list[ else: found = Lookup([*lookup.mpath, *(str(part) for part in path)], list(lookup.scopes)) params = {"refine": check.key} if check.kind == "refine" else {"optionSource": check.key} - reporting = Run(run.schema, run.sources, run.translate, match=run.match) - report(reporting, Position(path, found), code, params, path, found, None if code == "refineError" else check.message) + reporting = Run(run.schema, run.sources, run.translate, run.match) + report(reporting, Position(path, found), code, params, None if code == "refineError" else check.message) return reporting.issues # Fields @@ -322,7 +322,7 @@ def at(self, path: str) -> SchemaHandle: def _child(self, key: str) -> SchemaHandle: """The handle for one of an object's fields by its key, the same handle at gives when the key reads as itself, and its own for a key such as "a.b", "*" or "2024".""" - if key and key[0] not in ".[]*" and not key[0].isdigit() and not any(c in key for c in ".[]"): + if reads_as_key(key): return self.at(key) return self._handle("\x00" + key, lambda: [Step("key", key=key)]) @@ -353,7 +353,7 @@ def _describe(self, view: _View | None) -> tuple[Any, bool] | None: return (field.node, field.required) if field is not None else None # A view's mutations match in the schema's evaluation, with the view's context. def described(_context: dict[str, Any], match: Any) -> tuple[Any, bool] | None: - adjust = adjuster(match) + adjust = adjuster(match, store.mutated_rules) field = locate(store, root[0], self._steps, walk=Walk(view.values, view.start, adjust)) if field is None: return None diff --git a/src/featurevisor/schemas/_messages.py b/src/featurevisor/schemas/_messages.py index 8ebed86..8f86f11 100644 --- a/src/featurevisor/schemas/_messages.py +++ b/src/featurevisor/schemas/_messages.py @@ -5,7 +5,7 @@ import json import re from dataclasses import dataclass, field -from typing import Any, Mapping, Sequence +from typing import Any, Mapping, Sequence, TypeGuard from ._json import is_number, number_text, stringify from ._paths import message_path @@ -93,6 +93,11 @@ def replace(match: re.Match[str]) -> str: return _PLACEHOLDER.sub(replace, template) +def _is_message(message: Any) -> TypeGuard[Message]: + """Whether a message is text or a function, anything else being passed over.""" + return isinstance(message, str) or callable(message) + + def _apply(message: Message, params: Mapping[str, Any], info: MessageInfo) -> str: return fill_template(message, params) if isinstance(message, str) else message(params, info) @@ -188,7 +193,7 @@ def choose_message(code: str, params: Mapping[str, Any], path: Sequence[Any], lo # An option source's enum names no list, so a wording that fills one in is passed over. listless = code == "enum" and "options" not in params and "titles" not in params form = sources.form.get(SEPARATOR.join(lookup.mpath), {}).get(code) - if form is not None and _fits(form, listless): + if _is_message(form) and _fits(form, listless): return _apply(form, params, sources.info) for scope in lookup.scopes: if scope.base > len(lookup.mpath): @@ -200,6 +205,6 @@ def choose_message(code: str, params: Mapping[str, Any], path: Sequence[Any], lo if lookup.own is not None and _fits(lookup.own, listless): return fill_template(lookup.own, params) app = sources.app.get(code) - if app is not None and _fits(app, listless): + if _is_message(app) and _fits(app, listless): return _apply(app, params, sources.info) return default_message(code, params, path) diff --git a/src/featurevisor/schemas/_paths.py b/src/featurevisor/schemas/_paths.py index 236b909..b080ed3 100644 --- a/src/featurevisor/schemas/_paths.py +++ b/src/featurevisor/schemas/_paths.py @@ -30,12 +30,18 @@ def part(self) -> str: VALUES = Step("values") -def _step(text: str) -> Step: +def _step(text: str, key: str | None = None) -> Step: + """What a piece of a path is: every value, an index or a key, which is the text unless given.""" if text == "*": return VALUES if _INDEX.fullmatch(text): return Step("index", index=int(text)) - return Step("key", key=text) + return Step("key", key=text if key is None else key) + + +def reads_as_key(key: str) -> bool: + """Whether parse_path reads a key as itself, so at(key) and an object's own field are the same handle.""" + return key != "" and not any(character in key for character in ".[]") and _step(key).kind == "key" def parse_path(path: str) -> list[Step]: @@ -56,14 +62,8 @@ def parse_path(path: str) -> list[Step]: key = "" end = path.find("]", index) inside = path[index + 1:] if end == -1 else path[index + 1:end] - if inside == "": - steps.append(ITEMS) - elif inside == "*": - steps.append(VALUES) - elif _INDEX.fullmatch(inside): - steps.append(Step("index", index=int(inside))) - else: - steps.append(Step("key", key=inside.strip("\"'"))) + # Classified before the quotes come off, so ["0"] stays the key 0. + steps.append(ITEMS if inside == "" else _step(inside, inside.strip("\"'"))) index = len(path) if end == -1 else end + 1 else: key += character diff --git a/src/featurevisor/schemas/_store.py b/src/featurevisor/schemas/_store.py index 9bcb0c0..a6bf56c 100644 --- a/src/featurevisor/schemas/_store.py +++ b/src/featurevisor/schemas/_store.py @@ -9,7 +9,7 @@ from typing import Any, Callable, Sequence from ..modules import FeaturevisorModule -from ._engine import Resolver, Validator, compile_node +from ._engine import Resolver, Validator, compile_node, matched_of, mutated_rules from ._messages import Scope from ._paths import Step @@ -31,7 +31,16 @@ def __init__(self, f: Any) -> None: "Pass a child's context to validate instead.") self.f = f self._lock = threading.Lock() - self._compiled: dict[str, tuple[Any, Validator]] = {} + # Validators by the identity of their node, one cache for every handle, view and field of this instance, + # and the rules of a node with the mutations of an id applied, so a view's nodes are the same objects + # for the same matches. Each entry holds its node, which keeps its identity, and a new datafile starts them again. + # Two generations of each: a new datafile makes the current maps the previous ones, and a hit in the + # previous map moves into the current one, so unchanged schemas keep theirs and memory holds two datafiles' worth. + self._compiled: dict[int, tuple[Any, Validator]] = {} + self._compiled_before: dict[int, tuple[Any, Validator]] = {} + self._mutated: dict[tuple[int, str], tuple[Any, dict[str, Any]]] = {} + self._mutated_before: dict[tuple[int, str], tuple[Any, dict[str, Any]]] = {} + self._revision: Any = None self._reported: set[str] = set() api: dict[str, Any] = {} with _named_lock: @@ -86,14 +95,42 @@ def resolve(self, key: str) -> tuple[dict[str, Any], Validator] | None: node = self.entry(key) if node is None: return None + return node, self.compile(node) + + def _fresh(self) -> None: + revision = self.api["get_revision"]() + if revision != self._revision: + with self._lock: + self._compiled_before, self._compiled = self._compiled, {} + self._mutated_before, self._mutated = self._mutated, {} + self._revision = revision + + def compile(self, node: dict[str, Any]) -> Validator: + """A node's validator, compiled once for this instance, however many handles and views reach it.""" + self._fresh() with self._lock: - cached = self._compiled.get(key) - if cached is not None and cached[0] is node: - return node, cached[1] + cached = self._compiled.get(id(node)) or self._compiled_before.get(id(node)) + if cached is not None and cached[0] is node: + self._compiled[id(node)] = cached + return cached[1] validate = compile_node(node, self) with self._lock: - self._compiled[key] = (node, validate) - return node, validate + self._compiled[id(node)] = (node, validate) + return validate + + def mutated_rules(self, node: dict[str, Any], mutation_id: str) -> dict[str, Any]: + """A node's rules with the mutations an id names applied, the same object for the same id.""" + self._fresh() + key = (id(node), mutation_id) + with self._lock: + cached = self._mutated.get(key) or self._mutated_before.get(key) + if cached is not None and cached[0] is node: + self._mutated[key] = cached + return cached[1] + rules = mutated_rules(node, mutation_id) + with self._lock: + self._mutated[key] = (node, rules) + return rules def evaluate(self, schema: str, context: dict[str, Any] | None, callback: Callable[[dict[str, Any], Any], Any]) -> Any: """Runs the callback in the schema's package evaluation, so modules see it as they @@ -146,6 +183,11 @@ def report_missing(self, key: str) -> None: }) +# The node of an array without items, which holds strings, shared so that caches by node hit for its items. +# Nothing writes to a located node. +STRING_ITEMS: dict[str, Any] = {"type": "string"} + + @dataclass class Location: """A field inside a schema: its node, and the message path and messages around it.""" @@ -227,7 +269,7 @@ def locate(resolve: Resolver, root: Any, steps: Sequence[Step], mpath: Sequence[ # An index or []: every item of an array is described alike. if resolved.get("type") != "array": return None - node = resolved["items"] if "items" in resolved else {"type": "string"} + node = resolved["items"] if "items" in resolved else STRING_ITEMS mpath.append("[]") if in_view: value = value[step.index] if step.kind == "index" and isinstance(value, list) and step.index < len(value) else None diff --git a/src/featurevisor/schemas/_views.py b/src/featurevisor/schemas/_views.py index c54d791..281868c 100644 --- a/src/featurevisor/schemas/_views.py +++ b/src/featurevisor/schemas/_views.py @@ -4,18 +4,19 @@ from typing import Any, Callable, Sequence -from ._engine import Matcher, Resolver, has_mutations, inputs_of, matching_mutations, mutated_rules +from ._engine import Matcher, Resolver, has_mutations, inputs_of, matching_mutations from ._paths import Step -def adjuster(match: Matcher) -> Callable[[Any, Any], Any]: - """Applies a node's mutations whose conditions match the value at it, in the schema's package evaluation.""" +def adjuster(match: Matcher, rules_of: Callable[[Any, str], Any]) -> Callable[[Any, Any], Any]: + """Applies a node's mutations whose conditions match the value at it, in the schema's package evaluation. + The rules come from the store, so the same matches give the same node.""" def adjust(node: Any, value: Any) -> Any: if not has_mutations(node): return node try: - return mutated_rules(node, matching_mutations(node, value, match)) + return rules_of(node, matching_mutations(node, value, match)) except Exception: # noqa: BLE001 return node @@ -89,8 +90,8 @@ def visit(current: Any, at: str, seen: Sequence[str]) -> None: return for name in ("mutations", "issues"): for entry in current.get(name) or []: - def add(path: Any) -> None: - if isinstance(path, str) and join(at, path) not in reads: + def add(path: str) -> None: + if join(at, path) not in reads: reads.append(join(at, path)) inputs_of(entry.get("conditions") if isinstance(entry, dict) else None, add) key = current.get("schema") diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 32dd28e..180d75c 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -240,6 +240,72 @@ def test_instances_share_a_featurevisor_instance_and_close_cleanly(self) -> None self.assertTrue(third.is_valid("signUp", VALID)) self.assertNotIn("duplicate_module", self.diagnostics) + def test_an_application_message_that_is_not_text_or_a_function_is_passed_over(self) -> None: + s = create_schemas(self.f, messages={"required": 5, "minLength": None}) # type: ignore[dict-item] + messages = sorted(issue.message for issue in s.validate("signUp", {"password": "x"}).issues) + self.assertEqual(messages, ["Value at \"password\" must be at least 8 characters long (got 1).", + "Value at \"username\" is required."]) + form = s.get("signUp", messages={"password": {"minLength": 5}}) # type: ignore[dict-item] + self.assertEqual(form.validate({"username": "ada", "password": "x"}).issues[0].code, "minLength") + + def test_a_field_whose_key_starts_with_a_digit_is_the_handle_at_gives(self) -> None: + f = create_featurevisor({"datafile": datafile("1", {"account": { + "hash": "a1", "type": "object", "properties": {"2fa": {"type": "boolean"}, "2024": {"type": "string"}}}}), + "logLevel": "error"}) + handle = create_schemas(f).get("account") + by_key = {field.name: field for field in handle.fields} + self.assertIs(by_key["2fa"], handle.at("2fa")) + self.assertEqual(by_key["2fa"].path, "2fa") + self.assertEqual(by_key["2024"].path, "2024") + self.assertEqual(by_key["2024"].kind, "text") + + def test_one_compiled_validator_serves_every_view_and_field_of_an_instance(self) -> None: + s = create_schemas(self.f) + store = s._store + handle = s.get("signUp") + handle.is_valid(VALID) + counts = [] + for index in range(3): + view = handle.with_input({"username": f"user-{index}"}) + view.at("username").validate("ada") + view.validate(VALID) + counts.append(len(store._compiled)) + self.assertEqual(counts[0], counts[-1]) + + def test_a_field_named_like_a_built_in_member_is_kept_when_flattening(self) -> None: + f = create_featurevisor({"datafile": datafile("1", {"closed": { + "hash": "c1", "type": "object", "properties": {"name": {"type": "string"}}, + "additionalProperties": False}}), "logLevel": "error"}) + result = create_schemas(f).validate("closed", {"constructor": 1, "__proto__": 2}) + self.assertEqual(result.flatten().field_errors.keys(), {"constructor", "__proto__"}) + + def test_compiled_validators_survive_a_datafile_that_keeps_the_schema_and_go_after_two_that_do_not_use_it(self) -> None: + from unittest import mock + from featurevisor.schemas import _store + + s = create_schemas(self.f) + store = s._store + sign_up = s.get("signUp") + with mock.patch.object(_store, "compile_node", wraps=_store.compile_node) as compiling: + sign_up.validate(VALID) + sign_up.at("username").validate("ada") + first = compiling.call_count + self.assertGreater(first, 0) + # A merge that leaves the schemas out keeps the entry objects. + self.f.set_datafile(datafile("2", {})) + sign_up.validate(VALID) + sign_up.at("username").validate("ada") + self.assertEqual(compiling.call_count, first) + # Two more changes that never touch signUp drop it. + s.validate("spaced", "a b") + self.f.set_datafile(datafile("3", {})) + s.validate("spaced", "a b") + self.f.set_datafile(datafile("4", {})) + s.validate("spaced", "a b") + entry = store.entry("signUp") + self.assertNotIn(id(entry), store._compiled) + self.assertNotIn(id(entry), store._compiled_before) + def test_validates_from_many_threads_at_once(self) -> None: sign_up = create_schemas(self.f).get("signUp") with ThreadPoolExecutor(max_workers=8) as pool: From a2ab3723971a536121067d4e79b3a64d3e66c441 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 23:22:47 +0100 Subject: [PATCH 17/21] docs: beforeEvaluation runs for a schema validation too The Modules section said beforeEvaluation and afterEvaluation run for flags, variations and both kinds of variable, while a schema validation also runs every module's beforeEvaluation, with type and key naming the schema instead of a feature key, and never runs afterEvaluation. It now says so, and to check the type before reading the keys, as the JavaScript SDK's page does. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index cccf999..280bd3e 100644 --- a/README.md +++ b/README.md @@ -619,6 +619,8 @@ audit_module = { `beforeEvaluation` and `afterEvaluation` run for flags, variations and both kinds of variable, every module in registration order, and must return the options and the evaluation, changed or not. A variable evaluation without a `featureKey` is a global one. Snake case keys, such as `before_evaluation`, work too. +`beforeEvaluation` also runs when a [schema](#schemas) validates, with `type` `schema` and the schema's `key` instead of a `featureKey`, so context it adds reaches the schema's conditions too. `afterEvaluation` does not run then, since a validation's result is not an evaluation. Check `type` before reading the keys. + The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress. If `setup` raises, the module is not registered. The SDK removes the diagnostic subscriptions it made, reports `module_setup_error`, and calls its `close` if it has one. From af7930e7903808a7f85c5798a7fddd0c73dacef1 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Mon, 30 Nov 2026 20:06:43 +0100 Subject: [PATCH 18/21] fix(schemas): follow the JavaScript release fixes A schema used twice, such as an address for billing and for shipping, lost its constraints and choices the second time, since walks stopped at any schema already seen. The port now follows the JavaScript package's release fixes. Walks guard only the current path, and kind stops on a list of itself. A missing field reports no missing schema, the message translator runs last, and required applies without properties. A value nested more than 128 references deep fails closed at the 129th, and a check that throws fails closed with schema_check_error. Every diagnostic's dedupe resets with a new datafile, no handle is kept for a key the datafile lacks, patterns compile once into a cache capped at 4096 that holds failures, and an unknown type fails every value. Both conformance fixtures are copied again from the monorepo, with 150 validation cases and an address schema used twice. The README says how a field's handle treats a missing value and when schema_check_error is reported, and gives no minimum CLI version. An integer too large for a double now fails as Infinity does rather than raising OverflowError, and a deeply nested value is read without recursion, so it no longer raises RecursionError. Caches rotate on datafile_set, a view's memo follows the context and sticky values, and the README's stale second Schemas section is gone. --- README.md | 90 +-------- conformance/schemas-datafile.json | 110 ++++++++++- conformance/schemas-validation.json | 83 ++++++++- src/featurevisor/schemas/__init__.py | 5 +- src/featurevisor/schemas/_derived.py | 32 ++-- src/featurevisor/schemas/_engine.py | 66 ++++--- src/featurevisor/schemas/_handle.py | 34 ++-- src/featurevisor/schemas/_json.py | 57 ++++-- src/featurevisor/schemas/_store.py | 78 ++++++-- tests/test_schemas_review.py | 264 +++++++++++++++++++++++++++ 10 files changed, 651 insertions(+), 168 deletions(-) create mode 100644 tests/test_schemas_review.py diff --git a/README.md b/README.md index 280bd3e..a23a487 100644 --- a/README.md +++ b/README.md @@ -697,9 +697,9 @@ if not result.valid: - A validation runs as the schema's own evaluation, so a [module](#modules)'s `beforeEvaluation` sees it, with `type` `schema` and the schema's `key`, and context the module adds reaches every condition, as it does for flags. - `s.keys()` lists the schemas the datafile has, and `s.has(key)` says whether it has one. -A value can be dictionaries, lists, strings, numbers, booleans and `None`, or a dataclass, a pydantic model, a tuple or another mapping or sequence, converted first. +A value can be dictionaries, lists, strings, numbers, booleans and `None`, or a dataclass, a pydantic model, a tuple or another mapping or sequence, converted first. A `bool` is never a number, although Python makes it an `int`, and an `int` too big for a double reads as infinity, so it fails a `number` with a `type` issue, as in JavaScript. -A key the datafile does not have fails closed, with one `schemaNotFound` issue, and a `schema_not_found` [diagnostic](#diagnostics) at `warn`, once per key. +A key the datafile does not have fails closed, with one `schemaNotFound` issue, and a `schema_not_found` [diagnostic](#diagnostics) at `warn`, once per key and datafile revision. A field a schema in the datafile lacks reports its `schemaNotFound` issue only, with no diagnostic. A `type` the package does not know fails every value with a `type` issue. ### Read the issues @@ -749,7 +749,7 @@ A handle is stable, and reads the current datafile whenever it is used, so keep | `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | | `key`, `path`, `name` | The schema's key, and the field's path and own name | -`at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. +`at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. Python has no "no value" for a field handle, since `None` is JSON null and a value, so a field validated alone is always checked as given. `required` holds the keys it lists whatever `properties` holds, so an object with only `additionalProperties`, or none of either, still reports each missing key as `required`. ### Read constraints and choices @@ -854,7 +854,7 @@ result = await sign_up.avalidate(value) - `check` gets the value at its path, and `info` with the whole `input` and the `context`. It returns `True` when the value passes, or a coroutine of it. - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database. - Without a `path`, the check gets the whole value, and runs only when the value has no issue at all. `reads` names other fields whose issues hold it back too, such as `items` for a check of an order's total. -- Its issue has code `refine` and `params["refine"]` `"nameAvailable"`, with the field's title. A check that raises gives `refineError`, and validation fails closed. +- Its issue has code `refine` and `params["refine"]` `"nameAvailable"`, with the field's title. A check that raises gives `refineError`, validation fails closed, and one `schema_check_error` diagnostic at `error` says which check of which schema, once per schema and check and datafile revision, with the exception as `originalError` and `details` of `schemaKey`, `check` and `path`. A task that is cancelled reports nothing. In a field's handle from `at`, `info.input` is the field's value, and only checks that read no other field run there. A field of a view from the schema's root, such as `with_input(values).at("city")`, gets the whole input. - `avalidate` awaits every check, running them concurrently, and returns the result, whose issues say what failed. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. ### Options from your application @@ -915,7 +915,7 @@ A datafile whose schema is unchanged calls nothing. `s.close()`, or leaving a `w ### Patterns -Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value with one `schema_pattern_unsupported` diagnostic. A mutation whose operations cannot be applied fails the value with `refineError` and one `schema_mutation_error` diagnostic, and so does a schema that follows references more than 128 deep without reading deeper into the value, with `schema_reference_depth`. +Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value with one `schema_pattern_unsupported` diagnostic. A mutation whose operations cannot be applied fails the value with `refineError` and one `schema_mutation_error` diagnostic, and a check or lookup that raises fails it with `refineError` and one `schema_check_error` diagnostic. Validation follows at most 128 references inside one another, which limits how deep a value can nest through them: a tree whose nodes each reference the tree's schema can be 128 levels deep, and the node at the 129th fails closed with `refineError` and a `schema_reference_depth` diagnostic. A loop of references at one value reaches the limit too. Each of these diagnostics is reported once per datafile revision, and again for a new one. The translator `translate` runs last, once mutations have named their issues, so it sees `issue.mutation`. A `with_input` view recomputes its members when the instance's context or sticky values change. ## Close @@ -1044,84 +1044,6 @@ An invalid initial datafile in an owned instance fails `set_provider_and_wait` w See the [OpenFeature provider guide](https://featurevisor.com/docs/sdks/openfeature/) for resolution reasons, errors, metadata, tracking, lifecycle, and providers for other languages. -## Schemas - -Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/) a datafile carries, such as a sign up form's request, with the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript. They are the `featurevisor.schemas` subpackage, installed with the SDK and needing nothing more: - -```python -from featurevisor import create_featurevisor -from featurevisor.schemas import create_schemas - -f = create_featurevisor({"datafile": datafile}) -s = create_schemas(f) - -result = s.validate("signUp", request) - -if not result.valid: - for issue in result.issues: - print(issue.field, issue.message) -``` - -A value can be dicts, lists, strings, numbers, booleans and `None`, or a dataclass, a pydantic model, a tuple or another mapping or sequence, which is converted first. A `bool` is never a number, although Python makes it an `int`. `parse` returns the value when it passes and raises a `SchemaValidationError` with the issues when it does not. `flatten()` on a result or an error groups the messages by field name, such as `displayName` or `items.0.name`, for an error response. - -Every call reads the current datafile, so a new datafile takes effect at the next validation. A context passed to `validate` is merged over the instance's, for rules that change by segment. Validation runs as the schema's evaluation, so a module's `beforeEvaluation` sees `type` `schema` and the schema's `key`, and context it adds reaches every condition, as it does for flags. - -### Handles - -`s.get("signUp")` returns a schema's handle, and `at(path)` a field's, such as `address.city` or `items[].name`. A handle describes what its rules imply for rendering a form: - -```python -sign_up = s.get("signUp") - -[field.name for field in sign_up.fields] # ["accountType", "displayName", "taxId"], in the schema's order -sign_up.at("displayName").constraints # required, min_length and max_length -sign_up.at("accountType").options # personal and business, with their titles -sign_up.at("accountType").kind # "select" -``` - -`constraints.attributes()` gives them as HTML attributes, such as `required` and `maxlength`, for a template. `with_input(values)` returns the same handle for the values a form has so far, so its members describe the rules every matching mutation sets, such as a VAT number that becomes required for a business account. - -### Messages - -Issues are worded by the form's messages, then the schema's, then the application's, then a default in English: - -```python -s = create_schemas( - f, - messages={"required": "{title} is required"}, - translate=lambda issue, info: translations.get(issue.code), -) -``` - -A message can also be a function of the params and the info. A translator returning `None` keeps the chosen message. - -### Checks in code - -Refinements check what rules cannot express, and option sources check a value against choices from the application. Both run after the rules, only where the rules found nothing: - -```python -from featurevisor.schemas import OptionSource, Refinement - -async def username_is_free(value, info): - return await users.is_free(value) - -sign_up = s.get( - "signUp", - refine=[Refinement("usernameFree", username_is_free, path="username")], - option_sources=[OptionSource("cities", "city", lookup=lambda value, info: cities.find(value))], -) - -result = await sign_up.avalidate(request) -``` - -`avalidate` awaits every check, running them concurrently, and returns the result, whose issues say what failed. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. A lookup that finds nothing reports `enum`, and a check that raises reports `refineError`. `await handle.search(query)` returns the source's suggestions. - -Handles are safe to use from many threads. `close()` on the instance, or leaving a `with create_schemas(f) as s:` block, stops its subscriptions and removes its module from the Featurevisor instance. - -### Patterns - -Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value with one `schema_pattern_unsupported` diagnostic. A mutation whose operations cannot be applied fails the value with `refineError` and one `schema_mutation_error` diagnostic, and so does a schema that follows references more than 128 deep without reading deeper into the value, with `schema_reference_depth`. - ## CLI usage Install the package in your Python environment: @@ -1130,7 +1052,7 @@ Install the package in your Python environment: python -m pip install "featurevisor>=4.0.0,<5" ``` -The native test runner requires `@featurevisor/cli` 4.0.0 or later and Node.js 24 or later. Install the Node.js CLI in your Featurevisor project: +The native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project: ```bash npm install --save-dev @featurevisor/cli@^4.0.0 diff --git a/conformance/schemas-datafile.json b/conformance/schemas-datafile.json index affb9bc..e0642b2 100644 --- a/conformance/schemas-datafile.json +++ b/conformance/schemas-datafile.json @@ -4,7 +4,7 @@ "datafile": { "schemaVersion": "4", "featurevisorVersion": "4.13.0", - "revision": "Y2jhtKdlDE", + "revision": "IvtVCaCgSZ", "segments": { "netherlands": { "conditions": "{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}" @@ -16,8 +16,28 @@ "features": {}, "variables": {}, "schemas": { + "address": { + "hash": "VGKVaf20da", + "type": "object", + "properties": { + "city": { + "type": "string", + "maxLength": 40 + }, + "country": { + "type": "string", + "enum": [ + "GB", + "NL" + ] + } + }, + "required": [ + "city" + ] + }, "checkout": { - "hash": "gSboXrZWcM", + "hash": "CrZt1Can24", "type": "object", "properties": { "billingCountry": { @@ -34,6 +54,12 @@ }, "confirmPassword": { "type": "string" + }, + "billing": { + "schema": "address" + }, + "shipping": { + "schema": "address" } }, "required": [ @@ -77,7 +103,7 @@ } }, "register": { - "hash": "XlDf9sip1o", + "hash": "FxQEbFSCyQ", "type": "object", "properties": { "password": { @@ -451,6 +477,49 @@ }, "issues": [] }, + { + "schema": "checkout", + "value": { + "billingCountry": "nl", + "billing": { + "city": "Amsterdam", + "country": "NL" + }, + "shipping": { + "country": "FR" + } + }, + "context": {}, + "issues": [ + { + "message": "Value at \"shipping.city\" is required.", + "path": [ + "shipping", + "city" + ], + "code": "required", + "params": { + "key": "city" + }, + "schema": "checkout" + }, + { + "message": "Value at \"shipping.country\" must be one of GB, NL.", + "path": [ + "shipping", + "country" + ], + "code": "enum", + "params": { + "options": [ + "GB", + "NL" + ] + }, + "schema": "checkout" + } + ] + }, { "schema": "register", "value": { @@ -756,10 +825,12 @@ "checkout": { "path": "", "fieldKeys": [ + "billing", "billingCountry", "confirmPassword", "customsDescription", "password", + "shipping", "shippingCountry" ], "constraints": { @@ -769,9 +840,38 @@ "shippingCountry": {}, "customsDescription": {}, "password": {}, - "confirmPassword": {} + "confirmPassword": {}, + "billing": {}, + "billing.city": { + "required": true, + "maxLength": 40 + }, + "billing.country": {}, + "shipping": {}, + "shipping.city": { + "required": true, + "maxLength": 40 + }, + "shipping.country": {} + }, + "options": { + "billing.country": [ + { + "value": "GB" + }, + { + "value": "NL" + } + ], + "shipping.country": [ + { + "value": "GB" + }, + { + "value": "NL" + } + ] }, - "options": {}, "kind": "object", "reads": [ "shippingCountry", diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index b5fbdcb..c16ed64 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -3716,6 +3716,45 @@ "schema_reference_depth" ] }, + { + "name": "a value nested 128 references deep passes", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "schema": "subject" + } + } + }, + "schema": "subject", + "value": [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]], + "issues": [] + }, + { + "name": "a value nested more than 128 references deep fails closed at the 129th", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "schema": "subject" + } + } + }, + "schema": "subject", + "value": [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]], + "issues": [ + { + "code": "refineError", + "path": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + "params": {} + } + ], + "diagnostics": [ + "schema_reference_depth" + ] + }, { "name": "a mutation's conditions can be JSON text", "schemas": { @@ -4115,7 +4154,7 @@ "issues": [] }, { - "name": "required without properties is ignored", + "name": "required applies to an object without properties", "schemas": { "subject": { "hash": "subject-1", @@ -4127,7 +4166,47 @@ }, "schema": "subject", "value": {}, - "issues": [] + "issues": [ + { + "code": "required", + "path": [ + "a" + ], + "params": { + "key": "a" + } + } + ] + }, + { + "name": "required applies to an object with additionalProperties only", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "additionalProperties": { + "type": "string" + }, + "required": [ + "en" + ] + } + }, + "schema": "subject", + "value": { + "nl": "Hallo" + }, + "issues": [ + { + "code": "required", + "path": [ + "en" + ], + "params": { + "key": "en" + } + } + ] }, { "name": "const skips the typed rules", diff --git a/src/featurevisor/schemas/__init__.py b/src/featurevisor/schemas/__init__.py index 83bda91..8a430e0 100644 --- a/src/featurevisor/schemas/__init__.py +++ b/src/featurevisor/schemas/__init__.py @@ -66,7 +66,10 @@ def get(self, key: str, *, messages: Mapping[str, Mapping[str, Message]] | None with self._lock: handle = self._handles.get(key) if handle is None: - handle = self._handles[key] = SchemaHandle(self, key) + handle = SchemaHandle(self, key) + # Only for a key the datafile has, so asking for keys it lacks keeps nothing. + if self._store.entry(key) is not None: + self._handles[key] = handle return handle def validate(self, key: str, value: Any, context: Mapping[str, Any] | None = None) -> ValidationResult: diff --git a/src/featurevisor/schemas/_derived.py b/src/featurevisor/schemas/_derived.py index 13af0fe..7f21c40 100644 --- a/src/featurevisor/schemas/_derived.py +++ b/src/featurevisor/schemas/_derived.py @@ -77,11 +77,15 @@ def _by_path(node: Any, resolve: Resolver, read: Callable[[Any, bool], T | None] """What read says of each field of an object by dot path, nested objects included and lists left to their rows' handles, for the fields it says something of.""" result: dict[str, T] = {} + # The objects on the way to this one, so a schema that comes back to itself stops, + # while one used by two fields, such as an address, is walked for each. + chain: list[int] = [] def collect(current: dict[str, Any], prefix: str, depth: int) -> None: properties = current.get("properties") - if not isinstance(properties, dict) or depth > 64: + if not isinstance(properties, dict) or depth > 64 or id(current) in chain: return + chain.append(id(current)) listed = current.get("required") required: list[Any] = listed if isinstance(listed, list) else [] for key, child in properties.items(): @@ -92,6 +96,7 @@ def collect(current: dict[str, Any], prefix: str, depth: int) -> None: resolved = resolve_node(child, resolve) if is_object_node(resolved): collect(resolved, path + ".", depth + 1) # type: ignore[arg-type] + chain.pop() resolved = resolve_node(node, resolve) if is_object_node(resolved): @@ -104,11 +109,14 @@ def field_constraints_of(node: Any, resolve: Resolver) -> dict[str, Constraints] return _by_path(node, resolve, lambda child, required: constraints_of(child, required, resolve)) -def _choices_of(node: Any, resolve: Resolver, branch: bool = False, depth: int = 0) -> list[SchemaOption] | None: - """A node's choices in the order its rules list them, each as its value with what the schema says about it.""" +def _choices_of(node: Any, resolve: Resolver, branch: bool = False, depth: int = 0, + chain: tuple[int, ...] = ()) -> list[SchemaOption] | None: + """A node's choices in the order its rules list them, each as its value with what the schema says about it. + `chain` holds the nodes on the way, so a loop stops while two branches naming one schema both count.""" resolved = resolve_node(node, resolve) - if resolved is None or depth > 64: + if resolved is None or depth > 64 or id(resolved) in chain: return None + chain = (*chain, id(resolved)) if isinstance(resolved.get("enum"), list): return [make_option(value, option_entry(resolved, value)) for value in resolved["enum"]] if "const" in resolved: @@ -118,7 +126,7 @@ def _choices_of(node: Any, resolve: Resolver, branch: bool = False, depth: int = listed = is_const_list(resolved, resolve) choices: list[SchemaOption] = [] for each in resolved["oneOf"]: - found = _choices_of(each, resolve, listed, depth + 1) + found = _choices_of(each, resolve, listed, depth + 1, chain) if found is None: return None for option in found: @@ -126,7 +134,7 @@ def _choices_of(node: Any, resolve: Resolver, branch: bool = False, depth: int = choices.append(option) return choices if resolved.get("type") == "array" and "items" in resolved: - return _choices_of(resolved["items"], resolve, False, depth + 1) + return _choices_of(resolved["items"], resolve, False, depth + 1, chain) return None @@ -160,22 +168,24 @@ def field_keys_of(node: Any, resolve: Resolver) -> list[str]: return first + sorted(key for key in keys if key not in first) -def kind_of_field(node: Any, resolve: Resolver, depth: int = 0) -> str | None: - """What a node's rules make a field, or None for a oneOf of shapes.""" +def kind_of_field(node: Any, resolve: Resolver, depth: int = 0, chain: tuple[int, ...] = ()) -> str | None: + """What a node's rules make a field, or None for a oneOf of shapes. `chain` holds the nodes on the way, + so a schema that comes back to itself, such as a list of such lists, stops.""" resolved = resolve_node(node, resolve) - if resolved is None or depth > 64: + if resolved is None or depth > 64 or id(resolved) in chain: return None + chain = (*chain, id(resolved)) if isinstance(resolved.get("enum"), list) or "const" in resolved or is_const_list(resolved, resolve): return "boolean" if _is_boolean_choice(_values_of(resolved, resolve)) else "select" if isinstance(resolved.get("oneOf"), list): # A nullable field is what its other branch is. rules = non_null_branch(resolved, resolve) - return kind_of_field(rules, resolve, depth + 1) if rules is not None else None + return kind_of_field(rules, resolve, depth + 1, chain) if rules is not None else None kind = resolved.get("type") if kind == "string": return {"date-time": "date-time", "semver": "version"}.get(resolved.get("format"), "text") # type: ignore[arg-type] if kind == "array": - return "multiselect" if kind_of_field(resolved.get("items"), resolve, depth + 1) == "select" else "list" + return "multiselect" if kind_of_field(resolved.get("items"), resolve, depth + 1, chain) == "select" else "list" if kind in ("integer", "number"): return "number" if kind == "boolean": diff --git a/src/featurevisor/schemas/_engine.py b/src/featurevisor/schemas/_engine.py index b1e3bf2..344ff83 100644 --- a/src/featurevisor/schemas/_engine.py +++ b/src/featurevisor/schemas/_engine.py @@ -10,7 +10,7 @@ from ..compare_versions import is_valid_version from ..conditions import get_portable_timestamp from ..mutations import apply_variable_operations -from ._json import ABSENT, is_finite_number, is_integer, is_number, is_primitive, kind_of, same, stringify +from ._json import ABSENT, is_finite_number, is_integer, is_number, is_primitive, kind_of, same, stringify, to_double from ._messages import Lookup, Scope, Sources, choose_message from ._paths import is_at_or_inside from ._patterns import compile_pattern @@ -60,10 +60,12 @@ def node(self, key: str) -> dict[str, Any] | None: ... def reference_too_deep(self, schema: str) -> None: ... def unsupported_pattern(self, pattern: str) -> None: ... def mutation_failed(self, schema: str, error: Exception) -> None: ... + def check_failed(self, schema: str, check: str, path: str, error: BaseException) -> None: ... -# References a walk follows inside one another. Only a schema that references itself -# without reading deeper into the value gets this far, so the walk fails closed there. +# The most references a validation follows inside one another, which limits how deep a value can nest +# through them: a tree whose nodes each reference the tree's schema can be 128 levels deep. A loop of +# references at one value, which lint rejects, reaches the limit too. Past it, the walk fails closed. MAX_REFERENCE_DEPTH = 128 # Issues after which an object's issues could not trust the values they compare, format among them, @@ -84,12 +86,27 @@ def report(run: Run, at: Position, code: str, params: dict[str, Any], own: str | if lookup.title is not None: params = {**params, "title": lookup.title} message = choose_message(code, params, at.path, lookup, run.sources, own) - issue = SchemaIssue(message, tuple(at.path), code, params, run.schema) - if run.translate is not None: - translated = run.translate(issue, run.sources.info) - if isinstance(translated, str): - issue = replace(issue, message=translated) - run.issues.append(issue) + run.issues.append(SchemaIssue(message, tuple(at.path), code, params, run.schema)) + + +def translate_issues(run: Run, start: int = 0) -> None: + """Hands each issue from an index on to the instance's translator, the last step of its wording, + once mutations have named theirs, so a translator sees `mutation` too.""" + translate = run.translate + if translate is None: + return + for index in range(start, len(run.issues)): + issue = run.issues[index] + message = translate(issue, run.sources.info) + if isinstance(message, str): + run.issues[index] = replace(issue, message=message) + + +def missing_field(path: Sequence[Any], mpath: Sequence[str], scopes: Sequence[Scope], field_node: Any, + resolve: Resolver) -> Position: + """Where a missing field's issue sits: at the field, worded by the messages for that field, with its title.""" + return Position(list(path), Lookup(list(mpath), own_scopes(field_node, len(mpath), resolve, list(scopes)), + title_of(field_node, resolve))) def annotations_of(node: Any, resolve: Resolver, seen: set[str] | None = None) -> dict[str, Any] | None: @@ -284,9 +301,9 @@ def _compile_number(node: dict[str, Any]) -> Validator: maximum = _number_keyword(node, "maximum") def validate(value: Any, run: Run, at: Position) -> None: - if minimum is not None and float(value) < float(minimum): + if minimum is not None and to_double(value) < to_double(minimum): report(run, at, "minimum", {"minimum": minimum, "value": value}) - if maximum is not None and float(value) > float(maximum): + if maximum is not None and to_double(value) > to_double(maximum): report(run, at, "maximum", {"maximum": maximum, "value": value}) return validate @@ -331,15 +348,13 @@ def _compile_object(node: dict[str, Any], resolve: Resolver) -> Validator: closed = has_additional and additional is not True and compiled_additional is None def validate(value: Any, run: Run, at: Position) -> None: - if properties is not None: - for key in required: - if key in value: - continue - # A missing key's issue is at the key, worded by the messages for that field, with its title. - mpath = [*at.lookup.mpath, key] - scopes = own_scopes(properties.get(key), len(mpath), resolve, list(at.lookup.scopes)) - report(run, Position([*at.path, key], Lookup(mpath, scopes, title_of(properties.get(key), resolve))), - "required", {"key": key}) + # Each key `required` lists must be there, whatever `properties` holds. + for key in required: + if key in value: + continue + # A missing key's issue is at the key, worded by the messages for that field, with its title. + report(run, missing_field([*at.path, key], [*at.lookup.mpath, key], at.lookup.scopes, + (properties or {}).get(key), resolve), "required", {"key": key}) for key, child in value.items(): if key in compiled: compiled[key](child, run, Position([*at.path, key], Lookup([*at.lookup.mpath, key], at.lookup.scopes))) @@ -359,6 +374,10 @@ def validate(value: Any, run: Run, at: Position) -> None: return validate +def _no_value(_value: Any) -> bool: + return False + + _TYPE_CHECKS: dict[str, Callable[[Any], bool]] = { "string": lambda value: isinstance(value, str), "integer": is_integer, @@ -417,8 +436,11 @@ def validate_enum(value: Any, run: Run, at: Position) -> None: def _compile_typed(node: dict[str, Any], resolve: Resolver) -> Validator: """A node's rules by its type: the type itself, then the keywords that type takes.""" - kind = node.get("type") if isinstance(node.get("type"), str) else None - check = _TYPE_CHECKS.get(kind) if kind else None + kind = node.get("type") + check = _TYPE_CHECKS.get(kind) if isinstance(kind, str) else None + if "type" in node and check is None: + # A type it does not know, such as `null`, fails every value. + check = _no_value # With a type, only its own keywords can apply, so only they are compiled. string = _compile_string(node, resolve) if kind in (None, "string") else None number = _compile_number(node) if kind in (None, "integer", "number") else None diff --git a/src/featurevisor/schemas/_handle.py b/src/featurevisor/schemas/_handle.py index 8ce4156..85a31c7 100644 --- a/src/featurevisor/schemas/_handle.py +++ b/src/featurevisor/schemas/_handle.py @@ -10,7 +10,7 @@ from ._derived import (constraints_of, field_constraints_of, field_keys_of, field_options_of, kind_of_field, options_of) -from ._engine import Position, Run, Validator, annotations_of, report, title_of +from ._engine import Position, Run, Validator, annotations_of, report, title_of, translate_issues from ._json import plain, same from ._messages import Lookup, Sources, form_messages from ._paths import ITEMS, Step, format_steps, is_at_or_inside, matches_steps, parse_path, reads_as_key, steps_of @@ -35,6 +35,7 @@ class _Check: key: str message: str | None kind: str + path: str steps: Sequence[Step] reads: Sequence[Sequence[Step]] run: Callable[[Any, CheckInfo], Any] @@ -96,7 +97,7 @@ def __init__(self, schemas: Schemas, key: str, options: Mapping[str, Any] | None self._lock = threading.Lock() self._handles: dict[str, SchemaHandle] = {} self._located: tuple[Any, Any, Lookup] | None = None - self._memo: tuple[Any, str, dict[str, Any]] | None = None + self._memo: tuple[Any, str, int | None, dict[str, Any]] | None = None @property def _store(self): @@ -133,7 +134,8 @@ def validate(self, value: Any, context: Mapping[str, Any] | None = None) -> Vali if hasattr(answer, "close"): answer.close() raise RuntimeError("A check that answers later cannot be waited for here") - except Exception: # noqa: BLE001 + except Exception as broken: # noqa: BLE001 + self._store.check_failed(self.key, check.key, check.path, broken) issues += self._report_check(run, located, "refineError", check, path) continue if not self._passes(check, answer): @@ -166,6 +168,8 @@ async def answer(check: _Check, target: Any) -> Any: if isinstance(outcome, asyncio.CancelledError): raise outcome if isinstance(outcome, BaseException): + if isinstance(outcome, Exception): + self._store.check_failed(self.key, check.key, check.path, outcome) issues += self._report_check(run, located, "refineError", check, path) elif not self._passes(check, outcome): issues += self._report_check(run, located, "refine" if check.kind == "refine" else "enum", check, path) @@ -236,13 +240,18 @@ def _locate(self, value: Any, run: Run) -> tuple[Validator, Any, Lookup] | None: def _apply_rules(self, value: Any, run: Run) -> tuple[Validator, Any, Lookup] | None: located = self._locate(value, run) if located is None: - self._store.report_missing(self.key) + # A field the schema lacks is not a schema the datafile lacks. + if self._store.entry(self.key) is None: + self._store.report_missing(self.key) params: dict[str, Any] = {"schema": self.key} if self._steps: params["field"] = self.path report(run, Position([], Lookup([])), "schemaNotFound", params) + translate_issues(run) return None located[0](value, run, Position([], located[2])) + # Last, once mutations have named their issues. + translate_issues(run) return located def _in_root_view(self) -> bool: @@ -256,14 +265,14 @@ def add(key: str, message: str | None, kind: str, path: str, reads: Sequence[str owner_steps = parse_path(path) parsed_reads = [parse_path(read) for read in reads] if not self._steps: - checks.append(_Check(key, message, kind, owner_steps, parsed_reads, run)) + checks.append(_Check(key, message, kind, path, owner_steps, parsed_reads, run)) return # A field's handle carries the checks at or inside it. One that reads other # fields needs the whole input, which only a view from the schema's root holds. if (parsed_reads and not self._in_root_view()) or len(owner_steps) < len(self._steps): return if all(_reaches(owner_steps[index], own) for index, own in enumerate(self._steps)): - checks.append(_Check(key, message, kind, owner_steps[len(self._steps):], parsed_reads, run)) + checks.append(_Check(key, message, kind, path, owner_steps[len(self._steps):], parsed_reads, run)) for source in self._options.get("option_sources") or (): if source.lookup is not None: @@ -311,6 +320,7 @@ def _report_check(self, run: Run, located, code: str, check: _Check, path: list[ params = {"refine": check.key} if check.kind == "refine" else {"optionSource": check.key} reporting = Run(run.schema, run.sources, run.translate, run.match) report(reporting, Position(path, found), code, params, None if code == "refineError" else check.message) + translate_issues(reporting) return reporting.issues # Fields @@ -367,16 +377,18 @@ def _derive(self, kind: str, make: Callable[[Any, bool], Any], otherwise: Any) - return otherwise version = store.version(self.key) revision = store.api["get_revision"]() + # A view's is kept until the context or sticky values change too, since its mutations' conditions read them. + context = store.context_version() if self._view is not None else None with self._lock: memo = self._memo - if memo is not None and memo[0] == version and memo[1] == revision and kind in memo[2]: - return memo[2][kind] + if memo is not None and memo[:3] == (version, revision, context) and kind in memo[3]: + return memo[3][kind] described = self._describe(self._view) made = make(described[0] if described else None, described[1] if described else False) with self._lock: - if self._memo is None or self._memo[0] != version or self._memo[1] != revision: - self._memo = (version, revision, {}) - self._memo[2][kind] = made + if self._memo is None or self._memo[:3] != (version, revision, context): + self._memo = (version, revision, context, {}) + self._memo[3][kind] = made return made @property diff --git a/src/featurevisor/schemas/_json.py b/src/featurevisor/schemas/_json.py index 008d502..803d875 100644 --- a/src/featurevisor/schemas/_json.py +++ b/src/featurevisor/schemas/_json.py @@ -5,6 +5,7 @@ import dataclasses import json import math +from decimal import Decimal from collections.abc import Mapping, Sequence from typing import Any @@ -12,13 +13,25 @@ ABSENT = MISSING +# How deep `plain` converts, and `_is_plain` looks. +_MAX_DEPTH = 256 + def is_number(value: Any) -> bool: return isinstance(value, (int, float)) and not isinstance(value, bool) +def to_double(value: Any) -> float: + """A number as a double. An int too big for one is Infinity, as JavaScript reads it.""" + try: + return float(value) + except OverflowError: + return math.inf if value > 0 else -math.inf + + def is_finite_number(value: Any) -> bool: - return is_number(value) and math.isfinite(value) + """A number that is not NaN or infinite. An int that does not fit a double reads as Infinity.""" + return is_number(value) and math.isfinite(to_double(value)) def is_integer(value: Any) -> bool: @@ -39,7 +52,7 @@ def same(first: Any, second: Any) -> bool: if isinstance(first, bool) or isinstance(second, bool): return isinstance(first, bool) and isinstance(second, bool) and first == second if is_number(first) and is_number(second): - return float(first) == float(second) + return to_double(first) == to_double(second) if isinstance(first, str) and isinstance(second, str): return first == second if isinstance(first, list) and isinstance(second, list): @@ -62,7 +75,7 @@ def kind_of(value: Any) -> str: if isinstance(value, str): return "string" if is_number(value): - number = float(value) + number = to_double(value) if math.isnan(number): return "NaN" if math.isinf(number): @@ -77,7 +90,7 @@ def plain(value: Any, depth: int = 0) -> Any: pydantic models are converted, and anything else kept, so an issue names its kind.""" if value is None or isinstance(value, (str, bool, int, float)): return value - if depth > 256: + if depth > _MAX_DEPTH: return value if isinstance(value, dict): if all(isinstance(key, str) for key in value) and all(_is_plain(item) for item in value.values()): @@ -100,18 +113,33 @@ def plain(value: Any, depth: int = 0) -> Any: def _is_plain(value: Any) -> bool: - if value is None or isinstance(value, (str, bool, int, float)): - return True - if isinstance(value, dict): - return all(isinstance(key, str) for key in value) and all(_is_plain(item) for item in value.values()) - if isinstance(value, list): - return all(_is_plain(item) for item in value) - return False + """Whether a value is JSON as decoded all the way down. It walks with its own stack, so a deep value + cannot raise RecursionError, reads a container once however often it is shared, and stops looking + past the depth `plain` stops converting at.""" + stack: list[tuple[Any, int]] = [(value, 0)] + seen: set[int] = set() + while stack: + current, depth = stack.pop() + if current is None or isinstance(current, (str, bool, int, float)): + continue + if isinstance(current, dict): + if not all(isinstance(key, str) for key in current): + return False + children: Any = current.values() + elif isinstance(current, list): + children = current + else: + return False + if depth > _MAX_DEPTH or id(current) in seen: + continue + seen.add(id(current)) + stack.extend((child, depth + 1) for child in children) + return True def number_text(value: Any) -> str: """A number as JavaScript writes it: 2 for 2.0, 0.0001, 1e+21.""" - number = float(value) + number = to_double(value) if math.isnan(number): return "NaN" if math.isinf(number): @@ -131,7 +159,8 @@ def number_text(value: Any) -> str: return str(int(number)) text = repr(number) if "e" in text: - text = f"{number:.17f}".rstrip("0").rstrip(".") + # Positional digits of the shortest round trip text, as JavaScript writes 0.000012345678901234567. + text = format(Decimal(text), "f") return text @@ -142,7 +171,7 @@ def stringify(value: Any) -> str: if isinstance(value, bool): return "true" if value else "false" if is_number(value): - return number_text(value) if math.isfinite(value) else "null" + return number_text(value) if is_finite_number(value) else "null" if isinstance(value, str): return json.dumps(value, ensure_ascii=False) if isinstance(value, list): diff --git a/src/featurevisor/schemas/_store.py b/src/featurevisor/schemas/_store.py index a6bf56c..5fc8d4c 100644 --- a/src/featurevisor/schemas/_store.py +++ b/src/featurevisor/schemas/_store.py @@ -9,7 +9,7 @@ from typing import Any, Callable, Sequence from ..modules import FeaturevisorModule -from ._engine import Resolver, Validator, compile_node, matched_of, mutated_rules +from ._engine import MAX_REFERENCE_DEPTH, Resolver, Validator, compile_node, matched_of, mutated_rules from ._messages import Scope from ._paths import Step @@ -40,8 +40,12 @@ def __init__(self, f: Any) -> None: self._compiled_before: dict[int, tuple[Any, Validator]] = {} self._mutated: dict[tuple[int, str], tuple[Any, dict[str, Any]]] = {} self._mutated_before: dict[tuple[int, str], tuple[Any, dict[str, Any]]] = {} + # What was reported for the datafile of this revision, dropped for a new one. self._revision: Any = None self._reported: set[str] = set() + self._context_changes = 0 + self._watching = False + self._stops: list[Callable[[], None]] = [] api: dict[str, Any] = {} with _named_lock: takes_name = f not in _named @@ -61,8 +65,13 @@ def __init__(self, f: Any) -> None: self.close() raise RuntimeError("featurevisor.schemas needs a featurevisor whose modules can read datafile sections.") self.api = api + # A new datafile starts the compiled maps again, whether or not its revision changed. + self._stops.append(f.on("datafile_set", lambda _details: self._rotate())) def close(self) -> None: + for stop in self._stops: + stop() + self._stops.clear() if self._remove is not None: self._remove() self._remove = None @@ -97,17 +106,29 @@ def resolve(self, key: str) -> tuple[dict[str, Any], Validator] | None: return None return node, self.compile(node) - def _fresh(self) -> None: - revision = self.api["get_revision"]() - if revision != self._revision: - with self._lock: - self._compiled_before, self._compiled = self._compiled, {} - self._mutated_before, self._mutated = self._mutated, {} - self._revision = revision + def _rotate(self) -> None: + """Makes the current maps the previous ones, on every datafile_set, so repeated sets of one revision + keep the cache bounded too.""" + with self._lock: + self._compiled_before, self._compiled = self._compiled, {} + self._mutated_before, self._mutated = self._mutated, {} + + def context_version(self) -> int: + """A number that changes when the instance's context or sticky values do, which a view's conditions + read. It listens from the first call on, so an instance without a view is never watched.""" + with self._lock: + watching, self._watching = self._watching, True + if not watching: + for event in ("context_set", "sticky_features_set", "sticky_variables_set"): + self._stops.append(self.f.on(event, lambda _details: self._context_changed())) + return self._context_changes + + def _context_changed(self) -> None: + with self._lock: + self._context_changes += 1 def compile(self, node: dict[str, Any]) -> Validator: """A node's validator, compiled once for this instance, however many handles and views reach it.""" - self._fresh() with self._lock: cached = self._compiled.get(id(node)) or self._compiled_before.get(id(node)) if cached is not None and cached[0] is node: @@ -120,7 +141,6 @@ def compile(self, node: dict[str, Any]) -> Validator: def mutated_rules(self, node: dict[str, Any], mutation_id: str) -> dict[str, Any]: """A node's rules with the mutations an id names applied, the same object for the same id.""" - self._fresh() key = (id(node), mutation_id) with self._lock: cached = self._mutated.get(key) or self._mutated_before.get(key) @@ -142,14 +162,19 @@ def evaluate(self, schema: str, context: dict[str, Any] | None, callback: Callab ) def _once(self, key: str) -> bool: + """Whether a diagnostic is new for the datafile of this revision, which forgets the earlier ones.""" + revision = self.api["get_revision"]() with self._lock: + if revision != self._revision: + self._revision = revision + self._reported.clear() if key in self._reported: return False self._reported.add(key) return True def unsupported_pattern(self, pattern: str) -> None: - if self._once("pattern " + pattern): + if self._once(json.dumps(["pattern", pattern])): self.api["report_diagnostic"]({ "level": "error", "code": "schema_pattern_unsupported", "message": f"Pattern {json.dumps(pattern)} does not compile in Python, so it fails every value.", @@ -157,7 +182,7 @@ def unsupported_pattern(self, pattern: str) -> None: }) def mutation_failed(self, schema: str, error: Exception) -> None: - if self._once("mutation " + schema): + if self._once(json.dumps(["mutation", schema])): self.api["report_diagnostic"]({ "level": "error", "code": "schema_mutation_error", "message": f"A mutation of schema {json.dumps(schema)} cannot be applied, so the rules it changes fail every value.", @@ -165,17 +190,28 @@ def mutation_failed(self, schema: str, error: Exception) -> None: }) def reference_too_deep(self, schema: str) -> None: - if self._once("depth " + schema): + if self._once(json.dumps(["depth", schema])): self.api["report_diagnostic"]({ "level": "error", "code": "schema_reference_depth", - "message": f"Schema {json.dumps(schema)} follows references more than 128 deep, so it fails the value. " - "A schema that references itself must read deeper into the value each time.", + "message": f"Schema {_quote(schema)} fails the value closed, since the value is nested more than " + f"{MAX_REFERENCE_DEPTH} references deep.", "details": {"schemaKey": schema}, }) + def check_failed(self, schema: str, check: str, path: str, error: BaseException) -> None: + """A check in code or an option source's lookup that threw or rejected, once per schema and check.""" + if self._once(json.dumps(["check", schema, check])): + self.api["report_diagnostic"]({ + "level": "error", "code": "schema_check_error", + "message": f"Check {_quote(check)} of schema {_quote(schema)} threw or rejected, " + "so the value it checks fails closed.", + "details": {"schemaKey": schema, "check": check, "path": path}, + "originalError": error, + }) + def report_missing(self, key: str) -> None: - """Reports schema_not_found once per key.""" - if self._once("missing " + key): + """Reports schema_not_found once per key and datafile revision.""" + if self._once(json.dumps(["missing", key])): self.api["report_diagnostic"]({ "level": "warn", "code": "schema_not_found", "message": f'Schema "{key}" is not in the datafile. Check that a target delivers it.', @@ -183,6 +219,11 @@ def report_missing(self, key: str) -> None: }) +def _quote(text: str) -> str: + """Text in double quotes as JavaScript's JSON.stringify writes it.""" + return json.dumps(text, ensure_ascii=False) + + # The node of an array without items, which holds strings, shared so that caches by node hit for its items. # Nothing writes to a located node. STRING_ITEMS: dict[str, Any] = {"type": "string"} @@ -245,10 +286,11 @@ def locate(resolve: Resolver, root: Any, steps: Sequence[Step], mpath: Sequence[ required = False if step.kind == "key": properties = resolved.get("properties") + # A key `required` lists is required whatever `properties` holds. + required = isinstance(resolved.get("required"), list) and step.key in resolved["required"] if isinstance(properties, dict) and step.key in properties: node = properties[step.key] mpath.append(step.key) - required = isinstance(resolved.get("required"), list) and step.key in resolved["required"] elif isinstance(resolved.get("additionalProperties"), dict): node = resolved["additionalProperties"] mpath.append("*") diff --git a/tests/test_schemas_review.py b/tests/test_schemas_review.py new file mode 100644 index 0000000..6c95682 --- /dev/null +++ b/tests/test_schemas_review.py @@ -0,0 +1,264 @@ +import asyncio +import unittest + +from featurevisor import create_featurevisor +from featurevisor.schemas import Refinement, create_schemas +from featurevisor.schemas._json import number_text + + +def datafile(revision, schemas, segments=None): + return {"schemaVersion": "4", "revision": revision, "segments": segments or {}, "features": {}, + "variables": {}, "schemas": schemas} + + +def make(schemas, revision="1", **options): + diagnostics = [] + f = create_featurevisor({"datafile": datafile(revision, schemas), "logLevel": "warn", + "onDiagnostic": diagnostics.append, **options}) + return f, diagnostics + + +ADDRESS = {"type": "object", "properties": {"city": {"type": "string", "minLength": 2}, "country": {"enum": ["nl", "de"]}}, + "required": ["city"]} + + +class ReleaseReviewTests(unittest.TestCase): + def test_a_schema_used_twice_keeps_its_constraints_and_choices_in_both_places(self) -> None: + f, _ = make({ + "address": ADDRESS, + "checkout": {"type": "object", "properties": {"billing": {"schema": "address"}, "shipping": {"schema": "address"}}}, + "pick": {"oneOf": [{"schema": "colours"}, {"schema": "colours"}]}, + "colours": {"enum": ["red", "blue"]}, + }) + s = create_schemas(f) + constraints = s.get("checkout").field_constraints + self.assertEqual(constraints["billing.city"].min_length, 2) + self.assertEqual(constraints["shipping.city"].min_length, 2) + self.assertTrue(constraints["shipping.city"].required) + options = s.get("checkout").field_options + self.assertEqual([o.value for o in options["shipping.country"]], ["nl", "de"]) + self.assertEqual([o.value for o in s.get("pick").options], ["red", "blue"]) + + def test_kind_stops_on_a_list_of_itself(self) -> None: + f, _ = make({"tree": {"type": "array", "items": {"schema": "tree"}}, + "holder": {"type": "object", "properties": {"rows": {"schema": "tree"}}}}) + s = create_schemas(f) + self.assertEqual(s.get("tree").kind, "list") + self.assertEqual(s.get("holder").at("rows").kind, "list") + self.assertEqual(s.get("tree").with_input([]).kind, "list") + + def test_a_missing_field_is_not_a_missing_schema(self) -> None: + f, diagnostics = make({"a": {"type": "object", "properties": {"x": {"type": "string"}}}}) + s = create_schemas(f) + result = s.get("a").at("nope").validate("v") + self.assertEqual([i.code for i in result.issues], ["schemaNotFound"]) + self.assertEqual(result.issues[0].params, {"schema": "a", "field": "nope"}) + self.assertEqual([d["code"] for d in diagnostics], []) + s.validate("gone", 1) + s.validate("gone", 1) + self.assertEqual([d["code"] for d in diagnostics], ["schema_not_found"]) + + def test_no_handle_is_kept_for_a_key_the_datafile_lacks(self) -> None: + f, _ = make({"a": {"type": "string"}}) + s = create_schemas(f) + for index in range(20): + s.get(f"missing-{index}") + s.get("a") + self.assertEqual(list(s._handles), ["a"]) + self.assertIs(s.get("a"), s.get("a")) + + def test_the_translator_runs_last_and_sees_the_mutation(self) -> None: + seen = [] + + def translate(issue, info): + seen.append((issue.code, issue.mutation)) + return f"translated {issue.mutation}" + + schema = {"type": "object", "properties": {"n": {"type": "integer"}}, + "mutations": [{"key": "strict", "conditions": [{"attribute": "country", "operator": "equals", "value": "nl"}], + "operations": [{"op": "set", "path": ["properties", "n", "minimum"], "value": 10}]}]} + f, _ = make({"s": schema}, context={"country": "nl"}) + s = create_schemas(f, translate=translate) + result = s.validate("s", {"n": 1}) + self.assertEqual(seen, [("minimum", "strict")]) + self.assertEqual(result.issues[0].message, "translated strict") + + def test_an_unknown_type_fails_every_value(self) -> None: + f, _ = make({"a": {"type": "null"}, "b": {"type": "constructor"}}) + s = create_schemas(f) + for key in ("a", "b"): + for value in (None, 1, "x", {}, []): + self.assertEqual([i.code for i in s.validate(key, value).issues], ["type"], (key, value)) + + def test_required_holds_whatever_properties_holds(self) -> None: + f, _ = make({"a": {"type": "object", "required": ["k"], "additionalProperties": {"type": "string"}}, + "b": {"type": "object", "required": ["k"]}}) + s = create_schemas(f) + for key in ("a", "b"): + issue = s.validate(key, {}).issues[0] + self.assertEqual((issue.code, issue.path, issue.params), ("required", ("k",), {"key": "k"}), key) + self.assertTrue(s.get("a").at("k").constraints.required) + + def test_the_nesting_limit_message(self) -> None: + f, diagnostics = make({"node": {"type": "object", "properties": {"next": {"schema": "node"}}}}) + s = create_schemas(f) + value: dict = {} + cursor = value + for _ in range(140): + cursor["next"] = {} + cursor = cursor["next"] + result = s.validate("node", value) + self.assertEqual([i.code for i in result.issues], ["refineError"]) + self.assertEqual(diagnostics[0]["code"], "schema_reference_depth") + self.assertEqual(diagnostics[0]["message"], + 'Schema "node" fails the value closed, since the value is nested more than 128 references deep.') + + def test_a_check_that_raises_reports_once_per_schema_and_check_and_revision(self) -> None: + def broken(value, info): + raise ValueError("no") + + schema = {"type": "object", "properties": {"n": {"type": "string"}}} + f, diagnostics = make({"s": schema}) + s = create_schemas(f) + handle = s.get("s", refine=[Refinement("taken", broken, path="n")]) + for _ in range(2): + result = handle.validate({"n": "x"}) + self.assertEqual([i.code for i in result.issues], ["refineError"]) + found = [d for d in diagnostics if d["code"] == "schema_check_error"] + self.assertEqual(len(found), 1) + self.assertEqual(found[0]["level"], "error") + self.assertEqual(found[0]["message"], + 'Check "taken" of schema "s" threw or rejected, so the value it checks fails closed.') + self.assertEqual(found[0]["details"], {"schemaKey": "s", "check": "taken", "path": "n"}) + self.assertIsInstance(found[0]["originalError"], ValueError) + + async def rejects(value, info): + raise ValueError("later") + + later = s.get("s", refine=[Refinement("later", rejects, path="n")]) + asyncio.run(later.avalidate({"n": "x"})) + asyncio.run(later.avalidate({"n": "x"})) + self.assertEqual(len([d for d in diagnostics if d["code"] == "schema_check_error"]), 2) + + # A new revision reports again. + f.set_datafile(datafile("2", {"s": schema}), True) + handle.validate({"n": "x"}) + self.assertEqual(len([d for d in diagnostics if d["code"] == "schema_check_error"]), 3) + + def test_a_cancelled_check_reports_nothing(self) -> None: + async def slow(value, info): + await asyncio.sleep(10) + return True + + f, diagnostics = make({"s": {"type": "object", "properties": {"n": {"type": "string"}}}}) + handle = create_schemas(f).get("s", refine=[Refinement("slow", slow, path="n")]) + + async def run(): + task = asyncio.ensure_future(handle.avalidate({"n": "x"})) + await asyncio.sleep(0.05) + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + + asyncio.run(run()) + self.assertEqual([d for d in diagnostics if d["code"] == "schema_check_error"], []) + + def test_dedupe_sets_reset_when_the_revision_changes(self) -> None: + schemas = {"p": {"type": "string", "pattern": "(?a)"}} + f, diagnostics = make(schemas) + s = create_schemas(f) + s.validate("p", "a") + s.validate("p", "a") + s.validate("gone", 1) + s.validate("gone", 1) + self.assertEqual(sorted(d["code"] for d in diagnostics), ["schema_not_found", "schema_pattern_unsupported"]) + f.set_datafile(datafile("1", schemas), True) + s.validate("p", "a") + self.assertEqual(len(diagnostics), 2) + f.set_datafile(datafile("2", schemas), True) + s.validate("p", "a") + s.validate("gone", 1) + self.assertEqual(len(diagnostics), 4) + + def test_a_view_follows_context_and_sticky_values(self) -> None: + schema = {"type": "object", "properties": {"tax": {"type": "string", "minLength": 1}}, + "mutations": [{"key": "dutch", "conditions": [{"attribute": "country", "operator": "equals", "value": "nl"}], + "operations": [{"op": "set", "path": ["properties", "tax", "minLength"], "value": 9}]}]} + f, _ = make({"s": schema}, context={"country": "de"}) + view = create_schemas(f).get("s").with_input({}) + self.assertEqual(view.at("tax").constraints.min_length, 1) + f.set_context({"country": "nl"}) + self.assertEqual(view.at("tax").constraints.min_length, 9) + f.set_context({"country": "de"}) + self.assertEqual(view.at("tax").constraints.min_length, 1) + + def test_huge_integers_read_as_infinity(self) -> None: + f, _ = make({"n": {"type": "number"}, "i": {"type": "integer"}, "any": {"maximum": 5}}) + s = create_schemas(f) + for key in ("n", "i"): + for value in (10**400, -(10**400)): + result = s.validate(key, value) + self.assertEqual([i.code for i in result.issues], ["type"]) + self.assertIn("Infinity", s.validate("n", 10**400).issues[0].message) + self.assertEqual([i.code for i in s.validate("any", 10**400).issues], ["maximum"]) + self.assertTrue(s.validate("n", 10**300).valid) + + def test_a_deep_value_validates_without_raising(self) -> None: + f, _ = make({"o": {"type": "object"}, "a": {"type": "array"}, + "tree": {"type": "object", "properties": {"next": {"schema": "tree"}}}}) + s = create_schemas(f) + for size in (400, 600, 5000): + value: dict = {} + cursor = value + for _ in range(size): + cursor["a"] = {} + cursor = cursor["a"] + self.assertEqual([i.code for i in s.validate("o", value).issues], ["type"]) + deep: list = [] + for _ in range(size): + deep = [deep] + self.assertEqual([i.code for i in s.validate("a", deep).issues], ["type"]) + nested: dict = {} + cursor = nested + for _ in range(size): + cursor["next"] = {} + cursor = cursor["next"] + self.assertEqual([i.code for i in s.validate("tree", nested).issues], ["refineError"]) + cyclic: list = [] + cyclic.append(cyclic) + cyclic.append(cyclic) + s.validate("a", cyclic) + + def test_repeated_sets_of_one_revision_keep_the_compiled_cache_bounded(self) -> None: + schemas = {"s": {"type": "object", "properties": {"n": {"type": "integer"}}}} + f, _ = make(schemas) + s = create_schemas(f) + s.validate("s", {"n": 1}) + for _ in range(50): + f.set_datafile(datafile("1", schemas), True) + s.validate("s", {"n": 1}) + store = s._store + self.assertLessEqual(len(store._compiled) + len(store._compiled_before), 8) + + def test_small_floats_are_written_as_javascript_writes_them(self) -> None: + self.assertEqual(number_text(1.2345e-5), "0.000012345") + self.assertEqual(number_text(0.00001), "0.00001") + self.assertEqual(number_text(0.000001), "0.000001") + self.assertEqual(number_text(1.5e-7), "1.5e-7") + + def test_the_pattern_cache_holds_failures_and_stops_at_4096(self) -> None: + from featurevisor.schemas import _patterns + + _patterns._cache.clear() + for index in range(5000): + _patterns.compile_pattern(f"^x{index}$") + _patterns.compile_pattern("(?a)") + self.assertLessEqual(len(_patterns._cache), 4096) + _patterns._cache.clear() + _patterns.compile_pattern("(?a)") + self.assertIn("(?a)", _patterns._cache) + self.assertIsNone(_patterns._cache["(?a)"]) + + +if __name__ == "__main__": + unittest.main() From 9047d800287732875260b268dbc2939edcd237db Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Mon, 30 Nov 2026 21:05:19 +0100 Subject: [PATCH 19/21] refactor(schemas): a field's handle comes from field(path), not at(path) Test specs already use at for a bucket position, and schema specs may need it too once their conditions read rollouts, so at(path) on a handle read as one more meaning of the same word. The port follows the JavaScript package: field(path) pairs with fields and is what the docs call the result, a field's handle. Nothing is released yet, so the rename needs no deprecation. The README's Schemas section, the tests and the comments say field now. --- README.md | 20 ++++++++++---------- src/featurevisor/schemas/_handle.py | 6 +++--- src/featurevisor/schemas/_paths.py | 2 +- src/featurevisor/schemas/_views.py | 2 +- tests/test_schemas.py | 24 ++++++++++++------------ tests/test_schemas_conformance.py | 6 +++--- tests/test_schemas_review.py | 12 ++++++------ 7 files changed, 36 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index a23a487..cc3dfff 100644 --- a/README.md +++ b/README.md @@ -738,7 +738,7 @@ A handle is stable, and reads the current datafile whenever it is used, so keep | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | `validate`, `is_valid`, `parse` | As on `s`, without the key | | `avalidate` | Validation awaiting your [checks in code](#check-in-code) | -| `at(path)` | The handle of one field, such as `at("displayName")` | +| `field(path)` | The handle of one field, such as `field("displayName")` | | `fields` | An object's fields' handles, in [order](#read-annotations), each with its `name` | | `constraints`, `field_constraints` | HTML validation attributes, `field_constraints` by field path on an object, [below](#read-constraints-and-choices) | | `options`, `field_options`, `option(value)` | Its choices, `field_options` by field path on an object, and one choice by value | @@ -749,17 +749,17 @@ A handle is stable, and reads the current datafile whenever it is used, so keep | `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | | `key`, `path`, `name` | The schema's key, and the field's path and own name | -`at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. Python has no "no value" for a field handle, since `None` is JSON null and a value, so a field validated alone is always checked as given. `required` holds the keys it lists whatever `properties` holds, so an object with only `additionalProperties`, or none of either, still reports each missing key as `required`. +`field` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. Python has no "no value" for a field handle, since `None` is JSON null and a value, so a field validated alone is always checked as given. `required` holds the keys it lists whatever `properties` holds, so an object with only `additionalProperties`, or none of either, still reports each missing key as `required`. ### Read constraints and choices `constraints` are named after HTML attributes: ```python -sign_up.at("displayName").constraints +sign_up.field("displayName").constraints # Constraints(required=True, min_length=2, max_length=40) -sign_up.at("displayName").constraints.attributes() +sign_up.field("displayName").constraints.attributes() # {"required": True, "minlength": 2, "maxlength": 40}, for a template ``` @@ -772,7 +772,7 @@ sign_up.at("displayName").constraints.attributes() `options` lists a field's choices in the order of its rules, each with what its [annotations](https://featurevisor.com/docs/schemas/#label-the-choices) say, and `option(value)` finds one, for showing a value saved earlier: ```python -country = sign_up.at("country") +country = sign_up.field("country") country.options # nl, de and be, each a SchemaOption country.option("nl").title # "Netherlands" @@ -804,8 +804,8 @@ values = { "country": "nl", } -sign_up.at("taxId").constraints.required # False -sign_up.with_input(values).at("taxId").constraints.required # True +sign_up.field("taxId").constraints.required # False +sign_up.with_input(values).field("taxId").constraints.required # True ``` Every member follows the input, at every depth. `reads` lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes. @@ -854,7 +854,7 @@ result = await sign_up.avalidate(value) - `check` gets the value at its path, and `info` with the whole `input` and the `context`. It returns `True` when the value passes, or a coroutine of it. - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database. - Without a `path`, the check gets the whole value, and runs only when the value has no issue at all. `reads` names other fields whose issues hold it back too, such as `items` for a check of an order's total. -- Its issue has code `refine` and `params["refine"]` `"nameAvailable"`, with the field's title. A check that raises gives `refineError`, validation fails closed, and one `schema_check_error` diagnostic at `error` says which check of which schema, once per schema and check and datafile revision, with the exception as `originalError` and `details` of `schemaKey`, `check` and `path`. A task that is cancelled reports nothing. In a field's handle from `at`, `info.input` is the field's value, and only checks that read no other field run there. A field of a view from the schema's root, such as `with_input(values).at("city")`, gets the whole input. +- Its issue has code `refine` and `params["refine"]` `"nameAvailable"`, with the field's title. A check that raises gives `refineError`, validation fails closed, and one `schema_check_error` diagnostic at `error` says which check of which schema, once per schema and check and datafile revision, with the exception as `originalError` and `details` of `schemaKey`, `check` and `path`. A task that is cancelled reports nothing. In a field's handle from `field`, `info.input` is the field's value, and only checks that read no other field run there. A field of a view from the schema's root, such as `with_input(values).field("city")`, gets the whole input. - `avalidate` awaits every check, running them concurrently, and returns the result, whose issues say what failed. `validate` answers at once, so a check that is a coroutine function reports `refineError` there. ### Options from your application @@ -874,7 +874,7 @@ cities = OptionSource( ) sign_up = s.get("signUp", option_sources=[cities]) -city = sign_up.with_input({"country": "nl"}).at("city") +city = sign_up.with_input({"country": "nl"}).field("city") await city.search("am") # [SchemaOption(value="Amsterdam"), SchemaOption(value="Amersfoort")] @@ -908,7 +908,7 @@ A rule changed in your project reaches the browser and the server at their next `subscribe` calls back when a new datafile changes the schema, through a schema it references too, and returns a function that stops it: ```python -stop = s.get("signUp").at("country").subscribe(lambda: render_choices()) +stop = s.get("signUp").field("country").subscribe(lambda: render_choices()) ``` A datafile whose schema is unchanged calls nothing. `s.close()`, or leaving a `with create_schemas(f) as s:` block, stops every listener the instance started and removes its module from the Featurevisor instance. diff --git a/src/featurevisor/schemas/_handle.py b/src/featurevisor/schemas/_handle.py index 85a31c7..58e0dbf 100644 --- a/src/featurevisor/schemas/_handle.py +++ b/src/featurevisor/schemas/_handle.py @@ -325,15 +325,15 @@ def _report_check(self, run: Run, located, code: str, check: _Check, path: list[ # Fields - def at(self, path: str) -> SchemaHandle: + def field(self, path: str) -> SchemaHandle: """The handle for a field at a path, such as "address.city", "items[].name" or "labels.*".""" return self._handle(path, lambda: parse_path(path)) def _child(self, key: str) -> SchemaHandle: - """The handle for one of an object's fields by its key, the same handle at gives + """The handle for one of an object's fields by its key, the same handle field gives when the key reads as itself, and its own for a key such as "a.b", "*" or "2024".""" if reads_as_key(key): - return self.at(key) + return self.field(key) return self._handle("\x00" + key, lambda: [Step("key", key=key)]) def _handle(self, handle_id: str, more: Callable[[], list[Step]]) -> SchemaHandle: diff --git a/src/featurevisor/schemas/_paths.py b/src/featurevisor/schemas/_paths.py index b080ed3..3c99587 100644 --- a/src/featurevisor/schemas/_paths.py +++ b/src/featurevisor/schemas/_paths.py @@ -40,7 +40,7 @@ def _step(text: str, key: str | None = None) -> Step: def reads_as_key(key: str) -> bool: - """Whether parse_path reads a key as itself, so at(key) and an object's own field are the same handle.""" + """Whether parse_path reads a key as itself, so field(key) and an object's own field are the same handle.""" return key != "" and not any(character in key for character in ".[]") and _step(key).kind == "key" diff --git a/src/featurevisor/schemas/_views.py b/src/featurevisor/schemas/_views.py index 281868c..3db0243 100644 --- a/src/featurevisor/schemas/_views.py +++ b/src/featurevisor/schemas/_views.py @@ -78,7 +78,7 @@ def place(values: Any, steps: Sequence[Step], value: Any) -> Any: def reads_of(node: Any, resolve: Resolver) -> list[str]: """The fields, relative to a node, that the conditions of its mutations and issues - read, at any depth and through references, as at takes paths: accountType, + read, at any depth and through references, as field takes paths: accountType, address.country or items[].room.""" reads: list[str] = [] diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 180d75c..204c481 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -78,7 +78,7 @@ def codes(result): self.assertEqual(codes(s.validate("signUp", {"name": "Ada"})), [("required", "taxId"), ("refine", "name")]) self.assertEqual(codes(s.validate("signUp", {"name": "Ada", "taxId": "x"})), [("refine", "name")]) - self.assertTrue(s.get("signUp").with_input({}).at("taxId").constraints.required) + self.assertTrue(s.get("signUp").with_input({}).field("taxId").constraints.required) # One evaluation per validation and per view, each the schema's own. self.assertTrue(seen) self.assertEqual(set(seen), {("schema", "signUp")}) @@ -148,16 +148,16 @@ async def search(query, info): source = OptionSource("cities", "city", search=search, lookup=lambda value, info: {"title": cities[value]} if value in cities else None) sign_up = create_schemas(self.f).get("signUp", option_sources=[source]) - city = sign_up.at("city") + city = sign_up.field("city") self.assertTrue(city.can_search) - self.assertFalse(sign_up.at("username").can_search) + self.assertFalse(sign_up.field("username").can_search) suggestions = asyncio.run(city.search("ut")) self.assertEqual([option.value for option in suggestions], ["utrecht"]) self.assertEqual(suggestions[0].title, "Utrecht") self.assertEqual(asyncio.run(city.lookup("rotterdam")).title, "Rotterdam") self.assertIsNone(asyncio.run(city.lookup("amstelveen"))) # The schema's own choices come first. - self.assertEqual(asyncio.run(sign_up.at("country").lookup("nl")).value, "nl") + self.assertEqual(asyncio.run(sign_up.field("country").lookup("nl")).value, "nl") result = sign_up.validate({"username": "ada", "password": "long enough", "city": "amstelveen"}) self.assertEqual([issue.code for issue in result.issues], ["enum"]) self.assertEqual(dict(result.issues[0].params), {"optionSource": "cities"}) @@ -194,7 +194,7 @@ def test_a_missing_schema_or_field_is_an_issue_reported_once(self) -> None: self.assertEqual(missing.issues[0].message, 'Schema "nothing" was not found.') s.validate("nothing", {}) self.assertEqual(self.diagnostics.count("schema_not_found"), 1) - self.assertEqual(dict(s.get("signUp").at("address.city").validate("x").issues[0].params), + self.assertEqual(dict(s.get("signUp").field("address.city").validate("x").issues[0].params), {"schema": "signUp", "field": "address.city"}) self.assertEqual(s.keys(), ["braces", "broken", "digits", "dots", "signUp", "spaced"]) self.assertTrue(s.has("signUp")) @@ -204,16 +204,16 @@ def test_handles_read_the_current_datafile_and_tell_when_their_schema_changes(se s = create_schemas(self.f) sign_up = s.get("signUp") self.assertIs(sign_up, s.get("signUp")) - self.assertIs(sign_up.at("username"), sign_up.at("username")) + self.assertIs(sign_up.field("username"), sign_up.field("username")) changes = [] stop = sign_up.subscribe(lambda: changes.append(1)) - self.assertEqual(sign_up.at("username").constraints.min_length, 3) + self.assertEqual(sign_up.field("username").constraints.min_length, 3) # A datafile that leaves the schema alone changes nothing. self.f.set_datafile(datafile("2", {})) self.assertEqual(changes, []) self.f.set_datafile(datafile("3", {"signUp": {"hash": "s2", "type": "object", "properties": {"username": {"type": "string", "minLength": 5}}}})) self.assertEqual(len(changes), 1) - self.assertEqual(sign_up.at("username").constraints.min_length, 5) + self.assertEqual(sign_up.field("username").constraints.min_length, 5) self.assertEqual([issue.code for issue in sign_up.validate({"username": "ada"}).issues], ["minLength"]) stop() self.f.set_datafile(datafile("4", {"signUp": {"hash": "s3", "type": "object"}})) @@ -254,7 +254,7 @@ def test_a_field_whose_key_starts_with_a_digit_is_the_handle_at_gives(self) -> N "logLevel": "error"}) handle = create_schemas(f).get("account") by_key = {field.name: field for field in handle.fields} - self.assertIs(by_key["2fa"], handle.at("2fa")) + self.assertIs(by_key["2fa"], handle.field("2fa")) self.assertEqual(by_key["2fa"].path, "2fa") self.assertEqual(by_key["2024"].path, "2024") self.assertEqual(by_key["2024"].kind, "text") @@ -267,7 +267,7 @@ def test_one_compiled_validator_serves_every_view_and_field_of_an_instance(self) counts = [] for index in range(3): view = handle.with_input({"username": f"user-{index}"}) - view.at("username").validate("ada") + view.field("username").validate("ada") view.validate(VALID) counts.append(len(store._compiled)) self.assertEqual(counts[0], counts[-1]) @@ -288,13 +288,13 @@ def test_compiled_validators_survive_a_datafile_that_keeps_the_schema_and_go_aft sign_up = s.get("signUp") with mock.patch.object(_store, "compile_node", wraps=_store.compile_node) as compiling: sign_up.validate(VALID) - sign_up.at("username").validate("ada") + sign_up.field("username").validate("ada") first = compiling.call_count self.assertGreater(first, 0) # A merge that leaves the schemas out keeps the entry objects. self.f.set_datafile(datafile("2", {})) sign_up.validate(VALID) - sign_up.at("username").validate("ada") + sign_up.field("username").validate("ada") self.assertEqual(compiling.call_count, first) # Two more changes that never touch signUp drop it. s.validate("spaced", "a b") diff --git a/tests/test_schemas_conformance.py b/tests/test_schemas_conformance.py index 2785a3b..a5bbb05 100644 --- a/tests/test_schemas_conformance.py +++ b/tests/test_schemas_conformance.py @@ -90,9 +90,9 @@ def test_describes_fields_as_javascript_does(self) -> None: sign_up = s.get("signUp") business = sign_up.with_input({"accountType": "business"}) handles = { - "signUp": sign_up, "accountType": sign_up.at("accountType"), "displayName": sign_up.at("displayName"), - "taxId": sign_up.at("taxId"), "businessTaxId": business.at("taxId"), "business": business, - "newsletter": sign_up.at("newsletter"), "businessNewsletter": business.at("newsletter"), + "signUp": sign_up, "accountType": sign_up.field("accountType"), "displayName": sign_up.field("displayName"), + "taxId": sign_up.field("taxId"), "businessTaxId": business.field("taxId"), "business": business, + "newsletter": sign_up.field("newsletter"), "businessNewsletter": business.field("newsletter"), "checkout": s.get("checkout"), "register": s.get("register"), "profile": s.get("profile"), } diff --git a/tests/test_schemas_review.py b/tests/test_schemas_review.py index 6c95682..26fe11b 100644 --- a/tests/test_schemas_review.py +++ b/tests/test_schemas_review.py @@ -44,13 +44,13 @@ def test_kind_stops_on_a_list_of_itself(self) -> None: "holder": {"type": "object", "properties": {"rows": {"schema": "tree"}}}}) s = create_schemas(f) self.assertEqual(s.get("tree").kind, "list") - self.assertEqual(s.get("holder").at("rows").kind, "list") + self.assertEqual(s.get("holder").field("rows").kind, "list") self.assertEqual(s.get("tree").with_input([]).kind, "list") def test_a_missing_field_is_not_a_missing_schema(self) -> None: f, diagnostics = make({"a": {"type": "object", "properties": {"x": {"type": "string"}}}}) s = create_schemas(f) - result = s.get("a").at("nope").validate("v") + result = s.get("a").field("nope").validate("v") self.assertEqual([i.code for i in result.issues], ["schemaNotFound"]) self.assertEqual(result.issues[0].params, {"schema": "a", "field": "nope"}) self.assertEqual([d["code"] for d in diagnostics], []) @@ -97,7 +97,7 @@ def test_required_holds_whatever_properties_holds(self) -> None: for key in ("a", "b"): issue = s.validate(key, {}).issues[0] self.assertEqual((issue.code, issue.path, issue.params), ("required", ("k",), {"key": "k"}), key) - self.assertTrue(s.get("a").at("k").constraints.required) + self.assertTrue(s.get("a").field("k").constraints.required) def test_the_nesting_limit_message(self) -> None: f, diagnostics = make({"node": {"type": "object", "properties": {"next": {"schema": "node"}}}}) @@ -186,11 +186,11 @@ def test_a_view_follows_context_and_sticky_values(self) -> None: "operations": [{"op": "set", "path": ["properties", "tax", "minLength"], "value": 9}]}]} f, _ = make({"s": schema}, context={"country": "de"}) view = create_schemas(f).get("s").with_input({}) - self.assertEqual(view.at("tax").constraints.min_length, 1) + self.assertEqual(view.field("tax").constraints.min_length, 1) f.set_context({"country": "nl"}) - self.assertEqual(view.at("tax").constraints.min_length, 9) + self.assertEqual(view.field("tax").constraints.min_length, 9) f.set_context({"country": "de"}) - self.assertEqual(view.at("tax").constraints.min_length, 1) + self.assertEqual(view.field("tax").constraints.min_length, 1) def test_huge_integers_read_as_infinity(self) -> None: f, _ = make({"n": {"type": "number"}, "i": {"type": "integer"}, "any": {"maximum": 5}}) From b17946a3534a131d16f28fe1863bfd5380c709fb Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Mon, 30 Nov 2026 23:02:14 +0100 Subject: [PATCH 20/21] refactor(schemas): a handle says what a field renders as with render_as, not kind kind named what a field's rules say it renders as, such as select or list, but the word told a reader nothing without the docs and already names condition kinds. The port follows the JavaScript package, which calls it renderAs. The values are unchanged, and nothing is released yet, so the rename needs no deprecation. The handle's property is render_as. The README's Schemas section, the tests, the comments and the datafile fixture, whose member is renderAs, follow. --- README.md | 4 ++-- conformance/schemas-datafile.json | 22 +++++++++++----------- src/featurevisor/schemas/_derived.py | 8 ++++---- src/featurevisor/schemas/_handle.py | 8 ++++---- tests/test_schemas.py | 2 +- tests/test_schemas_conformance.py | 4 ++-- tests/test_schemas_review.py | 6 +++--- 7 files changed, 27 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index cc3dfff..4a82388 100644 --- a/README.md +++ b/README.md @@ -742,7 +742,7 @@ A handle is stable, and reads the current datafile whenever it is used, so keep | `fields` | An object's fields' handles, in [order](#read-annotations), each with its `name` | | `constraints`, `field_constraints` | HTML validation attributes, `field_constraints` by field path on an object, [below](#read-constraints-and-choices) | | `options`, `field_options`, `option(value)` | Its choices, `field_options` by field path on an object, and one choice by value | -| `kind` | What its rules make the field, such as `"select"` | +| `render_as` | What its rules say the field renders as, such as `"select"` | | `annotations` | Its [annotations](#read-annotations) | | `with_input(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | | `reads` | The fields its rules' conditions read | @@ -779,7 +779,7 @@ country.option("nl").title # "Netherlands" country.option("fr") # None ``` -A schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. `kind` answers the switch every generic form writes, from the field's rules alone: `"text"`, `"date-time"`, `"version"`, `"number"`, `"boolean"`, `"select"`, `"multiselect"`, `"object"` or `"list"`. Your own annotation, such as `input: select`, still wins over it. +A schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. `render_as` answers the switch every generic form writes, from the field's rules alone: `"text"`, `"date-time"`, `"version"`, `"number"`, `"boolean"`, `"select"`, `"multiselect"`, `"object"` or `"list"`. Your own annotation, such as `input: select`, still wins over it. ### Read annotations diff --git a/conformance/schemas-datafile.json b/conformance/schemas-datafile.json index e0642b2..1c78756 100644 --- a/conformance/schemas-datafile.json +++ b/conformance/schemas-datafile.json @@ -662,7 +662,7 @@ } ] }, - "kind": "object", + "renderAs": "object", "reads": [ "accountType" ], @@ -692,7 +692,7 @@ "title": "Business" } ], - "kind": "select", + "renderAs": "select", "reads": [], "annotations": { "title": "Account type", @@ -716,7 +716,7 @@ "maxLength": 40 }, "options": [], - "kind": "text", + "renderAs": "text", "reads": [], "annotations": { "title": "Display name", @@ -731,7 +731,7 @@ "fieldKeys": [], "constraints": {}, "options": [], - "kind": "text", + "renderAs": "text", "reads": [], "annotations": { "title": "VAT number" @@ -744,7 +744,7 @@ "required": true }, "options": [], - "kind": "text", + "renderAs": "text", "reads": [], "annotations": { "title": "VAT number" @@ -755,7 +755,7 @@ "fieldKeys": [], "constraints": {}, "options": [], - "kind": "boolean", + "renderAs": "boolean", "reads": [], "annotations": { "title": "Send me product news", @@ -767,7 +767,7 @@ "fieldKeys": [], "constraints": {}, "options": [], - "kind": "boolean", + "renderAs": "boolean", "reads": [], "annotations": { "title": "Send me product news", @@ -808,7 +808,7 @@ } ] }, - "kind": "object", + "renderAs": "object", "reads": [ "accountType" ], @@ -872,7 +872,7 @@ } ] }, - "kind": "object", + "renderAs": "object", "reads": [ "shippingCountry", "billingCountry" @@ -897,7 +897,7 @@ "billingCountry": {} }, "options": {}, - "kind": "object", + "renderAs": "object", "reads": [ "confirmPassword", "password", @@ -923,7 +923,7 @@ "😀": {} }, "options": {}, - "kind": "object", + "renderAs": "object", "reads": [], "annotations": {} } diff --git a/src/featurevisor/schemas/_derived.py b/src/featurevisor/schemas/_derived.py index 7f21c40..35da19e 100644 --- a/src/featurevisor/schemas/_derived.py +++ b/src/featurevisor/schemas/_derived.py @@ -1,4 +1,4 @@ -"""What a handle derives from its node: constraints, choices, kind, field order and annotations.""" +"""What a handle derives from its node: constraints, choices, what a field renders as, field order and annotations.""" from __future__ import annotations @@ -168,7 +168,7 @@ def field_keys_of(node: Any, resolve: Resolver) -> list[str]: return first + sorted(key for key in keys if key not in first) -def kind_of_field(node: Any, resolve: Resolver, depth: int = 0, chain: tuple[int, ...] = ()) -> str | None: +def render_as_of(node: Any, resolve: Resolver, depth: int = 0, chain: tuple[int, ...] = ()) -> str | None: """What a node's rules make a field, or None for a oneOf of shapes. `chain` holds the nodes on the way, so a schema that comes back to itself, such as a list of such lists, stops.""" resolved = resolve_node(node, resolve) @@ -180,12 +180,12 @@ def kind_of_field(node: Any, resolve: Resolver, depth: int = 0, chain: tuple[int if isinstance(resolved.get("oneOf"), list): # A nullable field is what its other branch is. rules = non_null_branch(resolved, resolve) - return kind_of_field(rules, resolve, depth + 1, chain) if rules is not None else None + return render_as_of(rules, resolve, depth + 1, chain) if rules is not None else None kind = resolved.get("type") if kind == "string": return {"date-time": "date-time", "semver": "version"}.get(resolved.get("format"), "text") # type: ignore[arg-type] if kind == "array": - return "multiselect" if kind_of_field(resolved.get("items"), resolve, depth + 1, chain) == "select" else "list" + return "multiselect" if render_as_of(resolved.get("items"), resolve, depth + 1, chain) == "select" else "list" if kind in ("integer", "number"): return "number" if kind == "boolean": diff --git a/src/featurevisor/schemas/_handle.py b/src/featurevisor/schemas/_handle.py index 58e0dbf..941e360 100644 --- a/src/featurevisor/schemas/_handle.py +++ b/src/featurevisor/schemas/_handle.py @@ -8,7 +8,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable, Mapping, Sequence -from ._derived import (constraints_of, field_constraints_of, field_keys_of, field_options_of, kind_of_field, +from ._derived import (constraints_of, field_constraints_of, field_keys_of, field_options_of, render_as_of, options_of) from ._engine import Position, Run, Validator, annotations_of, report, title_of, translate_issues from ._json import plain, same @@ -437,9 +437,9 @@ def option(self, value: Any) -> SchemaOption | None: return next((option for option in self.options if same(option.value, value)), None) @property - def kind(self) -> str | None: - """What the rules make the field, such as "text", "select" or "date-time", or None for a oneOf of shapes.""" - return self._derive("kind", lambda node, required: kind_of_field(node, self._store), None) + def render_as(self) -> str | None: + """What the rules say the field renders as, such as "text", "select" or "date-time", or None for a oneOf of shapes.""" + return self._derive("render_as", lambda node, required: render_as_of(node, self._store), None) # Option sources diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 204c481..6423297 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -257,7 +257,7 @@ def test_a_field_whose_key_starts_with_a_digit_is_the_handle_at_gives(self) -> N self.assertIs(by_key["2fa"], handle.field("2fa")) self.assertEqual(by_key["2fa"].path, "2fa") self.assertEqual(by_key["2024"].path, "2024") - self.assertEqual(by_key["2024"].kind, "text") + self.assertEqual(by_key["2024"].render_as, "text") def test_one_compiled_validator_serves_every_view_and_field_of_an_instance(self) -> None: s = create_schemas(self.f) diff --git a/tests/test_schemas_conformance.py b/tests/test_schemas_conformance.py index a5bbb05..c463d4a 100644 --- a/tests/test_schemas_conformance.py +++ b/tests/test_schemas_conformance.py @@ -106,10 +106,10 @@ def constraints(value): wanted = self.expected["members"][name] self.assertEqual(handle.path, wanted["path"]) self.assertEqual([field.name for field in handle.fields], wanted["fieldKeys"]) - self.assertEqual(handle.kind, wanted["kind"]) + self.assertEqual(handle.render_as, wanted["renderAs"]) self.assertEqual(handle.reads, wanted["reads"]) self.assertEqual(canonical(handle.annotations), canonical(wanted["annotations"])) - if handle.kind == "object": + if handle.render_as == "object": actual_constraints = {key: constraints(value) for key, value in handle.field_constraints.items()} actual_options = {key: [dict(option.fields) for option in options] for key, options in handle.field_options.items()} else: diff --git a/tests/test_schemas_review.py b/tests/test_schemas_review.py index 26fe11b..cbf63b4 100644 --- a/tests/test_schemas_review.py +++ b/tests/test_schemas_review.py @@ -43,9 +43,9 @@ def test_kind_stops_on_a_list_of_itself(self) -> None: f, _ = make({"tree": {"type": "array", "items": {"schema": "tree"}}, "holder": {"type": "object", "properties": {"rows": {"schema": "tree"}}}}) s = create_schemas(f) - self.assertEqual(s.get("tree").kind, "list") - self.assertEqual(s.get("holder").field("rows").kind, "list") - self.assertEqual(s.get("tree").with_input([]).kind, "list") + self.assertEqual(s.get("tree").render_as, "list") + self.assertEqual(s.get("holder").field("rows").render_as, "list") + self.assertEqual(s.get("tree").with_input([]).render_as, "list") def test_a_missing_field_is_not_a_missing_schema(self) -> None: f, diagnostics = make({"a": {"type": "object", "properties": {"x": {"type": "string"}}}}) From 39f3bd120591fed5bf1aab85b6d60a07870f8e77 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Tue, 1 Dec 2026 00:16:26 +0100 Subject: [PATCH 21/21] chore(release): 4.1.0 4.1.0 ships the extension seam and the schemas subpackage, as each SDK's next minor does. pyproject.toml says 4.1.0, which the publish workflow checks against the tag, and the README's release note names it. --- README.md | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4a82388..9493d89 100644 --- a/README.md +++ b/README.md @@ -1161,7 +1161,7 @@ make test-example-1 ## Releasing -The next breaking release is `4.0.0`, including the optional OpenFeature extra. Before tagging, run `make check`, build both distributions with `python -m build`, and validate them with `python -m twine check dist/*`. Verify a base wheel installation without OpenFeature and a separate installation with the extra. The publish workflow rejects a tag that does not match `pyproject.toml`. +The next release is `4.1.0`, including the optional OpenFeature extra and the schemas subpackage. Before tagging, run `make check`, build both distributions with `python -m build`, and validate them with `python -m twine check dist/*`. Verify a base wheel installation without OpenFeature and a separate installation with the extra. The publish workflow rejects a tag that does not match `pyproject.toml`. - Update version in pyproject.toml - Push commit to main branch diff --git a/pyproject.toml b/pyproject.toml index 251f467..b1ad459 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "featurevisor" -version = "4.0.0" +version = "4.1.0" description = "Featurevisor SDK for Python: feature flags, experiments and remote configuration" readme = "README.md" requires-python = ">=3.10"