From f490b44bdde450968a8673b52a2e94f3c7bf168e Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Thu, 12 Nov 2026 12:39:41 +0530 Subject: [PATCH 01/38] feat: merge equivalent checks in BatchCheck (beta) --- Makefile | 11 +- README.md | 25 + docs/opentelemetry.md | 17 +- openfga_sdk/client/client.py | 140 + openfga_sdk/client/equivalent_checks.py | 349 + openfga_sdk/client/model_cache.py | 202 + .../client/models/batch_check_response.py | 16 + openfga_sdk/sync/client/client.py | 134 + openfga_sdk/telemetry/attributes.py | 4 + openfga_sdk/telemetry/configuration.py | 10 + openfga_sdk/telemetry/counters.py | 24 + openfga_sdk/telemetry/metrics.py | 95 + test/client/batch_check_merge_test.py | 424 ++ test/client/equivalent_checks_cases_test.py | 92 + test/client/equivalent_checks_test.py | 229 + test/client/model_cache_test.py | 248 + test/data/equivalent-checks-cases.json | 5598 +++++++++++++++++ test/sync/client/batch_check_merge_test.py | 304 + test/telemetry/configuration_test.py | 9 +- test/telemetry/metrics_test.py | 85 + 20 files changed, 8007 insertions(+), 9 deletions(-) create mode 100644 openfga_sdk/client/equivalent_checks.py create mode 100644 openfga_sdk/client/model_cache.py create mode 100644 test/client/batch_check_merge_test.py create mode 100644 test/client/equivalent_checks_cases_test.py create mode 100644 test/client/equivalent_checks_test.py create mode 100644 test/client/model_cache_test.py create mode 100644 test/data/equivalent-checks-cases.json create mode 100644 test/sync/client/batch_check_merge_test.py diff --git a/Makefile b/Makefile index d43f4847..94c27fef 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,7 @@ -.PHONY: sync test lint fmt fix check doc +.PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases + +# openfga/language commit to copy the shared equivalent-checks cases from +LANGUAGE_REF ?= 5afcf707e44aa21d8ae17e47938b3f0164a13cc7 # Install/update dependencies sync: @@ -26,6 +29,11 @@ fix: uv run ruff check --fix . uv run ruff format . +# Copy the shared equivalent-checks cases from openfga/language +# Usage: make update-equivalent-checks-cases LANGUAGE_REF= +update-equivalent-checks-cases: + curl -fsSL https://raw.githubusercontent.com/openfga/language/$(LANGUAGE_REF)/tests/data/equivalent-checks-cases.json -o test/data/equivalent-checks-cases.json + # Run checks (lint + test) check: lint fmt test @@ -39,4 +47,5 @@ doc: @echo " fmt - Format code" @echo " fix - Fix fixable linting and formatting issues" @echo " check - Run both linting and tests" + @echo " update-equivalent-checks-cases - Copy the shared equivalent-checks cases from openfga/language (LANGUAGE_REF=)" @echo " doc - Show this help message" diff --git a/README.md b/README.md index ce6ace3d..5c155f0f 100644 --- a/README.md +++ b/README.md @@ -965,6 +965,31 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), # ] ``` +###### Merge equivalent checks (beta) + +Set `merge_equivalent_checks` to `True` to send checks that are certain to get the same answer only once. The SDK copies each answer back, so you still get one result per check you passed in. + +It merges: +- **Aliases:** with `define can_view: viewer`, checking both `viewer` and `can_view` for the same user and object sends one check. Chains like `define can_share: can_view` work too. +- **Exact repeats:** the same user, relation, object, context and contextual tuples. + +```python +options = { + "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1", # required, here or in the configuration + "merge_equivalent_checks": True, +} +response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), options) +# response.checks_sent: how many checks this call actually sent +``` + +- **Off by default.** With it off, nothing changes. +- **Needs an authorization model ID.** Without one, the call fails before anything is sent. +- **Reads the model once per client.** The SDK reads the model on first use and caches it. Create the client once and reuse it. +- **Falls back safely.** If the model can't be read (for example, no read access), the SDK logs a warning and sends the checks unmerged. +- **Errors are shared.** If a merged check returns an error, every check it stands for gets that error. +- **Correlation IDs** must match `^[\w\d-]{1,36}$` (ASCII). Missing ones are generated. +- **Telemetry:** see the `fga-client.batch_check.*` and `fga-client.model_cache.lookup` metrics in [OpenTelemetry](docs/opentelemetry.md). + ##### Client Batch Check diff --git a/docs/opentelemetry.md b/docs/opentelemetry.md index ce4ca6be..dfed134a 100644 --- a/docs/opentelemetry.md +++ b/docs/opentelemetry.md @@ -21,17 +21,22 @@ If you configure the OpenTelemetry SDK, these metrics will be exported and sent ### Supported Metrics -| Metric Name | Type | Enabled by Default | Description | -| -------------------------------- | --------- | ------------------ | --------------------------------------------------------------------------------- | -| `fga-client.request.duration` | Histogram | Yes | Total request time for FGA requests, in milliseconds | -| `fga-client.query.duration` | Histogram | Yes | Time taken by the FGA server to process and evaluate the request, in milliseconds | -| `fga-client.credentials.request` | Counter | Yes | Total number of new token requests initiated using the Client Credentials flow | -| `fga-client.request` | Counter | No | Total number of requests made to the FGA server | +| Metric Name | Type | Enabled by Default | Description | +| ----------------------------------------- | --------- | ------------------ | --------------------------------------------------------------------------------------------- | +| `fga-client.request.duration` | Histogram | Yes | Total request time for FGA requests, in milliseconds | +| `fga-client.query.duration` | Histogram | Yes | Time taken by the FGA server to process and evaluate the request, in milliseconds | +| `fga-client.credentials.request` | Counter | Yes | Total number of new token requests initiated using the Client Credentials flow | +| `fga-client.request` | Counter | No | Total number of requests made to the FGA server | +| `fga-client.batch_check.checks_requested` | Counter | Yes | Checks passed to `batch_check` with `merge_equivalent_checks` on | +| `fga-client.batch_check.checks_sent` | Counter | Yes | Checks actually sent by `batch_check` with `merge_equivalent_checks` on | +| `fga-client.batch_check.merge_fallback` | Counter | Yes | `batch_check` calls sent unmerged because the authorization model could not be read | +| `fga-client.model_cache.lookup` | Counter | Yes | Authorization model cache lookups by `merge_equivalent_checks`, with a `hit` or `miss` result | ### Supported Attributes | Attribute Name | Type | Enabled by Default | Description | | ------------------------------------- | ------ | ------------------ | --------------------------------------------------------------------------------- | +| `fga-client.model_cache.result` | string | Yes | Result of an authorization model cache lookup (`hit`/`miss`) | | `fga-client.request.batch_check_size` | int | No | The total size of the `check` list in a `BatchCheck` call | | `fga-client.request.client_id` | string | Yes | Client ID associated with the request, if any | | `fga-client.request.method` | string | Yes | FGA method/action that was performed (e.g., Check, ListObjects) in TitleCase | diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index b48a3ec8..833be8ae 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -1,4 +1,5 @@ import asyncio +import logging import uuid from collections.abc import AsyncIterator @@ -7,6 +8,13 @@ from openfga_sdk.api.open_fga_api import OpenFgaApi from openfga_sdk.api_client import ApiClient from openfga_sdk.client.configuration import ClientConfiguration +from openfga_sdk.client.equivalent_checks import ( + expand, + resolve, + unmerged, + validate_correlation_ids, +) +from openfga_sdk.client.model_cache import AsyncModelCache from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, @@ -71,9 +79,13 @@ WriteAuthorizationModelRequest, ) from openfga_sdk.models.write_request import WriteRequest +from openfga_sdk.telemetry.attributes import TelemetryAttributes from openfga_sdk.validation import is_well_formed_ulid_string +logger = logging.getLogger(__name__) + + def _chuck_array(array, max_size): """ Helper function to chuck array into arrays of max_size @@ -127,6 +139,16 @@ def options_to_kwargs( return kwargs +def _model_read_kwargs( + options: dict[str, int | str | dict[str, int | str]] | None = None, +) -> dict[str, int | str | dict[str, int | str]]: + """ + Return the kwargs a BatchCheck call passes on to its authorization model read + """ + kwargs = options_to_kwargs(options) + return {key: kwargs[key] for key in ("_headers", "_retry_params") if key in kwargs} + + def options_to_transaction_info( options: dict[str, int | str | dict[str, int | str]] | None = None, ): @@ -172,6 +194,7 @@ def __init__(self, configuration: ClientConfiguration): self._client_configuration = configuration self._api_client = ApiClient(configuration) self._api = OpenFgaApi(self._api_client) + self._model_cache = AsyncModelCache() # Set default headers from configuration if configuration.headers: @@ -185,6 +208,7 @@ async def __aexit__(self, exc_type, exc_value, traceback): await self.close() async def close(self): + await self._model_cache.close() await self._api.close() def _get_authorization_model_id( @@ -780,6 +804,7 @@ async def batch_check( :param authorization_model_id(options) - Overrides the authorization model id in the configuration :param max_parallel_requests(options) - Max number of requests to issue in parallel. Defaults to 10 :param max_batch_size(options) - Max number of checks to include in a request. Defaults to 50 + :param merge_equivalent_checks(options) - Beta. Send checks that are certain to get the same answer only once. Requires an authorization model id :param header(options) - Custom headers to send alongside the request :param retryParams(options) - Override the retry parameters for this request :param retryParams.maxRetry(options) - Override the max number of retries on each API request @@ -809,6 +834,11 @@ async def batch_check( elif isinstance(options["max_batch_size"], int): max_batch_size = options["max_batch_size"] + if options.get("merge_equivalent_checks") is True: + return await self._merged_batch_check( + body, options, max_parallel_requests, max_batch_size + ) + id_to_check: dict[str, ClientBatchCheckItem] = {} def track_and_transform(checks): @@ -866,6 +896,116 @@ async def coro(checks): return ClientBatchCheckResponse(result) + async def _merged_batch_check( + self, + body: ClientBatchCheckRequest, + options: dict[str, int | str | dict[str, int | str]], + max_parallel_requests: int, + max_batch_size: int, + ) -> ClientBatchCheckResponse: + """ + Run a BatchCheck with merge_equivalent_checks on + """ + # Reading the model and sending the checks must use the same model. + authorization_model_id = self._get_authorization_model_id(options) + if authorization_model_id is None: + raise FgaValidationException( + "authorization_model_id is required when merge_equivalent_checks is on" + ) + store_id = self._api_client._get_store_id() + + checks = body.checks + for check in checks: + if check.correlation_id is None: + check.correlation_id = str(uuid.uuid4()) + validate_correlation_ids(checks) + + if not checks: + return ClientBatchCheckResponse([], checks_sent=0) + + telemetry = self._api_client._telemetry.metrics + telemetry_configuration = self._api_client.configuration.telemetry + attributes = { + TelemetryAttributes.fga_client_request_store_id: store_id, + TelemetryAttributes.fga_client_request_model_id: authorization_model_id, + } + + async def load_model(): + try: + response = await self._api.read_authorization_model( + authorization_model_id, **_model_read_kwargs(options) + ) + if response.authorization_model is None: + raise ValueError("The authorization model response is empty") + return response.authorization_model + except Exception as err: + logger.warning( + "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " + "Sending checks unmerged.", + authorization_model_id, + store_id, + getattr(err, "status", None), + ) + raise + + lookup = await self._model_cache.get( + (store_id, authorization_model_id), load_model + ) + telemetry.modelCacheLookup( + attributes={ + **attributes, + TelemetryAttributes.fga_client_model_cache_result: ( + "hit" if lookup.hit else "miss" + ), + }, + configuration=telemetry_configuration, + ) + + if lookup.model is not None: + groups = resolve(lookup.model, checks) + else: + groups = unmerged(checks) + telemetry.batchCheckMergeFallback( + attributes={ + **attributes, + TelemetryAttributes.http_response_status_code: getattr( + lookup.error, "status", None + ), + }, + configuration=telemetry_configuration, + ) + + results = {} + sem = asyncio.Semaphore(max_parallel_requests) + consistency = self._get_consistency(options) + + async def send(chunk): + response = await self._single_batch_check( + BatchCheckRequest( + checks=[construct_batch_item(group.check) for group in chunk], + authorization_model_id=authorization_model_id, + consistency=consistency, + ), + sem, + options, + ) + results.update(response.result or {}) + + await asyncio.gather( + *[send(chunk) for chunk in _chuck_array(groups, max_batch_size)] + ) + + telemetry.batchCheckChecksRequested( + len(checks), attributes=attributes, configuration=telemetry_configuration + ) + telemetry.batchCheckChecksSent( + len(groups), attributes=attributes, configuration=telemetry_configuration + ) + + return ClientBatchCheckResponse( + expand(checks, groups, results), checks_sent=len(groups) + ) + async def expand( self, body: ClientExpandRequest, diff --git a/openfga_sdk/client/equivalent_checks.py b/openfga_sdk/client/equivalent_checks.py new file mode 100644 index 00000000..d54ab4c3 --- /dev/null +++ b/openfga_sdk/client/equivalent_checks.py @@ -0,0 +1,349 @@ +""" +Merge equivalent checks in BatchCheck (the `merge_equivalent_checks` option). + +Checks that are certain to get the same answer are sent once, and the answer is +copied back to every original check. Rules: https://github.com/openfga/rfcs/pull/40 +""" + +import math +import re +import struct + +from collections import Counter +from dataclasses import dataclass + +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.client.models.batch_check_single_response import ( + ClientBatchCheckSingleResponse, +) +from openfga_sdk.exceptions import FgaValidationException +from openfga_sdk.models.authorization_model import AuthorizationModel +from openfga_sdk.models.batch_check_single_result import BatchCheckSingleResult +from openfga_sdk.models.check_error import CheckError +from openfga_sdk.models.userset import Userset + + +CORRELATION_ID_PATTERN = re.compile(r"^[\w\d-]{1,36}$", re.ASCII) + +_MISSING = ("missing",) + + +class _Unmergeable(Exception): + """A value the SDK can't compare exactly, so the check is sent as is.""" + + +@dataclass +class EquivalentCheckGroup: + """ + A check to send, and the original checks it answers. + """ + + check: ClientBatchCheckItem + members: list[ClientBatchCheckItem] + + +def validate_correlation_ids(checks: list[ClientBatchCheckItem]) -> None: + """ + Raise if a correlation ID doesn't match the API rule, or is used twice. + """ + seen: set[str] = set() + for check in checks: + correlation_id = check.correlation_id + if not isinstance(correlation_id, str) or not CORRELATION_ID_PATTERN.match( + correlation_id + ): + raise FgaValidationException( + f"correlation_id ({correlation_id}) is invalid: it must match {CORRELATION_ID_PATTERN.pattern}" + ) + if correlation_id in seen: + raise FgaValidationException( + f"Duplicate correlation_id ({correlation_id}) provided" + ) + seen.add(correlation_id) + + +def unmerged(checks: list[ClientBatchCheckItem]) -> list[EquivalentCheckGroup]: + """ + One group per check, sent as is. + """ + return [EquivalentCheckGroup(check=check, members=[check]) for check in checks] + + +def resolve( + model: AuthorizationModel, checks: list[ClientBatchCheckItem] +) -> list[EquivalentCheckGroup]: + """ + Group checks that are certain to get the same answer, and build the checks to send. + + The result is deterministic: the same model and checks, in the same order, give the + same groups and IDs. Each group is placed at the position of its first check. + """ + types = { + type_definition.type: type_definition.relations or {} + for type_definition in model.type_definitions or [] + } + + entries: list[tuple[str, ClientBatchCheckItem | tuple]] = [] + groups: dict[tuple, list[ClientBatchCheckItem]] = {} + finals: dict[tuple, str] = {} + + for check in checks: + final_relation = _final_relation(types, check) + key = None + if final_relation is not None: + try: + key = ( + final_relation, + check.user, + check.object, + _context_key(check.context), + _contextual_tuples_key(check.contextual_tuples), + ) + except _Unmergeable: + key = None + + if key is None: + entries.append(("as_is", check)) + continue + + if key not in groups: + groups[key] = [] + finals[key] = final_relation + entries.append(("group", key)) + groups[key].append(check) + + caller_ids = {check.correlation_id for check in checks} + next_number = 1 + result: list[EquivalentCheckGroup] = [] + + for kind, entry in entries: + if kind == "as_is": + result.append(EquivalentCheckGroup(check=entry, members=[entry])) + continue + + members = groups[entry] + first = members[0] + if len(members) == 1: + correlation_id = first.correlation_id + else: + while f"merged-{next_number}" in caller_ids: + next_number += 1 + correlation_id = f"merged-{next_number}" + next_number += 1 + + result.append( + EquivalentCheckGroup( + check=ClientBatchCheckItem( + user=first.user, + relation=finals[entry], + object=first.object, + correlation_id=correlation_id, + contextual_tuples=first.contextual_tuples, + context=first.context, + ), + members=members, + ) + ) + + return result + + +def expand( + checks: list[ClientBatchCheckItem], + groups: list[EquivalentCheckGroup], + results: dict[str, BatchCheckSingleResult], +) -> list[ClientBatchCheckSingleResponse]: + """ + Copy each group's answer to every check in the group, in the order of `checks`. + + A group with no answer gives an error for every check in it. Answers with unknown + correlation IDs are ignored. + """ + responses: dict[str, ClientBatchCheckSingleResponse] = {} + + for group in groups: + sent_id = group.check.correlation_id + result = results.get(sent_id) + allowed = result.allowed if result is not None else None + error = ( + result.error + if result is not None + else CheckError( + message=f"No result returned for correlation_id ({sent_id})" + ) + ) + + for member in group.members: + responses[member.correlation_id] = ClientBatchCheckSingleResponse( + allowed=allowed, + request=member, + correlation_id=member.correlation_id, + error=error, + ) + + return [responses[check.correlation_id] for check in checks] + + +def _alias_target(rewrite: Userset | None) -> str | None: + """ + Return the relation an alias points to, or None if the rewrite isn't a lone computedUserset. + """ + if rewrite is None or rewrite.computed_userset is None: + return None + + if ( + rewrite.this is not None + or rewrite.tuple_to_userset is not None + or rewrite.union is not None + or rewrite.intersection is not None + or rewrite.difference is not None + ): + return None + + target = rewrite.computed_userset + if target.object or not target.relation: + return None + + return target.relation + + +def _alias_chain(relations: dict[str, Userset], relation: str) -> list[str] | None: + """ + Follow aliases from `relation`. Return every relation on the way, ending at the final + relation, or None if the chain points to a missing relation or loops. + """ + chain = [relation] + while True: + if chain[-1] not in relations: + return None + + target = _alias_target(relations[chain[-1]]) + if target is None: + return chain + + if target in chain: + return None + + chain.append(target) + + +def _final_relation(types: dict[str, dict[str, Userset]], check) -> str | None: + """ + Return the relation to send the check with, or None to send it as is. + """ + if not all( + isinstance(value, str) for value in (check.user, check.relation, check.object) + ): + return None + + object_type, separator, object_id = check.object.partition(":") + if not separator or object_type not in types: + return None + + relations = types[object_type] + if check.relation not in relations: + return None + + user_type, separator, user_rest = check.user.partition(":") + if not separator or user_type not in types: + return None + + user_id, userset_separator, user_relation = user_rest.partition("#") + if userset_separator and user_relation not in types[user_type]: + return None + + chain = _alias_chain(relations, check.relation) + if chain is None: + return None + + # The server says a userset always has its own relation on its own object, at every + # step of a chain, so a merged check could get a different answer. + if ( + userset_separator + and (user_type, user_id) == (object_type, object_id) + and user_relation in chain + ): + return None + + # The server's answer can depend on which of these tuples it reads first. + tuple_keys = [ + (contextual_tuple.user, contextual_tuple.relation, contextual_tuple.object) + for contextual_tuple in check.contextual_tuples or [] + ] + if len(set(tuple_keys)) != len(tuple_keys): + return None + + return chain[-1] + + +def _context_key(context) -> tuple: + if context is None: + return _MISSING + + if not isinstance(context, dict): + raise _Unmergeable() + + return _canonical(context) + + +def _contextual_tuples_key(contextual_tuples) -> tuple | frozenset: + if contextual_tuples is None: + return _MISSING + + items = [] + for contextual_tuple in contextual_tuples: + condition = contextual_tuple.condition + condition_key = _MISSING + if condition is not None: + condition_key = (condition.name, _context_key(condition.context)) + + items.append( + ( + contextual_tuple.user, + contextual_tuple.relation, + contextual_tuple.object, + condition_key, + ) + ) + + return frozenset(Counter(items).items()) + + +def _canonical(value) -> tuple: + """ + A hashable form of a JSON value, equal only for values the server sees as equal. + Numbers compare as doubles, including the sign of zero. + """ + if value is None: + return ("null",) + + if isinstance(value, bool): + return ("bool", value) + + if isinstance(value, int | float): + try: + number = float(value) + except OverflowError as err: + raise _Unmergeable() from err + + if not math.isfinite(number): + raise _Unmergeable() + + return ("number", struct.pack(">d", number)) + + if isinstance(value, str): + return ("string", value) + + if isinstance(value, list): + return ("list", tuple(_canonical(item) for item in value)) + + if isinstance(value, dict): + if not all(isinstance(key, str) for key in value): + raise _Unmergeable() + + return ( + "object", + frozenset((key, _canonical(item)) for key, item in value.items()), + ) + + raise _Unmergeable() diff --git a/openfga_sdk/client/model_cache.py b/openfga_sdk/client/model_cache.py new file mode 100644 index 00000000..1ade5549 --- /dev/null +++ b/openfga_sdk/client/model_cache.py @@ -0,0 +1,202 @@ +""" +In-memory cache of authorization models, used by BatchCheck's `merge_equivalent_checks` option. + +A model never changes once it's written, so a cached model never goes stale. Only +successful reads are cached. A failed read is remembered for a short time, so missing +read access doesn't add a read to every call. Calls for the same model share one +in-flight read. +""" + +import asyncio +import threading +import time + +from collections import OrderedDict +from collections.abc import Awaitable, Callable +from concurrent.futures import Future +from dataclasses import dataclass + +from openfga_sdk.models.authorization_model import AuthorizationModel + + +MAX_MODELS = 32 +FAILURE_TTL_SECONDS = 60.0 + +ModelCacheKey = tuple[str, str] + + +@dataclass +class ModelLookup: + """ + The result of a cache lookup: the model, or the error from reading it. + `hit` is True only when the model was already in the cache. + """ + + model: AuthorizationModel | None = None + hit: bool = False + error: Exception | None = None + + +class _ModelCacheState: + def __init__( + self, + max_models: int = MAX_MODELS, + failure_ttl: float = FAILURE_TTL_SECONDS, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self._max_models = max_models + self._failure_ttl = failure_ttl + self._clock = clock + self._models: OrderedDict[ModelCacheKey, AuthorizationModel] = OrderedDict() + self._failures: OrderedDict[ModelCacheKey, tuple[float, Exception]] = ( + OrderedDict() + ) + + def _cached(self, key: ModelCacheKey) -> ModelLookup | None: + model = self._models.get(key) + if model is not None: + self._models.move_to_end(key) + return ModelLookup(model=model, hit=True) + + failure = self._failures.get(key) + if failure is not None: + expires_at, error = failure + if self._clock() < expires_at: + return ModelLookup(error=error) + del self._failures[key] + + return None + + def _store(self, key: ModelCacheKey, model: AuthorizationModel) -> None: + self._failures.pop(key, None) + self._models[key] = model + self._models.move_to_end(key) + while len(self._models) > self._max_models: + self._models.popitem(last=False) + + def _remember_failure(self, key: ModelCacheKey, error: Exception) -> None: + self._failures[key] = (self._clock() + self._failure_ttl, error) + self._failures.move_to_end(key) + while len(self._failures) > self._max_models: + self._failures.popitem(last=False) + + +class AsyncModelCache(_ModelCacheState): + """ + Model cache for the async client. + """ + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self._loading: dict[ModelCacheKey, asyncio.Task] = {} + + async def get( + self, + key: ModelCacheKey, + load: Callable[[], Awaitable[AuthorizationModel]], + ) -> ModelLookup: + cached = self._cached(key) + if cached is not None: + return cached + + task = self._loading.get(key) + if task is None: + task = asyncio.ensure_future(self._load(key, load)) + task.add_done_callback(_retrieve_exception) + self._loading[key] = task + + # Shielded, so a cancelled caller doesn't cancel the read other callers share. + try: + return ModelLookup(model=await asyncio.shield(task)) + except asyncio.CancelledError: + raise + except Exception as error: + return ModelLookup(error=error) + + async def close(self) -> None: + """ + Cancel in-flight reads. + """ + tasks = list(self._loading.values()) + self._loading.clear() + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + async def _load( + self, + key: ModelCacheKey, + load: Callable[[], Awaitable[AuthorizationModel]], + ) -> AuthorizationModel: + try: + model = await load() + except Exception as error: + self._remember_failure(key, error) + raise + else: + self._store(key, model) + return model + finally: + if self._loading.get(key) is asyncio.current_task(): + del self._loading[key] + + +class ModelCache(_ModelCacheState): + """ + Model cache for the sync client. Safe to share across threads. + """ + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self._lock = threading.Lock() + self._loading: dict[ModelCacheKey, Future] = {} + + def get( + self, + key: ModelCacheKey, + load: Callable[[], AuthorizationModel], + ) -> ModelLookup: + with self._lock: + cached = self._cached(key) + if cached is not None: + return cached + + future = self._loading.get(key) + owner = future is None + if owner: + future = Future() + self._loading[key] = future + + if not owner: + try: + return ModelLookup(model=future.result()) + except Exception as error: + return ModelLookup(error=error) + + try: + model = load() + except Exception as error: + with self._lock: + self._remember_failure(key, error) + self._loading.pop(key, None) + future.set_exception(error) + return ModelLookup(error=error) + except BaseException: + with self._lock: + self._loading.pop(key, None) + future.set_exception( + RuntimeError("Reading the authorization model was interrupted") + ) + raise + + with self._lock: + self._store(key, model) + self._loading.pop(key, None) + future.set_result(model) + return ModelLookup(model=model) + + +def _retrieve_exception(task: asyncio.Task) -> None: + # Marks the error as seen, so asyncio doesn't log it when no caller is left waiting. + if not task.cancelled(): + task.exception() diff --git a/openfga_sdk/client/models/batch_check_response.py b/openfga_sdk/client/models/batch_check_response.py index bef97aa3..decc654b 100644 --- a/openfga_sdk/client/models/batch_check_response.py +++ b/openfga_sdk/client/models/batch_check_response.py @@ -7,8 +7,10 @@ class ClientBatchCheckResponse: def __init__( self, result: list[ClientBatchCheckSingleResponse], + checks_sent: int | None = None, ) -> None: self._result = result + self._checks_sent = checks_sent @property def result(self) -> list[ClientBatchCheckSingleResponse]: @@ -23,3 +25,17 @@ def result(self, result: list[ClientBatchCheckSingleResponse]) -> None: Set result """ self._result = result + + @property + def checks_sent(self) -> int | None: + """ + Return how many checks this call sent. Set only when merge_equivalent_checks is on. + """ + return self._checks_sent + + @checks_sent.setter + def checks_sent(self, checks_sent: int | None) -> None: + """ + Set checks_sent + """ + self._checks_sent = checks_sent diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index c736daec..baf474a7 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -1,3 +1,4 @@ +import logging import uuid from collections.abc import Iterator @@ -5,6 +6,13 @@ from typing import Any from openfga_sdk.client.configuration import ClientConfiguration +from openfga_sdk.client.equivalent_checks import ( + expand, + resolve, + unmerged, + validate_correlation_ids, +) +from openfga_sdk.client.model_cache import ModelCache from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, @@ -71,9 +79,13 @@ from openfga_sdk.models.write_request import WriteRequest from openfga_sdk.sync.api_client import ApiClient from openfga_sdk.sync.open_fga_api import OpenFgaApi +from openfga_sdk.telemetry.attributes import TelemetryAttributes from openfga_sdk.validation import is_well_formed_ulid_string +logger = logging.getLogger(__name__) + + def _chuck_array(array, max_size): """ Helper function to chuck array into arrays of max_size @@ -127,6 +139,16 @@ def options_to_kwargs( return kwargs +def _model_read_kwargs( + options: dict[str, int | str | dict[str, int | str]] | None = None, +) -> dict[str, int | str | dict[str, int | str]]: + """ + Return the kwargs a BatchCheck call passes on to its authorization model read + """ + kwargs = options_to_kwargs(options) + return {key: kwargs[key] for key in ("_headers", "_retry_params") if key in kwargs} + + def options_to_transaction_info( options: dict[str, int | str | dict[str, int | str]] | None = None, ): @@ -172,6 +194,7 @@ def __init__(self, configuration: ClientConfiguration) -> None: self._client_configuration = configuration self._api_client = ApiClient(configuration) self._api = OpenFgaApi(self._api_client) + self._model_cache = ModelCache() # Set default headers from configuration if configuration.headers: @@ -776,6 +799,7 @@ def batch_check( :param authorization_model_id(options) - Overrides the authorization model id in the configuration :param max_parallel_requests(options) - Max number of requests to issue in parallel. Defaults to 10 :param max_batch_size(options) - Max number of checks to include in a request. Defaults to 50 + :param merge_equivalent_checks(options) - Beta. Send checks that are certain to get the same answer only once. Requires an authorization model id :param header(options) - Custom headers to send alongside the request :param retryParams(options) - Override the retry parameters for this request :param retryParams.maxRetry(options) - Override the max number of retries on each API request @@ -805,6 +829,11 @@ def batch_check( elif isinstance(options["max_batch_size"], int): max_batch_size = options["max_batch_size"] + if options.get("merge_equivalent_checks") is True: + return self._merged_batch_check( + body, options, max_parallel_requests, max_batch_size + ) + id_to_check: dict[str, ClientBatchCheckItem] = {} def track_and_transform(checks): @@ -864,6 +893,111 @@ def single_batch_check(checks): return ClientBatchCheckResponse(result) + def _merged_batch_check( + self, + body: ClientBatchCheckRequest, + options: dict[str, int | str | dict[str, int | str]], + max_parallel_requests: int, + max_batch_size: int, + ) -> ClientBatchCheckResponse: + """ + Run a BatchCheck with merge_equivalent_checks on + """ + # Reading the model and sending the checks must use the same model. + authorization_model_id = self._get_authorization_model_id(options) + if authorization_model_id is None: + raise FgaValidationException( + "authorization_model_id is required when merge_equivalent_checks is on" + ) + store_id = self._api_client._get_store_id() + + checks = body.checks + for check in checks: + if check.correlation_id is None: + check.correlation_id = str(uuid.uuid4()) + validate_correlation_ids(checks) + + if not checks: + return ClientBatchCheckResponse([], checks_sent=0) + + telemetry = self._api_client._telemetry.metrics + telemetry_configuration = self._api_client.configuration.telemetry + attributes = { + TelemetryAttributes.fga_client_request_store_id: store_id, + TelemetryAttributes.fga_client_request_model_id: authorization_model_id, + } + + def load_model(): + try: + response = self._api.read_authorization_model( + authorization_model_id, **_model_read_kwargs(options) + ) + if response.authorization_model is None: + raise ValueError("The authorization model response is empty") + return response.authorization_model + except Exception as err: + logger.warning( + "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " + "Sending checks unmerged.", + authorization_model_id, + store_id, + getattr(err, "status", None), + ) + raise + + lookup = self._model_cache.get((store_id, authorization_model_id), load_model) + telemetry.modelCacheLookup( + attributes={ + **attributes, + TelemetryAttributes.fga_client_model_cache_result: ( + "hit" if lookup.hit else "miss" + ), + }, + configuration=telemetry_configuration, + ) + + if lookup.model is not None: + groups = resolve(lookup.model, checks) + else: + groups = unmerged(checks) + telemetry.batchCheckMergeFallback( + attributes={ + **attributes, + TelemetryAttributes.http_response_status_code: getattr( + lookup.error, "status", None + ), + }, + configuration=telemetry_configuration, + ) + + consistency = self._get_consistency(options) + + def send(chunk): + return self._single_batch_check( + BatchCheckRequest( + checks=[construct_batch_item(group.check) for group in chunk], + authorization_model_id=authorization_model_id, + consistency=consistency, + ), + options, + ) + + results = {} + with ThreadPoolExecutor(max_workers=max_parallel_requests) as executor: + for response in executor.map(send, _chuck_array(groups, max_batch_size)): + results.update(response.result or {}) + + telemetry.batchCheckChecksRequested( + len(checks), attributes=attributes, configuration=telemetry_configuration + ) + telemetry.batchCheckChecksSent( + len(groups), attributes=attributes, configuration=telemetry_configuration + ) + + return ClientBatchCheckResponse( + expand(checks, groups, results), checks_sent=len(groups) + ) + def expand( self, body: ClientExpandRequest, diff --git a/openfga_sdk/telemetry/attributes.py b/openfga_sdk/telemetry/attributes.py index 02451c1f..edb06b09 100644 --- a/openfga_sdk/telemetry/attributes.py +++ b/openfga_sdk/telemetry/attributes.py @@ -38,6 +38,9 @@ class TelemetryAttributes: fga_client_user: TelemetryAttribute = TelemetryAttribute( name="fga-client.user", ) + fga_client_model_cache_result: TelemetryAttribute = TelemetryAttribute( + name="fga-client.model_cache.result", + ) http_client_request_duration: TelemetryAttribute = TelemetryAttribute( name="http.client.request.duration", format="int", @@ -78,6 +81,7 @@ class TelemetryAttributes: fga_client_request_store_id, fga_client_response_model_id, fga_client_user, + fga_client_model_cache_result, http_client_request_duration, http_host, http_request_method, diff --git a/openfga_sdk/telemetry/configuration.py b/openfga_sdk/telemetry/configuration.py index 40958e88..b8922010 100644 --- a/openfga_sdk/telemetry/configuration.py +++ b/openfga_sdk/telemetry/configuration.py @@ -479,6 +479,7 @@ def clear(self) -> None: TelemetryAttributes.fga_client_request_store_id: False, TelemetryAttributes.fga_client_response_model_id: False, TelemetryAttributes.fga_client_user: False, + TelemetryAttributes.fga_client_model_cache_result: False, TelemetryAttributes.http_client_request_duration: False, TelemetryAttributes.http_host: False, TelemetryAttributes.http_request_method: False, @@ -616,6 +617,7 @@ def getSdkDefaults() -> dict[TelemetryAttribute | str, bool]: TelemetryAttributes.fga_client_request_store_id: True, TelemetryAttributes.fga_client_response_model_id: True, TelemetryAttributes.fga_client_user: False, + TelemetryAttributes.fga_client_model_cache_result: True, TelemetryAttributes.http_client_request_duration: False, TelemetryAttributes.http_host: True, TelemetryAttributes.http_request_method: True, @@ -828,6 +830,10 @@ def clear(self) -> None: TelemetryCounters.fga_client_credentials_request: None, TelemetryHistograms.fga_client_request_duration: None, TelemetryHistograms.fga_client_query_duration: None, + TelemetryCounters.fga_client_batch_check_checks_requested: None, + TelemetryCounters.fga_client_batch_check_checks_sent: None, + TelemetryCounters.fga_client_model_cache_lookup: None, + TelemetryCounters.fga_client_batch_check_merge_fallback: None, } self._valid = True @@ -990,6 +996,10 @@ def getSdkDefaults() -> dict[ TelemetryCounters.fga_client_credentials_request: TelemetryMetricConfiguration.getSdkDefaults(), TelemetryHistograms.fga_client_query_duration: TelemetryMetricConfiguration.getSdkDefaults(), TelemetryHistograms.fga_client_request_duration: TelemetryMetricConfiguration.getSdkDefaults(), + TelemetryCounters.fga_client_batch_check_checks_requested: TelemetryMetricConfiguration.getSdkDefaults(), + TelemetryCounters.fga_client_batch_check_checks_sent: TelemetryMetricConfiguration.getSdkDefaults(), + TelemetryCounters.fga_client_model_cache_lookup: TelemetryMetricConfiguration.getSdkDefaults(), + TelemetryCounters.fga_client_batch_check_merge_fallback: TelemetryMetricConfiguration.getSdkDefaults(), } diff --git a/openfga_sdk/telemetry/counters.py b/openfga_sdk/telemetry/counters.py index 7e2e0ae0..efc9d20e 100644 --- a/openfga_sdk/telemetry/counters.py +++ b/openfga_sdk/telemetry/counters.py @@ -18,9 +18,33 @@ class TelemetryCounters: description="Total number of requests made to the FGA server.", ) + fga_client_batch_check_checks_requested: TelemetryCounter = TelemetryCounter( + name="fga-client.batch_check.checks_requested", + description="Total number of checks passed to BatchCheck with merge_equivalent_checks on.", + ) + + fga_client_batch_check_checks_sent: TelemetryCounter = TelemetryCounter( + name="fga-client.batch_check.checks_sent", + description="Total number of checks sent by BatchCheck with merge_equivalent_checks on.", + ) + + fga_client_model_cache_lookup: TelemetryCounter = TelemetryCounter( + name="fga-client.model_cache.lookup", + description="Total number of authorization model cache lookups.", + ) + + fga_client_batch_check_merge_fallback: TelemetryCounter = TelemetryCounter( + name="fga-client.batch_check.merge_fallback", + description="Total number of BatchCheck calls sent unmerged because the authorization model couldn't be read.", + ) + _counters: list[TelemetryCounter] = [ fga_client_credentials_request, fga_client_request, + fga_client_batch_check_checks_requested, + fga_client_batch_check_checks_sent, + fga_client_model_cache_lookup, + fga_client_batch_check_merge_fallback, ] @staticmethod diff --git a/openfga_sdk/telemetry/metrics.py b/openfga_sdk/telemetry/metrics.py index 3cc9d739..8d8d1fe0 100644 --- a/openfga_sdk/telemetry/metrics.py +++ b/openfga_sdk/telemetry/metrics.py @@ -63,6 +63,101 @@ def histogram(self, histogram: TelemetryHistogram) -> Histogram: return self._histograms[histogram.name] + def _add( + self, + counter: TelemetryCounter, + value: int, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None, + configuration: TelemetryConfiguration | None, + ) -> Counter: + instrument = self.counter(counter) + + if isMetricEnabled(configuration, counter): + attribute_filters = None + + if isinstance(configuration, TelemetryConfiguration) and isinstance( + configuration.metrics, TelemetryMetricsConfiguration + ): + metric_configuration = configuration.metrics.getMetrics( + filter_enabled=False + ).get(counter) + + if isinstance(metric_configuration, TelemetryMetricConfiguration): + attribute_filters = metric_configuration.getAttributes() + + prepared_attributes = TelemetryAttributes.prepare( + attributes, + filter=attribute_filters, + ) + + instrument.add(amount=value, attributes=prepared_attributes) + + return instrument + + def batchCheckChecksRequested( + self, + value: int, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None = None, + configuration: TelemetryConfiguration | None = None, + ) -> Counter: + """ + Record the checks passed to BatchCheck with merge_equivalent_checks on. + """ + return self._add( + TelemetryCounters.fga_client_batch_check_checks_requested, + value, + attributes, + configuration, + ) + + def batchCheckChecksSent( + self, + value: int, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None = None, + configuration: TelemetryConfiguration | None = None, + ) -> Counter: + """ + Record the checks sent by BatchCheck with merge_equivalent_checks on. + """ + return self._add( + TelemetryCounters.fga_client_batch_check_checks_sent, + value, + attributes, + configuration, + ) + + def modelCacheLookup( + self, + value: int = 1, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None = None, + configuration: TelemetryConfiguration | None = None, + ) -> Counter: + """ + Record an authorization model cache lookup. + """ + return self._add( + TelemetryCounters.fga_client_model_cache_lookup, + value, + attributes, + configuration, + ) + + def batchCheckMergeFallback( + self, + value: int = 1, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None = None, + configuration: TelemetryConfiguration | None = None, + ) -> Counter: + """ + Record a BatchCheck call sent unmerged because the authorization model couldn't be read. + """ + return self._add( + TelemetryCounters.fga_client_batch_check_merge_fallback, + value, + attributes, + configuration, + ) + def request( self, value: int = 1, diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py new file mode 100644 index 00000000..9e59363d --- /dev/null +++ b/test/client/batch_check_merge_test.py @@ -0,0 +1,424 @@ +import asyncio +import json + +from unittest import IsolatedAsyncioTestCase +from unittest.mock import patch + +import urllib3 + +from openfga_sdk import rest +from openfga_sdk.client import ClientConfiguration +from openfga_sdk.client.client import OpenFgaClient +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest +from openfga_sdk.exceptions import ( + FgaValidationException, + ForbiddenException, + ValidationException, +) +from openfga_sdk.telemetry.attributes import TelemetryAttributes +from openfga_sdk.telemetry.metrics import TelemetryMetrics + + +STORE_ID = "01YCP46JKYM8FJCQ37NMBYHE5X" +MODEL_ID = "01GXSA8YR785C4FYS3C0RTG7B1" +API_URL = "http://api.fga.example" +MODEL_URL = f"{API_URL}/stores/{STORE_ID}/authorization-models/{MODEL_ID}" +BATCH_CHECK_URL = f"{API_URL}/stores/{STORE_ID}/batch-check" + +# define viewer: [user], can_view: viewer, can_share: can_view, editor: [user] +MODEL = { + "id": MODEL_ID, + "schema_version": "1.1", + "type_definitions": [ + {"type": "user"}, + { + "type": "document", + "relations": { + "viewer": {"this": {}}, + "can_view": {"computedUserset": {"relation": "viewer"}}, + "can_share": {"computedUserset": {"relation": "can_view"}}, + "editor": {"this": {}}, + }, + "metadata": { + "relations": { + "viewer": {"directly_related_user_types": [{"type": "user"}]}, + "can_view": {"directly_related_user_types": []}, + "can_share": {"directly_related_user_types": []}, + "editor": {"directly_related_user_types": [{"type": "user"}]}, + } + }, + }, + ], +} + + +def http_mock_response(body, status): + headers = urllib3.response.HTTPHeaderDict({"content-type": "application/json"}) + return urllib3.HTTPResponse( + body.encode("utf-8"), headers, status, preload_content=False + ) + + +def mock_response(body, status=200): + obj = http_mock_response(body, status) + return rest.RESTResponse(obj, obj.data) + + +def checks(): + return [ + ClientBatchCheckItem( + user="user:anne", relation="viewer", object="document:1", correlation_id="a" + ), + ClientBatchCheckItem( + user="user:anne", + relation="can_view", + object="document:1", + correlation_id="b", + ), + ClientBatchCheckItem( + user="user:anne", + relation="can_share", + object="document:1", + correlation_id="c", + ), + ClientBatchCheckItem( + user="user:anne", relation="editor", object="document:1", correlation_id="d" + ), + ] + + +class FakeServer: + """ + Answers model reads and BatchCheck requests, and records what was sent. + """ + + def __init__(self, model_error=None, answer=None): + self.model_error = model_error + self.answer = answer or ( + lambda check: {"allowed": check["tuple_key"]["relation"] == "viewer"} + ) + self.model_reads = 0 + self.sent = [] + + def __call__(self, method, url, **kwargs): + if method == "GET" and url == MODEL_URL: + self.model_reads += 1 + if self.model_error is not None: + raise self.model_error + return mock_response(json.dumps({"authorization_model": MODEL})) + + if method == "POST" and url == BATCH_CHECK_URL: + body = kwargs["body"] + self.sent.append(body) + return mock_response( + json.dumps( + { + "result": { + check["correlation_id"]: self.answer(check) + for check in body["checks"] + } + } + ) + ) + + raise AssertionError(f"Unexpected request: {method} {url}") + + +def sent_checks(server): + return [ + ( + check["correlation_id"], + check["tuple_key"]["relation"], + ) + for body in server.sent + for check in body["checks"] + ] + + +def forbidden(): + return ForbiddenException(http_resp=http_mock_response("{}", 403)) + + +class TestBatchCheckMergeEquivalentChecks(IsolatedAsyncioTestCase): + def setUp(self): + self.configuration = ClientConfiguration( + api_url=API_URL, + store_id=STORE_ID, + authorization_model_id=MODEL_ID, + ) + + async def batch_check(self, client, items, options=None): + return await client.batch_check( + ClientBatchCheckRequest(checks=items), + options={"merge_equivalent_checks": True, **(options or {})}, + ) + + @patch.object(rest.RESTClientObject, "request") + async def test_merges_aliases_and_copies_the_answer_back(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + items = checks() + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, items) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) + self.assertEqual(server.sent[0]["authorization_model_id"], MODEL_ID) + self.assertEqual(response.checks_sent, 2) + self.assertEqual( + [(r.correlation_id, r.allowed, r.error) for r in response.result], + [ + ("a", True, None), + ("b", True, None), + ("c", True, None), + ("d", False, None), + ], + ) + self.assertEqual([r.request for r in response.result], items) + + @patch.object(rest.RESTClientObject, "request") + async def test_merges_checks_that_would_land_in_different_batches( + self, mock_request + ): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check( + client, checks()[:3], options={"max_batch_size": 1} + ) + + self.assertEqual(sent_checks(server), [("merged-1", "viewer")]) + self.assertEqual(response.checks_sent, 1) + self.assertEqual(len(response.result), 3) + + @patch.object(rest.RESTClientObject, "request") + async def test_reads_the_model_once_for_parallel_and_later_calls( + self, mock_request + ): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + await asyncio.gather( + *[self.batch_check(client, checks()) for _ in range(5)] + ) + await self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(len(server.sent), 6) + + @patch.object(rest.RESTClientObject, "request") + async def test_requires_a_model_id(self, mock_request): + self.configuration.authorization_model_id = None + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaises(FgaValidationException): + await self.batch_check(client, checks()) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_rejects_invalid_correlation_ids(self, mock_request): + for correlation_id in ["has space", "x" * 37, "é"]: + items = checks() + items[0].correlation_id = correlation_id + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaises(FgaValidationException): + await self.batch_check(client, items) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_rejects_duplicate_correlation_ids(self, mock_request): + items = checks() + items[1].correlation_id = "a" + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex( + FgaValidationException, r"Duplicate correlation_id \(a\) provided" + ): + await self.batch_check(client, items) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_generates_missing_correlation_ids(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + items = checks() + items[3].correlation_id = None + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, items) + + self.assertIsNotNone(items[3].correlation_id) + self.assertEqual(response.result[3].correlation_id, items[3].correlation_id) + + @patch.object(rest.RESTClientObject, "request") + async def test_no_checks_sends_nothing(self, mock_request): + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, []) + + self.assertEqual(response.result, []) + self.assertEqual(response.checks_sent, 0) + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): + server = FakeServer(model_error=forbidden()) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs("openfga_sdk.client.client", "WARNING") as logs: + response = await self.batch_check(client, checks()) + second = await self.batch_check(client, checks()) + + self.assertEqual(len(logs.records), 1) + self.assertIn(MODEL_ID, logs.output[0]) + self.assertIn(STORE_ID, logs.output[0]) + self.assertIn("403", logs.output[0]) + self.assertEqual(server.model_reads, 1) + unmerged = [ + ("a", "viewer"), + ("b", "can_view"), + ("c", "can_share"), + ("d", "editor"), + ] + self.assertEqual(sent_checks(server), unmerged * 2) + self.assertEqual(response.checks_sent, 4) + self.assertEqual(second.checks_sent, 4) + self.assertEqual( + [r.allowed for r in response.result], [True, False, False, False] + ) + + @patch.object(rest.RESTClientObject, "request") + async def test_copies_an_error_to_every_check_in_the_group(self, mock_request): + server = FakeServer( + answer=lambda check: ( + {"error": {"message": "boom"}} + if check["correlation_id"] == "merged-1" + else {"allowed": True} + ) + ) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, checks()) + + for result in response.result[:3]: + self.assertFalse(result.allowed) + self.assertEqual(result.error.message, "boom") + self.assertTrue(response.result[3].allowed) + self.assertIsNone(response.result[3].error) + + @patch.object(rest.RESTClientObject, "request") + async def test_a_missing_answer_is_an_error_and_unknown_answers_are_ignored( + self, mock_request + ): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + return mock_response( + json.dumps( + {"result": {"d": {"allowed": True}, "unknown": {"allowed": True}}} + ) + ) + + mock_request.side_effect = handle + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, checks()) + + self.assertEqual( + [r.correlation_id for r in response.result], ["a", "b", "c", "d"] + ) + for result in response.result[:3]: + self.assertFalse(result.allowed) + self.assertEqual( + result.error.message, "No result returned for correlation_id (merged-1)" + ) + self.assertTrue(response.result[3].allowed) + + @patch.object(rest.RESTClientObject, "request") + async def test_a_failed_request_fails_the_call(self, mock_request): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + raise ValidationException(http_resp=http_mock_response("{}", 400)) + + mock_request.side_effect = handle + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaises(ValidationException): + await self.batch_check(client, checks()) + + @patch.object(rest.RESTClientObject, "request") + async def test_option_off_is_unchanged(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + response = await client.batch_check( + ClientBatchCheckRequest(checks=checks()) + ) + + self.assertEqual(server.model_reads, 0) + self.assertEqual( + sent_checks(server), + [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")], + ) + self.assertIsNone(response.checks_sent) + + @patch.object(TelemetryMetrics, "batchCheckChecksSent") + @patch.object(TelemetryMetrics, "batchCheckChecksRequested") + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(TelemetryMetrics, "modelCacheLookup") + @patch.object(rest.RESTClientObject, "request") + async def test_records_telemetry( + self, mock_request, mock_lookup, mock_fallback, mock_requested, mock_sent + ): + mock_request.side_effect = FakeServer() + attributes = { + TelemetryAttributes.fga_client_request_store_id: STORE_ID, + TelemetryAttributes.fga_client_request_model_id: MODEL_ID, + } + + async with OpenFgaClient(self.configuration) as client: + await self.batch_check(client, checks()) + await self.batch_check(client, checks()) + + self.assertEqual( + [ + call.kwargs["attributes"][ + TelemetryAttributes.fga_client_model_cache_result + ] + for call in mock_lookup.call_args_list + ], + ["miss", "hit"], + ) + mock_fallback.assert_not_called() + self.assertEqual(mock_requested.call_args.args, (4,)) + self.assertEqual(mock_requested.call_args.kwargs["attributes"], attributes) + self.assertEqual(mock_sent.call_args.args, (2,)) + self.assertEqual(mock_sent.call_args.kwargs["attributes"], attributes) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_records_the_fallback_with_its_status_code( + self, mock_request, mock_fallback + ): + mock_request.side_effect = FakeServer(model_error=forbidden()) + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs("openfga_sdk.client.client", "WARNING"): + await self.batch_check(client, checks()) + + attributes = mock_fallback.call_args.kwargs["attributes"] + self.assertEqual(attributes[TelemetryAttributes.http_response_status_code], 403) + self.assertEqual( + attributes[TelemetryAttributes.fga_client_request_model_id], MODEL_ID + ) diff --git a/test/client/equivalent_checks_cases_test.py b/test/client/equivalent_checks_cases_test.py new file mode 100644 index 00000000..2897e166 --- /dev/null +++ b/test/client/equivalent_checks_cases_test.py @@ -0,0 +1,92 @@ +""" +Runs the shared equivalent-checks cases from openfga/language against the Python resolver. + +The cases file is copied from openfga/language. Run `make update-equivalent-checks-cases` +to update it. +""" + +import json + +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openfga_sdk.client.equivalent_checks import resolve +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.client.models.tuple import ClientTuple +from openfga_sdk.models.relationship_condition import RelationshipCondition +from openfga_sdk.sync.api_client import ApiClient + + +CASES_FILE = Path(__file__).parent.parent / "data" / "equivalent-checks-cases.json" +CASES = json.loads(CASES_FILE.read_text())["cases"] +MODEL_ID = "01GXSA8YR785C4FYS3C0RTG7B1" + + +def _model(model_json): + with ApiClient() as api_client: + return api_client.deserialize( + SimpleNamespace(data=json.dumps(dict(model_json, id=MODEL_ID))), + "AuthorizationModel", + ) + + +def _contextual_tuple(tuple_json): + condition = tuple_json.get("condition") + return ClientTuple( + user=tuple_json["user"], + relation=tuple_json["relation"], + object=tuple_json["object"], + condition=( + RelationshipCondition( + name=condition["name"], context=condition.get("context") + ) + if condition is not None + else None + ), + ) + + +def _check(check_json): + contextual_tuples = check_json.get("contextual_tuples") + return ClientBatchCheckItem( + user=check_json["user"], + relation=check_json["relation"], + object=check_json["object"], + correlation_id=check_json["id"], + context=check_json.get("context"), + contextual_tuples=( + [_contextual_tuple(item) for item in contextual_tuples] + if contextual_tuples is not None + else None + ), + ) + + +def test_cases_file_is_not_empty(): + assert len(CASES) > 0 + + +@pytest.mark.parametrize("case", CASES, ids=[case["name"] for case in CASES]) +def test_equivalent_checks_case(case): + checks = [_check(check) for check in case["checks"]] + + groups = resolve(_model(case["model"]), checks) + + actual = [ + { + "id": group.check.correlation_id, + "user": group.check.user, + "relation": group.check.relation, + "object": group.check.object, + "for": [member.correlation_id for member in group.members], + } + for group in groups + ] + assert actual == case["expected_sent"] + + for group in groups: + first = group.members[0] + assert group.check.context is first.context + assert group.check.contextual_tuples is first.contextual_tuples diff --git a/test/client/equivalent_checks_test.py b/test/client/equivalent_checks_test.py new file mode 100644 index 00000000..d404d4cd --- /dev/null +++ b/test/client/equivalent_checks_test.py @@ -0,0 +1,229 @@ +import datetime +import math + +import pytest + +from openfga_sdk.client.equivalent_checks import ( + EquivalentCheckGroup, + expand, + resolve, + unmerged, + validate_correlation_ids, +) +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.client.models.tuple import ClientTuple +from openfga_sdk.exceptions import FgaValidationException +from openfga_sdk.models.authorization_model import AuthorizationModel +from openfga_sdk.models.batch_check_single_result import BatchCheckSingleResult +from openfga_sdk.models.check_error import CheckError +from openfga_sdk.models.object_relation import ObjectRelation +from openfga_sdk.models.relationship_condition import RelationshipCondition +from openfga_sdk.models.type_definition import TypeDefinition +from openfga_sdk.models.userset import Userset + + +# define viewer: [user], can_view: viewer +MODEL = AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", + schema_version="1.1", + type_definitions=[ + TypeDefinition(type="user"), + TypeDefinition( + type="document", + relations={ + "viewer": Userset(this={}), + "can_view": Userset( + computed_userset=ObjectRelation(object="", relation="viewer") + ), + }, + ), + ], +) + + +def check(correlation_id, relation="can_view", context=None, contextual_tuples=None): + return ClientBatchCheckItem( + user="user:anne", + relation=relation, + object="document:1", + correlation_id=correlation_id, + context=context, + contextual_tuples=contextual_tuples, + ) + + +def sent(groups): + return [ + ( + group.check.correlation_id, + group.check.relation, + [member.correlation_id for member in group.members], + ) + for group in groups + ] + + +@pytest.mark.parametrize( + "value", + [ + math.nan, + math.inf, + 10**400, + (1, 2), + datetime.datetime(2026, 1, 1), + {1: "non-string key"}, + {"nested": [object()]}, + ], + ids=["nan", "inf", "huge-int", "tuple", "datetime", "int-key", "object"], +) +def test_values_that_cannot_be_compared_are_sent_as_is(value): + groups = resolve( + MODEL, + [check("a", context={"x": value}), check("b", context={"x": value})], + ) + + assert sent(groups) == [("a", "can_view", ["a"]), ("b", "can_view", ["b"])] + + +def test_a_context_that_is_not_an_object_is_sent_as_is(): + groups = resolve(MODEL, [check("a", context=["x"]), check("b", context=["x"])]) + + assert sent(groups) == [("a", "can_view", ["a"]), ("b", "can_view", ["b"])] + + +def test_values_in_a_condition_context_that_cannot_be_compared_are_sent_as_is(): + contextual_tuples = [ + ClientTuple( + user="user:anne", + relation="viewer", + object="document:2", + condition=RelationshipCondition(name="c", context={"x": math.nan}), + ) + ] + + groups = resolve( + MODEL, + [ + check("a", contextual_tuples=contextual_tuples), + check("b", contextual_tuples=contextual_tuples), + ], + ) + + assert sent(groups) == [("a", "can_view", ["a"]), ("b", "can_view", ["b"])] + + +def test_checks_that_are_not_strings_are_sent_as_is(): + item = check("a") + item.user = None + + assert sent(resolve(MODEL, [item])) == [("a", "can_view", ["a"])] + + +def test_a_model_without_type_definitions_sends_everything_as_is(): + model = AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", schema_version="1.1", type_definitions=[] + ) + + assert sent(resolve(model, [check("a"), check("b")])) == [ + ("a", "can_view", ["a"]), + ("b", "can_view", ["b"]), + ] + + +def test_unmerged_sends_every_check_as_is(): + items = [check("a"), check("b")] + + assert sent(unmerged(items)) == [ + ("a", "can_view", ["a"]), + ("b", "can_view", ["b"]), + ] + + +@pytest.mark.parametrize( + "correlation_id", + ["", "has space", "x" * 37, "é", "a/b", 1], +) +def test_validate_correlation_ids_rejects_invalid_ids(correlation_id): + with pytest.raises(FgaValidationException, match="is invalid"): + validate_correlation_ids([check(correlation_id)]) + + +def test_validate_correlation_ids_accepts_valid_ids(): + validate_correlation_ids([check("a_b-1"), check("x" * 36)]) + + +def test_validate_correlation_ids_rejects_duplicates(): + with pytest.raises( + FgaValidationException, match=r"Duplicate correlation_id \(a\) provided" + ): + validate_correlation_ids([check("a"), check("a")]) + + +def test_expand_copies_answers_in_input_order(): + a, b, c = check("a"), check("b"), check("c", relation="viewer") + groups = [ + EquivalentCheckGroup(check=check("c", relation="viewer"), members=[c]), + EquivalentCheckGroup( + check=check("merged-1", relation="viewer"), members=[a, b] + ), + ] + error = CheckError(message="boom") + + responses = expand( + [a, b, c], + groups, + { + "merged-1": BatchCheckSingleResult(error=error), + "c": BatchCheckSingleResult(allowed=True), + "unknown": BatchCheckSingleResult(allowed=True), + }, + ) + + assert [(r.correlation_id, r.allowed, r.error) for r in responses] == [ + ("a", False, error), + ("b", False, error), + ("c", True, None), + ] + assert [r.request for r in responses] == [a, b, c] + + +def test_expand_turns_a_missing_answer_into_an_error(): + a, b = check("a"), check("b") + + responses = expand( + [a, b], + [EquivalentCheckGroup(check=check("merged-1"), members=[a, b])], + {}, + ) + + for response in responses: + assert response.allowed is False + assert response.error.message == ( + "No result returned for correlation_id (merged-1)" + ) + + +@pytest.mark.parametrize( + "can_view", + [ + Userset(computed_userset=ObjectRelation(object="parent", relation="viewer")), + Userset(this={}, computed_userset=ObjectRelation(object="", relation="viewer")), + ], + ids=["object-set", "mixed-rewrite"], +) +def test_rewrites_that_only_look_like_aliases_are_not_merged(can_view): + model = AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", + schema_version="1.1", + type_definitions=[ + TypeDefinition(type="user"), + TypeDefinition( + type="document", + relations={"viewer": Userset(this={}), "can_view": can_view}, + ), + ], + ) + + groups = resolve(model, [check("a", relation="viewer"), check("b")]) + + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "can_view", ["b"])] diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py new file mode 100644 index 00000000..b30a4798 --- /dev/null +++ b/test/client/model_cache_test.py @@ -0,0 +1,248 @@ +import asyncio +import threading +import time + +from unittest import IsolatedAsyncioTestCase, TestCase + +from openfga_sdk.client.model_cache import AsyncModelCache, ModelCache + + +KEY = ("store", "model") + + +class FakeClock: + def __init__(self): + self.now = 0.0 + + def __call__(self): + return self.now + + +class TestAsyncModelCache(IsolatedAsyncioTestCase): + async def test_parallel_lookups_share_one_read_and_later_lookups_hit(self): + cache = AsyncModelCache() + release = asyncio.Event() + reads = 0 + + async def load(): + nonlocal reads + reads += 1 + await release.wait() + return "model" + + lookups = [asyncio.ensure_future(cache.get(KEY, load)) for _ in range(3)] + await asyncio.sleep(0) + release.set() + results = await asyncio.gather(*lookups) + + self.assertEqual(reads, 1) + self.assertEqual([(r.model, r.hit) for r in results], [("model", False)] * 3) + + later = await cache.get(KEY, load) + self.assertEqual((later.model, later.hit, reads), ("model", True, 1)) + + async def test_a_failed_read_is_remembered_for_a_short_time(self): + clock = FakeClock() + cache = AsyncModelCache(failure_ttl=60, clock=clock) + reads = 0 + error = RuntimeError("forbidden") + + async def load(): + nonlocal reads + reads += 1 + raise error + + first = await cache.get(KEY, load) + clock.now = 59 + second = await cache.get(KEY, load) + + self.assertIs(first.error, error) + self.assertIs(second.error, error) + self.assertIsNone(second.model) + self.assertEqual(reads, 1) + + clock.now = 60 + await cache.get(KEY, load) + self.assertEqual(reads, 2) + + async def test_drops_the_least_recently_used_model(self): + cache = AsyncModelCache(max_models=2) + + async def load_for(key): + async def load(): + return f"model-{key}" + + return await cache.get(key, load) + + await load_for("a") + await load_for("b") + self.assertTrue((await load_for("a")).hit) + await load_for("c") + + self.assertTrue((await load_for("a")).hit) + self.assertFalse((await load_for("b")).hit) + + async def test_a_cancelled_caller_does_not_cancel_the_shared_read(self): + cache = AsyncModelCache() + release = asyncio.Event() + + async def load(): + await release.wait() + return "model" + + cancelled = asyncio.ensure_future(cache.get(KEY, load)) + waiting = asyncio.ensure_future(cache.get(KEY, load)) + await asyncio.sleep(0) + cancelled.cancel() + release.set() + + self.assertEqual((await waiting).model, "model") + with self.assertRaises(asyncio.CancelledError): + await cancelled + + async def test_close_cancels_in_flight_reads_without_caching_them(self): + cache = AsyncModelCache() + started = asyncio.Event() + + async def hang(): + started.set() + await asyncio.Event().wait() + + lookup = asyncio.ensure_future(cache.get(KEY, hang)) + await started.wait() + await cache.close() + + with self.assertRaises(asyncio.CancelledError): + await lookup + + async def load(): + return "model" + + self.assertEqual((await cache.get(KEY, load)).model, "model") + + +class TestModelCache(TestCase): + def test_threads_share_one_read_and_later_lookups_hit(self): + cache = ModelCache() + started = threading.Event() + release = threading.Event() + reads = 0 + + def load(): + nonlocal reads + reads += 1 + started.set() + release.wait() + return "model" + + results = [] + owner = threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + owner.start() + started.wait() + waiters = [ + threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + for _ in range(3) + ] + for waiter in waiters: + waiter.start() + release.set() + for thread in [owner, *waiters]: + thread.join() + + self.assertEqual(reads, 1) + self.assertEqual([r.model for r in results], ["model"] * 4) + self.assertTrue(cache.get(KEY, load).hit) + + def test_a_failed_read_is_remembered_for_a_short_time(self): + clock = FakeClock() + cache = ModelCache(failure_ttl=60, clock=clock) + reads = 0 + error = RuntimeError("forbidden") + + def load(): + nonlocal reads + reads += 1 + raise error + + self.assertIs(cache.get(KEY, load).error, error) + clock.now = 59 + self.assertIs(cache.get(KEY, load).error, error) + self.assertEqual(reads, 1) + + clock.now = 60 + cache.get(KEY, load) + self.assertEqual(reads, 2) + + def test_drops_the_least_recently_used_model(self): + cache = ModelCache(max_models=2) + + def get(key): + return cache.get(key, lambda: f"model-{key}") + + get("a") + get("b") + self.assertTrue(get("a").hit) + get("c") + + self.assertTrue(get("a").hit) + self.assertFalse(get("b").hit) + + def test_threads_waiting_on_a_failed_read_get_its_error(self): + cache = ModelCache() + started = threading.Event() + release = threading.Event() + error = RuntimeError("forbidden") + + def load(): + started.set() + release.wait() + raise error + + results = [] + owner = threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + owner.start() + started.wait() + waiters = [ + threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + for _ in range(3) + ] + for waiter in waiters: + waiter.start() + time.sleep(0.05) + release.set() + for thread in [owner, *waiters]: + thread.join() + + self.assertEqual([r.error for r in results], [error] * 4) + + def test_remembers_a_bounded_number_of_failures(self): + cache = ModelCache(max_models=2) + reads = [] + + def get(key): + def load(): + reads.append(key) + raise RuntimeError(key) + + return cache.get(key, load) + + get("a") + get("b") + get("c") + get("b") + get("c") + self.assertEqual(reads, ["a", "b", "c"]) + + get("a") + self.assertEqual(reads, ["a", "b", "c", "a"]) + + def test_an_interrupted_read_is_not_cached(self): + cache = ModelCache() + + def interrupt(): + raise KeyboardInterrupt() + + with self.assertRaises(KeyboardInterrupt): + cache.get(KEY, interrupt) + + self.assertEqual(cache.get(KEY, lambda: "model").model, "model") diff --git a/test/data/equivalent-checks-cases.json b/test/data/equivalent-checks-cases.json new file mode 100644 index 00000000..debbb0f7 --- /dev/null +++ b/test/data/equivalent-checks-cases.json @@ -0,0 +1,5598 @@ +{ + "note": "Generated from equivalent-checks-cases.yaml, with every model as JSON. Don't edit this file: edit the YAML file and run `make generate-equivalent-checks-json`.", + "cases": [ + { + "name": "merges an alias with the relation it points to", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges an alias chain into its final relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:bob", + "relation": "can_share", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b", "c"] + }, + { + "id": "d", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["d"] + } + ] + }, + { + "name": "sends a lone alias check with its final relation and the caller's id", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + } + ] + }, + { + "name": "merges exact repeats", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "editor": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "does not merge checks that end at different relations", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_edit": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_edit": { + "computedUserset": { + "relation": "editor" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_edit", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge checks for different users", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge checks on different objects", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:2" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:2", + "for": ["b"] + } + ] + }, + { + "name": "follows the aliases of the object's type only", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "owner": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": {} + } + }, + "relations": { + "owner": { + "this": {} + }, + "viewer": { + "computedUserset": { + "relation": "owner" + } + } + }, + "type": "folder" + }, + { + "metadata": { + "relations": { + "owner": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "owner": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "folder:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "owner", + "object": "folder:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:anne", + "relation": "owner", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "owner", + "object": "folder:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "owner", + "object": "document:1", + "for": ["d"] + } + ] + }, + { + "name": "sends checks in the order of each group's first check", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:bob", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "e", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "c"] + }, + { + "id": "merged-2", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["b", "d"] + }, + { + "id": "e", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["e"] + } + ] + }, + { + "name": "stops the chain at a union", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "union": { + "child": [ + { + "computedUserset": { + "relation": "viewer" + } + }, + { + "computedUserset": { + "relation": "editor" + } + } + ] + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at an intersection", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "intersection": { + "child": [ + { + "computedUserset": { + "relation": "viewer" + } + }, + { + "computedUserset": { + "relation": "editor" + } + } + ] + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at an exclusion", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "blocked": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "blocked": { + "this": {} + }, + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "difference": { + "base": { + "computedUserset": { + "relation": "viewer" + } + }, + "subtract": { + "computedUserset": { + "relation": "blocked" + } + } + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at a relation from a parent", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "viewer": { + "this": {} + } + }, + "type": "folder" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "parent": { + "directly_related_user_types": [ + { + "type": "folder" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "tupleToUserset": { + "computedUserset": { + "relation": "viewer" + }, + "tupleset": { + "relation": "parent" + } + } + }, + "parent": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at direct types combined with an alias", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "union": { + "child": [ + { + "this": {} + }, + { + "computedUserset": { + "relation": "viewer" + } + } + ] + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at a union with a single child", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": { + "directly_related_user_types": [] + }, + "can_view": { + "directly_related_user_types": [] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "union": { + "child": [ + { + "computedUserset": { + "relation": "viewer" + } + } + ] + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "sends checks as is when the alias chain points to a missing relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "missing" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_share", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "sends checks as is when the alias chain loops", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "loop_a": {}, + "loop_b": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "loop_a": { + "computedUserset": { + "relation": "loop_b" + } + }, + "loop_b": { + "computedUserset": { + "relation": "loop_a" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "loop_a", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "loop_b", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "loop_a", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "loop_b", + "object": "document:1", + "for": ["b"] + }, + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c", "d"] + } + ] + }, + { + "name": "sends as is a userset on the same object whose relation is the one asked for", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#can_share", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#viewer", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "document:1#can_share", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "document:1#viewer", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "sends as is a userset on the same object whose relation is in the chain", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#can_view", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "document:1#can_view", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "document:1#can_view", + "relation": "can_view", + "object": "document:1", + "for": ["b"] + }, + { + "id": "c", + "user": "document:1#can_view", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "sends as is a userset on the same object whose relation is the final relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#viewer", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#viewer", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "document:1#viewer", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "document:1#viewer", + "relation": "can_view", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge repeats of a userset on the same object whose relation is in the chain", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "merges a userset on the same object whose relation isn't in the chain", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "editor", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#editor", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#editor", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "document:1#editor", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a userset on the same object whose relation is another alias of the final relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_read": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_read", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_read": { + "computedUserset": { + "relation": "viewer" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#can_read", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#can_read", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "document:1#can_read", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a userset on another object", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:2#can_view", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:2#can_view", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "document:2#can_view", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a userset on an object of another type with the same id", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "viewer": { + "this": {} + } + }, + "type": "folder" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "viewer", + "type": "folder" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "folder:1#viewer", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "folder:1#viewer", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "folder:1#viewer", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a userset of another type", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "member", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "team:eng#member", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "team:eng#member", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a wildcard user", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "type": "user", + "wildcard": {} + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:*", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:*", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a user whose type is in the model but not allowed on the relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "team:eng", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "team:eng", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "team:eng", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "sends as is a check on an unknown object type", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "folder:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "folder:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "sends as is a check with an unknown relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "sends as is a check with an unknown user type", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "employee:1", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "employee:*", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "employee:1#member", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "employee:1", + "relation": "can_view", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "employee:*", + "relation": "can_view", + "object": "document:1", + "for": ["b"] + }, + { + "id": "c", + "user": "employee:1#member", + "relation": "can_view", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "sends as is a check with an unknown userset relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "member", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "team:eng#owner", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "team:eng#member", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "team:eng#owner", + "relation": "can_view", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge repeats of a check that isn't in the model", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "merges checks with the same context", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu" + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges context with keys in a different order", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\" && x > 0.0", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + }, + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "x": 1.5 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1.5, + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges 1 and 1.0", + "model": { + "conditions": { + "positive": { + "expression": "x > 0.0", + "name": "positive", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "positive", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": 1 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1.0 + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges integers that are the same double", + "model": { + "conditions": { + "at_most": { + "expression": "x <= 9007199254740992.0", + "name": "at_most", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "at_most", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": 9007199254740993 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 9007199254740992 + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "does not merge 0 and -0.0", + "model": { + "conditions": { + "negative_sign": { + "expression": "1.0 / x < 0.0", + "name": "negative_sign", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "negative_sign", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": 0 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": -0.0 + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge true and 1", + "model": { + "conditions": { + "positive": { + "expression": "x > 0.0", + "name": "positive", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "positive", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": true + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1 + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge the string \"1\" and the number 1", + "model": { + "conditions": { + "positive": { + "expression": "x > 0.0", + "name": "positive", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "positive", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": "1" + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1 + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge when a field is missing", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "x": 1 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge null and a missing field", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "x": null + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge no context and an empty context", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": {} + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge strings that differ by a trailing space", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu" + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu " + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge strings that differ only in Unicode form", + "model": { + "conditions": { + "in_city": { + "expression": "city == \"caf\\u00e9\"", + "name": "in_city", + "parameters": { + "city": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_city", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "city": "caf\u00e9" + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "city": "cafe\u0301" + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge lists in a different order", + "model": { + "conditions": { + "first_tag": { + "expression": "tags[0] == \"a\"", + "name": "first_tag", + "parameters": { + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "first_tag", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "tags": ["a", "b"] + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "tags": ["b", "a"] + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge lists with a repeated item", + "model": { + "conditions": { + "one_tag": { + "expression": "size(tags) == 1", + "name": "one_tag", + "parameters": { + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "one_tag", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "tags": ["a"] + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "tags": ["a", "a"] + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "merges nested values that match at every level", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "level": 1, + "items": [ + 1, + { + "k": "v", + "count": 2 + } + ] + } + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "meta": { + "items": [ + 1.0, + { + "count": 2.0, + "k": "v" + } + ], + "level": 1.0 + }, + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "does not merge nested values that differ", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [0] + } + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [-0.0] + } + } + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [false] + } + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "merges checks with the same contextual tuples", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "member", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges contextual tuples in a different order", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "member", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + } + ] + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "does not merge different contextual tuples", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:2" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge no contextual tuples and some", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge no contextual tuples and an empty list", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "sends as is a check whose contextual tuples repeat a tuple", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "does not merge a contextual tuple with and without a condition", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge contextual tuples with different condition names", + "model": { + "conditions": { + "in_eu": { + "expression": "region == \"eu\"", + "name": "in_eu", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + }, + "in_us": { + "expression": "region == \"us\"", + "name": "in_us", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_eu", + "type": "user" + }, + { + "condition": "in_us", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge contextual tuples with different condition context", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge a contextual tuple condition with no context and an empty context", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu" + }, + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region" + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + }, + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": {} + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "merges contextual tuple condition context that matches at every level", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\" && x > 0.0", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + }, + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "x": 1 + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "x": 1.0, + "region": "eu" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "sends as is checks whose contextual tuples repeat a user, relation and object with different conditions", + "model": { + "conditions": { + "in_eu": { + "expression": "region == \"eu\"", + "name": "in_eu", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + }, + "in_us": { + "expression": "region == \"us\"", + "name": "in_us", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_eu", + "type": "user" + }, + { + "condition": "in_us", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "numbers merged groups in order and skips groups of one", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + }, + { + "id": "b", + "user": "user:bob", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "e", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["a"] + }, + { + "id": "merged-1", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["b", "c"] + }, + { + "id": "merged-2", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["d", "e"] + } + ] + }, + { + "name": "skips a generated id that matches a caller's id", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["merged-1"] + }, + { + "id": "merged-2", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b", "c"] + } + ] + }, + { + "name": "skips generated ids that match caller ids inside merged groups", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "merged-2", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "c", + "user": "user:bob", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "d", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-3", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["merged-1", "merged-2"] + }, + { + "id": "merged-4", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["c", "d"] + } + ] + } + ] +} diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py new file mode 100644 index 00000000..94ec276e --- /dev/null +++ b/test/sync/client/batch_check_merge_test.py @@ -0,0 +1,304 @@ +import json + +from concurrent.futures import ThreadPoolExecutor +from unittest import TestCase +from unittest.mock import patch + +from openfga_sdk.client import ClientConfiguration +from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest +from openfga_sdk.exceptions import FgaValidationException, ForbiddenException +from openfga_sdk.sync import rest +from openfga_sdk.sync.client.client import OpenFgaClient +from openfga_sdk.telemetry.attributes import TelemetryAttributes +from openfga_sdk.telemetry.metrics import TelemetryMetrics +from test.client.batch_check_merge_test import ( + API_URL, + BATCH_CHECK_URL, + MODEL, + MODEL_ID, + MODEL_URL, + STORE_ID, + checks, + http_mock_response, + sent_checks, +) + + +def mock_response(body, status=200): + obj = http_mock_response(body, status) + return rest.RESTResponse(obj, obj.data) + + +class FakeServer: + """ + Answers model reads and BatchCheck requests, and records what was sent. + """ + + def __init__(self, model_error=None, answer=None): + self.model_error = model_error + self.answer = answer or ( + lambda check: {"allowed": check["tuple_key"]["relation"] == "viewer"} + ) + self.model_reads = 0 + self.sent = [] + + def __call__(self, method, url, **kwargs): + if method == "GET" and url == MODEL_URL: + self.model_reads += 1 + if self.model_error is not None: + raise self.model_error + return mock_response(json.dumps({"authorization_model": MODEL})) + + if method == "POST" and url == BATCH_CHECK_URL: + body = kwargs["body"] + self.sent.append(body) + return mock_response( + json.dumps( + { + "result": { + check["correlation_id"]: self.answer(check) + for check in body["checks"] + } + } + ) + ) + + raise AssertionError(f"Unexpected request: {method} {url}") + + +def forbidden(): + return ForbiddenException(http_resp=http_mock_response("{}", 403)) + + +class TestSyncBatchCheckMergeEquivalentChecks(TestCase): + def setUp(self): + self.configuration = ClientConfiguration( + api_url=API_URL, + store_id=STORE_ID, + authorization_model_id=MODEL_ID, + ) + + def batch_check(self, client, items, options=None): + return client.batch_check( + ClientBatchCheckRequest(checks=items), + options={"merge_equivalent_checks": True, **(options or {})}, + ) + + @patch.object(rest.RESTClientObject, "request") + def test_merges_aliases_and_copies_the_answer_back(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + items = checks() + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, items) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) + self.assertEqual(server.sent[0]["authorization_model_id"], MODEL_ID) + self.assertEqual(response.checks_sent, 2) + self.assertEqual( + [(r.correlation_id, r.allowed, r.error) for r in response.result], + [ + ("a", True, None), + ("b", True, None), + ("c", True, None), + ("d", False, None), + ], + ) + self.assertEqual([r.request for r in response.result], items) + + @patch.object(rest.RESTClientObject, "request") + def test_merges_checks_that_would_land_in_different_batches(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check( + client, checks()[:3], options={"max_batch_size": 1} + ) + + self.assertEqual(sent_checks(server), [("merged-1", "viewer")]) + self.assertEqual(response.checks_sent, 1) + self.assertEqual(len(response.result), 3) + + @patch.object(rest.RESTClientObject, "request") + def test_reads_the_model_once_across_threads_and_later_calls(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with ThreadPoolExecutor(max_workers=5) as executor: + list( + executor.map(lambda _: self.batch_check(client, checks()), range(5)) + ) + self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(len(server.sent), 6) + + @patch.object(rest.RESTClientObject, "request") + def test_requires_a_model_id(self, mock_request): + self.configuration.authorization_model_id = None + + with OpenFgaClient(self.configuration) as client: + with self.assertRaises(FgaValidationException): + self.batch_check(client, checks()) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_rejects_invalid_and_duplicate_correlation_ids(self, mock_request): + invalid = checks() + invalid[0].correlation_id = "has space" + duplicate = checks() + duplicate[1].correlation_id = "a" + + with OpenFgaClient(self.configuration) as client: + with self.assertRaises(FgaValidationException): + self.batch_check(client, invalid) + with self.assertRaisesRegex( + FgaValidationException, r"Duplicate correlation_id \(a\) provided" + ): + self.batch_check(client, duplicate) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_generates_missing_correlation_ids(self, mock_request): + mock_request.side_effect = FakeServer() + items = checks() + items[3].correlation_id = None + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, items) + + self.assertIsNotNone(items[3].correlation_id) + self.assertEqual(response.result[3].correlation_id, items[3].correlation_id) + + @patch.object(rest.RESTClientObject, "request") + def test_no_checks_sends_nothing(self, mock_request): + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, []) + + self.assertEqual(response.result, []) + self.assertEqual(response.checks_sent, 0) + mock_request.assert_not_called() + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_the_model_cannot_be_read( + self, mock_request, mock_fallback + ): + server = FakeServer(model_error=forbidden()) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs("openfga_sdk.sync.client.client", "WARNING") as logs: + response = self.batch_check(client, checks()) + self.batch_check(client, checks()) + + self.assertEqual(len(logs.records), 1) + self.assertIn("403", logs.output[0]) + self.assertEqual(server.model_reads, 1) + unmerged = [ + ("a", "viewer"), + ("b", "can_view"), + ("c", "can_share"), + ("d", "editor"), + ] + self.assertEqual(sent_checks(server), unmerged * 2) + self.assertEqual(response.checks_sent, 4) + self.assertEqual(mock_fallback.call_count, 2) + self.assertEqual( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ], + 403, + ) + + @patch.object(rest.RESTClientObject, "request") + def test_copies_an_error_to_every_check_in_the_group(self, mock_request): + mock_request.side_effect = FakeServer( + answer=lambda check: ( + {"error": {"message": "boom"}} + if check["correlation_id"] == "merged-1" + else {"allowed": True} + ) + ) + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, checks()) + + for result in response.result[:3]: + self.assertFalse(result.allowed) + self.assertEqual(result.error.message, "boom") + self.assertTrue(response.result[3].allowed) + + @patch.object(rest.RESTClientObject, "request") + def test_a_missing_answer_is_an_error_and_unknown_answers_are_ignored( + self, mock_request + ): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + return mock_response( + json.dumps( + {"result": {"d": {"allowed": True}, "unknown": {"allowed": True}}} + ) + ) + + mock_request.side_effect = handle + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, checks()) + + self.assertEqual( + [r.correlation_id for r in response.result], ["a", "b", "c", "d"] + ) + for result in response.result[:3]: + self.assertFalse(result.allowed) + self.assertEqual( + result.error.message, "No result returned for correlation_id (merged-1)" + ) + self.assertTrue(response.result[3].allowed) + + @patch.object(rest.RESTClientObject, "request") + def test_option_off_is_unchanged(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + response = client.batch_check(ClientBatchCheckRequest(checks=checks())) + + self.assertEqual(server.model_reads, 0) + self.assertEqual( + sent_checks(server), + [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")], + ) + self.assertIsNone(response.checks_sent) + + @patch.object(TelemetryMetrics, "batchCheckChecksSent") + @patch.object(TelemetryMetrics, "batchCheckChecksRequested") + @patch.object(TelemetryMetrics, "modelCacheLookup") + @patch.object(rest.RESTClientObject, "request") + def test_records_telemetry( + self, mock_request, mock_lookup, mock_requested, mock_sent + ): + mock_request.side_effect = FakeServer() + + with OpenFgaClient(self.configuration) as client: + self.batch_check(client, checks()) + self.batch_check(client, checks()) + + self.assertEqual( + [ + call.kwargs["attributes"][ + TelemetryAttributes.fga_client_model_cache_result + ] + for call in mock_lookup.call_args_list + ], + ["miss", "hit"], + ) + self.assertEqual(mock_requested.call_args.args, (4,)) + self.assertEqual(mock_sent.call_args.args, (2,)) diff --git a/test/telemetry/configuration_test.py b/test/telemetry/configuration_test.py index 7b3761a4..48562217 100644 --- a/test/telemetry/configuration_test.py +++ b/test/telemetry/configuration_test.py @@ -282,18 +282,22 @@ def test_default_telemetry_metrics_configuration(): metrics_config = TelemetryMetricsConfiguration.getSdkDefaults() assert isinstance(metrics_config, dict) - assert len(metrics_config) == 3 + assert len(metrics_config) == 7 assert TelemetryCounters.fga_client_credentials_request in metrics_config assert TelemetryHistograms.fga_client_query_duration in metrics_config assert TelemetryHistograms.fga_client_request_duration in metrics_config + assert TelemetryCounters.fga_client_batch_check_checks_requested in metrics_config + assert TelemetryCounters.fga_client_batch_check_checks_sent in metrics_config + assert TelemetryCounters.fga_client_model_cache_lookup in metrics_config + assert TelemetryCounters.fga_client_batch_check_merge_fallback in metrics_config def test_default_telemetry_metric_configuration(): metric_config = TelemetryMetricConfiguration.getSdkDefaults() assert isinstance(metric_config, dict) - assert len(metric_config) == 16 + assert len(metric_config) == 17 assert ( metric_config[TelemetryAttributes.fga_client_request_batch_check_size] is False @@ -304,6 +308,7 @@ def test_default_telemetry_metric_configuration(): assert metric_config[TelemetryAttributes.fga_client_request_store_id] is True assert metric_config[TelemetryAttributes.fga_client_response_model_id] is True assert metric_config[TelemetryAttributes.fga_client_user] is False + assert metric_config[TelemetryAttributes.fga_client_model_cache_result] is True assert metric_config[TelemetryAttributes.http_client_request_duration] is False assert metric_config[TelemetryAttributes.http_host] is True assert metric_config[TelemetryAttributes.http_request_method] is True diff --git a/test/telemetry/metrics_test.py b/test/telemetry/metrics_test.py index 1de3af4c..93457f3a 100644 --- a/test/telemetry/metrics_test.py +++ b/test/telemetry/metrics_test.py @@ -4,6 +4,8 @@ from opentelemetry.metrics import Counter, Histogram, Meter +from openfga_sdk.telemetry.attributes import TelemetryAttributes +from openfga_sdk.telemetry.configuration import TelemetryConfiguration from openfga_sdk.telemetry.counters import TelemetryCounters from openfga_sdk.telemetry.histograms import TelemetryHistograms from openfga_sdk.telemetry.metrics import TelemetryMetrics @@ -80,3 +82,86 @@ def test_invalid_histogram_key(): telemetry = TelemetryMetrics() with pytest.raises(ValueError): telemetry.histogram("invalid_histogram_key") + + +@patch("openfga_sdk.telemetry.metrics.get_meter") +def test_batch_check_merge_counters_use_their_attribute_filters(mock_get_meter): + mock_meter = MagicMock(spec=Meter) + mock_counter = MagicMock(spec=Counter) + mock_get_meter.return_value = mock_meter + mock_meter.create_counter.return_value = mock_counter + + telemetry = TelemetryMetrics() + configuration = TelemetryConfiguration( + { + "metrics": { + "fga-client.model_cache.lookup": { + "fga-client.model_cache.result": True, + }, + } + } + ) + + telemetry.modelCacheLookup( + attributes={ + TelemetryAttributes.fga_client_model_cache_result: "hit", + TelemetryAttributes.fga_client_request_store_id: "store", + }, + configuration=configuration, + ) + mock_counter.add.assert_called_once_with( + amount=1, attributes={"fga-client.model_cache.result": "hit"} + ) + + # Not configured, so not recorded + mock_counter.add.reset_mock() + telemetry.batchCheckChecksSent(2, configuration=configuration) + telemetry.batchCheckChecksRequested(4, configuration=configuration) + telemetry.batchCheckMergeFallback(configuration=configuration) + mock_counter.add.assert_not_called() + + +@patch("openfga_sdk.telemetry.metrics.get_meter") +def test_batch_check_merge_counters_are_on_by_default(mock_get_meter): + mock_meter = MagicMock(spec=Meter) + mock_counter = MagicMock(spec=Counter) + mock_get_meter.return_value = mock_meter + mock_meter.create_counter.return_value = mock_counter + + telemetry = TelemetryMetrics() + configuration = TelemetryConfiguration(TelemetryConfiguration.getSdkDefaults()) + attributes = { + TelemetryAttributes.fga_client_request_store_id: "store", + TelemetryAttributes.fga_client_request_model_id: "model", + } + + telemetry.batchCheckChecksRequested(4, attributes, configuration) + telemetry.batchCheckChecksSent(2, attributes, configuration) + telemetry.batchCheckMergeFallback( + attributes={**attributes, TelemetryAttributes.http_response_status_code: 403}, + configuration=configuration, + ) + telemetry.modelCacheLookup( + attributes={ + **attributes, + TelemetryAttributes.fga_client_model_cache_result: "miss", + }, + configuration=configuration, + ) + + expected = { + "fga-client.request.store_id": "store", + "fga-client.request.model_id": "model", + } + assert [call.kwargs for call in mock_counter.add.call_args_list] == [ + {"amount": 4, "attributes": expected}, + {"amount": 2, "attributes": expected}, + { + "amount": 1, + "attributes": {**expected, "http.response.status_code": 403}, + }, + { + "amount": 1, + "attributes": {**expected, "fga-client.model_cache.result": "miss"}, + }, + ] From 3f707aad50b29d5af4ab1d6a06f391bf9cf87a60 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Thu, 12 Nov 2026 15:14:22 +0530 Subject: [PATCH 02/38] fix: tighten merge_equivalent_checks validation - Reject a non-bool merge_equivalent_checks value instead of silently leaving merging off. - Use fullmatch for correlation IDs so a trailing newline is rejected. - Test that the model read carries the caller's headers. - README: clarify the model cache is per model. --- README.md | 4 ++-- openfga_sdk/client/client.py | 3 ++- openfga_sdk/client/equivalent_checks.py | 16 ++++++++++++- openfga_sdk/sync/client/client.py | 3 ++- test/client/batch_check_merge_test.py | 28 +++++++++++++++++++++- test/client/equivalent_checks_test.py | 25 ++++++++++++++++++- test/sync/client/batch_check_merge_test.py | 26 +++++++++++++++++++- 7 files changed, 97 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 5c155f0f..68a36459 100644 --- a/README.md +++ b/README.md @@ -982,9 +982,9 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), # response.checks_sent: how many checks this call actually sent ``` -- **Off by default.** With it off, nothing changes. +- **Off by default.** With it off, nothing changes. The value must be a bool, or the call fails with a validation error. - **Needs an authorization model ID.** Without one, the call fails before anything is sent. -- **Reads the model once per client.** The SDK reads the model on first use and caches it. Create the client once and reuse it. +- **Reads each model once per client.** The SDK reads a model the first time it needs it and caches it. Create the client once and reuse it. - **Falls back safely.** If the model can't be read (for example, no read access), the SDK logs a warning and sends the checks unmerged. - **Errors are shared.** If a merged check returns an error, every check it stands for gets that error. - **Correlation IDs** must match `^[\w\d-]{1,36}$` (ASCII). Missing ones are generated. diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 833be8ae..9aee12d6 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -10,6 +10,7 @@ from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.equivalent_checks import ( expand, + merge_enabled, resolve, unmerged, validate_correlation_ids, @@ -834,7 +835,7 @@ async def batch_check( elif isinstance(options["max_batch_size"], int): max_batch_size = options["max_batch_size"] - if options.get("merge_equivalent_checks") is True: + if merge_enabled(options): return await self._merged_batch_check( body, options, max_parallel_requests, max_batch_size ) diff --git a/openfga_sdk/client/equivalent_checks.py b/openfga_sdk/client/equivalent_checks.py index d54ab4c3..17fe9b2d 100644 --- a/openfga_sdk/client/equivalent_checks.py +++ b/openfga_sdk/client/equivalent_checks.py @@ -42,6 +42,19 @@ class EquivalentCheckGroup: members: list[ClientBatchCheckItem] +def merge_enabled(options: dict | None) -> bool: + """ + Return whether the `merge_equivalent_checks` option is on. Raise if it isn't a bool, + so a value like "true" can't silently leave it off. + """ + value = (options or {}).get("merge_equivalent_checks") + if value is not None and not isinstance(value, bool): + raise FgaValidationException( + f"merge_equivalent_checks must be a bool, got {type(value).__name__}" + ) + return value is True + + def validate_correlation_ids(checks: list[ClientBatchCheckItem]) -> None: """ Raise if a correlation ID doesn't match the API rule, or is used twice. @@ -49,7 +62,8 @@ def validate_correlation_ids(checks: list[ClientBatchCheckItem]) -> None: seen: set[str] = set() for check in checks: correlation_id = check.correlation_id - if not isinstance(correlation_id, str) or not CORRELATION_ID_PATTERN.match( + # fullmatch, since `$` alone would also accept a trailing newline + if not isinstance(correlation_id, str) or not CORRELATION_ID_PATTERN.fullmatch( correlation_id ): raise FgaValidationException( diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index baf474a7..95e67a23 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -8,6 +8,7 @@ from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.equivalent_checks import ( expand, + merge_enabled, resolve, unmerged, validate_correlation_ids, @@ -829,7 +830,7 @@ def batch_check( elif isinstance(options["max_batch_size"], int): max_batch_size = options["max_batch_size"] - if options.get("merge_equivalent_checks") is True: + if merge_enabled(options): return self._merged_batch_check( body, options, max_parallel_requests, max_batch_size ) diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index 9e59363d..f8b852f6 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -99,11 +99,13 @@ def __init__(self, model_error=None, answer=None): lambda check: {"allowed": check["tuple_key"]["relation"] == "viewer"} ) self.model_reads = 0 + self.model_read_headers = [] self.sent = [] def __call__(self, method, url, **kwargs): if method == "GET" and url == MODEL_URL: self.model_reads += 1 + self.model_read_headers.append(kwargs.get("headers") or {}) if self.model_error is not None: raise self.model_error return mock_response(json.dumps({"authorization_model": MODEL})) @@ -220,9 +222,33 @@ async def test_requires_a_model_id(self, mock_request): mock_request.assert_not_called() + @patch.object(rest.RESTClientObject, "request") + async def test_rejects_an_option_value_that_is_not_a_bool(self, mock_request): + async with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex( + FgaValidationException, "merge_equivalent_checks must be a bool" + ): + await self.batch_check( + client, checks(), options={"merge_equivalent_checks": "true"} + ) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_reads_the_model_with_the_callers_headers(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + await self.batch_check( + client, checks(), options={"headers": {"X-Custom": "1"}} + ) + + self.assertEqual(server.model_read_headers[0].get("X-Custom"), "1") + @patch.object(rest.RESTClientObject, "request") async def test_rejects_invalid_correlation_ids(self, mock_request): - for correlation_id in ["has space", "x" * 37, "é"]: + for correlation_id in ["has space", "x" * 37, "é", "a\n"]: items = checks() items[0].correlation_id = correlation_id diff --git a/test/client/equivalent_checks_test.py b/test/client/equivalent_checks_test.py index d404d4cd..7d6b9587 100644 --- a/test/client/equivalent_checks_test.py +++ b/test/client/equivalent_checks_test.py @@ -6,6 +6,7 @@ from openfga_sdk.client.equivalent_checks import ( EquivalentCheckGroup, expand, + merge_enabled, resolve, unmerged, validate_correlation_ids, @@ -141,13 +142,35 @@ def test_unmerged_sends_every_check_as_is(): @pytest.mark.parametrize( "correlation_id", - ["", "has space", "x" * 37, "é", "a/b", 1], + ["", "has space", "x" * 37, "é", "a/b", "a\n", 1], ) def test_validate_correlation_ids_rejects_invalid_ids(correlation_id): with pytest.raises(FgaValidationException, match="is invalid"): validate_correlation_ids([check(correlation_id)]) +@pytest.mark.parametrize( + "options, enabled", + [ + (None, False), + ({}, False), + ({"merge_equivalent_checks": None}, False), + ({"merge_equivalent_checks": False}, False), + ({"merge_equivalent_checks": True}, True), + ], +) +def test_merge_enabled(options, enabled): + assert merge_enabled(options) is enabled + + +@pytest.mark.parametrize("value", ["true", 1, "yes"]) +def test_merge_enabled_rejects_values_that_are_not_bools(value): + with pytest.raises( + FgaValidationException, match="merge_equivalent_checks must be a bool" + ): + merge_enabled({"merge_equivalent_checks": value}) + + def test_validate_correlation_ids_accepts_valid_ids(): validate_correlation_ids([check("a_b-1"), check("x" * 36)]) diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 94ec276e..15fc32e1 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -40,11 +40,13 @@ def __init__(self, model_error=None, answer=None): lambda check: {"allowed": check["tuple_key"]["relation"] == "viewer"} ) self.model_reads = 0 + self.model_read_headers = [] self.sent = [] def __call__(self, method, url, **kwargs): if method == "GET" and url == MODEL_URL: self.model_reads += 1 + self.model_read_headers.append(kwargs.get("headers") or {}) if self.model_error is not None: raise self.model_error return mock_response(json.dumps({"authorization_model": MODEL})) @@ -147,10 +149,32 @@ def test_requires_a_model_id(self, mock_request): mock_request.assert_not_called() + @patch.object(rest.RESTClientObject, "request") + def test_rejects_an_option_value_that_is_not_a_bool(self, mock_request): + with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex( + FgaValidationException, "merge_equivalent_checks must be a bool" + ): + self.batch_check( + client, checks(), options={"merge_equivalent_checks": 1} + ) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_reads_the_model_with_the_callers_headers(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + self.batch_check(client, checks(), options={"headers": {"X-Custom": "1"}}) + + self.assertEqual(server.model_read_headers[0].get("X-Custom"), "1") + @patch.object(rest.RESTClientObject, "request") def test_rejects_invalid_and_duplicate_correlation_ids(self, mock_request): invalid = checks() - invalid[0].correlation_id = "has space" + invalid[0].correlation_id = "a\n" duplicate = checks() duplicate[1].correlation_id = "a" From e07c07f5ce8ee3d55efec7c0b4ee4d7e3993d8f3 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Thu, 12 Nov 2026 15:44:10 +0530 Subject: [PATCH 03/38] test: cover an empty model response and the checks_sent setter --- test/client/batch_check_merge_test.py | 32 ++++++++++++++++++++-- test/sync/client/batch_check_merge_test.py | 23 ++++++++++++++-- 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index f8b852f6..ecf9e50a 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -11,6 +11,7 @@ from openfga_sdk.client.client import OpenFgaClient from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest +from openfga_sdk.client.models.batch_check_response import ClientBatchCheckResponse from openfga_sdk.exceptions import ( FgaValidationException, ForbiddenException, @@ -93,8 +94,11 @@ class FakeServer: Answers model reads and BatchCheck requests, and records what was sent. """ - def __init__(self, model_error=None, answer=None): + def __init__(self, model_error=None, answer=None, model_body=None): self.model_error = model_error + self.model_body = ( + {"authorization_model": MODEL} if model_body is None else model_body + ) self.answer = answer or ( lambda check: {"allowed": check["tuple_key"]["relation"] == "viewer"} ) @@ -108,7 +112,7 @@ def __call__(self, method, url, **kwargs): self.model_read_headers.append(kwargs.get("headers") or {}) if self.model_error is not None: raise self.model_error - return mock_response(json.dumps({"authorization_model": MODEL})) + return mock_response(json.dumps(self.model_body)) if method == "POST" and url == BATCH_CHECK_URL: body = kwargs["body"] @@ -284,6 +288,14 @@ async def test_generates_missing_correlation_ids(self, mock_request): self.assertIsNotNone(items[3].correlation_id) self.assertEqual(response.result[3].correlation_id, items[3].correlation_id) + def test_checks_sent_defaults_to_none_and_can_be_set(self): + response = ClientBatchCheckResponse([]) + self.assertIsNone(response.checks_sent) + + response.checks_sent = 3 + + self.assertEqual(response.checks_sent, 3) + @patch.object(rest.RESTClientObject, "request") async def test_no_checks_sends_nothing(self, mock_request): async with OpenFgaClient(self.configuration) as client: @@ -321,6 +333,22 @@ async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): [r.allowed for r in response.result], [True, False, False, False] ) + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_the_model_response_is_empty(self, mock_request): + server = FakeServer(model_body={}) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs("openfga_sdk.client.client", "WARNING") as logs: + response = await self.batch_check(client, checks()) + + self.assertEqual(len(logs.records), 1) + self.assertEqual( + sent_checks(server), + [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")], + ) + self.assertEqual(response.checks_sent, 4) + @patch.object(rest.RESTClientObject, "request") async def test_copies_an_error_to_every_check_in_the_group(self, mock_request): server = FakeServer( diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 15fc32e1..38e02c44 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -34,8 +34,11 @@ class FakeServer: Answers model reads and BatchCheck requests, and records what was sent. """ - def __init__(self, model_error=None, answer=None): + def __init__(self, model_error=None, answer=None, model_body=None): self.model_error = model_error + self.model_body = ( + {"authorization_model": MODEL} if model_body is None else model_body + ) self.answer = answer or ( lambda check: {"allowed": check["tuple_key"]["relation"] == "viewer"} ) @@ -49,7 +52,7 @@ def __call__(self, method, url, **kwargs): self.model_read_headers.append(kwargs.get("headers") or {}) if self.model_error is not None: raise self.model_error - return mock_response(json.dumps({"authorization_model": MODEL})) + return mock_response(json.dumps(self.model_body)) if method == "POST" and url == BATCH_CHECK_URL: body = kwargs["body"] @@ -241,6 +244,22 @@ def test_sends_unmerged_when_the_model_cannot_be_read( 403, ) + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_the_model_response_is_empty(self, mock_request): + server = FakeServer(model_body={}) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs("openfga_sdk.sync.client.client", "WARNING") as logs: + response = self.batch_check(client, checks()) + + self.assertEqual(len(logs.records), 1) + self.assertEqual( + sent_checks(server), + [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")], + ) + self.assertEqual(response.checks_sent, 4) + @patch.object(rest.RESTClientObject, "request") def test_copies_an_error_to_every_check_in_the_group(self, mock_request): mock_request.side_effect = FakeServer( From fae993954654c20ae0fec815f0535ec6d283ae20 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 13 Nov 2026 14:00:18 +0530 Subject: [PATCH 04/38] docs: note that merge_equivalent_checks may change while in beta --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 68a36459..ecd65198 100644 --- a/README.md +++ b/README.md @@ -967,7 +967,7 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), ###### Merge equivalent checks (beta) -Set `merge_equivalent_checks` to `True` to send checks that are certain to get the same answer only once. The SDK copies each answer back, so you still get one result per check you passed in. +Set `merge_equivalent_checks` to `True` to send checks that are certain to get the same answer only once. The SDK copies each answer back, so you still get one result per check you passed in. It's in beta, so its behavior may change based on feedback. It merges: - **Aliases:** with `define can_view: viewer`, checking both `viewer` and `can_view` for the same user and object sends one check. Chains like `define can_share: can_view` work too. From 4805d231e400f519d2508522fc2b017706273faa Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 13 Nov 2026 14:14:39 +0530 Subject: [PATCH 05/38] fix: count merged checks even when a request fails Record checks_requested and checks_sent before sending, since every chunk is sent even if another fails. Document that a missing or None merge_equivalent_checks means off. --- README.md | 2 +- openfga_sdk/client/client.py | 15 +++++++------ openfga_sdk/client/equivalent_checks.py | 4 ++-- openfga_sdk/sync/client/client.py | 15 +++++++------ test/client/batch_check_merge_test.py | 20 +++++++++++++++++ test/sync/client/batch_check_merge_test.py | 26 +++++++++++++++++++++- 6 files changed, 64 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index ecd65198..54e0666c 100644 --- a/README.md +++ b/README.md @@ -982,7 +982,7 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), # response.checks_sent: how many checks this call actually sent ``` -- **Off by default.** With it off, nothing changes. The value must be a bool, or the call fails with a validation error. +- **Off by default.** With it off, nothing changes. Leaving it out or passing `None` keeps it off; any other non-bool value, like `"true"`, fails with a validation error. - **Needs an authorization model ID.** Without one, the call fails before anything is sent. - **Reads each model once per client.** The SDK reads a model the first time it needs it and caches it. Create the client once and reuse it. - **Falls back safely.** If the model can't be read (for example, no read access), the SDK logs a warning and sends the checks unmerged. diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 9aee12d6..9f976c1a 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -976,6 +976,14 @@ async def load_model(): configuration=telemetry_configuration, ) + # Every chunk is sent even if another one fails, so count them up front. + telemetry.batchCheckChecksRequested( + len(checks), attributes=attributes, configuration=telemetry_configuration + ) + telemetry.batchCheckChecksSent( + len(groups), attributes=attributes, configuration=telemetry_configuration + ) + results = {} sem = asyncio.Semaphore(max_parallel_requests) consistency = self._get_consistency(options) @@ -996,13 +1004,6 @@ async def send(chunk): *[send(chunk) for chunk in _chuck_array(groups, max_batch_size)] ) - telemetry.batchCheckChecksRequested( - len(checks), attributes=attributes, configuration=telemetry_configuration - ) - telemetry.batchCheckChecksSent( - len(groups), attributes=attributes, configuration=telemetry_configuration - ) - return ClientBatchCheckResponse( expand(checks, groups, results), checks_sent=len(groups) ) diff --git a/openfga_sdk/client/equivalent_checks.py b/openfga_sdk/client/equivalent_checks.py index 17fe9b2d..0f60619a 100644 --- a/openfga_sdk/client/equivalent_checks.py +++ b/openfga_sdk/client/equivalent_checks.py @@ -44,8 +44,8 @@ class EquivalentCheckGroup: def merge_enabled(options: dict | None) -> bool: """ - Return whether the `merge_equivalent_checks` option is on. Raise if it isn't a bool, - so a value like "true" can't silently leave it off. + Return whether the `merge_equivalent_checks` option is on. Missing or None means off, + like other options. Raise for any other non-bool, so "true" can't silently leave it off. """ value = (options or {}).get("merge_equivalent_checks") if value is not None and not isinstance(value, bool): diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index 95e67a23..dce79582 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -971,6 +971,14 @@ def load_model(): configuration=telemetry_configuration, ) + # Every chunk is sent even if another one fails, so count them up front. + telemetry.batchCheckChecksRequested( + len(checks), attributes=attributes, configuration=telemetry_configuration + ) + telemetry.batchCheckChecksSent( + len(groups), attributes=attributes, configuration=telemetry_configuration + ) + consistency = self._get_consistency(options) def send(chunk): @@ -988,13 +996,6 @@ def send(chunk): for response in executor.map(send, _chuck_array(groups, max_batch_size)): results.update(response.result or {}) - telemetry.batchCheckChecksRequested( - len(checks), attributes=attributes, configuration=telemetry_configuration - ) - telemetry.batchCheckChecksSent( - len(groups), attributes=attributes, configuration=telemetry_configuration - ) - return ClientBatchCheckResponse( expand(checks, groups, results), checks_sent=len(groups) ) diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index ecf9e50a..ffdfb5b6 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -410,6 +410,26 @@ def handle(method, url, **kwargs): with self.assertRaises(ValidationException): await self.batch_check(client, checks()) + @patch.object(TelemetryMetrics, "batchCheckChecksSent") + @patch.object(TelemetryMetrics, "batchCheckChecksRequested") + @patch.object(rest.RESTClientObject, "request") + async def test_counts_checks_even_when_a_request_fails( + self, mock_request, mock_requested, mock_sent + ): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + raise ValidationException(http_resp=http_mock_response("{}", 400)) + + mock_request.side_effect = handle + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaises(ValidationException): + await self.batch_check(client, checks()) + + self.assertEqual(mock_requested.call_args.args, (4,)) + self.assertEqual(mock_sent.call_args.args, (2,)) + @patch.object(rest.RESTClientObject, "request") async def test_option_off_is_unchanged(self, mock_request): server = FakeServer() diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 38e02c44..64669386 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -6,7 +6,11 @@ from openfga_sdk.client import ClientConfiguration from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest -from openfga_sdk.exceptions import FgaValidationException, ForbiddenException +from openfga_sdk.exceptions import ( + FgaValidationException, + ForbiddenException, + ValidationException, +) from openfga_sdk.sync import rest from openfga_sdk.sync.client.client import OpenFgaClient from openfga_sdk.telemetry.attributes import TelemetryAttributes @@ -306,6 +310,26 @@ def handle(method, url, **kwargs): ) self.assertTrue(response.result[3].allowed) + @patch.object(TelemetryMetrics, "batchCheckChecksSent") + @patch.object(TelemetryMetrics, "batchCheckChecksRequested") + @patch.object(rest.RESTClientObject, "request") + def test_a_failed_request_fails_the_call_and_still_counts_checks( + self, mock_request, mock_requested, mock_sent + ): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + raise ValidationException(http_resp=http_mock_response("{}", 400)) + + mock_request.side_effect = handle + + with OpenFgaClient(self.configuration) as client: + with self.assertRaises(ValidationException): + self.batch_check(client, checks()) + + self.assertEqual(mock_requested.call_args.args, (4,)) + self.assertEqual(mock_sent.call_args.args, (2,)) + @patch.object(rest.RESTClientObject, "request") def test_option_off_is_unchanged(self, mock_request): server = FakeServer() From 45d733c672a2806009ff90ca05f9decb5ff8d3bd Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 13 Nov 2026 14:16:27 +0530 Subject: [PATCH 06/38] fix: don't keep a model read that finished before it was registered With an eager task factory, a read that doesn't suspend finishes inside ensure_future, so its cleanup runs before it's added to _loading. The done task then stayed there, and a failed read was never retried. --- openfga_sdk/client/model_cache.py | 4 +++- test/client/model_cache_test.py | 22 +++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/openfga_sdk/client/model_cache.py b/openfga_sdk/client/model_cache.py index 1ade5549..17d8e77e 100644 --- a/openfga_sdk/client/model_cache.py +++ b/openfga_sdk/client/model_cache.py @@ -103,7 +103,9 @@ async def get( if task is None: task = asyncio.ensure_future(self._load(key, load)) task.add_done_callback(_retrieve_exception) - self._loading[key] = task + # An eager task can finish before it's registered, so don't keep a done one. + if not task.done(): + self._loading[key] = task # Shielded, so a cancelled caller doesn't cancel the read other callers share. try: diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py index b30a4798..307bb403 100644 --- a/test/client/model_cache_test.py +++ b/test/client/model_cache_test.py @@ -1,8 +1,9 @@ import asyncio +import sys import threading import time -from unittest import IsolatedAsyncioTestCase, TestCase +from unittest import IsolatedAsyncioTestCase, TestCase, skipIf from openfga_sdk.client.model_cache import AsyncModelCache, ModelCache @@ -65,6 +66,25 @@ async def load(): await cache.get(KEY, load) self.assertEqual(reads, 2) + @skipIf(sys.version_info < (3, 12), "eager tasks need Python 3.12+") + async def test_retries_a_failed_read_that_finished_eagerly(self): + asyncio.get_running_loop().set_task_factory(asyncio.eager_task_factory) + clock = FakeClock() + cache = AsyncModelCache(failure_ttl=60, clock=clock) + reads = 0 + + async def load(): + nonlocal reads + reads += 1 + raise RuntimeError("forbidden") + + await cache.get(KEY, load) + self.assertEqual(cache._loading, {}) + + clock.now = 60 + await cache.get(KEY, load) + self.assertEqual(reads, 2) + async def test_drops_the_least_recently_used_model(self): cache = AsyncModelCache(max_models=2) From d579913d49a335ba22dca2e08e3b0f7db452807d Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 23 Nov 2026 05:06:33 +0530 Subject: [PATCH 07/38] test: check the sent context and contextual tuples in shared cases Bumps the shared cases to openfga/language@2dca421, which states the context and contextual tuples of each sent check. --- Makefile | 2 +- test/client/equivalent_checks_cases_test.py | 40 +- test/data/equivalent-checks-cases.json | 971 +++++++++++++++++++- 3 files changed, 958 insertions(+), 55 deletions(-) diff --git a/Makefile b/Makefile index 94c27fef..4f4d4d90 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases # openfga/language commit to copy the shared equivalent-checks cases from -LANGUAGE_REF ?= 5afcf707e44aa21d8ae17e47938b3f0164a13cc7 +LANGUAGE_REF ?= 2dca4214bc8b05cf8e889e9c75df65065826f793 # Install/update dependencies sync: diff --git a/test/client/equivalent_checks_cases_test.py b/test/client/equivalent_checks_cases_test.py index 2897e166..23942742 100644 --- a/test/client/equivalent_checks_cases_test.py +++ b/test/client/equivalent_checks_cases_test.py @@ -64,6 +64,33 @@ def _check(check_json): ) +def _tuple_as_json(item): + result = {"user": item.user, "relation": item.relation, "object": item.object} + if item.condition is not None: + result["condition"] = {"name": item.condition.name} + if item.condition.context is not None: + result["condition"]["context"] = item.condition.context + return result + + +def _sent_as_json(group): + check = group.check + result = { + "id": check.correlation_id, + "user": check.user, + "relation": check.relation, + "object": check.object, + } + if check.context is not None: + result["context"] = check.context + if check.contextual_tuples is not None: + result["contextual_tuples"] = [ + _tuple_as_json(item) for item in check.contextual_tuples + ] + result["for"] = [member.correlation_id for member in group.members] + return result + + def test_cases_file_is_not_empty(): assert len(CASES) > 0 @@ -74,18 +101,9 @@ def test_equivalent_checks_case(case): groups = resolve(_model(case["model"]), checks) - actual = [ - { - "id": group.check.correlation_id, - "user": group.check.user, - "relation": group.check.relation, - "object": group.check.object, - "for": [member.correlation_id for member in group.members], - } - for group in groups - ] - assert actual == case["expected_sent"] + assert [_sent_as_json(group) for group in groups] == case["expected_sent"] + # `==` treats 1 and 1.0 as equal, so also make sure the first check's values are sent unchanged. for group in groups: first = group.members[0] assert group.check.context is first.context diff --git a/test/data/equivalent-checks-cases.json b/test/data/equivalent-checks-cases.json index debbb0f7..83dae358 100644 --- a/test/data/equivalent-checks-cases.json +++ b/test/data/equivalent-checks-cases.json @@ -2742,6 +2742,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu" + }, "for": ["a", "b"] } ] @@ -2827,6 +2830,10 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu", + "x": 1.5 + }, "for": ["a", "b"] } ] @@ -2907,6 +2914,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "x": 1 + }, "for": ["a", "b"] } ] @@ -2987,6 +2997,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "x": 9007199254740993 + }, "for": ["a", "b"] } ] @@ -3067,6 +3080,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "x": 0 + }, "for": ["a"] }, { @@ -3074,6 +3090,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "x": -0.0 + }, "for": ["b"] } ] @@ -3154,6 +3173,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "x": true + }, "for": ["a"] }, { @@ -3161,6 +3183,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "x": 1 + }, "for": ["b"] } ] @@ -3241,6 +3266,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "x": "1" + }, "for": ["a"] }, { @@ -3248,6 +3276,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "x": 1 + }, "for": ["b"] } ] @@ -3329,6 +3360,10 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu", + "x": 1 + }, "for": ["a"] }, { @@ -3336,6 +3371,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu" + }, "for": ["b"] } ] @@ -3417,6 +3455,10 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu", + "x": null + }, "for": ["a"] }, { @@ -3424,6 +3466,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu" + }, "for": ["b"] } ] @@ -3506,6 +3551,7 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": {}, "for": ["b"] } ] @@ -3586,6 +3632,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu" + }, "for": ["a"] }, { @@ -3593,6 +3642,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu " + }, "for": ["b"] } ] @@ -3673,6 +3725,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "city": "caf\u00e9" + }, "for": ["a"] }, { @@ -3680,6 +3735,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "city": "cafe\u0301" + }, "for": ["b"] } ] @@ -3765,6 +3823,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "tags": ["a", "b"] + }, "for": ["a"] }, { @@ -3772,6 +3833,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "tags": ["b", "a"] + }, "for": ["b"] } ] @@ -3857,6 +3921,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "tags": ["a"] + }, "for": ["a"] }, { @@ -3864,6 +3931,9 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "tags": ["a", "a"] + }, "for": ["b"] } ] @@ -3964,6 +4034,19 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu", + "meta": { + "level": 1, + "items": [ + 1, + { + "k": "v", + "count": 2 + } + ] + } + }, "for": ["a", "b"] } ] @@ -4062,6 +4145,12 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [0] + } + }, "for": ["a"] }, { @@ -4069,6 +4158,12 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [-0.0] + } + }, "for": ["b"] }, { @@ -4076,6 +4171,12 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [false] + } + }, "for": ["c"] } ] @@ -4182,6 +4283,18 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ], "for": ["a", "b"] } ] @@ -4288,6 +4401,18 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ], "for": ["a", "b"] } ] @@ -4361,6 +4486,13 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], "for": ["a"] }, { @@ -4368,6 +4500,13 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:2" + } + ], "for": ["b"] } ] @@ -4441,6 +4580,13 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], "for": ["b"] } ] @@ -4508,6 +4654,7 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [], "for": ["b"] } ] @@ -4604,6 +4751,13 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], "for": ["a"] }, { @@ -4611,6 +4765,18 @@ "user": "user:anne", "relation": "can_view", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], "for": ["b"] }, { @@ -4618,6 +4784,18 @@ "user": "user:anne", "relation": "can_view", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], "for": ["c"] } ] @@ -4712,6 +4890,19 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ], "for": ["a"] }, { @@ -4719,6 +4910,13 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], "for": ["b"] } ] @@ -4829,6 +5027,19 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + } + ], "for": ["a"] }, { @@ -4836,6 +5047,19 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ], "for": ["b"] } ] @@ -4933,6 +5157,19 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ], "for": ["a"] }, { @@ -4940,6 +5177,19 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ], "for": ["b"] } ] @@ -5038,6 +5288,19 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "context": { + "region": "eu" + }, + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region" + } + } + ], "for": ["a"] }, { @@ -5045,16 +5308,30 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", - "for": ["b"] - } - ] - }, - { - "name": "merges contextual tuple condition context that matches at every level", - "model": { - "conditions": { - "in_region": { - "expression": "region == \"eu\" && x > 0.0", + "context": { + "region": "eu" + }, + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": {} + } + } + ], + "for": ["b"] + } + ] + }, + { + "name": "merges contextual tuple condition context that matches at every level", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\" && x > 0.0", "name": "in_region", "parameters": { "region": { @@ -5114,7 +5391,17 @@ "name": "in_region", "context": { "region": "eu", - "x": 1 + "x": 1, + "meta": { + "level": 1, + "items": [ + 1, + { + "k": "v", + "count": 2 + } + ] + } } } } @@ -5133,6 +5420,16 @@ "condition": { "name": "in_region", "context": { + "meta": { + "items": [ + 1.0, + { + "count": 2.0, + "k": "v" + } + ], + "level": 1.0 + }, "x": 1.0, "region": "eu" } @@ -5147,26 +5444,237 @@ "user": "user:anne", "relation": "viewer", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "x": 1, + "meta": { + "level": 1, + "items": [ + 1, + { + "k": "v", + "count": 2 + } + ] + } + } + } + } + ], "for": ["a", "b"] } ] }, { - "name": "sends as is checks whose contextual tuples repeat a user, relation and object with different conditions", + "name": "does not merge contextual tuple condition context that differs at a nested level", "model": { "conditions": { - "in_eu": { - "expression": "region == \"eu\"", - "name": "in_eu", + "in_region": { + "expression": "region == \"eu\" && x > 0.0", + "name": "in_region", "parameters": { "region": { "type_name": "TYPE_NAME_STRING" + }, + "x": { + "type_name": "TYPE_NAME_DOUBLE" } } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" }, - "in_us": { - "expression": "region == \"us\"", - "name": "in_us", + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "x": 1, + "meta": { + "items": [0] + } + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "x": 1, + "meta": { + "items": [-0.0] + } + } + } + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "x": 1, + "meta": { + "items": [false] + } + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "x": 1, + "meta": { + "items": [0] + } + } + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "x": 1, + "meta": { + "items": [-0.0] + } + } + } + } + ], + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "x": 1, + "meta": { + "items": [false] + } + } + } + } + ], + "for": ["c"] + } + ] + }, + { + "name": "sends as is checks whose contextual tuples repeat a user, relation and object with the same condition", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", "parameters": { "region": { "type_name": "TYPE_NAME_STRING" @@ -5186,11 +5694,7 @@ "viewer": { "directly_related_user_types": [ { - "condition": "in_eu", - "type": "user" - }, - { - "condition": "in_us", + "condition": "in_region", "type": "user" } ] @@ -5223,7 +5727,7 @@ "relation": "viewer", "object": "document:1", "condition": { - "name": "in_eu", + "name": "in_region", "context": { "region": "eu" } @@ -5234,9 +5738,9 @@ "relation": "viewer", "object": "document:1", "condition": { - "name": "in_us", + "name": "in_region", "context": { - "region": "eu" + "region": "us" } } } @@ -5253,9 +5757,9 @@ "relation": "viewer", "object": "document:1", "condition": { - "name": "in_us", + "name": "in_region", "context": { - "region": "eu" + "region": "us" } } }, @@ -5264,7 +5768,7 @@ "relation": "viewer", "object": "document:1", "condition": { - "name": "in_eu", + "name": "in_region", "context": { "region": "eu" } @@ -5283,7 +5787,7 @@ "relation": "viewer", "object": "document:1", "condition": { - "name": "in_eu", + "name": "in_region", "context": { "region": "eu" } @@ -5294,28 +5798,106 @@ "relation": "viewer", "object": "document:1", "condition": { - "name": "in_us", + "name": "in_region", "context": { - "region": "eu" + "region": "us" } } } ] - } - ], - "expected_sent": [ - { - "id": "a", - "user": "user:anne", - "relation": "can_view", - "object": "document:1", - "for": ["a"] }, { - "id": "b", + "id": "d", "user": "user:anne", - "relation": "viewer", + "relation": "can_view", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ], "for": ["b"] }, { @@ -5323,6 +5905,309 @@ "user": "user:anne", "relation": "can_view", "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ], + "for": ["c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ], + "for": ["d"] + } + ] + }, + { + "name": "sends as is checks whose contextual tuples repeat a user, relation and object with different conditions", + "model": { + "conditions": { + "in_eu": { + "expression": "region == \"eu\"", + "name": "in_eu", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + }, + "in_us": { + "expression": "region == \"us\"", + "name": "in_us", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_eu", + "type": "user" + }, + { + "condition": "in_us", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + } + ], + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ], "for": ["c"] } ] From ccf64fb357cbc13230ea8f88bc4b30a765dc08f1 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 23 Nov 2026 18:26:01 +0530 Subject: [PATCH 08/38] test: update shared cases to declare contextual tuple condition params --- Makefile | 2 +- test/data/equivalent-checks-cases.json | 132 +++++++++++++------------ 2 files changed, 71 insertions(+), 63 deletions(-) diff --git a/Makefile b/Makefile index 4f4d4d90..2a9edb99 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases # openfga/language commit to copy the shared equivalent-checks cases from -LANGUAGE_REF ?= 2dca4214bc8b05cf8e889e9c75df65065826f793 +LANGUAGE_REF ?= bca096c2f02edcdbf753be641d90aadb9476e45e # Install/update dependencies sync: diff --git a/test/data/equivalent-checks-cases.json b/test/data/equivalent-checks-cases.json index 83dae358..72055e3c 100644 --- a/test/data/equivalent-checks-cases.json +++ b/test/data/equivalent-checks-cases.json @@ -5331,14 +5331,27 @@ "model": { "conditions": { "in_region": { - "expression": "region == \"eu\" && x > 0.0", + "expression": "region == \"eu\"", "name": "in_region", "parameters": { + "limits": { + "generic_types": [ + { + "type_name": "TYPE_NAME_DOUBLE" + } + ], + "type_name": "TYPE_NAME_MAP" + }, "region": { "type_name": "TYPE_NAME_STRING" }, - "x": { - "type_name": "TYPE_NAME_DOUBLE" + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" } } } @@ -5391,17 +5404,11 @@ "name": "in_region", "context": { "region": "eu", - "x": 1, - "meta": { - "level": 1, - "items": [ - 1, - { - "k": "v", - "count": 2 - } - ] - } + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["x", "y"] } } } @@ -5420,17 +5427,11 @@ "condition": { "name": "in_region", "context": { - "meta": { - "items": [ - 1.0, - { - "count": 2.0, - "k": "v" - } - ], - "level": 1.0 + "tags": ["x", "y"], + "limits": { + "write": 2.0, + "read": 1.0 }, - "x": 1.0, "region": "eu" } } @@ -5453,17 +5454,11 @@ "name": "in_region", "context": { "region": "eu", - "x": 1, - "meta": { - "level": 1, - "items": [ - 1, - { - "k": "v", - "count": 2 - } - ] - } + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["x", "y"] } } } @@ -5477,14 +5472,27 @@ "model": { "conditions": { "in_region": { - "expression": "region == \"eu\" && x > 0.0", + "expression": "region == \"eu\"", "name": "in_region", "parameters": { + "limits": { + "generic_types": [ + { + "type_name": "TYPE_NAME_DOUBLE" + } + ], + "type_name": "TYPE_NAME_MAP" + }, "region": { "type_name": "TYPE_NAME_STRING" }, - "x": { - "type_name": "TYPE_NAME_DOUBLE" + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" } } } @@ -5537,10 +5545,10 @@ "name": "in_region", "context": { "region": "eu", - "x": 1, - "meta": { - "items": [0] - } + "limits": { + "read": 0 + }, + "tags": ["x"] } } } @@ -5560,10 +5568,10 @@ "name": "in_region", "context": { "region": "eu", - "x": 1, - "meta": { - "items": [-0.0] - } + "limits": { + "read": -0.0 + }, + "tags": ["x"] } } } @@ -5583,10 +5591,10 @@ "name": "in_region", "context": { "region": "eu", - "x": 1, - "meta": { - "items": [false] - } + "limits": { + "read": 0 + }, + "tags": ["y"] } } } @@ -5608,10 +5616,10 @@ "name": "in_region", "context": { "region": "eu", - "x": 1, - "meta": { - "items": [0] - } + "limits": { + "read": 0 + }, + "tags": ["x"] } } } @@ -5632,10 +5640,10 @@ "name": "in_region", "context": { "region": "eu", - "x": 1, - "meta": { - "items": [-0.0] - } + "limits": { + "read": -0.0 + }, + "tags": ["x"] } } } @@ -5656,10 +5664,10 @@ "name": "in_region", "context": { "region": "eu", - "x": 1, - "meta": { - "items": [false] - } + "limits": { + "read": 0 + }, + "tags": ["y"] } } } From 23b945ece1007770365d498a8051c83cea0230a8 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 23 Nov 2026 18:47:21 +0530 Subject: [PATCH 09/38] fix: send checks with deeply nested context as is when merging Comparing a context nested more than 100 levels deep is skipped, and the check is sent as is. Before, a context nested about 500 levels deep raised RecursionError with merge_equivalent_checks on, while the same batch worked with it off. --- openfga_sdk/client/equivalent_checks.py | 14 +++++++++++--- test/client/equivalent_checks_test.py | 10 +++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/openfga_sdk/client/equivalent_checks.py b/openfga_sdk/client/equivalent_checks.py index 0f60619a..e855bdf6 100644 --- a/openfga_sdk/client/equivalent_checks.py +++ b/openfga_sdk/client/equivalent_checks.py @@ -27,6 +27,9 @@ _MISSING = ("missing",) +# Values nested deeper than this are sent as is, so comparing them can't run out of stack. +_MAX_DEPTH = 100 + class _Unmergeable(Exception): """A value the SDK can't compare exactly, so the check is sent as is.""" @@ -323,11 +326,14 @@ def _contextual_tuples_key(contextual_tuples) -> tuple | frozenset: return frozenset(Counter(items).items()) -def _canonical(value) -> tuple: +def _canonical(value, depth: int = 0) -> tuple: """ A hashable form of a JSON value, equal only for values the server sees as equal. Numbers compare as doubles, including the sign of zero. """ + if depth > _MAX_DEPTH: + raise _Unmergeable() + if value is None: return ("null",) @@ -349,7 +355,7 @@ def _canonical(value) -> tuple: return ("string", value) if isinstance(value, list): - return ("list", tuple(_canonical(item) for item in value)) + return ("list", tuple(_canonical(item, depth + 1) for item in value)) if isinstance(value, dict): if not all(isinstance(key, str) for key in value): @@ -357,7 +363,9 @@ def _canonical(value) -> tuple: return ( "object", - frozenset((key, _canonical(item)) for key, item in value.items()), + frozenset( + (key, _canonical(item, depth + 1)) for key, item in value.items() + ), ) raise _Unmergeable() diff --git a/test/client/equivalent_checks_test.py b/test/client/equivalent_checks_test.py index 7d6b9587..31a2f658 100644 --- a/test/client/equivalent_checks_test.py +++ b/test/client/equivalent_checks_test.py @@ -42,6 +42,13 @@ ) +def nested(depth): + value = 1 + for _ in range(depth): + value = {"k": value} + return value + + def check(correlation_id, relation="can_view", context=None, contextual_tuples=None): return ClientBatchCheckItem( user="user:anne", @@ -74,8 +81,9 @@ def sent(groups): datetime.datetime(2026, 1, 1), {1: "non-string key"}, {"nested": [object()]}, + nested(600), ], - ids=["nan", "inf", "huge-int", "tuple", "datetime", "int-key", "object"], + ids=["nan", "inf", "huge-int", "tuple", "datetime", "int-key", "object", "deep"], ) def test_values_that_cannot_be_compared_are_sent_as_is(value): groups = resolve( From 1d4d01a71bec2a53677f846362e08a87f3cc0426 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 23 Nov 2026 18:47:21 +0530 Subject: [PATCH 10/38] test: check that merged batch checks send the consistency option --- test/client/batch_check_merge_test.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index ffdfb5b6..373eb5ea 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -17,6 +17,7 @@ ForbiddenException, ValidationException, ) +from openfga_sdk.models.consistency_preference import ConsistencyPreference from openfga_sdk.telemetry.attributes import TelemetryAttributes from openfga_sdk.telemetry.metrics import TelemetryMetrics @@ -250,6 +251,20 @@ async def test_reads_the_model_with_the_callers_headers(self, mock_request): self.assertEqual(server.model_read_headers[0].get("X-Custom"), "1") + @patch.object(rest.RESTClientObject, "request") + async def test_sends_the_consistency_option(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + await self.batch_check( + client, + checks(), + options={"consistency": ConsistencyPreference.HIGHER_CONSISTENCY}, + ) + + self.assertEqual(server.sent[0]["consistency"], "HIGHER_CONSISTENCY") + @patch.object(rest.RESTClientObject, "request") async def test_rejects_invalid_correlation_ids(self, mock_request): for correlation_id in ["has space", "x" * 37, "é", "a\n"]: From 882d25e40ce9746c90caeeb2ec6dbf1dcef9a4b9 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 23 Nov 2026 20:45:14 +0530 Subject: [PATCH 11/38] fix: fail early when the model doesn't exist and retry transient model read errors A missing model or store now fails the call before any check is sent, with the same error BatchCheck returns. Only a 403 or 429 is remembered; other read failures are retried on the next call. --- README.md | 3 +- openfga_sdk/client/client.py | 7 ++++- openfga_sdk/client/model_cache.py | 21 +++++++++++-- openfga_sdk/sync/client/client.py | 7 ++++- test/client/batch_check_merge_test.py | 33 ++++++++++++++++++-- test/client/model_cache_test.py | 35 ++++++++++++++++++++-- test/sync/client/batch_check_merge_test.py | 17 +++++++++-- 7 files changed, 109 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 54e0666c..33147d92 100644 --- a/README.md +++ b/README.md @@ -985,7 +985,8 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), - **Off by default.** With it off, nothing changes. Leaving it out or passing `None` keeps it off; any other non-bool value, like `"true"`, fails with a validation error. - **Needs an authorization model ID.** Without one, the call fails before anything is sent. - **Reads each model once per client.** The SDK reads a model the first time it needs it and caches it. Create the client once and reuse it. -- **Falls back safely.** If the model can't be read (for example, no read access), the SDK logs a warning and sends the checks unmerged. +- **Falls back safely.** If the model can't be read (for example, no read access), the SDK logs a warning and sends the checks unmerged. A 403 or 429 is remembered for about a minute; other failures are retried on the next call. +- **Fails early if the model doesn't exist.** If the model or store isn't found, the call fails with that error before any check is sent, as BatchCheck would. - **Errors are shared.** If a merged check returns an error, every check it stands for gets that error. - **Correlation IDs** must match `^[\w\d-]{1,36}$` (ASCII). Missing ones are generated. - **Telemetry:** see the `fga-client.batch_check.*` and `fga-client.model_cache.lookup` metrics in [OpenTelemetry](docs/opentelemetry.md). diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 9f976c1a..70aa176f 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -15,7 +15,7 @@ unmerged, validate_correlation_ids, ) -from openfga_sdk.client.model_cache import AsyncModelCache +from openfga_sdk.client.model_cache import AsyncModelCache, model_not_found from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, @@ -940,6 +940,8 @@ async def load_model(): raise ValueError("The authorization model response is empty") return response.authorization_model except Exception as err: + if model_not_found(err): + raise logger.warning( "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " "Sending checks unmerged.", @@ -964,6 +966,9 @@ async def load_model(): if lookup.model is not None: groups = resolve(lookup.model, checks) + elif model_not_found(lookup.error): + # BatchCheck would fail with the same error, so fail before sending anything. + raise lookup.error else: groups = unmerged(checks) telemetry.batchCheckMergeFallback( diff --git a/openfga_sdk/client/model_cache.py b/openfga_sdk/client/model_cache.py index 17d8e77e..27990168 100644 --- a/openfga_sdk/client/model_cache.py +++ b/openfga_sdk/client/model_cache.py @@ -2,9 +2,9 @@ In-memory cache of authorization models, used by BatchCheck's `merge_equivalent_checks` option. A model never changes once it's written, so a cached model never goes stale. Only -successful reads are cached. A failed read is remembered for a short time, so missing -read access doesn't add a read to every call. Calls for the same model share one -in-flight read. +successful reads are cached. A 403 or 429 is remembered for a short time, so missing +read access or rate limiting doesn't add a read to every call. Other failures aren't, +so the next call reads again. Calls for the same model share one in-flight read. """ import asyncio @@ -16,15 +16,25 @@ from concurrent.futures import Future from dataclasses import dataclass +from openfga_sdk.exceptions import ApiException from openfga_sdk.models.authorization_model import AuthorizationModel MAX_MODELS = 32 FAILURE_TTL_SECONDS = 60.0 +REMEMBERED_FAILURE_STATUSES = frozenset({403, 429}) +NOT_FOUND_CODES = frozenset({"authorization_model_not_found", "store_id_not_found"}) ModelCacheKey = tuple[str, str] +def model_not_found(error: Exception | None) -> bool: + """ + Whether a model read failed because the model or store doesn't exist + """ + return isinstance(error, ApiException) and error.code in NOT_FOUND_CODES + + @dataclass class ModelLookup: """ @@ -75,6 +85,11 @@ def _store(self, key: ModelCacheKey, model: AuthorizationModel) -> None: self._models.popitem(last=False) def _remember_failure(self, key: ModelCacheKey, error: Exception) -> None: + if not ( + isinstance(error, ApiException) + and error.status in REMEMBERED_FAILURE_STATUSES + ): + return self._failures[key] = (self._clock() + self._failure_ttl, error) self._failures.move_to_end(key) while len(self._failures) > self._max_models: diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index dce79582..43a6c9f9 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -13,7 +13,7 @@ unmerged, validate_correlation_ids, ) -from openfga_sdk.client.model_cache import ModelCache +from openfga_sdk.client.model_cache import ModelCache, model_not_found from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, @@ -937,6 +937,8 @@ def load_model(): raise ValueError("The authorization model response is empty") return response.authorization_model except Exception as err: + if model_not_found(err): + raise logger.warning( "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " "Sending checks unmerged.", @@ -959,6 +961,9 @@ def load_model(): if lookup.model is not None: groups = resolve(lookup.model, checks) + elif model_not_found(lookup.error): + # BatchCheck would fail with the same error, so fail before sending anything. + raise lookup.error else: groups = unmerged(checks) telemetry.batchCheckMergeFallback( diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index 373eb5ea..bbe5e6bc 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -112,7 +112,7 @@ def __call__(self, method, url, **kwargs): self.model_reads += 1 self.model_read_headers.append(kwargs.get("headers") or {}) if self.model_error is not None: - raise self.model_error + raise self.model_error() return mock_response(json.dumps(self.model_body)) if method == "POST" and url == BATCH_CHECK_URL: @@ -147,6 +147,14 @@ def forbidden(): return ForbiddenException(http_resp=http_mock_response("{}", 403)) +def model_not_found(): + body = { + "code": "authorization_model_not_found", + "message": f"Authorization Model '{MODEL_ID}' not found", + } + return ValidationException(http_resp=http_mock_response(json.dumps(body), 400)) + + class TestBatchCheckMergeEquivalentChecks(IsolatedAsyncioTestCase): def setUp(self): self.configuration = ClientConfiguration( @@ -322,7 +330,7 @@ async def test_no_checks_sends_nothing(self, mock_request): @patch.object(rest.RESTClientObject, "request") async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): - server = FakeServer(model_error=forbidden()) + server = FakeServer(model_error=forbidden) mock_request.side_effect = server async with OpenFgaClient(self.configuration) as client: @@ -348,6 +356,25 @@ async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): [r.allowed for r in response.result], [True, False, False, False] ) + @patch.object(rest.RESTClientObject, "request") + async def test_fails_before_sending_when_the_model_does_not_exist( + self, mock_request + ): + server = FakeServer(model_error=model_not_found) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs("openfga_sdk.client.client", "WARNING"): + for _ in range(2): + with self.assertRaises(ValidationException) as raised: + await self.batch_check(client, checks()) + self.assertEqual( + raised.exception.code, "authorization_model_not_found" + ) + + self.assertEqual(server.sent, []) + self.assertEqual(server.model_reads, 2) + @patch.object(rest.RESTClientObject, "request") async def test_sends_unmerged_when_the_model_response_is_empty(self, mock_request): server = FakeServer(model_body={}) @@ -500,7 +527,7 @@ async def test_records_telemetry( async def test_records_the_fallback_with_its_status_code( self, mock_request, mock_fallback ): - mock_request.side_effect = FakeServer(model_error=forbidden()) + mock_request.side_effect = FakeServer(model_error=forbidden) async with OpenFgaClient(self.configuration) as client: with self.assertLogs("openfga_sdk.client.client", "WARNING"): diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py index 307bb403..e0dd42c8 100644 --- a/test/client/model_cache_test.py +++ b/test/client/model_cache_test.py @@ -6,6 +6,13 @@ from unittest import IsolatedAsyncioTestCase, TestCase, skipIf from openfga_sdk.client.model_cache import AsyncModelCache, ModelCache +from openfga_sdk.exceptions import ( + ForbiddenException, + RateLimitExceededError, + ServiceException, + UnauthorizedException, + ValidationException, +) KEY = ("store", "model") @@ -46,7 +53,7 @@ async def test_a_failed_read_is_remembered_for_a_short_time(self): clock = FakeClock() cache = AsyncModelCache(failure_ttl=60, clock=clock) reads = 0 - error = RuntimeError("forbidden") + error = ForbiddenException(status=403) async def load(): nonlocal reads @@ -177,7 +184,7 @@ def test_a_failed_read_is_remembered_for_a_short_time(self): clock = FakeClock() cache = ModelCache(failure_ttl=60, clock=clock) reads = 0 - error = RuntimeError("forbidden") + error = ForbiddenException(status=403) def load(): nonlocal reads @@ -193,6 +200,28 @@ def load(): cache.get(KEY, load) self.assertEqual(reads, 2) + def test_only_a_403_or_429_is_remembered(self): + for error, remembered in [ + (ForbiddenException(status=403), True), + (RateLimitExceededError(status=429), True), + (UnauthorizedException(status=401), False), + (ValidationException(status=400), False), + (ServiceException(status=500), False), + (TimeoutError(), False), + ]: + with self.subTest(error=type(error).__name__): + cache = ModelCache() + reads = 0 + + def load(): + nonlocal reads + reads += 1 + raise error + + cache.get(KEY, load) + cache.get(KEY, load) + self.assertEqual(reads, 1 if remembered else 2) + def test_drops_the_least_recently_used_model(self): cache = ModelCache(max_models=2) @@ -242,7 +271,7 @@ def test_remembers_a_bounded_number_of_failures(self): def get(key): def load(): reads.append(key) - raise RuntimeError(key) + raise ForbiddenException(status=403) return cache.get(key, load) diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 64669386..39a89afe 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -24,6 +24,7 @@ STORE_ID, checks, http_mock_response, + model_not_found, sent_checks, ) @@ -55,7 +56,7 @@ def __call__(self, method, url, **kwargs): self.model_reads += 1 self.model_read_headers.append(kwargs.get("headers") or {}) if self.model_error is not None: - raise self.model_error + raise self.model_error() return mock_response(json.dumps(self.model_body)) if method == "POST" and url == BATCH_CHECK_URL: @@ -221,7 +222,7 @@ def test_no_checks_sends_nothing(self, mock_request): def test_sends_unmerged_when_the_model_cannot_be_read( self, mock_request, mock_fallback ): - server = FakeServer(model_error=forbidden()) + server = FakeServer(model_error=forbidden) mock_request.side_effect = server with OpenFgaClient(self.configuration) as client: @@ -248,6 +249,18 @@ def test_sends_unmerged_when_the_model_cannot_be_read( 403, ) + @patch.object(rest.RESTClientObject, "request") + def test_fails_before_sending_when_the_model_does_not_exist(self, mock_request): + server = FakeServer(model_error=model_not_found) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertRaises(ValidationException) as raised: + self.batch_check(client, checks()) + + self.assertEqual(raised.exception.code, "authorization_model_not_found") + self.assertEqual(server.sent, []) + @patch.object(rest.RESTClientObject, "request") def test_sends_unmerged_when_the_model_response_is_empty(self, mock_request): server = FakeServer(model_body={}) From ce0957a9976264b8f6b04ff2e418b2bf556bcae6 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Tue, 24 Nov 2026 16:30:23 +0530 Subject: [PATCH 12/38] fix: fail the call when the credentials can't read the model With merge_equivalent_checks on, a 401 or 403 on the model read, or a failed token request, now fails the call before any check is sent. Falling back hid wrong credentials. These failures aren't remembered, so the next call works as soon as the credentials are fixed. A 429, 5xx, timeout or network error still sends the checks unmerged, and only a 429 is remembered. --- README.md | 3 +- openfga_sdk/client/client.py | 12 +++--- openfga_sdk/client/model_cache.py | 23 ++++++---- openfga_sdk/sync/client/client.py | 12 +++--- test/client/batch_check_merge_test.py | 49 ++++++++++++++++++---- test/client/model_cache_test.py | 48 ++++++++++++++++++--- test/sync/client/batch_check_merge_test.py | 40 ++++++++++++++---- 7 files changed, 146 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 33147d92..60894a04 100644 --- a/README.md +++ b/README.md @@ -985,8 +985,9 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), - **Off by default.** With it off, nothing changes. Leaving it out or passing `None` keeps it off; any other non-bool value, like `"true"`, fails with a validation error. - **Needs an authorization model ID.** Without one, the call fails before anything is sent. - **Reads each model once per client.** The SDK reads a model the first time it needs it and caches it. Create the client once and reuse it. -- **Falls back safely.** If the model can't be read (for example, no read access), the SDK logs a warning and sends the checks unmerged. A 403 or 429 is remembered for about a minute; other failures are retried on the next call. +- **Needs read access to the model.** If the credentials can't read the model (a 401 or 403, or the token request fails), the call fails with that error before any check is sent. Turn the option off for credentials that can only run checks. - **Fails early if the model doesn't exist.** If the model or store isn't found, the call fails with that error before any check is sent, as BatchCheck would. +- **Falls back on other read failures.** If the read fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks unmerged. A 429 is remembered for about a minute; other failures are retried on the next call. - **Errors are shared.** If a merged check returns an error, every check it stands for gets that error. - **Correlation IDs** must match `^[\w\d-]{1,36}$` (ASCII). Missing ones are generated. - **Telemetry:** see the `fga-client.batch_check.*` and `fga-client.model_cache.lookup` metrics in [OpenTelemetry](docs/opentelemetry.md). diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 70aa176f..622c690c 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -15,7 +15,7 @@ unmerged, validate_correlation_ids, ) -from openfga_sdk.client.model_cache import AsyncModelCache, model_not_found +from openfga_sdk.client.model_cache import AsyncModelCache, model_read_fails_call from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, @@ -805,7 +805,7 @@ async def batch_check( :param authorization_model_id(options) - Overrides the authorization model id in the configuration :param max_parallel_requests(options) - Max number of requests to issue in parallel. Defaults to 10 :param max_batch_size(options) - Max number of checks to include in a request. Defaults to 50 - :param merge_equivalent_checks(options) - Beta. Send checks that are certain to get the same answer only once. Requires an authorization model id + :param merge_equivalent_checks(options) - Beta. Send checks that are certain to get the same answer only once. Requires an authorization model id and read access to that model :param header(options) - Custom headers to send alongside the request :param retryParams(options) - Override the retry parameters for this request :param retryParams.maxRetry(options) - Override the max number of retries on each API request @@ -940,7 +940,7 @@ async def load_model(): raise ValueError("The authorization model response is empty") return response.authorization_model except Exception as err: - if model_not_found(err): + if model_read_fails_call(err): raise logger.warning( "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " @@ -966,8 +966,10 @@ async def load_model(): if lookup.model is not None: groups = resolve(lookup.model, checks) - elif model_not_found(lookup.error): - # BatchCheck would fail with the same error, so fail before sending anything. + elif model_read_fails_call(lookup.error): + # BatchCheck would fail too if the model is missing or no token can be fetched, + # and falling back on a 401 or 403 would hide wrong credentials. Fail before + # sending anything. raise lookup.error else: groups = unmerged(checks) diff --git a/openfga_sdk/client/model_cache.py b/openfga_sdk/client/model_cache.py index 27990168..70113c49 100644 --- a/openfga_sdk/client/model_cache.py +++ b/openfga_sdk/client/model_cache.py @@ -2,9 +2,9 @@ In-memory cache of authorization models, used by BatchCheck's `merge_equivalent_checks` option. A model never changes once it's written, so a cached model never goes stale. Only -successful reads are cached. A 403 or 429 is remembered for a short time, so missing -read access or rate limiting doesn't add a read to every call. Other failures aren't, -so the next call reads again. Calls for the same model share one in-flight read. +successful reads are cached. A 429 is remembered for a short time, so rate limiting +doesn't add a read to every call. Other failures aren't, so the next call reads again. +Calls for the same model share one in-flight read. """ import asyncio @@ -16,23 +16,30 @@ from concurrent.futures import Future from dataclasses import dataclass -from openfga_sdk.exceptions import ApiException +from openfga_sdk.exceptions import ApiException, AuthenticationError from openfga_sdk.models.authorization_model import AuthorizationModel MAX_MODELS = 32 FAILURE_TTL_SECONDS = 60.0 -REMEMBERED_FAILURE_STATUSES = frozenset({403, 429}) +REMEMBERED_FAILURE_STATUSES = frozenset({429}) +CREDENTIAL_FAILURE_STATUSES = frozenset({401, 403}) NOT_FOUND_CODES = frozenset({"authorization_model_not_found", "store_id_not_found"}) ModelCacheKey = tuple[str, str] -def model_not_found(error: Exception | None) -> bool: +def model_read_fails_call(error: Exception | None) -> bool: """ - Whether a model read failed because the model or store doesn't exist + Whether a model read error fails the BatchCheck call instead of sending the checks + unmerged: the model or store doesn't exist, or the credentials can't read the model + (a 401 or 403, or the token request failed) """ - return isinstance(error, ApiException) and error.code in NOT_FOUND_CODES + if isinstance(error, AuthenticationError): + return True + return isinstance(error, ApiException) and ( + error.code in NOT_FOUND_CODES or error.status in CREDENTIAL_FAILURE_STATUSES + ) @dataclass diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index 43a6c9f9..df4850de 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -13,7 +13,7 @@ unmerged, validate_correlation_ids, ) -from openfga_sdk.client.model_cache import ModelCache, model_not_found +from openfga_sdk.client.model_cache import ModelCache, model_read_fails_call from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, @@ -800,7 +800,7 @@ def batch_check( :param authorization_model_id(options) - Overrides the authorization model id in the configuration :param max_parallel_requests(options) - Max number of requests to issue in parallel. Defaults to 10 :param max_batch_size(options) - Max number of checks to include in a request. Defaults to 50 - :param merge_equivalent_checks(options) - Beta. Send checks that are certain to get the same answer only once. Requires an authorization model id + :param merge_equivalent_checks(options) - Beta. Send checks that are certain to get the same answer only once. Requires an authorization model id and read access to that model :param header(options) - Custom headers to send alongside the request :param retryParams(options) - Override the retry parameters for this request :param retryParams.maxRetry(options) - Override the max number of retries on each API request @@ -937,7 +937,7 @@ def load_model(): raise ValueError("The authorization model response is empty") return response.authorization_model except Exception as err: - if model_not_found(err): + if model_read_fails_call(err): raise logger.warning( "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " @@ -961,8 +961,10 @@ def load_model(): if lookup.model is not None: groups = resolve(lookup.model, checks) - elif model_not_found(lookup.error): - # BatchCheck would fail with the same error, so fail before sending anything. + elif model_read_fails_call(lookup.error): + # BatchCheck would fail too if the model is missing or no token can be fetched, + # and falling back on a 401 or 403 would hide wrong credentials. Fail before + # sending anything. raise lookup.error else: groups = unmerged(checks) diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index bbe5e6bc..3ce02eaa 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -12,9 +12,12 @@ from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest from openfga_sdk.client.models.batch_check_response import ClientBatchCheckResponse +from openfga_sdk.configuration import RetryParams from openfga_sdk.exceptions import ( FgaValidationException, ForbiddenException, + RateLimitExceededError, + UnauthorizedException, ValidationException, ) from openfga_sdk.models.consistency_preference import ConsistencyPreference @@ -147,6 +150,17 @@ def forbidden(): return ForbiddenException(http_resp=http_mock_response("{}", 403)) +def unauthorized(): + return UnauthorizedException(http_resp=http_mock_response("{}", 401)) + + +def rate_limited(): + return RateLimitExceededError(http_resp=http_mock_response("{}", 429)) + + +NO_RETRY = {"retry_params": RetryParams(max_retry=0)} + + def model_not_found(): body = { "code": "authorization_model_not_found", @@ -330,18 +344,18 @@ async def test_no_checks_sends_nothing(self, mock_request): @patch.object(rest.RESTClientObject, "request") async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): - server = FakeServer(model_error=forbidden) + server = FakeServer(model_error=rate_limited) mock_request.side_effect = server async with OpenFgaClient(self.configuration) as client: with self.assertLogs("openfga_sdk.client.client", "WARNING") as logs: - response = await self.batch_check(client, checks()) - second = await self.batch_check(client, checks()) + response = await self.batch_check(client, checks(), NO_RETRY) + second = await self.batch_check(client, checks(), NO_RETRY) self.assertEqual(len(logs.records), 1) self.assertIn(MODEL_ID, logs.output[0]) self.assertIn(STORE_ID, logs.output[0]) - self.assertIn("403", logs.output[0]) + self.assertIn("429", logs.output[0]) self.assertEqual(server.model_reads, 1) unmerged = [ ("a", "viewer"), @@ -375,6 +389,27 @@ async def test_fails_before_sending_when_the_model_does_not_exist( self.assertEqual(server.sent, []) self.assertEqual(server.model_reads, 2) + @patch.object(rest.RESTClientObject, "request") + async def test_fails_before_sending_when_the_credentials_cannot_read_the_model( + self, mock_request + ): + for model_error, error_type in [ + (unauthorized, UnauthorizedException), + (forbidden, ForbiddenException), + ]: + with self.subTest(status=error_type.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs("openfga_sdk.client.client", "WARNING"): + for _ in range(2): + with self.assertRaises(error_type): + await self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + self.assertEqual(server.model_reads, 2) + @patch.object(rest.RESTClientObject, "request") async def test_sends_unmerged_when_the_model_response_is_empty(self, mock_request): server = FakeServer(model_body={}) @@ -527,14 +562,14 @@ async def test_records_telemetry( async def test_records_the_fallback_with_its_status_code( self, mock_request, mock_fallback ): - mock_request.side_effect = FakeServer(model_error=forbidden) + mock_request.side_effect = FakeServer(model_error=rate_limited) async with OpenFgaClient(self.configuration) as client: with self.assertLogs("openfga_sdk.client.client", "WARNING"): - await self.batch_check(client, checks()) + await self.batch_check(client, checks(), NO_RETRY) attributes = mock_fallback.call_args.kwargs["attributes"] - self.assertEqual(attributes[TelemetryAttributes.http_response_status_code], 403) + self.assertEqual(attributes[TelemetryAttributes.http_response_status_code], 429) self.assertEqual( attributes[TelemetryAttributes.fga_client_request_model_id], MODEL_ID ) diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py index e0dd42c8..307fbfdf 100644 --- a/test/client/model_cache_test.py +++ b/test/client/model_cache_test.py @@ -3,11 +3,18 @@ import threading import time +from types import SimpleNamespace from unittest import IsolatedAsyncioTestCase, TestCase, skipIf -from openfga_sdk.client.model_cache import AsyncModelCache, ModelCache +from openfga_sdk.client.model_cache import ( + AsyncModelCache, + ModelCache, + model_read_fails_call, +) from openfga_sdk.exceptions import ( + AuthenticationError, ForbiddenException, + NotFoundException, RateLimitExceededError, ServiceException, UnauthorizedException, @@ -53,7 +60,7 @@ async def test_a_failed_read_is_remembered_for_a_short_time(self): clock = FakeClock() cache = AsyncModelCache(failure_ttl=60, clock=clock) reads = 0 - error = ForbiddenException(status=403) + error = RateLimitExceededError(status=429) async def load(): nonlocal reads @@ -184,7 +191,7 @@ def test_a_failed_read_is_remembered_for_a_short_time(self): clock = FakeClock() cache = ModelCache(failure_ttl=60, clock=clock) reads = 0 - error = ForbiddenException(status=403) + error = RateLimitExceededError(status=429) def load(): nonlocal reads @@ -200,10 +207,10 @@ def load(): cache.get(KEY, load) self.assertEqual(reads, 2) - def test_only_a_403_or_429_is_remembered(self): + def test_only_a_429_is_remembered(self): for error, remembered in [ - (ForbiddenException(status=403), True), (RateLimitExceededError(status=429), True), + (ForbiddenException(status=403), False), (UnauthorizedException(status=401), False), (ValidationException(status=400), False), (ServiceException(status=500), False), @@ -271,7 +278,7 @@ def test_remembers_a_bounded_number_of_failures(self): def get(key): def load(): reads.append(key) - raise ForbiddenException(status=403) + raise RateLimitExceededError(status=429) return cache.get(key, load) @@ -295,3 +302,32 @@ def interrupt(): cache.get(KEY, interrupt) self.assertEqual(cache.get(KEY, lambda: "model").model, "model") + + +def with_code(error, code): + error.parsed_exception = SimpleNamespace(code=code) + return error + + +class TestModelReadFailsCall(TestCase): + def test_fails_when_the_model_is_missing_or_the_credentials_cannot_read_it(self): + for error, fails in [ + ( + with_code( + ValidationException(status=400), "authorization_model_not_found" + ), + True, + ), + (with_code(NotFoundException(status=404), "store_id_not_found"), True), + (UnauthorizedException(status=401), True), + (ForbiddenException(status=403), True), + (AuthenticationError(status=500), True), + (with_code(ValidationException(status=400), "validation_error"), False), + (RateLimitExceededError(status=429), False), + (ServiceException(status=500), False), + (TimeoutError(), False), + (ValueError("The authorization model response is empty"), False), + (None, False), + ]: + with self.subTest(error=repr(error)): + self.assertEqual(model_read_fails_call(error), fails) diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 39a89afe..dd070de4 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -9,6 +9,7 @@ from openfga_sdk.exceptions import ( FgaValidationException, ForbiddenException, + UnauthorizedException, ValidationException, ) from openfga_sdk.sync import rest @@ -21,11 +22,15 @@ MODEL, MODEL_ID, MODEL_URL, + NO_RETRY, STORE_ID, checks, + forbidden, http_mock_response, model_not_found, + rate_limited, sent_checks, + unauthorized, ) @@ -76,10 +81,6 @@ def __call__(self, method, url, **kwargs): raise AssertionError(f"Unexpected request: {method} {url}") -def forbidden(): - return ForbiddenException(http_resp=http_mock_response("{}", 403)) - - class TestSyncBatchCheckMergeEquivalentChecks(TestCase): def setUp(self): self.configuration = ClientConfiguration( @@ -222,16 +223,16 @@ def test_no_checks_sends_nothing(self, mock_request): def test_sends_unmerged_when_the_model_cannot_be_read( self, mock_request, mock_fallback ): - server = FakeServer(model_error=forbidden) + server = FakeServer(model_error=rate_limited) mock_request.side_effect = server with OpenFgaClient(self.configuration) as client: with self.assertLogs("openfga_sdk.sync.client.client", "WARNING") as logs: - response = self.batch_check(client, checks()) - self.batch_check(client, checks()) + response = self.batch_check(client, checks(), NO_RETRY) + self.batch_check(client, checks(), NO_RETRY) self.assertEqual(len(logs.records), 1) - self.assertIn("403", logs.output[0]) + self.assertIn("429", logs.output[0]) self.assertEqual(server.model_reads, 1) unmerged = [ ("a", "viewer"), @@ -246,7 +247,7 @@ def test_sends_unmerged_when_the_model_cannot_be_read( mock_fallback.call_args.kwargs["attributes"][ TelemetryAttributes.http_response_status_code ], - 403, + 429, ) @patch.object(rest.RESTClientObject, "request") @@ -261,6 +262,27 @@ def test_fails_before_sending_when_the_model_does_not_exist(self, mock_request): self.assertEqual(raised.exception.code, "authorization_model_not_found") self.assertEqual(server.sent, []) + @patch.object(rest.RESTClientObject, "request") + def test_fails_before_sending_when_the_credentials_cannot_read_the_model( + self, mock_request + ): + for model_error, error_type in [ + (unauthorized, UnauthorizedException), + (forbidden, ForbiddenException), + ]: + with self.subTest(status=error_type.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs("openfga_sdk.sync.client.client", "WARNING"): + for _ in range(2): + with self.assertRaises(error_type): + self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + self.assertEqual(server.model_reads, 2) + @patch.object(rest.RESTClientObject, "request") def test_sends_unmerged_when_the_model_response_is_empty(self, mock_request): server = FakeServer(model_body={}) From 16a29a283962564a11a544f299b5aff3a74a4ffd Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Tue, 24 Nov 2026 17:32:35 +0530 Subject: [PATCH 13/38] docs: drop beta wording from merge_equivalent_checks --- README.md | 4 ++-- openfga_sdk/client/client.py | 2 +- openfga_sdk/sync/client/client.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 60894a04..7c6620ae 100644 --- a/README.md +++ b/README.md @@ -965,9 +965,9 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), # ] ``` -###### Merge equivalent checks (beta) +###### Merge equivalent checks -Set `merge_equivalent_checks` to `True` to send checks that are certain to get the same answer only once. The SDK copies each answer back, so you still get one result per check you passed in. It's in beta, so its behavior may change based on feedback. +Set `merge_equivalent_checks` to `True` to send checks that are certain to get the same answer only once. The SDK copies each answer back, so you still get one result per check you passed in. It merges: - **Aliases:** with `define can_view: viewer`, checking both `viewer` and `can_view` for the same user and object sends one check. Chains like `define can_share: can_view` work too. diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 622c690c..2f9e14ea 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -805,7 +805,7 @@ async def batch_check( :param authorization_model_id(options) - Overrides the authorization model id in the configuration :param max_parallel_requests(options) - Max number of requests to issue in parallel. Defaults to 10 :param max_batch_size(options) - Max number of checks to include in a request. Defaults to 50 - :param merge_equivalent_checks(options) - Beta. Send checks that are certain to get the same answer only once. Requires an authorization model id and read access to that model + :param merge_equivalent_checks(options) - Send checks that are certain to get the same answer only once. Requires an authorization model id and read access to that model :param header(options) - Custom headers to send alongside the request :param retryParams(options) - Override the retry parameters for this request :param retryParams.maxRetry(options) - Override the max number of retries on each API request diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index df4850de..5e672624 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -800,7 +800,7 @@ def batch_check( :param authorization_model_id(options) - Overrides the authorization model id in the configuration :param max_parallel_requests(options) - Max number of requests to issue in parallel. Defaults to 10 :param max_batch_size(options) - Max number of checks to include in a request. Defaults to 50 - :param merge_equivalent_checks(options) - Beta. Send checks that are certain to get the same answer only once. Requires an authorization model id and read access to that model + :param merge_equivalent_checks(options) - Send checks that are certain to get the same answer only once. Requires an authorization model id and read access to that model :param header(options) - Custom headers to send alongside the request :param retryParams(options) - Override the retry parameters for this request :param retryParams.maxRetry(options) - Override the max number of retries on each API request From f74eac157edfd34c09c0cfa360c70c4f8557c3e0 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Tue, 24 Nov 2026 23:23:34 +0530 Subject: [PATCH 14/38] test: update shared equivalent-checks cases to openfga/language@153c7a9 --- Makefile | 2 +- test/data/equivalent-checks-cases.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 2a9edb99..438fe36c 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases # openfga/language commit to copy the shared equivalent-checks cases from -LANGUAGE_REF ?= bca096c2f02edcdbf753be641d90aadb9476e45e +LANGUAGE_REF ?= 153c7a93ef8775b81ef1e53a5a6a3fa04d469803 # Install/update dependencies sync: diff --git a/test/data/equivalent-checks-cases.json b/test/data/equivalent-checks-cases.json index 72055e3c..4dea16af 100644 --- a/test/data/equivalent-checks-cases.json +++ b/test/data/equivalent-checks-cases.json @@ -1,5 +1,5 @@ { - "note": "Generated from equivalent-checks-cases.yaml, with every model as JSON. Don't edit this file: edit the YAML file and run `make generate-equivalent-checks-json`.", + "note": "Generated from equivalent-checks-cases.yaml, with every model as JSON. Don't edit this file: edit the YAML file and run `make -C pkg/go generate-equivalent-checks-json`.", "cases": [ { "name": "merges an alias with the relation it points to", From c1f6de37707552be04de4f93be0f213bd680632f Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Wed, 25 Nov 2026 15:19:32 +0530 Subject: [PATCH 15/38] refactor: address review on merge_equivalent_checks - Validate the model ID, correlation IDs and store ID in batch_check first - Read the model through a private client helper and cache its resolved aliases - Share the send step with the normal path, and the grouping, fallback and telemetry steps between sync and async - Split the model cache into async, sync and a private shared module - Send unmerged if grouping fails; send uncomparable checks on their own - Only compare context and contextual tuples for checks that could merge - Add tests for 5xx, timeouts, missing store, token failures, grouping failures, model ID in options, and cache keys across stores and models - Rewrite the README section --- README.md | 34 +-- docs/opentelemetry.md | 2 +- openfga_sdk/client/_batch_check_merge.py | 112 ++++++++++ openfga_sdk/client/_model_cache_base.py | 104 +++++++++ openfga_sdk/client/client.py | 223 +++++++++---------- openfga_sdk/client/equivalent_checks.py | 181 ++++++++++------ openfga_sdk/client/model_cache.py | 175 ++------------- openfga_sdk/sync/client/client.py | 225 +++++++++----------- openfga_sdk/sync/client/model_cache.py | 71 ++++++ test/client/batch_check_merge_test.py | 190 +++++++++++++++-- test/client/equivalent_checks_cases_test.py | 4 +- test/client/equivalent_checks_test.py | 73 +++++-- test/client/model_cache_test.py | 187 +++------------- test/sync/client/batch_check_merge_test.py | 168 +++++++++++++-- test/sync/client/model_cache_test.py | 199 +++++++++++++++++ 15 files changed, 1250 insertions(+), 698 deletions(-) create mode 100644 openfga_sdk/client/_batch_check_merge.py create mode 100644 openfga_sdk/client/_model_cache_base.py create mode 100644 openfga_sdk/sync/client/model_cache.py create mode 100644 test/sync/client/model_cache_test.py diff --git a/README.md b/README.md index 7c6620ae..16378c30 100644 --- a/README.md +++ b/README.md @@ -967,30 +967,34 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), ###### Merge equivalent checks -Set `merge_equivalent_checks` to `True` to send checks that are certain to get the same answer only once. The SDK copies each answer back, so you still get one result per check you passed in. +If you set `merge_equivalent_checks` to `True` in the options, the SDK sends checks that will get the same answer only once, then copies that answer back to each of them. You still get one result for every check you passed in. -It merges: -- **Aliases:** with `define can_view: viewer`, checking both `viewer` and `can_view` for the same user and object sends one check. Chains like `define can_share: can_view` work too. -- **Exact repeats:** the same user, relation, object, context and contextual tuples. +Two kinds of checks are merged: + +- Checks on a relation that is an alias of another one. With `define can_view: viewer`, a check on `can_view` and a check on `viewer` for the same user and object become one check on `viewer`. Chains like `define can_share: can_view` are followed too. +- Exact repeats, with the same user, relation, object, context and contextual tuples. ```python options = { - "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1", # required, here or in the configuration + # Required, either here or in the configuration + "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1", "merge_equivalent_checks": True, } response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), options) -# response.checks_sent: how many checks this call actually sent +# response.checks_sent is how many checks were sent to the server ``` -- **Off by default.** With it off, nothing changes. Leaving it out or passing `None` keeps it off; any other non-bool value, like `"true"`, fails with a validation error. -- **Needs an authorization model ID.** Without one, the call fails before anything is sent. -- **Reads each model once per client.** The SDK reads a model the first time it needs it and caches it. Create the client once and reuse it. -- **Needs read access to the model.** If the credentials can't read the model (a 401 or 403, or the token request fails), the call fails with that error before any check is sent. Turn the option off for credentials that can only run checks. -- **Fails early if the model doesn't exist.** If the model or store isn't found, the call fails with that error before any check is sent, as BatchCheck would. -- **Falls back on other read failures.** If the read fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks unmerged. A 429 is remembered for about a minute; other failures are retried on the next call. -- **Errors are shared.** If a merged check returns an error, every check it stands for gets that error. -- **Correlation IDs** must match `^[\w\d-]{1,36}$` (ASCII). Missing ones are generated. -- **Telemetry:** see the `fga-client.batch_check.*` and `fga-client.model_cache.lookup` metrics in [OpenTelemetry](docs/opentelemetry.md). +The option is off by default, and nothing changes while it is off. Leaving it out or setting it to `None` keeps it off. Any other value that isn't a bool, like `"true"`, fails with a validation error. + +To find aliases, the SDK reads the authorization model the first time it needs it and keeps it in memory, so create the client once and reuse it. The call fails before any check is sent when: + +- no authorization model ID is set +- the model or the store doesn't exist +- the credentials can't read the model (a 401 or 403, or the token request fails). If your credentials can only run checks, leave the option off. + +If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. After a 429 it waits about a minute before reading the model again. After any other failure it tries again on the next call. + +If a merged check returns an error, every check it stands for gets that error. Correlation IDs must match `^[\w\d-]{1,36}$` (ASCII), and missing ones are generated. For metrics, see `fga-client.batch_check.*` and `fga-client.model_cache.lookup` in [OpenTelemetry](docs/opentelemetry.md). ##### Client Batch Check diff --git a/docs/opentelemetry.md b/docs/opentelemetry.md index dfed134a..31bb1619 100644 --- a/docs/opentelemetry.md +++ b/docs/opentelemetry.md @@ -29,7 +29,7 @@ If you configure the OpenTelemetry SDK, these metrics will be exported and sent | `fga-client.request` | Counter | No | Total number of requests made to the FGA server | | `fga-client.batch_check.checks_requested` | Counter | Yes | Checks passed to `batch_check` with `merge_equivalent_checks` on | | `fga-client.batch_check.checks_sent` | Counter | Yes | Checks actually sent by `batch_check` with `merge_equivalent_checks` on | -| `fga-client.batch_check.merge_fallback` | Counter | Yes | `batch_check` calls sent unmerged because the authorization model could not be read | +| `fga-client.batch_check.merge_fallback` | Counter | Yes | `batch_check` calls sent unmerged because the model could not be read or the checks grouped | | `fga-client.model_cache.lookup` | Counter | Yes | Authorization model cache lookups by `merge_equivalent_checks`, with a `hit` or `miss` result | ### Supported Attributes diff --git a/openfga_sdk/client/_batch_check_merge.py b/openfga_sdk/client/_batch_check_merge.py new file mode 100644 index 00000000..7a420560 --- /dev/null +++ b/openfga_sdk/client/_batch_check_merge.py @@ -0,0 +1,112 @@ +""" +Steps of a BatchCheck call with `merge_equivalent_checks` on that are the same in the +async and sync clients. The clients only read the model and send the checks. Not part +of the public API. +""" + +import logging + +from openfga_sdk.client._model_cache_base import ModelLookup, model_read_fails_call +from openfga_sdk.client.equivalent_checks import ( + EquivalentCheckGroup, + resolve, + unmerged, +) +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.telemetry.attributes import TelemetryAttributes + + +logger = logging.getLogger(__name__) + + +def log_model_read_failure( + error: Exception, store_id: str, authorization_model_id: str +) -> None: + """ + Warn that the checks go out unmerged, unless the error fails the call. + """ + if model_read_fails_call(error): + return + logger.warning( + "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " + "Sending checks unmerged.", + authorization_model_id, + store_id, + getattr(error, "status", None), + ) + + +def checks_to_send( + api_client, + store_id: str, + authorization_model_id: str, + lookup: ModelLookup, + checks: list[ClientBatchCheckItem], +) -> list[EquivalentCheckGroup]: + """ + Group the checks using the model from the cache, or send them unmerged if the model + couldn't be read or grouping failed. Raise if the model read error fails the call. + """ + metrics = _MergeMetrics(api_client, store_id, authorization_model_id) + metrics.model_cache_lookup(lookup.hit) + + if lookup.aliases is None: + if model_read_fails_call(lookup.error): + # BatchCheck would fail too if the model is missing or no token can be + # fetched, and falling back on a 401 or 403 would hide wrong credentials. + # Fail before sending anything. + raise lookup.error + groups = unmerged(checks) + metrics.fallback(getattr(lookup.error, "status", None)) + else: + try: + groups = resolve(lookup.aliases, checks) + except Exception: + logger.warning( + "merge_equivalent_checks: couldn't group the checks. Sending checks unmerged.", + exc_info=True, + ) + groups = unmerged(checks) + metrics.fallback(None) + + # Every chunk is sent even if another one fails, so count them up front. + metrics.checks(requested=len(checks), sent=len(groups)) + return groups + + +class _MergeMetrics: + def __init__(self, api_client, store_id: str, authorization_model_id: str) -> None: + self._metrics = api_client._telemetry.metrics + self._configuration = api_client.configuration.telemetry + self._attributes = { + TelemetryAttributes.fga_client_request_store_id: store_id, + TelemetryAttributes.fga_client_request_model_id: authorization_model_id, + } + + def model_cache_lookup(self, hit: bool) -> None: + self._metrics.modelCacheLookup( + attributes={ + **self._attributes, + TelemetryAttributes.fga_client_model_cache_result: ( + "hit" if hit else "miss" + ), + }, + configuration=self._configuration, + ) + + def fallback(self, status: int | None) -> None: + self._metrics.batchCheckMergeFallback( + attributes={ + **self._attributes, + TelemetryAttributes.http_response_status_code: status, + }, + configuration=self._configuration, + ) + + def checks(self, requested: int, sent: int) -> None: + self._metrics.batchCheckChecksRequested( + requested, attributes=self._attributes, configuration=self._configuration + ) + self._metrics.batchCheckChecksSent( + sent, attributes=self._attributes, configuration=self._configuration + ) diff --git a/openfga_sdk/client/_model_cache_base.py b/openfga_sdk/client/_model_cache_base.py new file mode 100644 index 00000000..4b9c675a --- /dev/null +++ b/openfga_sdk/client/_model_cache_base.py @@ -0,0 +1,104 @@ +""" +The parts of the BatchCheck model cache that the async and sync clients share. Not +part of the public API. + +A model never changes once it's written, so a cached model never goes stale. Only +successful reads are cached. A 429 is remembered for a short time, so rate limiting +doesn't add a read to every call. Other failures aren't, so the next call reads again. +""" + +import time + +from collections import OrderedDict +from collections.abc import Callable +from dataclasses import dataclass + +from openfga_sdk.client.equivalent_checks import ModelAliases +from openfga_sdk.exceptions import ApiException, AuthenticationError + + +MAX_MODELS = 32 +FAILURE_TTL_SECONDS = 60.0 +REMEMBERED_FAILURE_STATUSES = frozenset({429}) +CREDENTIAL_FAILURE_STATUSES = frozenset({401, 403}) +NOT_FOUND_CODES = frozenset({"authorization_model_not_found", "store_id_not_found"}) + +ModelCacheKey = tuple[str, str] + + +def model_read_fails_call(error: Exception | None) -> bool: + """ + Whether a model read error fails the BatchCheck call instead of sending the checks + unmerged: the model or store doesn't exist, or the credentials can't read the model + (a 401 or 403, or the token request failed) + """ + if isinstance(error, AuthenticationError): + return True + return isinstance(error, ApiException) and ( + error.code in NOT_FOUND_CODES or error.status in CREDENTIAL_FAILURE_STATUSES + ) + + +@dataclass +class ModelLookup: + """ + The result of a cache lookup: the model's aliases, or the error from reading it. + `hit` is True only when they were already in the cache. + """ + + aliases: ModelAliases | None = None + hit: bool = False + error: Exception | None = None + + +class ModelCacheBase: + """ + The cached models and remembered failures. The async and sync caches add the reads. + """ + + def __init__( + self, + max_models: int = MAX_MODELS, + failure_ttl: float = FAILURE_TTL_SECONDS, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self._max_models = max_models + self._failure_ttl = failure_ttl + self._clock = clock + self._models: OrderedDict[ModelCacheKey, ModelAliases] = OrderedDict() + self._failures: OrderedDict[ModelCacheKey, tuple[float, Exception]] = ( + OrderedDict() + ) + + def _cached(self, key: ModelCacheKey) -> ModelLookup | None: + aliases = self._models.get(key) + if aliases is not None: + self._models.move_to_end(key) + return ModelLookup(aliases=aliases, hit=True) + + failure = self._failures.get(key) + if failure is not None: + expires_at, error = failure + if self._clock() < expires_at: + return ModelLookup(error=error) + del self._failures[key] + + return None + + def _store(self, key: ModelCacheKey, aliases: ModelAliases) -> None: + self._failures.pop(key, None) + self._models[key] = aliases + self._models.move_to_end(key) + while len(self._models) > self._max_models: + self._models.popitem(last=False) + + def _remember_failure(self, key: ModelCacheKey, error: Exception) -> None: + if not ( + isinstance(error, ApiException) + and error.status in REMEMBERED_FAILURE_STATUSES + ): + return + self._failures[key] = (self._clock() + self._failure_ttl, error) + self._failures.move_to_end(key) + while len(self._failures) > self._max_models: + self._failures.popitem(last=False) diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 2f9e14ea..a5691763 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -1,21 +1,24 @@ import asyncio -import logging import uuid -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Callable from typing import Any from openfga_sdk.api.open_fga_api import OpenFgaApi from openfga_sdk.api_client import ApiClient +from openfga_sdk.client._batch_check_merge import ( + checks_to_send, + log_model_read_failure, +) +from openfga_sdk.client._model_cache_base import ModelLookup from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.equivalent_checks import ( + ModelAliases, expand, merge_enabled, - resolve, - unmerged, - validate_correlation_ids, + prepare_checks, ) -from openfga_sdk.client.model_cache import AsyncModelCache, model_read_fails_call +from openfga_sdk.client.model_cache import AsyncModelCache from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, @@ -58,7 +61,9 @@ UnauthorizedException, ) from openfga_sdk.models.assertion import Assertion +from openfga_sdk.models.batch_check_item import BatchCheckItem from openfga_sdk.models.batch_check_request import BatchCheckRequest +from openfga_sdk.models.batch_check_response import BatchCheckResponse from openfga_sdk.models.check_request import CheckRequest from openfga_sdk.models.contextual_tuple_keys import ContextualTupleKeys from openfga_sdk.models.create_store_request import CreateStoreRequest @@ -80,13 +85,9 @@ WriteAuthorizationModelRequest, ) from openfga_sdk.models.write_request import WriteRequest -from openfga_sdk.telemetry.attributes import TelemetryAttributes from openfga_sdk.validation import is_well_formed_ulid_string -logger = logging.getLogger(__name__) - - def _chuck_array(array, max_size): """ Helper function to chuck array into arrays of max_size @@ -836,8 +837,16 @@ async def batch_check( max_batch_size = options["max_batch_size"] if merge_enabled(options): + # Reading the model and sending the checks must use the same model and store. + authorization_model_id = self._get_authorization_model_id(options) + prepare_checks(body.checks, authorization_model_id) return await self._merged_batch_check( - body, options, max_parallel_requests, max_batch_size + body.checks, + self._api_client._get_store_id(), + authorization_model_id, + options, + max_parallel_requests, + max_batch_size, ) id_to_check: dict[str, ClientBatchCheckItem] = {} @@ -866,7 +875,6 @@ def track_and_transform(checks): ] result = [] - sem = asyncio.Semaphore(max_parallel_requests) def map_response(id, result): check = id_to_check[id] @@ -877,144 +885,117 @@ def map_response(id, result): error=result.error, ) - async def coro(checks): - res = await self._single_batch_check( - BatchCheckRequest( - checks=checks, - authorization_model_id=self._get_authorization_model_id(options), - consistency=self._get_consistency(options), - ), - sem, - options, - ) - + def add_results(response): result.extend( - [map_response(c_id, c_result) for c_id, c_result in res.result.items()] + [ + map_response(c_id, c_result) + for c_id, c_result in response.result.items() + ] ) - batch_check_coros = [coro(request) for request in checks] - await asyncio.gather(*batch_check_coros) + if checks: + await self._send_batch_checks( + checks, + self._get_authorization_model_id(options), + options, + max_parallel_requests, + add_results, + ) return ClientBatchCheckResponse(result) - async def _merged_batch_check( + async def _send_batch_checks( self, - body: ClientBatchCheckRequest, + chunks: list[list[BatchCheckItem]], + authorization_model_id: str | None, options: dict[str, int | str | dict[str, int | str]], max_parallel_requests: int, - max_batch_size: int, - ) -> ClientBatchCheckResponse: + on_response: Callable[[BatchCheckResponse], None], + ) -> None: """ - Run a BatchCheck with merge_equivalent_checks on + Send each chunk of checks as one BatchCheck request, with at most + max_parallel_requests in flight, and pass each response to on_response """ - # Reading the model and sending the checks must use the same model. - authorization_model_id = self._get_authorization_model_id(options) - if authorization_model_id is None: - raise FgaValidationException( - "authorization_model_id is required when merge_equivalent_checks is on" - ) - store_id = self._api_client._get_store_id() - - checks = body.checks - for check in checks: - if check.correlation_id is None: - check.correlation_id = str(uuid.uuid4()) - validate_correlation_ids(checks) - - if not checks: - return ClientBatchCheckResponse([], checks_sent=0) - - telemetry = self._api_client._telemetry.metrics - telemetry_configuration = self._api_client.configuration.telemetry - attributes = { - TelemetryAttributes.fga_client_request_store_id: store_id, - TelemetryAttributes.fga_client_request_model_id: authorization_model_id, - } - - async def load_model(): - try: - response = await self._api.read_authorization_model( - authorization_model_id, **_model_read_kwargs(options) - ) - if response.authorization_model is None: - raise ValueError("The authorization model response is empty") - return response.authorization_model - except Exception as err: - if model_read_fails_call(err): - raise - logger.warning( - "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " - "Sending checks unmerged.", - authorization_model_id, - store_id, - getattr(err, "status", None), - ) - raise - - lookup = await self._model_cache.get( - (store_id, authorization_model_id), load_model - ) - telemetry.modelCacheLookup( - attributes={ - **attributes, - TelemetryAttributes.fga_client_model_cache_result: ( - "hit" if lookup.hit else "miss" - ), - }, - configuration=telemetry_configuration, - ) - - if lookup.model is not None: - groups = resolve(lookup.model, checks) - elif model_read_fails_call(lookup.error): - # BatchCheck would fail too if the model is missing or no token can be fetched, - # and falling back on a 401 or 403 would hide wrong credentials. Fail before - # sending anything. - raise lookup.error - else: - groups = unmerged(checks) - telemetry.batchCheckMergeFallback( - attributes={ - **attributes, - TelemetryAttributes.http_response_status_code: getattr( - lookup.error, "status", None - ), - }, - configuration=telemetry_configuration, - ) - - # Every chunk is sent even if another one fails, so count them up front. - telemetry.batchCheckChecksRequested( - len(checks), attributes=attributes, configuration=telemetry_configuration - ) - telemetry.batchCheckChecksSent( - len(groups), attributes=attributes, configuration=telemetry_configuration - ) - - results = {} sem = asyncio.Semaphore(max_parallel_requests) consistency = self._get_consistency(options) - async def send(chunk): + async def send(checks): response = await self._single_batch_check( BatchCheckRequest( - checks=[construct_batch_item(group.check) for group in chunk], + checks=checks, authorization_model_id=authorization_model_id, consistency=consistency, ), sem, options, ) - results.update(response.result or {}) + on_response(response) + + await asyncio.gather(*[send(checks) for checks in chunks]) + + async def _merged_batch_check( + self, + checks: list[ClientBatchCheckItem], + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]], + max_parallel_requests: int, + max_batch_size: int, + ) -> ClientBatchCheckResponse: + """ + Run a BatchCheck with merge_equivalent_checks on, for checks already validated + """ + if not checks: + return ClientBatchCheckResponse([], checks_sent=0) - await asyncio.gather( - *[send(chunk) for chunk in _chuck_array(groups, max_batch_size)] + lookup = await self._read_and_cache_model_aliases( + store_id, authorization_model_id, options + ) + groups = checks_to_send( + self._api_client, store_id, authorization_model_id, lookup, checks + ) + + results = {} + await self._send_batch_checks( + [ + [construct_batch_item(group.check) for group in chunk] + for chunk in _chuck_array(groups, max_batch_size) + ], + authorization_model_id, + options, + max_parallel_requests, + lambda response: results.update(response.result or {}), ) return ClientBatchCheckResponse( expand(checks, groups, results), checks_sent=len(groups) ) + async def _read_and_cache_model_aliases( + self, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None = None, + ) -> ModelLookup: + """ + Read an authorization model through the client's model cache, and work out its + aliases for merge_equivalent_checks + :param header(options) - Custom headers to send alongside the request + :param retryParams(options) - Override the retry parameters for this request + """ + + async def load(): + try: + response = await self._api.read_authorization_model( + authorization_model_id, **_model_read_kwargs(options) + ) + return ModelAliases(response.authorization_model) + except Exception as error: + log_model_read_failure(error, store_id, authorization_model_id) + raise + + return await self._model_cache.get((store_id, authorization_model_id), load) + async def expand( self, body: ClientExpandRequest, diff --git a/openfga_sdk/client/equivalent_checks.py b/openfga_sdk/client/equivalent_checks.py index e855bdf6..4fe16942 100644 --- a/openfga_sdk/client/equivalent_checks.py +++ b/openfga_sdk/client/equivalent_checks.py @@ -8,6 +8,7 @@ import math import re import struct +import uuid from collections import Counter from dataclasses import dataclass @@ -26,6 +27,7 @@ CORRELATION_ID_PATTERN = re.compile(r"^[\w\d-]{1,36}$", re.ASCII) _MISSING = ("missing",) +_UNCOMPARABLE = ("uncomparable",) # Values nested deeper than this are sent as is, so comparing them can't run out of stack. _MAX_DEPTH = 100 @@ -58,6 +60,24 @@ def merge_enabled(options: dict | None) -> bool: return value is True +def prepare_checks( + checks: list[ClientBatchCheckItem], authorization_model_id: str | None +) -> None: + """ + Check what merging needs before anything is sent: a model ID, and correlation IDs + that are valid and unique. Checks without a correlation ID get a generated one. + """ + if authorization_model_id is None: + raise FgaValidationException( + "authorization_model_id is required when merge_equivalent_checks is on" + ) + + for check in checks: + if check.correlation_id is None: + check.correlation_id = str(uuid.uuid4()) + validate_correlation_ids(checks) + + def validate_correlation_ids(checks: list[ClientBatchCheckItem]) -> None: """ Raise if a correlation ID doesn't match the API rule, or is used twice. @@ -86,8 +106,75 @@ def unmerged(checks: list[ClientBatchCheckItem]) -> list[EquivalentCheckGroup]: return [EquivalentCheckGroup(check=check, members=[check]) for check in checks] +class ModelAliases: + """ + Where every relation in a model ends after following its aliases. Worked out once + per model and kept in the model cache, so a call only looks relations up. + """ + + def __init__(self, model: AuthorizationModel | None) -> None: + if model is None: + raise ValueError("The authorization model response is empty") + + # type -> relation -> (final relation, every relation in the chain), or None + # if the chain points to a missing relation or loops. + self._types: dict[str, dict[str, tuple[str, frozenset[str]] | None]] = {} + for type_definition in model.type_definitions or []: + relations = type_definition.relations or {} + self._types[type_definition.type] = { + relation: _resolved_chain(relations, relation) for relation in relations + } + + def final_relation(self, check: ClientBatchCheckItem) -> str | None: + """ + Return the relation to send the check with, or None to send it as is. + """ + if not all( + isinstance(value, str) + for value in (check.user, check.relation, check.object) + ): + return None + + object_type, separator, object_id = check.object.partition(":") + relations = self._types.get(object_type) + if not separator or relations is None or check.relation not in relations: + return None + + user_type, separator, user_rest = check.user.partition(":") + if not separator or user_type not in self._types: + return None + + user_id, userset_separator, user_relation = user_rest.partition("#") + if userset_separator and user_relation not in self._types[user_type]: + return None + + resolved = relations[check.relation] + if resolved is None: + return None + final_relation, chain = resolved + + # The server says a userset always has its own relation on its own object, at + # every step of a chain, so a merged check could get a different answer. + if ( + userset_separator + and (user_type, user_id) == (object_type, object_id) + and user_relation in chain + ): + return None + + # The server's answer can depend on which of these tuples it reads first. + tuple_keys = [ + (contextual_tuple.user, contextual_tuple.relation, contextual_tuple.object) + for contextual_tuple in check.contextual_tuples or [] + ] + if len(set(tuple_keys)) != len(tuple_keys): + return None + + return final_relation + + def resolve( - model: AuthorizationModel, checks: list[ClientBatchCheckItem] + aliases: ModelAliases, checks: list[ClientBatchCheckItem] ) -> list[EquivalentCheckGroup]: """ Group checks that are certain to get the same answer, and build the checks to send. @@ -95,37 +182,39 @@ def resolve( The result is deterministic: the same model and checks, in the same order, give the same groups and IDs. Each group is placed at the position of its first check. """ - types = { - type_definition.type: type_definition.relations or {} - for type_definition in model.type_definitions or [] - } + finals = [aliases.final_relation(check) for check in checks] + + # Comparing context and contextual tuples is the slow part, so only do it for checks + # that share a final relation, user and object with another check. + shared = Counter( + (final_relation, check.user, check.object) + for final_relation, check in zip(finals, checks, strict=True) + if final_relation is not None + ) entries: list[tuple[str, ClientBatchCheckItem | tuple]] = [] groups: dict[tuple, list[ClientBatchCheckItem]] = {} - finals: dict[tuple, str] = {} - for check in checks: - final_relation = _final_relation(types, check) - key = None - if final_relation is not None: + for position, (final_relation, check) in enumerate( + zip(finals, checks, strict=True) + ): + if final_relation is None: + entries.append(("as_is", check)) + continue + + key = (final_relation, check.user, check.object) + if shared[key] > 1: try: - key = ( - final_relation, - check.user, - check.object, + key += ( _context_key(check.context), _contextual_tuples_key(check.contextual_tuples), ) except _Unmergeable: - key = None - - if key is None: - entries.append(("as_is", check)) - continue + # It can't be compared with the others, so it's a group of its own. + key += (_UNCOMPARABLE, position) if key not in groups: groups[key] = [] - finals[key] = final_relation entries.append(("group", key)) groups[key].append(check) @@ -152,7 +241,7 @@ def resolve( EquivalentCheckGroup( check=ClientBatchCheckItem( user=first.user, - relation=finals[entry], + relation=entry[0], object=first.object, correlation_id=correlation_id, contextual_tuples=first.contextual_tuples, @@ -244,53 +333,13 @@ def _alias_chain(relations: dict[str, Userset], relation: str) -> list[str] | No chain.append(target) -def _final_relation(types: dict[str, dict[str, Userset]], check) -> str | None: - """ - Return the relation to send the check with, or None to send it as is. - """ - if not all( - isinstance(value, str) for value in (check.user, check.relation, check.object) - ): - return None - - object_type, separator, object_id = check.object.partition(":") - if not separator or object_type not in types: - return None - - relations = types[object_type] - if check.relation not in relations: - return None - - user_type, separator, user_rest = check.user.partition(":") - if not separator or user_type not in types: - return None - - user_id, userset_separator, user_relation = user_rest.partition("#") - if userset_separator and user_relation not in types[user_type]: - return None - - chain = _alias_chain(relations, check.relation) +def _resolved_chain( + relations: dict[str, Userset], relation: str +) -> tuple[str, frozenset[str]] | None: + chain = _alias_chain(relations, relation) if chain is None: return None - - # The server says a userset always has its own relation on its own object, at every - # step of a chain, so a merged check could get a different answer. - if ( - userset_separator - and (user_type, user_id) == (object_type, object_id) - and user_relation in chain - ): - return None - - # The server's answer can depend on which of these tuples it reads first. - tuple_keys = [ - (contextual_tuple.user, contextual_tuple.relation, contextual_tuple.object) - for contextual_tuple in check.contextual_tuples or [] - ] - if len(set(tuple_keys)) != len(tuple_keys): - return None - - return chain[-1] + return chain[-1], frozenset(chain) def _context_key(context) -> tuple: diff --git a/openfga_sdk/client/model_cache.py b/openfga_sdk/client/model_cache.py index 70113c49..1048758e 100644 --- a/openfga_sdk/client/model_cache.py +++ b/openfga_sdk/client/model_cache.py @@ -1,109 +1,21 @@ """ -In-memory cache of authorization models, used by BatchCheck's `merge_equivalent_checks` option. - -A model never changes once it's written, so a cached model never goes stale. Only -successful reads are cached. A 429 is remembered for a short time, so rate limiting -doesn't add a read to every call. Other failures aren't, so the next call reads again. -Calls for the same model share one in-flight read. +In-memory cache of authorization models for the async client, used by BatchCheck's +`merge_equivalent_checks` option. Calls for the same model share one in-flight read. """ import asyncio -import threading -import time -from collections import OrderedDict from collections.abc import Awaitable, Callable -from concurrent.futures import Future -from dataclasses import dataclass - -from openfga_sdk.exceptions import ApiException, AuthenticationError -from openfga_sdk.models.authorization_model import AuthorizationModel - - -MAX_MODELS = 32 -FAILURE_TTL_SECONDS = 60.0 -REMEMBERED_FAILURE_STATUSES = frozenset({429}) -CREDENTIAL_FAILURE_STATUSES = frozenset({401, 403}) -NOT_FOUND_CODES = frozenset({"authorization_model_not_found", "store_id_not_found"}) - -ModelCacheKey = tuple[str, str] - - -def model_read_fails_call(error: Exception | None) -> bool: - """ - Whether a model read error fails the BatchCheck call instead of sending the checks - unmerged: the model or store doesn't exist, or the credentials can't read the model - (a 401 or 403, or the token request failed) - """ - if isinstance(error, AuthenticationError): - return True - return isinstance(error, ApiException) and ( - error.code in NOT_FOUND_CODES or error.status in CREDENTIAL_FAILURE_STATUSES - ) - - -@dataclass -class ModelLookup: - """ - The result of a cache lookup: the model, or the error from reading it. - `hit` is True only when the model was already in the cache. - """ - - model: AuthorizationModel | None = None - hit: bool = False - error: Exception | None = None - - -class _ModelCacheState: - def __init__( - self, - max_models: int = MAX_MODELS, - failure_ttl: float = FAILURE_TTL_SECONDS, - clock: Callable[[], float] = time.monotonic, - ) -> None: - self._max_models = max_models - self._failure_ttl = failure_ttl - self._clock = clock - self._models: OrderedDict[ModelCacheKey, AuthorizationModel] = OrderedDict() - self._failures: OrderedDict[ModelCacheKey, tuple[float, Exception]] = ( - OrderedDict() - ) - - def _cached(self, key: ModelCacheKey) -> ModelLookup | None: - model = self._models.get(key) - if model is not None: - self._models.move_to_end(key) - return ModelLookup(model=model, hit=True) - - failure = self._failures.get(key) - if failure is not None: - expires_at, error = failure - if self._clock() < expires_at: - return ModelLookup(error=error) - del self._failures[key] - - return None - def _store(self, key: ModelCacheKey, model: AuthorizationModel) -> None: - self._failures.pop(key, None) - self._models[key] = model - self._models.move_to_end(key) - while len(self._models) > self._max_models: - self._models.popitem(last=False) +from openfga_sdk.client._model_cache_base import ( + ModelCacheBase, + ModelCacheKey, + ModelLookup, +) +from openfga_sdk.client.equivalent_checks import ModelAliases - def _remember_failure(self, key: ModelCacheKey, error: Exception) -> None: - if not ( - isinstance(error, ApiException) - and error.status in REMEMBERED_FAILURE_STATUSES - ): - return - self._failures[key] = (self._clock() + self._failure_ttl, error) - self._failures.move_to_end(key) - while len(self._failures) > self._max_models: - self._failures.popitem(last=False) - -class AsyncModelCache(_ModelCacheState): +class AsyncModelCache(ModelCacheBase): """ Model cache for the async client. """ @@ -115,7 +27,7 @@ def __init__(self, *args, **kwargs) -> None: async def get( self, key: ModelCacheKey, - load: Callable[[], Awaitable[AuthorizationModel]], + load: Callable[[], Awaitable[ModelAliases]], ) -> ModelLookup: cached = self._cached(key) if cached is not None: @@ -131,7 +43,7 @@ async def get( # Shielded, so a cancelled caller doesn't cancel the read other callers share. try: - return ModelLookup(model=await asyncio.shield(task)) + return ModelLookup(aliases=await asyncio.shield(task)) except asyncio.CancelledError: raise except Exception as error: @@ -150,76 +62,21 @@ async def close(self) -> None: async def _load( self, key: ModelCacheKey, - load: Callable[[], Awaitable[AuthorizationModel]], - ) -> AuthorizationModel: + load: Callable[[], Awaitable[ModelAliases]], + ) -> ModelAliases: try: - model = await load() + aliases = await load() except Exception as error: self._remember_failure(key, error) raise else: - self._store(key, model) - return model + self._store(key, aliases) + return aliases finally: if self._loading.get(key) is asyncio.current_task(): del self._loading[key] -class ModelCache(_ModelCacheState): - """ - Model cache for the sync client. Safe to share across threads. - """ - - def __init__(self, *args, **kwargs) -> None: - super().__init__(*args, **kwargs) - self._lock = threading.Lock() - self._loading: dict[ModelCacheKey, Future] = {} - - def get( - self, - key: ModelCacheKey, - load: Callable[[], AuthorizationModel], - ) -> ModelLookup: - with self._lock: - cached = self._cached(key) - if cached is not None: - return cached - - future = self._loading.get(key) - owner = future is None - if owner: - future = Future() - self._loading[key] = future - - if not owner: - try: - return ModelLookup(model=future.result()) - except Exception as error: - return ModelLookup(error=error) - - try: - model = load() - except Exception as error: - with self._lock: - self._remember_failure(key, error) - self._loading.pop(key, None) - future.set_exception(error) - return ModelLookup(error=error) - except BaseException: - with self._lock: - self._loading.pop(key, None) - future.set_exception( - RuntimeError("Reading the authorization model was interrupted") - ) - raise - - with self._lock: - self._store(key, model) - self._loading.pop(key, None) - future.set_result(model) - return ModelLookup(model=model) - - def _retrieve_exception(task: asyncio.Task) -> None: # Marks the error as seen, so asyncio doesn't log it when no caller is left waiting. if not task.cancelled(): diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index 5e672624..54ba2c9b 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -1,19 +1,21 @@ -import logging import uuid -from collections.abc import Iterator +from collections.abc import Callable, Iterator from concurrent.futures import ThreadPoolExecutor from typing import Any +from openfga_sdk.client._batch_check_merge import ( + checks_to_send, + log_model_read_failure, +) +from openfga_sdk.client._model_cache_base import ModelLookup from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.equivalent_checks import ( + ModelAliases, expand, merge_enabled, - resolve, - unmerged, - validate_correlation_ids, + prepare_checks, ) -from openfga_sdk.client.model_cache import ModelCache, model_read_fails_call from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, @@ -56,7 +58,9 @@ UnauthorizedException, ) from openfga_sdk.models.assertion import Assertion +from openfga_sdk.models.batch_check_item import BatchCheckItem from openfga_sdk.models.batch_check_request import BatchCheckRequest +from openfga_sdk.models.batch_check_response import BatchCheckResponse from openfga_sdk.models.check_request import CheckRequest from openfga_sdk.models.contextual_tuple_keys import ContextualTupleKeys from openfga_sdk.models.create_store_request import CreateStoreRequest @@ -79,14 +83,11 @@ ) from openfga_sdk.models.write_request import WriteRequest from openfga_sdk.sync.api_client import ApiClient +from openfga_sdk.sync.client.model_cache import ModelCache from openfga_sdk.sync.open_fga_api import OpenFgaApi -from openfga_sdk.telemetry.attributes import TelemetryAttributes from openfga_sdk.validation import is_well_formed_ulid_string -logger = logging.getLogger(__name__) - - def _chuck_array(array, max_size): """ Helper function to chuck array into arrays of max_size @@ -831,8 +832,16 @@ def batch_check( max_batch_size = options["max_batch_size"] if merge_enabled(options): + # Reading the model and sending the checks must use the same model and store. + authorization_model_id = self._get_authorization_model_id(options) + prepare_checks(body.checks, authorization_model_id) return self._merged_batch_check( - body, options, max_parallel_requests, max_batch_size + body.checks, + self._api_client._get_store_id(), + authorization_model_id, + options, + max_parallel_requests, + max_batch_size, ) id_to_check: dict[str, ClientBatchCheckItem] = {} @@ -860,6 +869,8 @@ def track_and_transform(checks): for i in range((len(body.checks) + max_batch_size - 1) // max_batch_size) ] + result = [] + def map_response(id, result): check = id_to_check[id] return ClientBatchCheckSingleResponse( @@ -869,144 +880,116 @@ def map_response(id, result): error=result.error, ) - def single_batch_check(checks): - res = self._single_batch_check( + def add_results(response): + result.extend( + [ + map_response(c_id, c_result) + for c_id, c_result in response.result.items() + ] + ) + + if checks: + self._send_batch_checks( + checks, + self._get_authorization_model_id(options), + options, + max_parallel_requests, + add_results, + ) + + return ClientBatchCheckResponse(result) + + def _send_batch_checks( + self, + chunks: list[list[BatchCheckItem]], + authorization_model_id: str | None, + options: dict[str, int | str | dict[str, int | str]], + max_parallel_requests: int, + on_response: Callable[[BatchCheckResponse], None], + ) -> None: + """ + Send each chunk of checks as one BatchCheck request, with at most + max_parallel_requests in flight, and pass each response to on_response + """ + consistency = self._get_consistency(options) + + def send(checks): + return self._single_batch_check( BatchCheckRequest( checks=checks, - authorization_model_id=self._get_authorization_model_id(options), - consistency=self._get_consistency(options), + authorization_model_id=authorization_model_id, + consistency=consistency, ), options, ) - return res - - result = [] - with ThreadPoolExecutor(max_workers=max_parallel_requests) as executor: - for response in executor.map(single_batch_check, checks): - result.extend( - [ - map_response(c_id, c_result) - for c_id, c_result in response.result.items() - ] - ) - - return ClientBatchCheckResponse(result) + for response in executor.map(send, chunks): + on_response(response) def _merged_batch_check( self, - body: ClientBatchCheckRequest, + checks: list[ClientBatchCheckItem], + store_id: str, + authorization_model_id: str, options: dict[str, int | str | dict[str, int | str]], max_parallel_requests: int, max_batch_size: int, ) -> ClientBatchCheckResponse: """ - Run a BatchCheck with merge_equivalent_checks on + Run a BatchCheck with merge_equivalent_checks on, for checks already validated """ - # Reading the model and sending the checks must use the same model. - authorization_model_id = self._get_authorization_model_id(options) - if authorization_model_id is None: - raise FgaValidationException( - "authorization_model_id is required when merge_equivalent_checks is on" - ) - store_id = self._api_client._get_store_id() - - checks = body.checks - for check in checks: - if check.correlation_id is None: - check.correlation_id = str(uuid.uuid4()) - validate_correlation_ids(checks) - if not checks: return ClientBatchCheckResponse([], checks_sent=0) - telemetry = self._api_client._telemetry.metrics - telemetry_configuration = self._api_client.configuration.telemetry - attributes = { - TelemetryAttributes.fga_client_request_store_id: store_id, - TelemetryAttributes.fga_client_request_model_id: authorization_model_id, - } - - def load_model(): - try: - response = self._api.read_authorization_model( - authorization_model_id, **_model_read_kwargs(options) - ) - if response.authorization_model is None: - raise ValueError("The authorization model response is empty") - return response.authorization_model - except Exception as err: - if model_read_fails_call(err): - raise - logger.warning( - "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " - "Sending checks unmerged.", - authorization_model_id, - store_id, - getattr(err, "status", None), - ) - raise - - lookup = self._model_cache.get((store_id, authorization_model_id), load_model) - telemetry.modelCacheLookup( - attributes={ - **attributes, - TelemetryAttributes.fga_client_model_cache_result: ( - "hit" if lookup.hit else "miss" - ), - }, - configuration=telemetry_configuration, + lookup = self._read_and_cache_model_aliases( + store_id, authorization_model_id, options ) - - if lookup.model is not None: - groups = resolve(lookup.model, checks) - elif model_read_fails_call(lookup.error): - # BatchCheck would fail too if the model is missing or no token can be fetched, - # and falling back on a 401 or 403 would hide wrong credentials. Fail before - # sending anything. - raise lookup.error - else: - groups = unmerged(checks) - telemetry.batchCheckMergeFallback( - attributes={ - **attributes, - TelemetryAttributes.http_response_status_code: getattr( - lookup.error, "status", None - ), - }, - configuration=telemetry_configuration, - ) - - # Every chunk is sent even if another one fails, so count them up front. - telemetry.batchCheckChecksRequested( - len(checks), attributes=attributes, configuration=telemetry_configuration + groups = checks_to_send( + self._api_client, store_id, authorization_model_id, lookup, checks ) - telemetry.batchCheckChecksSent( - len(groups), attributes=attributes, configuration=telemetry_configuration - ) - - consistency = self._get_consistency(options) - - def send(chunk): - return self._single_batch_check( - BatchCheckRequest( - checks=[construct_batch_item(group.check) for group in chunk], - authorization_model_id=authorization_model_id, - consistency=consistency, - ), - options, - ) results = {} - with ThreadPoolExecutor(max_workers=max_parallel_requests) as executor: - for response in executor.map(send, _chuck_array(groups, max_batch_size)): - results.update(response.result or {}) + self._send_batch_checks( + [ + [construct_batch_item(group.check) for group in chunk] + for chunk in _chuck_array(groups, max_batch_size) + ], + authorization_model_id, + options, + max_parallel_requests, + lambda response: results.update(response.result or {}), + ) return ClientBatchCheckResponse( expand(checks, groups, results), checks_sent=len(groups) ) + def _read_and_cache_model_aliases( + self, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None = None, + ) -> ModelLookup: + """ + Read an authorization model through the client's model cache, and work out its + aliases for merge_equivalent_checks + :param header(options) - Custom headers to send alongside the request + :param retryParams(options) - Override the retry parameters for this request + """ + + def load(): + try: + response = self._api.read_authorization_model( + authorization_model_id, **_model_read_kwargs(options) + ) + return ModelAliases(response.authorization_model) + except Exception as error: + log_model_read_failure(error, store_id, authorization_model_id) + raise + + return self._model_cache.get((store_id, authorization_model_id), load) + def expand( self, body: ClientExpandRequest, diff --git a/openfga_sdk/sync/client/model_cache.py b/openfga_sdk/sync/client/model_cache.py new file mode 100644 index 00000000..f46ac34b --- /dev/null +++ b/openfga_sdk/sync/client/model_cache.py @@ -0,0 +1,71 @@ +""" +In-memory cache of authorization models for the sync client, used by BatchCheck's +`merge_equivalent_checks` option. Calls for the same model share one in-flight read. +""" + +import threading + +from collections.abc import Callable +from concurrent.futures import Future + +from openfga_sdk.client._model_cache_base import ( + ModelCacheBase, + ModelCacheKey, + ModelLookup, +) +from openfga_sdk.client.equivalent_checks import ModelAliases + + +class ModelCache(ModelCacheBase): + """ + Model cache for the sync client. Safe to share across threads. + """ + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self._lock = threading.Lock() + self._loading: dict[ModelCacheKey, Future] = {} + + def get( + self, + key: ModelCacheKey, + load: Callable[[], ModelAliases], + ) -> ModelLookup: + with self._lock: + cached = self._cached(key) + if cached is not None: + return cached + + future = self._loading.get(key) + owner = future is None + if owner: + future = Future() + self._loading[key] = future + + if not owner: + try: + return ModelLookup(aliases=future.result()) + except Exception as error: + return ModelLookup(error=error) + + try: + aliases = load() + except Exception as error: + with self._lock: + self._remember_failure(key, error) + self._loading.pop(key, None) + future.set_exception(error) + return ModelLookup(error=error) + except BaseException: + with self._lock: + self._loading.pop(key, None) + future.set_exception( + RuntimeError("Reading the authorization model was interrupted") + ) + raise + + with self._lock: + self._store(key, aliases) + self._loading.pop(key, None) + future.set_result(aliases) + return ModelLookup(aliases=aliases) diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index 3ce02eaa..bf6e234a 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -14,9 +14,12 @@ from openfga_sdk.client.models.batch_check_response import ClientBatchCheckResponse from openfga_sdk.configuration import RetryParams from openfga_sdk.exceptions import ( + AuthenticationError, FgaValidationException, ForbiddenException, + NotFoundException, RateLimitExceededError, + ServiceException, UnauthorizedException, ValidationException, ) @@ -27,8 +30,9 @@ STORE_ID = "01YCP46JKYM8FJCQ37NMBYHE5X" MODEL_ID = "01GXSA8YR785C4FYS3C0RTG7B1" +OTHER_MODEL_ID = "01HVMMBCMGZNT3SED4Z17ECXCA" API_URL = "http://api.fga.example" -MODEL_URL = f"{API_URL}/stores/{STORE_ID}/authorization-models/{MODEL_ID}" +MODELS_URL = f"{API_URL}/stores/{STORE_ID}/authorization-models/" BATCH_CHECK_URL = f"{API_URL}/stores/{STORE_ID}/batch-check" # define viewer: [user], can_view: viewer, can_share: can_view, editor: [user] @@ -107,12 +111,14 @@ def __init__(self, model_error=None, answer=None, model_body=None): lambda check: {"allowed": check["tuple_key"]["relation"] == "viewer"} ) self.model_reads = 0 + self.model_ids_read = [] self.model_read_headers = [] self.sent = [] def __call__(self, method, url, **kwargs): - if method == "GET" and url == MODEL_URL: + if method == "GET" and url.startswith(MODELS_URL): self.model_reads += 1 + self.model_ids_read.append(url.removeprefix(MODELS_URL)) self.model_read_headers.append(kwargs.get("headers") or {}) if self.model_error is not None: raise self.model_error() @@ -158,8 +164,27 @@ def rate_limited(): return RateLimitExceededError(http_resp=http_mock_response("{}", 429)) +def server_error(): + return ServiceException(http_resp=http_mock_response("{}", 500)) + + +def timed_out(): + return TimeoutError("timed out") + + +def store_not_found(): + body = {"code": "store_id_not_found", "message": f"Store '{STORE_ID}' not found"} + return NotFoundException(http_resp=http_mock_response(json.dumps(body), 404)) + + +def token_request_failed(): + return AuthenticationError(http_resp=http_mock_response("{}", 400)) + + NO_RETRY = {"retry_params": RetryParams(max_retry=0)} +UNMERGED = [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")] + def model_not_found(): body = { @@ -244,11 +269,57 @@ async def test_requires_a_model_id(self, mock_request): self.configuration.authorization_model_id = None async with OpenFgaClient(self.configuration) as client: - with self.assertRaises(FgaValidationException): + with self.assertRaisesRegex( + FgaValidationException, "authorization_model_id" + ): + await self.batch_check(client, checks()) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_requires_a_store_id(self, mock_request): + self.configuration.store_id = None + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex(FgaValidationException, "store_id"): await self.batch_check(client, checks()) mock_request.assert_not_called() + @patch.object(rest.RESTClientObject, "request") + async def test_the_model_id_in_the_options_wins(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + await self.batch_check( + client, checks(), {"authorization_model_id": OTHER_MODEL_ID} + ) + await self.batch_check(client, checks()) + + self.assertEqual(server.model_ids_read, [OTHER_MODEL_ID, MODEL_ID]) + self.assertEqual( + [body["authorization_model_id"] for body in server.sent], + [OTHER_MODEL_ID, MODEL_ID], + ) + + @patch.object(rest.RESTClientObject, "request") + async def test_uses_the_model_id_in_the_options_when_none_is_configured( + self, mock_request + ): + self.configuration.authorization_model_id = None + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check( + client, checks(), {"authorization_model_id": OTHER_MODEL_ID} + ) + + self.assertEqual(server.model_ids_read, [OTHER_MODEL_ID]) + self.assertEqual(server.sent[0]["authorization_model_id"], OTHER_MODEL_ID) + self.assertEqual(response.checks_sent, 2) + @patch.object(rest.RESTClientObject, "request") async def test_rejects_an_option_value_that_is_not_a_bool(self, mock_request): async with OpenFgaClient(self.configuration) as client: @@ -348,7 +419,9 @@ async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): mock_request.side_effect = server async with OpenFgaClient(self.configuration) as client: - with self.assertLogs("openfga_sdk.client.client", "WARNING") as logs: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ) as logs: response = await self.batch_check(client, checks(), NO_RETRY) second = await self.batch_check(client, checks(), NO_RETRY) @@ -357,19 +430,92 @@ async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): self.assertIn(STORE_ID, logs.output[0]) self.assertIn("429", logs.output[0]) self.assertEqual(server.model_reads, 1) - unmerged = [ - ("a", "viewer"), - ("b", "can_view"), - ("c", "can_share"), - ("d", "editor"), - ] - self.assertEqual(sent_checks(server), unmerged * 2) + self.assertEqual(sent_checks(server), UNMERGED * 2) self.assertEqual(response.checks_sent, 4) self.assertEqual(second.checks_sent, 4) self.assertEqual( [r.allowed for r in response.result], [True, False, False, False] ) + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_the_server_fails_or_times_out( + self, mock_request, mock_fallback + ): + for model_error, status in [(server_error, 500), (timed_out, None)]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + response = await self.batch_check(client, checks(), NO_RETRY) + await self.batch_check(client, checks(), NO_RETRY) + + self.assertEqual(sent_checks(server), UNMERGED * 2) + self.assertEqual(response.checks_sent, 4) + # Only a 429 is remembered, so the next call reads again. + self.assertEqual(server.model_reads, 2) + self.assertEqual( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ], + status, + ) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch( + "openfga_sdk.client._batch_check_merge.resolve", + side_effect=RuntimeError("boom"), + ) + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_grouping_fails( + self, mock_request, _resolve, mock_fallback + ): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ) as logs: + response = await self.batch_check(client, checks()) + + self.assertIn("couldn't group the checks", logs.output[0]) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + self.assertEqual( + [r.allowed for r in response.result], [True, False, False, False] + ) + self.assertIsNone( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ] + ) + + @patch.object(rest.RESTClientObject, "request") + async def test_fails_before_sending_when_the_store_does_not_exist_or_no_token( + self, mock_request + ): + for model_error, error_type in [ + (store_not_found, NotFoundException), + (token_request_failed, AuthenticationError), + ]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + with self.assertRaises(error_type): + await self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + @patch.object(rest.RESTClientObject, "request") async def test_fails_before_sending_when_the_model_does_not_exist( self, mock_request @@ -378,7 +524,7 @@ async def test_fails_before_sending_when_the_model_does_not_exist( mock_request.side_effect = server async with OpenFgaClient(self.configuration) as client: - with self.assertNoLogs("openfga_sdk.client.client", "WARNING"): + with self.assertNoLogs("openfga_sdk.client._batch_check_merge", "WARNING"): for _ in range(2): with self.assertRaises(ValidationException) as raised: await self.batch_check(client, checks()) @@ -402,7 +548,9 @@ async def test_fails_before_sending_when_the_credentials_cannot_read_the_model( mock_request.side_effect = server async with OpenFgaClient(self.configuration) as client: - with self.assertNoLogs("openfga_sdk.client.client", "WARNING"): + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): for _ in range(2): with self.assertRaises(error_type): await self.batch_check(client, checks()) @@ -416,14 +564,13 @@ async def test_sends_unmerged_when_the_model_response_is_empty(self, mock_reques mock_request.side_effect = server async with OpenFgaClient(self.configuration) as client: - with self.assertLogs("openfga_sdk.client.client", "WARNING") as logs: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ) as logs: response = await self.batch_check(client, checks()) self.assertEqual(len(logs.records), 1) - self.assertEqual( - sent_checks(server), - [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")], - ) + self.assertEqual(sent_checks(server), UNMERGED) self.assertEqual(response.checks_sent, 4) @patch.object(rest.RESTClientObject, "request") @@ -518,10 +665,7 @@ async def test_option_off_is_unchanged(self, mock_request): ) self.assertEqual(server.model_reads, 0) - self.assertEqual( - sent_checks(server), - [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")], - ) + self.assertEqual(sent_checks(server), UNMERGED) self.assertIsNone(response.checks_sent) @patch.object(TelemetryMetrics, "batchCheckChecksSent") @@ -565,7 +709,7 @@ async def test_records_the_fallback_with_its_status_code( mock_request.side_effect = FakeServer(model_error=rate_limited) async with OpenFgaClient(self.configuration) as client: - with self.assertLogs("openfga_sdk.client.client", "WARNING"): + with self.assertLogs("openfga_sdk.client._batch_check_merge", "WARNING"): await self.batch_check(client, checks(), NO_RETRY) attributes = mock_fallback.call_args.kwargs["attributes"] diff --git a/test/client/equivalent_checks_cases_test.py b/test/client/equivalent_checks_cases_test.py index 23942742..ddec85dc 100644 --- a/test/client/equivalent_checks_cases_test.py +++ b/test/client/equivalent_checks_cases_test.py @@ -12,7 +12,7 @@ import pytest -from openfga_sdk.client.equivalent_checks import resolve +from openfga_sdk.client.equivalent_checks import ModelAliases, resolve from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem from openfga_sdk.client.models.tuple import ClientTuple from openfga_sdk.models.relationship_condition import RelationshipCondition @@ -99,7 +99,7 @@ def test_cases_file_is_not_empty(): def test_equivalent_checks_case(case): checks = [_check(check) for check in case["checks"]] - groups = resolve(_model(case["model"]), checks) + groups = resolve(ModelAliases(_model(case["model"])), checks) assert [_sent_as_json(group) for group in groups] == case["expected_sent"] diff --git a/test/client/equivalent_checks_test.py b/test/client/equivalent_checks_test.py index 31a2f658..b4075ce7 100644 --- a/test/client/equivalent_checks_test.py +++ b/test/client/equivalent_checks_test.py @@ -5,8 +5,10 @@ from openfga_sdk.client.equivalent_checks import ( EquivalentCheckGroup, + ModelAliases, expand, merge_enabled, + prepare_checks, resolve, unmerged, validate_correlation_ids, @@ -40,6 +42,7 @@ ), ], ) +ALIASES = ModelAliases(MODEL) def nested(depth): @@ -85,22 +88,47 @@ def sent(groups): ], ids=["nan", "inf", "huge-int", "tuple", "datetime", "int-key", "object", "deep"], ) -def test_values_that_cannot_be_compared_are_sent_as_is(value): +def test_values_that_cannot_be_compared_are_not_merged(value): groups = resolve( - MODEL, + ALIASES, [check("a", context={"x": value}), check("b", context={"x": value})], ) - assert sent(groups) == [("a", "can_view", ["a"]), ("b", "can_view", ["b"])] + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "viewer", ["b"])] -def test_a_context_that_is_not_an_object_is_sent_as_is(): - groups = resolve(MODEL, [check("a", context=["x"]), check("b", context=["x"])]) +def test_a_context_that_is_not_an_object_is_not_merged(): + groups = resolve(ALIASES, [check("a", context=["x"]), check("b", context=["x"])]) - assert sent(groups) == [("a", "can_view", ["a"]), ("b", "can_view", ["b"])] + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "viewer", ["b"])] -def test_values_in_a_condition_context_that_cannot_be_compared_are_sent_as_is(): +def test_a_value_that_cannot_be_compared_does_not_stop_other_checks_merging(): + groups = resolve( + ALIASES, + [check("a", context={"x": math.nan}), check("b"), check("c")], + ) + + assert sent(groups) == [("a", "viewer", ["a"]), ("merged-1", "viewer", ["b", "c"])] + + +class ContextThatMustNotBeRead(dict): + def items(self): + raise AssertionError("the context of a check with no match was read") + + +def test_only_compares_context_for_checks_that_could_merge(): + other_user = check("b", context=ContextThatMustNotBeRead(x=1)) + other_user.user = "user:bob" + + groups = resolve( + ALIASES, [check("a", context=ContextThatMustNotBeRead(x=1)), other_user] + ) + + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "viewer", ["b"])] + + +def test_values_in_a_condition_context_that_cannot_be_compared_are_not_merged(): contextual_tuples = [ ClientTuple( user="user:anne", @@ -111,21 +139,21 @@ def test_values_in_a_condition_context_that_cannot_be_compared_are_sent_as_is(): ] groups = resolve( - MODEL, + ALIASES, [ check("a", contextual_tuples=contextual_tuples), check("b", contextual_tuples=contextual_tuples), ], ) - assert sent(groups) == [("a", "can_view", ["a"]), ("b", "can_view", ["b"])] + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "viewer", ["b"])] def test_checks_that_are_not_strings_are_sent_as_is(): item = check("a") item.user = None - assert sent(resolve(MODEL, [item])) == [("a", "can_view", ["a"])] + assert sent(resolve(ALIASES, [item])) == [("a", "can_view", ["a"])] def test_a_model_without_type_definitions_sends_everything_as_is(): @@ -133,7 +161,7 @@ def test_a_model_without_type_definitions_sends_everything_as_is(): id="01GXSA8YR785C4FYS3C0RTG7B1", schema_version="1.1", type_definitions=[] ) - assert sent(resolve(model, [check("a"), check("b")])) == [ + assert sent(resolve(ModelAliases(model), [check("a"), check("b")])) == [ ("a", "can_view", ["a"]), ("b", "can_view", ["b"]), ] @@ -255,6 +283,27 @@ def test_rewrites_that_only_look_like_aliases_are_not_merged(can_view): ], ) - groups = resolve(model, [check("a", relation="viewer"), check("b")]) + groups = resolve(ModelAliases(model), [check("a", relation="viewer"), check("b")]) assert sent(groups) == [("a", "viewer", ["a"]), ("b", "can_view", ["b"])] + + +def test_model_aliases_rejects_an_empty_model(): + with pytest.raises(ValueError, match="The authorization model response is empty"): + ModelAliases(None) + + +def test_prepare_checks_needs_a_model_id(): + with pytest.raises(FgaValidationException, match="authorization_model_id"): + prepare_checks([check("a")], None) + + +def test_prepare_checks_fills_in_missing_ids_and_validates_them(): + items = [check(None), check("b")] + prepare_checks(items, "01GXSA8YR785C4FYS3C0RTG7B1") + + assert items[0].correlation_id + assert items[1].correlation_id == "b" + + with pytest.raises(FgaValidationException): + prepare_checks([check("a"), check("a")], "01GXSA8YR785C4FYS3C0RTG7B1") diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py index 307fbfdf..f997d70f 100644 --- a/test/client/model_cache_test.py +++ b/test/client/model_cache_test.py @@ -1,16 +1,11 @@ import asyncio import sys -import threading -import time from types import SimpleNamespace from unittest import IsolatedAsyncioTestCase, TestCase, skipIf -from openfga_sdk.client.model_cache import ( - AsyncModelCache, - ModelCache, - model_read_fails_call, -) +from openfga_sdk.client._model_cache_base import model_read_fails_call +from openfga_sdk.client.model_cache import AsyncModelCache from openfga_sdk.exceptions import ( AuthenticationError, ForbiddenException, @@ -51,10 +46,10 @@ async def load(): results = await asyncio.gather(*lookups) self.assertEqual(reads, 1) - self.assertEqual([(r.model, r.hit) for r in results], [("model", False)] * 3) + self.assertEqual([(r.aliases, r.hit) for r in results], [("model", False)] * 3) later = await cache.get(KEY, load) - self.assertEqual((later.model, later.hit, reads), ("model", True, 1)) + self.assertEqual((later.aliases, later.hit, reads), ("model", True, 1)) async def test_a_failed_read_is_remembered_for_a_short_time(self): clock = FakeClock() @@ -73,7 +68,7 @@ async def load(): self.assertIs(first.error, error) self.assertIs(second.error, error) - self.assertIsNone(second.model) + self.assertIsNone(second.aliases) self.assertEqual(reads, 1) clock.now = 60 @@ -130,7 +125,7 @@ async def load(): cancelled.cancel() release.set() - self.assertEqual((await waiting).model, "model") + self.assertEqual((await waiting).aliases, "model") with self.assertRaises(asyncio.CancelledError): await cancelled @@ -152,156 +147,34 @@ async def hang(): async def load(): return "model" - self.assertEqual((await cache.get(KEY, load)).model, "model") - - -class TestModelCache(TestCase): - def test_threads_share_one_read_and_later_lookups_hit(self): - cache = ModelCache() - started = threading.Event() - release = threading.Event() - reads = 0 - - def load(): - nonlocal reads - reads += 1 - started.set() - release.wait() - return "model" - - results = [] - owner = threading.Thread(target=lambda: results.append(cache.get(KEY, load))) - owner.start() - started.wait() - waiters = [ - threading.Thread(target=lambda: results.append(cache.get(KEY, load))) - for _ in range(3) - ] - for waiter in waiters: - waiter.start() - release.set() - for thread in [owner, *waiters]: - thread.join() + self.assertEqual((await cache.get(KEY, load)).aliases, "model") - self.assertEqual(reads, 1) - self.assertEqual([r.model for r in results], ["model"] * 4) - self.assertTrue(cache.get(KEY, load).hit) - - def test_a_failed_read_is_remembered_for_a_short_time(self): + async def test_keys_on_both_the_store_and_the_model(self): clock = FakeClock() - cache = ModelCache(failure_ttl=60, clock=clock) - reads = 0 - error = RateLimitExceededError(status=429) - - def load(): - nonlocal reads - reads += 1 - raise error - - self.assertIs(cache.get(KEY, load).error, error) - clock.now = 59 - self.assertIs(cache.get(KEY, load).error, error) - self.assertEqual(reads, 1) - - clock.now = 60 - cache.get(KEY, load) - self.assertEqual(reads, 2) - - def test_only_a_429_is_remembered(self): - for error, remembered in [ - (RateLimitExceededError(status=429), True), - (ForbiddenException(status=403), False), - (UnauthorizedException(status=401), False), - (ValidationException(status=400), False), - (ServiceException(status=500), False), - (TimeoutError(), False), - ]: - with self.subTest(error=type(error).__name__): - cache = ModelCache() - reads = 0 - - def load(): - nonlocal reads - reads += 1 - raise error - - cache.get(KEY, load) - cache.get(KEY, load) - self.assertEqual(reads, 1 if remembered else 2) - - def test_drops_the_least_recently_used_model(self): - cache = ModelCache(max_models=2) - - def get(key): - return cache.get(key, lambda: f"model-{key}") - - get("a") - get("b") - self.assertTrue(get("a").hit) - get("c") - - self.assertTrue(get("a").hit) - self.assertFalse(get("b").hit) - - def test_threads_waiting_on_a_failed_read_get_its_error(self): - cache = ModelCache() - started = threading.Event() - release = threading.Event() - error = RuntimeError("forbidden") - - def load(): - started.set() - release.wait() - raise error - - results = [] - owner = threading.Thread(target=lambda: results.append(cache.get(KEY, load))) - owner.start() - started.wait() - waiters = [ - threading.Thread(target=lambda: results.append(cache.get(KEY, load))) - for _ in range(3) - ] - for waiter in waiters: - waiter.start() - time.sleep(0.05) - release.set() - for thread in [owner, *waiters]: - thread.join() - - self.assertEqual([r.error for r in results], [error] * 4) - - def test_remembers_a_bounded_number_of_failures(self): - cache = ModelCache(max_models=2) + cache = AsyncModelCache(clock=clock) reads = [] - def get(key): - def load(): - reads.append(key) - raise RateLimitExceededError(status=429) - - return cache.get(key, load) - - get("a") - get("b") - get("c") - get("b") - get("c") - self.assertEqual(reads, ["a", "b", "c"]) - - get("a") - self.assertEqual(reads, ["a", "b", "c", "a"]) - - def test_an_interrupted_read_is_not_cached(self): - cache = ModelCache() - - def interrupt(): - raise KeyboardInterrupt() - - with self.assertRaises(KeyboardInterrupt): - cache.get(KEY, interrupt) - - self.assertEqual(cache.get(KEY, lambda: "model").model, "model") + async def get(store, model, error=None): + async def load(): + reads.append((store, model)) + if error is not None: + raise error + return f"{store}/{model}" + + return await cache.get((store, model), load) + + self.assertEqual((await get("a", "1")).aliases, "a/1") + self.assertEqual((await get("b", "1")).aliases, "b/1") + self.assertEqual((await get("a", "2")).aliases, "a/2") + self.assertTrue((await get("a", "1")).hit) + self.assertTrue((await get("b", "1")).hit) + self.assertTrue((await get("a", "2")).hit) + self.assertEqual(reads, [("a", "1"), ("b", "1"), ("a", "2")]) + + await get("c", "1", RateLimitExceededError(status=429)) + self.assertEqual((await get("d", "1")).aliases, "d/1") + self.assertEqual((await get("c", "2")).aliases, "c/2") + self.assertEqual(reads[3:], [("c", "1"), ("d", "1"), ("c", "2")]) def with_code(error, code): diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index dd070de4..6c3551d5 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -7,8 +7,10 @@ from openfga_sdk.client import ClientConfiguration from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest from openfga_sdk.exceptions import ( + AuthenticationError, FgaValidationException, ForbiddenException, + NotFoundException, UnauthorizedException, ValidationException, ) @@ -21,15 +23,21 @@ BATCH_CHECK_URL, MODEL, MODEL_ID, - MODEL_URL, + MODELS_URL, NO_RETRY, + OTHER_MODEL_ID, STORE_ID, + UNMERGED, checks, forbidden, http_mock_response, model_not_found, rate_limited, sent_checks, + server_error, + store_not_found, + timed_out, + token_request_failed, unauthorized, ) @@ -53,12 +61,14 @@ def __init__(self, model_error=None, answer=None, model_body=None): lambda check: {"allowed": check["tuple_key"]["relation"] == "viewer"} ) self.model_reads = 0 + self.model_ids_read = [] self.model_read_headers = [] self.sent = [] def __call__(self, method, url, **kwargs): - if method == "GET" and url == MODEL_URL: + if method == "GET" and url.startswith(MODELS_URL): self.model_reads += 1 + self.model_ids_read.append(url.removeprefix(MODELS_URL)) self.model_read_headers.append(kwargs.get("headers") or {}) if self.model_error is not None: raise self.model_error() @@ -153,11 +163,57 @@ def test_requires_a_model_id(self, mock_request): self.configuration.authorization_model_id = None with OpenFgaClient(self.configuration) as client: - with self.assertRaises(FgaValidationException): + with self.assertRaisesRegex( + FgaValidationException, "authorization_model_id" + ): + self.batch_check(client, checks()) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_requires_a_store_id(self, mock_request): + self.configuration.store_id = None + + with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex(FgaValidationException, "store_id"): self.batch_check(client, checks()) mock_request.assert_not_called() + @patch.object(rest.RESTClientObject, "request") + def test_the_model_id_in_the_options_wins(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + self.batch_check( + client, checks(), {"authorization_model_id": OTHER_MODEL_ID} + ) + self.batch_check(client, checks()) + + self.assertEqual(server.model_ids_read, [OTHER_MODEL_ID, MODEL_ID]) + self.assertEqual( + [body["authorization_model_id"] for body in server.sent], + [OTHER_MODEL_ID, MODEL_ID], + ) + + @patch.object(rest.RESTClientObject, "request") + def test_uses_the_model_id_in_the_options_when_none_is_configured( + self, mock_request + ): + self.configuration.authorization_model_id = None + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check( + client, checks(), {"authorization_model_id": OTHER_MODEL_ID} + ) + + self.assertEqual(server.model_ids_read, [OTHER_MODEL_ID]) + self.assertEqual(server.sent[0]["authorization_model_id"], OTHER_MODEL_ID) + self.assertEqual(response.checks_sent, 2) + @patch.object(rest.RESTClientObject, "request") def test_rejects_an_option_value_that_is_not_a_bool(self, mock_request): with OpenFgaClient(self.configuration) as client: @@ -227,20 +283,16 @@ def test_sends_unmerged_when_the_model_cannot_be_read( mock_request.side_effect = server with OpenFgaClient(self.configuration) as client: - with self.assertLogs("openfga_sdk.sync.client.client", "WARNING") as logs: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ) as logs: response = self.batch_check(client, checks(), NO_RETRY) self.batch_check(client, checks(), NO_RETRY) self.assertEqual(len(logs.records), 1) self.assertIn("429", logs.output[0]) self.assertEqual(server.model_reads, 1) - unmerged = [ - ("a", "viewer"), - ("b", "can_view"), - ("c", "can_share"), - ("d", "editor"), - ] - self.assertEqual(sent_checks(server), unmerged * 2) + self.assertEqual(sent_checks(server), UNMERGED * 2) self.assertEqual(response.checks_sent, 4) self.assertEqual(mock_fallback.call_count, 2) self.assertEqual( @@ -250,6 +302,82 @@ def test_sends_unmerged_when_the_model_cannot_be_read( 429, ) + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_the_server_fails_or_times_out( + self, mock_request, mock_fallback + ): + for model_error, status in [(server_error, 500), (timed_out, None)]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + response = self.batch_check(client, checks(), NO_RETRY) + self.batch_check(client, checks(), NO_RETRY) + + self.assertEqual(sent_checks(server), UNMERGED * 2) + self.assertEqual(response.checks_sent, 4) + # Only a 429 is remembered, so the next call reads again. + self.assertEqual(server.model_reads, 2) + self.assertEqual( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ], + status, + ) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch( + "openfga_sdk.client._batch_check_merge.resolve", + side_effect=RuntimeError("boom"), + ) + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_grouping_fails( + self, mock_request, _resolve, mock_fallback + ): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ) as logs: + response = self.batch_check(client, checks()) + + self.assertIn("couldn't group the checks", logs.output[0]) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + self.assertIsNone( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ] + ) + + @patch.object(rest.RESTClientObject, "request") + def test_fails_before_sending_when_the_store_does_not_exist_or_no_token( + self, mock_request + ): + for model_error, error_type in [ + (store_not_found, NotFoundException), + (token_request_failed, AuthenticationError), + ]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + with self.assertRaises(error_type): + self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + @patch.object(rest.RESTClientObject, "request") def test_fails_before_sending_when_the_model_does_not_exist(self, mock_request): server = FakeServer(model_error=model_not_found) @@ -275,7 +403,9 @@ def test_fails_before_sending_when_the_credentials_cannot_read_the_model( mock_request.side_effect = server with OpenFgaClient(self.configuration) as client: - with self.assertNoLogs("openfga_sdk.sync.client.client", "WARNING"): + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): for _ in range(2): with self.assertRaises(error_type): self.batch_check(client, checks()) @@ -289,14 +419,13 @@ def test_sends_unmerged_when_the_model_response_is_empty(self, mock_request): mock_request.side_effect = server with OpenFgaClient(self.configuration) as client: - with self.assertLogs("openfga_sdk.sync.client.client", "WARNING") as logs: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ) as logs: response = self.batch_check(client, checks()) self.assertEqual(len(logs.records), 1) - self.assertEqual( - sent_checks(server), - [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")], - ) + self.assertEqual(sent_checks(server), UNMERGED) self.assertEqual(response.checks_sent, 4) @patch.object(rest.RESTClientObject, "request") @@ -374,10 +503,7 @@ def test_option_off_is_unchanged(self, mock_request): response = client.batch_check(ClientBatchCheckRequest(checks=checks())) self.assertEqual(server.model_reads, 0) - self.assertEqual( - sent_checks(server), - [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")], - ) + self.assertEqual(sent_checks(server), UNMERGED) self.assertIsNone(response.checks_sent) @patch.object(TelemetryMetrics, "batchCheckChecksSent") diff --git a/test/sync/client/model_cache_test.py b/test/sync/client/model_cache_test.py new file mode 100644 index 00000000..b13ab771 --- /dev/null +++ b/test/sync/client/model_cache_test.py @@ -0,0 +1,199 @@ +import threading +import time + +from unittest import TestCase + +from openfga_sdk.exceptions import ( + ForbiddenException, + RateLimitExceededError, + ServiceException, + UnauthorizedException, + ValidationException, +) +from openfga_sdk.sync.client.model_cache import ModelCache + + +KEY = ("store", "model") + + +class FakeClock: + def __init__(self): + self.now = 0.0 + + def __call__(self): + return self.now + + +class TestModelCache(TestCase): + def test_threads_share_one_read_and_later_lookups_hit(self): + cache = ModelCache() + started = threading.Event() + release = threading.Event() + reads = 0 + + def load(): + nonlocal reads + reads += 1 + started.set() + release.wait() + return "model" + + results = [] + owner = threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + owner.start() + started.wait() + waiters = [ + threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + for _ in range(3) + ] + for waiter in waiters: + waiter.start() + release.set() + for thread in [owner, *waiters]: + thread.join() + + self.assertEqual(reads, 1) + self.assertEqual([r.aliases for r in results], ["model"] * 4) + self.assertTrue(cache.get(KEY, load).hit) + + def test_a_failed_read_is_remembered_for_a_short_time(self): + clock = FakeClock() + cache = ModelCache(failure_ttl=60, clock=clock) + reads = 0 + error = RateLimitExceededError(status=429) + + def load(): + nonlocal reads + reads += 1 + raise error + + self.assertIs(cache.get(KEY, load).error, error) + clock.now = 59 + self.assertIs(cache.get(KEY, load).error, error) + self.assertEqual(reads, 1) + + clock.now = 60 + cache.get(KEY, load) + self.assertEqual(reads, 2) + + def test_only_a_429_is_remembered(self): + for error, remembered in [ + (RateLimitExceededError(status=429), True), + (ForbiddenException(status=403), False), + (UnauthorizedException(status=401), False), + (ValidationException(status=400), False), + (ServiceException(status=500), False), + (TimeoutError(), False), + ]: + with self.subTest(error=type(error).__name__): + cache = ModelCache() + reads = 0 + + def load(): + nonlocal reads + reads += 1 + raise error + + cache.get(KEY, load) + cache.get(KEY, load) + self.assertEqual(reads, 1 if remembered else 2) + + def test_drops_the_least_recently_used_model(self): + cache = ModelCache(max_models=2) + + def get(key): + return cache.get(key, lambda: f"model-{key}") + + get("a") + get("b") + self.assertTrue(get("a").hit) + get("c") + + self.assertTrue(get("a").hit) + self.assertFalse(get("b").hit) + + def test_threads_waiting_on_a_failed_read_get_its_error(self): + cache = ModelCache() + started = threading.Event() + release = threading.Event() + error = RuntimeError("forbidden") + + def load(): + started.set() + release.wait() + raise error + + results = [] + owner = threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + owner.start() + started.wait() + waiters = [ + threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + for _ in range(3) + ] + for waiter in waiters: + waiter.start() + time.sleep(0.05) + release.set() + for thread in [owner, *waiters]: + thread.join() + + self.assertEqual([r.error for r in results], [error] * 4) + + def test_remembers_a_bounded_number_of_failures(self): + cache = ModelCache(max_models=2) + reads = [] + + def get(key): + def load(): + reads.append(key) + raise RateLimitExceededError(status=429) + + return cache.get(key, load) + + get("a") + get("b") + get("c") + get("b") + get("c") + self.assertEqual(reads, ["a", "b", "c"]) + + get("a") + self.assertEqual(reads, ["a", "b", "c", "a"]) + + def test_an_interrupted_read_is_not_cached(self): + cache = ModelCache() + + def interrupt(): + raise KeyboardInterrupt() + + with self.assertRaises(KeyboardInterrupt): + cache.get(KEY, interrupt) + + self.assertEqual(cache.get(KEY, lambda: "model").aliases, "model") + + def test_keys_on_both_the_store_and_the_model(self): + cache = ModelCache() + reads = [] + + def get(store, model, error=None): + def load(): + reads.append((store, model)) + if error is not None: + raise error + return f"{store}/{model}" + + return cache.get((store, model), load) + + self.assertEqual(get("a", "1").aliases, "a/1") + self.assertEqual(get("b", "1").aliases, "b/1") + self.assertEqual(get("a", "2").aliases, "a/2") + self.assertTrue(get("a", "1").hit) + self.assertTrue(get("b", "1").hit) + self.assertTrue(get("a", "2").hit) + self.assertEqual(reads, [("a", "1"), ("b", "1"), ("a", "2")]) + + get("c", "1", RateLimitExceededError(status=429)) + self.assertEqual(get("d", "1").aliases, "d/1") + self.assertEqual(get("c", "2").aliases, "c/2") + self.assertEqual(reads[3:], [("c", "1"), ("d", "1"), ("c", "2")]) From 56574bc5c432a01fc32f23eba4427d92387ad854 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Thu, 26 Nov 2026 07:58:44 +0530 Subject: [PATCH 16/38] fix: don't retry the model read for merge_equivalent_checks A failed read made the first call take over a second with retries, and on services where rejected requests count toward the rate limit, retries make a 429 worse. The read now runs with max_retry=0, even if the call sets retry_params, so a failure costs one request and the checks go out unmerged right away. The checks keep their retry settings. Also note the cost of the option in the README. --- README.md | 10 +++++++- openfga_sdk/client/client.py | 14 +++++++---- openfga_sdk/sync/client/client.py | 14 +++++++---- test/client/batch_check_merge_test.py | 29 ++++++++++++++++------ test/sync/client/batch_check_merge_test.py | 27 ++++++++++++++++---- 5 files changed, 71 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 392188b7..17b5a7ea 100644 --- a/README.md +++ b/README.md @@ -992,7 +992,15 @@ To find aliases, the SDK reads the authorization model the first time it needs i - the model or the store doesn't exist - the credentials can't read the model (a 401 or 403, or the token request fails). If your credentials can only run checks, leave the option off. -If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. After a 429 it waits about a minute before reading the model again. After any other failure it tries again on the next call. +If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. After a 429 it waits about a minute before reading the model again. After any other failure it tries again on the next call. + +Compared with leaving the option off, a call: + +- makes one extra request the first time the client needs a model, to read it. Later calls use the copy in memory, and calls running at the same time share one read. +- spends a little time grouping the checks and copying the answers back. This happens in memory and is small next to a request. +- sends fewer checks when some of them merge, so the checks themselves can finish sooner. + +Each client reads each model once. Some services rate limit model reads much lower than checks, so if many clients start at the same time, some may get a 429 and send checks unmerged for about a minute. If a merged check returns an error, every check it stands for gets that error. Correlation IDs must match `^[\w\d-]{1,36}$` (ASCII), and missing ones are generated. For metrics, see `fga-client.batch_check.*` and `fga-client.model_cache.lookup` in [OpenTelemetry](docs/opentelemetry.md). diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index a5691763..a6650afa 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -49,6 +49,7 @@ construct_write_single_response, ) from openfga_sdk.client.models.write_transaction_opts import WriteTransactionOpts +from openfga_sdk.configuration import RetryParams from openfga_sdk.constants import ( CLIENT_BULK_REQUEST_ID_HEADER, CLIENT_MAX_BATCH_SIZE, @@ -145,10 +146,14 @@ def _model_read_kwargs( options: dict[str, int | str | dict[str, int | str]] | None = None, ) -> dict[str, int | str | dict[str, int | str]]: """ - Return the kwargs a BatchCheck call passes on to its authorization model read + Return the kwargs a BatchCheck call passes on to its authorization model read. + The read is never retried: if it fails, the checks are sent unmerged right away. """ - kwargs = options_to_kwargs(options) - return {key: kwargs[key] for key in ("_headers", "_retry_params") if key in kwargs} + kwargs = {"_retry_params": RetryParams(max_retry=0)} + headers = options_to_kwargs(options).get("_headers") + if headers: + kwargs["_headers"] = headers + return kwargs def options_to_transaction_info( @@ -979,9 +984,8 @@ async def _read_and_cache_model_aliases( ) -> ModelLookup: """ Read an authorization model through the client's model cache, and work out its - aliases for merge_equivalent_checks + aliases for merge_equivalent_checks. The read is never retried. :param header(options) - Custom headers to send alongside the request - :param retryParams(options) - Override the retry parameters for this request """ async def load(): diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index 54ba2c9b..e1e8dd16 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -46,6 +46,7 @@ construct_write_single_response, ) from openfga_sdk.client.models.write_transaction_opts import WriteTransactionOpts +from openfga_sdk.configuration import RetryParams from openfga_sdk.constants import ( CLIENT_BULK_REQUEST_ID_HEADER, CLIENT_MAX_BATCH_SIZE, @@ -145,10 +146,14 @@ def _model_read_kwargs( options: dict[str, int | str | dict[str, int | str]] | None = None, ) -> dict[str, int | str | dict[str, int | str]]: """ - Return the kwargs a BatchCheck call passes on to its authorization model read + Return the kwargs a BatchCheck call passes on to its authorization model read. + The read is never retried: if it fails, the checks are sent unmerged right away. """ - kwargs = options_to_kwargs(options) - return {key: kwargs[key] for key in ("_headers", "_retry_params") if key in kwargs} + kwargs = {"_retry_params": RetryParams(max_retry=0)} + headers = options_to_kwargs(options).get("_headers") + if headers: + kwargs["_headers"] = headers + return kwargs def options_to_transaction_info( @@ -973,9 +978,8 @@ def _read_and_cache_model_aliases( ) -> ModelLookup: """ Read an authorization model through the client's model cache, and work out its - aliases for merge_equivalent_checks + aliases for merge_equivalent_checks. The read is never retried. :param header(options) - Custom headers to send alongside the request - :param retryParams(options) - Override the retry parameters for this request """ def load(): diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index bf6e234a..4e4061f4 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -181,8 +181,6 @@ def token_request_failed(): return AuthenticationError(http_resp=http_mock_response("{}", 400)) -NO_RETRY = {"retry_params": RetryParams(max_retry=0)} - UNMERGED = [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")] @@ -422,8 +420,8 @@ async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): with self.assertLogs( "openfga_sdk.client._batch_check_merge", "WARNING" ) as logs: - response = await self.batch_check(client, checks(), NO_RETRY) - second = await self.batch_check(client, checks(), NO_RETRY) + response = await self.batch_check(client, checks()) + second = await self.batch_check(client, checks()) self.assertEqual(len(logs.records), 1) self.assertIn(MODEL_ID, logs.output[0]) @@ -451,8 +449,8 @@ async def test_sends_unmerged_when_the_server_fails_or_times_out( with self.assertLogs( "openfga_sdk.client._batch_check_merge", "WARNING" ): - response = await self.batch_check(client, checks(), NO_RETRY) - await self.batch_check(client, checks(), NO_RETRY) + response = await self.batch_check(client, checks()) + await self.batch_check(client, checks()) self.assertEqual(sent_checks(server), UNMERGED * 2) self.assertEqual(response.checks_sent, 4) @@ -465,6 +463,23 @@ async def test_sends_unmerged_when_the_server_fails_or_times_out( status, ) + @patch.object(rest.RESTClientObject, "request") + async def test_does_not_retry_the_model_read(self, mock_request): + retries = {"retry_params": RetryParams(max_retry=3, min_wait_in_ms=1)} + for model_error in [rate_limited, server_error]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + await self.batch_check(client, checks(), retries) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), UNMERGED) + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") @patch( "openfga_sdk.client._batch_check_merge.resolve", @@ -710,7 +725,7 @@ async def test_records_the_fallback_with_its_status_code( async with OpenFgaClient(self.configuration) as client: with self.assertLogs("openfga_sdk.client._batch_check_merge", "WARNING"): - await self.batch_check(client, checks(), NO_RETRY) + await self.batch_check(client, checks()) attributes = mock_fallback.call_args.kwargs["attributes"] self.assertEqual(attributes[TelemetryAttributes.http_response_status_code], 429) diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 6c3551d5..21912fa8 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -6,6 +6,7 @@ from openfga_sdk.client import ClientConfiguration from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest +from openfga_sdk.configuration import RetryParams from openfga_sdk.exceptions import ( AuthenticationError, FgaValidationException, @@ -24,7 +25,6 @@ MODEL, MODEL_ID, MODELS_URL, - NO_RETRY, OTHER_MODEL_ID, STORE_ID, UNMERGED, @@ -286,8 +286,8 @@ def test_sends_unmerged_when_the_model_cannot_be_read( with self.assertLogs( "openfga_sdk.client._batch_check_merge", "WARNING" ) as logs: - response = self.batch_check(client, checks(), NO_RETRY) - self.batch_check(client, checks(), NO_RETRY) + response = self.batch_check(client, checks()) + self.batch_check(client, checks()) self.assertEqual(len(logs.records), 1) self.assertIn("429", logs.output[0]) @@ -316,8 +316,8 @@ def test_sends_unmerged_when_the_server_fails_or_times_out( with self.assertLogs( "openfga_sdk.client._batch_check_merge", "WARNING" ): - response = self.batch_check(client, checks(), NO_RETRY) - self.batch_check(client, checks(), NO_RETRY) + response = self.batch_check(client, checks()) + self.batch_check(client, checks()) self.assertEqual(sent_checks(server), UNMERGED * 2) self.assertEqual(response.checks_sent, 4) @@ -330,6 +330,23 @@ def test_sends_unmerged_when_the_server_fails_or_times_out( status, ) + @patch.object(rest.RESTClientObject, "request") + def test_does_not_retry_the_model_read(self, mock_request): + retries = {"retry_params": RetryParams(max_retry=3, min_wait_in_ms=1)} + for model_error in [rate_limited, server_error]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + self.batch_check(client, checks(), retries) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), UNMERGED) + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") @patch( "openfga_sdk.client._batch_check_merge.resolve", From 60aa1e85904e86709454e240fc0d51b5f15c3ec4 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 27 Nov 2026 16:22:53 +0530 Subject: [PATCH 17/38] test: check the model read isn't retried on network errors --- test/client/batch_check_merge_test.py | 7 ++++++- test/sync/client/batch_check_merge_test.py | 8 +++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index 4e4061f4..c8bee8ac 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -4,6 +4,7 @@ from unittest import IsolatedAsyncioTestCase from unittest.mock import patch +import aiohttp import urllib3 from openfga_sdk import rest @@ -172,6 +173,10 @@ def timed_out(): return TimeoutError("timed out") +def connection_dropped(): + return aiohttp.ClientConnectionError("connection reset") + + def store_not_found(): body = {"code": "store_id_not_found", "message": f"Store '{STORE_ID}' not found"} return NotFoundException(http_resp=http_mock_response(json.dumps(body), 404)) @@ -466,7 +471,7 @@ async def test_sends_unmerged_when_the_server_fails_or_times_out( @patch.object(rest.RESTClientObject, "request") async def test_does_not_retry_the_model_read(self, mock_request): retries = {"retry_params": RetryParams(max_retry=3, min_wait_in_ms=1)} - for model_error in [rate_limited, server_error]: + for model_error in [rate_limited, server_error, connection_dropped]: with self.subTest(error=model_error.__name__): server = FakeServer(model_error=model_error) mock_request.side_effect = server diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 21912fa8..5c24bdd2 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -4,6 +4,8 @@ from unittest import TestCase from unittest.mock import patch +import urllib3 + from openfga_sdk.client import ClientConfiguration from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest from openfga_sdk.configuration import RetryParams @@ -42,6 +44,10 @@ ) +def connection_dropped(): + return urllib3.exceptions.ProtocolError("connection aborted") + + def mock_response(body, status=200): obj = http_mock_response(body, status) return rest.RESTResponse(obj, obj.data) @@ -333,7 +339,7 @@ def test_sends_unmerged_when_the_server_fails_or_times_out( @patch.object(rest.RESTClientObject, "request") def test_does_not_retry_the_model_read(self, mock_request): retries = {"retry_params": RetryParams(max_retry=3, min_wait_in_ms=1)} - for model_error in [rate_limited, server_error]: + for model_error in [rate_limited, server_error, connection_dropped]: with self.subTest(error=model_error.__name__): server = FakeServer(model_error=model_error) mock_request.side_effect = server From 7550d14e259394f83cb2c13414681dea5a3894d2 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 27 Nov 2026 16:25:29 +0530 Subject: [PATCH 18/38] refactor: make the merge modules private --- openfga_sdk/client/_batch_check_merge.py | 4 ++-- .../{equivalent_checks.py => _equivalent_checks.py} | 0 openfga_sdk/client/{model_cache.py => _model_cache.py} | 2 +- openfga_sdk/client/_model_cache_base.py | 2 +- openfga_sdk/client/client.py | 8 ++++---- .../sync/client/{model_cache.py => _model_cache.py} | 2 +- openfga_sdk/sync/client/client.py | 8 ++++---- test/client/equivalent_checks_cases_test.py | 2 +- test/client/equivalent_checks_test.py | 2 +- test/client/model_cache_test.py | 2 +- test/sync/client/model_cache_test.py | 2 +- 11 files changed, 17 insertions(+), 17 deletions(-) rename openfga_sdk/client/{equivalent_checks.py => _equivalent_checks.py} (100%) rename openfga_sdk/client/{model_cache.py => _model_cache.py} (97%) rename openfga_sdk/sync/client/{model_cache.py => _model_cache.py} (96%) diff --git a/openfga_sdk/client/_batch_check_merge.py b/openfga_sdk/client/_batch_check_merge.py index 7a420560..f3c5026f 100644 --- a/openfga_sdk/client/_batch_check_merge.py +++ b/openfga_sdk/client/_batch_check_merge.py @@ -6,12 +6,12 @@ import logging -from openfga_sdk.client._model_cache_base import ModelLookup, model_read_fails_call -from openfga_sdk.client.equivalent_checks import ( +from openfga_sdk.client._equivalent_checks import ( EquivalentCheckGroup, resolve, unmerged, ) +from openfga_sdk.client._model_cache_base import ModelLookup, model_read_fails_call from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem from openfga_sdk.telemetry.attributes import TelemetryAttributes diff --git a/openfga_sdk/client/equivalent_checks.py b/openfga_sdk/client/_equivalent_checks.py similarity index 100% rename from openfga_sdk/client/equivalent_checks.py rename to openfga_sdk/client/_equivalent_checks.py diff --git a/openfga_sdk/client/model_cache.py b/openfga_sdk/client/_model_cache.py similarity index 97% rename from openfga_sdk/client/model_cache.py rename to openfga_sdk/client/_model_cache.py index 1048758e..f05f8836 100644 --- a/openfga_sdk/client/model_cache.py +++ b/openfga_sdk/client/_model_cache.py @@ -7,12 +7,12 @@ from collections.abc import Awaitable, Callable +from openfga_sdk.client._equivalent_checks import ModelAliases from openfga_sdk.client._model_cache_base import ( ModelCacheBase, ModelCacheKey, ModelLookup, ) -from openfga_sdk.client.equivalent_checks import ModelAliases class AsyncModelCache(ModelCacheBase): diff --git a/openfga_sdk/client/_model_cache_base.py b/openfga_sdk/client/_model_cache_base.py index 4b9c675a..ba05319d 100644 --- a/openfga_sdk/client/_model_cache_base.py +++ b/openfga_sdk/client/_model_cache_base.py @@ -13,7 +13,7 @@ from collections.abc import Callable from dataclasses import dataclass -from openfga_sdk.client.equivalent_checks import ModelAliases +from openfga_sdk.client._equivalent_checks import ModelAliases from openfga_sdk.exceptions import ApiException, AuthenticationError diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index afbb16c6..43398803 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -11,15 +11,15 @@ checks_to_send, log_model_read_failure, ) -from openfga_sdk.client._model_cache_base import ModelLookup -from openfga_sdk.client.configuration import ClientConfiguration -from openfga_sdk.client.equivalent_checks import ( +from openfga_sdk.client._equivalent_checks import ( ModelAliases, expand, merge_enabled, prepare_checks, ) -from openfga_sdk.client.model_cache import AsyncModelCache +from openfga_sdk.client._model_cache import AsyncModelCache +from openfga_sdk.client._model_cache_base import ModelLookup +from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, diff --git a/openfga_sdk/sync/client/model_cache.py b/openfga_sdk/sync/client/_model_cache.py similarity index 96% rename from openfga_sdk/sync/client/model_cache.py rename to openfga_sdk/sync/client/_model_cache.py index f46ac34b..5b3c455a 100644 --- a/openfga_sdk/sync/client/model_cache.py +++ b/openfga_sdk/sync/client/_model_cache.py @@ -8,12 +8,12 @@ from collections.abc import Callable from concurrent.futures import Future +from openfga_sdk.client._equivalent_checks import ModelAliases from openfga_sdk.client._model_cache_base import ( ModelCacheBase, ModelCacheKey, ModelLookup, ) -from openfga_sdk.client.equivalent_checks import ModelAliases class ModelCache(ModelCacheBase): diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index f6443e79..36a521a7 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -9,14 +9,14 @@ checks_to_send, log_model_read_failure, ) -from openfga_sdk.client._model_cache_base import ModelLookup -from openfga_sdk.client.configuration import ClientConfiguration -from openfga_sdk.client.equivalent_checks import ( +from openfga_sdk.client._equivalent_checks import ( ModelAliases, expand, merge_enabled, prepare_checks, ) +from openfga_sdk.client._model_cache_base import ModelLookup +from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( ClientBatchCheckItem, @@ -85,7 +85,7 @@ ) from openfga_sdk.models.write_request import WriteRequest from openfga_sdk.sync.api_client import ApiClient -from openfga_sdk.sync.client.model_cache import ModelCache +from openfga_sdk.sync.client._model_cache import ModelCache from openfga_sdk.sync.open_fga_api import OpenFgaApi from openfga_sdk.validation import is_well_formed_ulid_string diff --git a/test/client/equivalent_checks_cases_test.py b/test/client/equivalent_checks_cases_test.py index ddec85dc..eb4e38bb 100644 --- a/test/client/equivalent_checks_cases_test.py +++ b/test/client/equivalent_checks_cases_test.py @@ -12,7 +12,7 @@ import pytest -from openfga_sdk.client.equivalent_checks import ModelAliases, resolve +from openfga_sdk.client._equivalent_checks import ModelAliases, resolve from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem from openfga_sdk.client.models.tuple import ClientTuple from openfga_sdk.models.relationship_condition import RelationshipCondition diff --git a/test/client/equivalent_checks_test.py b/test/client/equivalent_checks_test.py index b4075ce7..21b2ddf9 100644 --- a/test/client/equivalent_checks_test.py +++ b/test/client/equivalent_checks_test.py @@ -3,7 +3,7 @@ import pytest -from openfga_sdk.client.equivalent_checks import ( +from openfga_sdk.client._equivalent_checks import ( EquivalentCheckGroup, ModelAliases, expand, diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py index f997d70f..b07c7b83 100644 --- a/test/client/model_cache_test.py +++ b/test/client/model_cache_test.py @@ -4,8 +4,8 @@ from types import SimpleNamespace from unittest import IsolatedAsyncioTestCase, TestCase, skipIf +from openfga_sdk.client._model_cache import AsyncModelCache from openfga_sdk.client._model_cache_base import model_read_fails_call -from openfga_sdk.client.model_cache import AsyncModelCache from openfga_sdk.exceptions import ( AuthenticationError, ForbiddenException, diff --git a/test/sync/client/model_cache_test.py b/test/sync/client/model_cache_test.py index b13ab771..447a2b96 100644 --- a/test/sync/client/model_cache_test.py +++ b/test/sync/client/model_cache_test.py @@ -10,7 +10,7 @@ UnauthorizedException, ValidationException, ) -from openfga_sdk.sync.client.model_cache import ModelCache +from openfga_sdk.sync.client._model_cache import ModelCache KEY = ("store", "model") From 77a90b127b3e6af1bd5847f467a1f702c36dc7cd Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 27 Nov 2026 20:04:56 +0530 Subject: [PATCH 19/38] refactor: return the responses from _send_batch_checks and share the model read kwargs --- openfga_sdk/client/_batch_check_merge.py | 15 ++++++ openfga_sdk/client/client.py | 60 ++++++++---------------- openfga_sdk/sync/client/client.py | 56 +++++++--------------- 3 files changed, 51 insertions(+), 80 deletions(-) diff --git a/openfga_sdk/client/_batch_check_merge.py b/openfga_sdk/client/_batch_check_merge.py index f3c5026f..5d69730b 100644 --- a/openfga_sdk/client/_batch_check_merge.py +++ b/openfga_sdk/client/_batch_check_merge.py @@ -13,12 +13,27 @@ ) from openfga_sdk.client._model_cache_base import ModelLookup, model_read_fails_call from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.configuration import RetryParams from openfga_sdk.telemetry.attributes import TelemetryAttributes logger = logging.getLogger(__name__) +def model_read_kwargs( + options: dict[str, int | str | dict[str, int | str]] | None = None, +) -> dict[str, int | str | dict[str, int | str]]: + """ + Return the kwargs for the authorization model read of a BatchCheck call: the + call's headers, and no retries. A failed read either fails the call (see + model_read_fails_call) or sends the checks unmerged right away. + """ + kwargs = {"_retry_params": RetryParams(max_retry=0)} + if options is not None and options.get("headers"): + kwargs["_headers"] = options["headers"] + return kwargs + + def log_model_read_failure( error: Exception, store_id: str, authorization_model_id: str ) -> None: diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 43398803..aa159384 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -1,7 +1,7 @@ import asyncio import uuid -from collections.abc import AsyncIterator, Callable +from collections.abc import AsyncIterator from contextlib import aclosing from typing import Any @@ -10,6 +10,7 @@ from openfga_sdk.client._batch_check_merge import ( checks_to_send, log_model_read_failure, + model_read_kwargs, ) from openfga_sdk.client._equivalent_checks import ( ModelAliases, @@ -50,7 +51,6 @@ construct_write_single_response, ) from openfga_sdk.client.models.write_transaction_opts import WriteTransactionOpts -from openfga_sdk.configuration import RetryParams from openfga_sdk.constants import ( CLIENT_BULK_REQUEST_ID_HEADER, CLIENT_MAX_BATCH_SIZE, @@ -143,20 +143,6 @@ def options_to_kwargs( return kwargs -def _model_read_kwargs( - options: dict[str, int | str | dict[str, int | str]] | None = None, -) -> dict[str, int | str | dict[str, int | str]]: - """ - Return the kwargs a BatchCheck call passes on to its authorization model read. - The read is never retried: if it fails, the checks are sent unmerged right away. - """ - kwargs = {"_retry_params": RetryParams(max_retry=0)} - headers = options_to_kwargs(options).get("_headers") - if headers: - kwargs["_headers"] = headers - return kwargs - - def options_to_transaction_info( options: dict[str, int | str | dict[str, int | str]] | None = None, ): @@ -891,21 +877,15 @@ def map_response(id, result): error=result.error, ) - def add_results(response): + for response in await self._send_batch_checks( + checks, + self._get_authorization_model_id(options), + options, + max_parallel_requests, + ): result.extend( - [ - map_response(c_id, c_result) - for c_id, c_result in response.result.items() - ] - ) - - if checks: - await self._send_batch_checks( - checks, - self._get_authorization_model_id(options), - options, - max_parallel_requests, - add_results, + map_response(c_id, c_result) + for c_id, c_result in response.result.items() ) return ClientBatchCheckResponse(result) @@ -916,17 +896,16 @@ async def _send_batch_checks( authorization_model_id: str | None, options: dict[str, int | str | dict[str, int | str]], max_parallel_requests: int, - on_response: Callable[[BatchCheckResponse], None], - ) -> None: + ) -> list[BatchCheckResponse]: """ Send each chunk of checks as one BatchCheck request, with at most - max_parallel_requests in flight, and pass each response to on_response + max_parallel_requests in flight, and return the responses in chunk order """ sem = asyncio.Semaphore(max_parallel_requests) consistency = self._get_consistency(options) - async def send(checks): - response = await self._single_batch_check( + def send(checks): + return self._single_batch_check( BatchCheckRequest( checks=checks, authorization_model_id=authorization_model_id, @@ -935,9 +914,8 @@ async def send(checks): sem, options, ) - on_response(response) - await asyncio.gather(*[send(checks) for checks in chunks]) + return await asyncio.gather(*[send(checks) for checks in chunks]) async def _merged_batch_check( self, @@ -962,7 +940,7 @@ async def _merged_batch_check( ) results = {} - await self._send_batch_checks( + for response in await self._send_batch_checks( [ [construct_batch_item(group.check) for group in chunk] for chunk in _chuck_array(groups, max_batch_size) @@ -970,8 +948,8 @@ async def _merged_batch_check( authorization_model_id, options, max_parallel_requests, - lambda response: results.update(response.result or {}), - ) + ): + results.update(response.result or {}) return ClientBatchCheckResponse( expand(checks, groups, results), checks_sent=len(groups) @@ -992,7 +970,7 @@ async def _read_and_cache_model_aliases( async def load(): try: response = await self._api.read_authorization_model( - authorization_model_id, **_model_read_kwargs(options) + authorization_model_id, **model_read_kwargs(options) ) return ModelAliases(response.authorization_model) except Exception as error: diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index 36a521a7..5372c54f 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -1,6 +1,6 @@ import uuid -from collections.abc import Callable, Iterator +from collections.abc import Iterator from concurrent.futures import ThreadPoolExecutor from contextlib import closing from typing import Any @@ -8,6 +8,7 @@ from openfga_sdk.client._batch_check_merge import ( checks_to_send, log_model_read_failure, + model_read_kwargs, ) from openfga_sdk.client._equivalent_checks import ( ModelAliases, @@ -47,7 +48,6 @@ construct_write_single_response, ) from openfga_sdk.client.models.write_transaction_opts import WriteTransactionOpts -from openfga_sdk.configuration import RetryParams from openfga_sdk.constants import ( CLIENT_BULK_REQUEST_ID_HEADER, CLIENT_MAX_BATCH_SIZE, @@ -143,20 +143,6 @@ def options_to_kwargs( return kwargs -def _model_read_kwargs( - options: dict[str, int | str | dict[str, int | str]] | None = None, -) -> dict[str, int | str | dict[str, int | str]]: - """ - Return the kwargs a BatchCheck call passes on to its authorization model read. - The read is never retried: if it fails, the checks are sent unmerged right away. - """ - kwargs = {"_retry_params": RetryParams(max_retry=0)} - headers = options_to_kwargs(options).get("_headers") - if headers: - kwargs["_headers"] = headers - return kwargs - - def options_to_transaction_info( options: dict[str, int | str | dict[str, int | str]] | None = None, ): @@ -886,21 +872,15 @@ def map_response(id, result): error=result.error, ) - def add_results(response): + for response in self._send_batch_checks( + checks, + self._get_authorization_model_id(options), + options, + max_parallel_requests, + ): result.extend( - [ - map_response(c_id, c_result) - for c_id, c_result in response.result.items() - ] - ) - - if checks: - self._send_batch_checks( - checks, - self._get_authorization_model_id(options), - options, - max_parallel_requests, - add_results, + map_response(c_id, c_result) + for c_id, c_result in response.result.items() ) return ClientBatchCheckResponse(result) @@ -911,11 +891,10 @@ def _send_batch_checks( authorization_model_id: str | None, options: dict[str, int | str | dict[str, int | str]], max_parallel_requests: int, - on_response: Callable[[BatchCheckResponse], None], - ) -> None: + ) -> list[BatchCheckResponse]: """ Send each chunk of checks as one BatchCheck request, with at most - max_parallel_requests in flight, and pass each response to on_response + max_parallel_requests in flight, and return the responses in chunk order """ consistency = self._get_consistency(options) @@ -930,8 +909,7 @@ def send(checks): ) with ThreadPoolExecutor(max_workers=max_parallel_requests) as executor: - for response in executor.map(send, chunks): - on_response(response) + return list(executor.map(send, chunks)) def _merged_batch_check( self, @@ -956,7 +934,7 @@ def _merged_batch_check( ) results = {} - self._send_batch_checks( + for response in self._send_batch_checks( [ [construct_batch_item(group.check) for group in chunk] for chunk in _chuck_array(groups, max_batch_size) @@ -964,8 +942,8 @@ def _merged_batch_check( authorization_model_id, options, max_parallel_requests, - lambda response: results.update(response.result or {}), - ) + ): + results.update(response.result or {}) return ClientBatchCheckResponse( expand(checks, groups, results), checks_sent=len(groups) @@ -986,7 +964,7 @@ def _read_and_cache_model_aliases( def load(): try: response = self._api.read_authorization_model( - authorization_model_id, **_model_read_kwargs(options) + authorization_model_id, **model_read_kwargs(options) ) return ModelAliases(response.authorization_model) except Exception as error: From 429aeac6143866bdce756f4fdfe44b5285267120 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 27 Nov 2026 20:04:56 +0530 Subject: [PATCH 20/38] docs: say when batch_check calls are sent unmerged --- docs/opentelemetry.md | 20 ++++++++++---------- openfga_sdk/telemetry/counters.py | 2 +- openfga_sdk/telemetry/metrics.py | 4 +++- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/opentelemetry.md b/docs/opentelemetry.md index 31bb1619..c534a796 100644 --- a/docs/opentelemetry.md +++ b/docs/opentelemetry.md @@ -21,16 +21,16 @@ If you configure the OpenTelemetry SDK, these metrics will be exported and sent ### Supported Metrics -| Metric Name | Type | Enabled by Default | Description | -| ----------------------------------------- | --------- | ------------------ | --------------------------------------------------------------------------------------------- | -| `fga-client.request.duration` | Histogram | Yes | Total request time for FGA requests, in milliseconds | -| `fga-client.query.duration` | Histogram | Yes | Time taken by the FGA server to process and evaluate the request, in milliseconds | -| `fga-client.credentials.request` | Counter | Yes | Total number of new token requests initiated using the Client Credentials flow | -| `fga-client.request` | Counter | No | Total number of requests made to the FGA server | -| `fga-client.batch_check.checks_requested` | Counter | Yes | Checks passed to `batch_check` with `merge_equivalent_checks` on | -| `fga-client.batch_check.checks_sent` | Counter | Yes | Checks actually sent by `batch_check` with `merge_equivalent_checks` on | -| `fga-client.batch_check.merge_fallback` | Counter | Yes | `batch_check` calls sent unmerged because the model could not be read or the checks grouped | -| `fga-client.model_cache.lookup` | Counter | Yes | Authorization model cache lookups by `merge_equivalent_checks`, with a `hit` or `miss` result | +| Metric Name | Type | Enabled by Default | Description | +| ----------------------------------------- | --------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `fga-client.request.duration` | Histogram | Yes | Total request time for FGA requests, in milliseconds | +| `fga-client.query.duration` | Histogram | Yes | Time taken by the FGA server to process and evaluate the request, in milliseconds | +| `fga-client.credentials.request` | Counter | Yes | Total number of new token requests initiated using the Client Credentials flow | +| `fga-client.request` | Counter | No | Total number of requests made to the FGA server | +| `fga-client.batch_check.checks_requested` | Counter | Yes | Checks passed to `batch_check` with `merge_equivalent_checks` on | +| `fga-client.batch_check.checks_sent` | Counter | Yes | Checks actually sent by `batch_check` with `merge_equivalent_checks` on | +| `fga-client.batch_check.merge_fallback` | Counter | Yes | `batch_check` calls sent unmerged because the model read failed with an error that doesn't fail the call (such as a 429, a 5xx or a timeout), or the checks couldn't be grouped. Has the `http.response.status_code` of the failed read, when there is one | +| `fga-client.model_cache.lookup` | Counter | Yes | Authorization model cache lookups by `merge_equivalent_checks`, with a `hit` or `miss` result | ### Supported Attributes diff --git a/openfga_sdk/telemetry/counters.py b/openfga_sdk/telemetry/counters.py index efc9d20e..17954bc8 100644 --- a/openfga_sdk/telemetry/counters.py +++ b/openfga_sdk/telemetry/counters.py @@ -35,7 +35,7 @@ class TelemetryCounters: fga_client_batch_check_merge_fallback: TelemetryCounter = TelemetryCounter( name="fga-client.batch_check.merge_fallback", - description="Total number of BatchCheck calls sent unmerged because the authorization model couldn't be read.", + description="Total number of BatchCheck calls sent unmerged because the authorization model read failed with an error that doesn't fail the call (such as a 429, a 5xx or a timeout), or the checks couldn't be grouped.", ) _counters: list[TelemetryCounter] = [ diff --git a/openfga_sdk/telemetry/metrics.py b/openfga_sdk/telemetry/metrics.py index 8d8d1fe0..128583fb 100644 --- a/openfga_sdk/telemetry/metrics.py +++ b/openfga_sdk/telemetry/metrics.py @@ -149,7 +149,9 @@ def batchCheckMergeFallback( configuration: TelemetryConfiguration | None = None, ) -> Counter: """ - Record a BatchCheck call sent unmerged because the authorization model couldn't be read. + Record a BatchCheck call sent unmerged because the authorization model read + failed with an error that doesn't fail the call (such as a 429, a 5xx or a + timeout), or the checks couldn't be grouped. """ return self._add( TelemetryCounters.fga_client_batch_check_merge_fallback, From 70d49d79c94e1197e4e702c8b7626637b4b60326 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 27 Nov 2026 20:04:56 +0530 Subject: [PATCH 21/38] test: update the shared equivalent-checks cases to 67 --- Makefile | 2 +- test/data/equivalent-checks-cases.json | 536 ++++++++++++++++++++++++- 2 files changed, 534 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 438fe36c..d008a69e 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases # openfga/language commit to copy the shared equivalent-checks cases from -LANGUAGE_REF ?= 153c7a93ef8775b81ef1e53a5a6a3fa04d469803 +LANGUAGE_REF ?= 22e223f804fc4d2daef358f300361c9831318f78 # Install/update dependencies sync: diff --git a/test/data/equivalent-checks-cases.json b/test/data/equivalent-checks-cases.json index 4dea16af..0702e719 100644 --- a/test/data/equivalent-checks-cases.json +++ b/test/data/equivalent-checks-cases.json @@ -1,5 +1,5 @@ { - "note": "Generated from equivalent-checks-cases.yaml, with every model as JSON. Don't edit this file: edit the YAML file and run `make -C pkg/go generate-equivalent-checks-json`.", + "note": "Generated from equivalent-checks-cases.yaml, with every model as JSON. It's committed because SDKs without a DSL parser download it from GitHub at a pinned commit. Don't edit this file: edit the YAML file and run `make -C pkg/go generate-equivalent-checks-json`.", "cases": [ { "name": "merges an alias with the relation it points to", @@ -4184,6 +4184,33 @@ { "name": "merges checks with the same contextual tuples", "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "limits": { + "generic_types": [ + { + "type_name": "TYPE_NAME_DOUBLE" + } + ], + "type_name": "TYPE_NAME_MAP" + }, + "region": { + "type_name": "TYPE_NAME_STRING" + }, + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" + } + } + } + }, "schema_version": "1.1", "type_definitions": [ { @@ -4196,6 +4223,10 @@ "directly_related_user_types": [ { "type": "user" + }, + { + "condition": "in_region", + "type": "user" } ] } @@ -4217,6 +4248,11 @@ { "type": "user" }, + { + "condition": "in_region", + "type": "user", + "wildcard": {} + }, { "relation": "member", "type": "team" @@ -4255,6 +4291,37 @@ "user": "team:eng#member", "relation": "viewer", "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["x", "y"] + } + } + }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "region": "us", + "limits": { + "read": 0.5 + }, + "tags": [] + } + } } ] }, @@ -4264,17 +4331,146 @@ "relation": "viewer", "object": "document:1", "contextual_tuples": [ + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "tags": ["x", "y"], + "limits": { + "write": 2.0, + "read": 1.0 + }, + "region": "eu" + } + } + }, { "user": "user:anne", "relation": "member", "object": "team:eng" }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "tags": [], + "region": "us", + "limits": { + "read": 0.5 + } + } + } + }, { "user": "team:eng#member", "relation": "viewer", "object": "document:1" } ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "limits": { + "read": 0.5 + }, + "tags": [], + "region": "us" + } + } + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "limits": { + "write": 2, + "read": 1 + }, + "region": "eu", + "tags": ["x", "y"] + } + } + }, + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + } + ] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["y", "x"] + } + } + }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "region": "us", + "limits": { + "read": 0.5 + }, + "tags": [] + } + } + } + ] } ], "expected_sent": [ @@ -4293,9 +4489,90 @@ "user": "team:eng#member", "relation": "viewer", "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["x", "y"] + } + } + }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "region": "us", + "limits": { + "read": 0.5 + }, + "tags": [] + } + } + } + ], + "for": ["a", "b", "c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["y", "x"] + } + } + }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "region": "us", + "limits": { + "read": 0.5 + }, + "tags": [] + } + } } ], - "for": ["a", "b"] + "for": ["d"] } ] }, @@ -4418,7 +4695,7 @@ ] }, { - "name": "does not merge different contextual tuples", + "name": "does not merge contextual tuples with a different object, user or relation", "model": { "schema_version": "1.1", "type_definitions": [ @@ -4429,6 +4706,13 @@ "metadata": { "relations": { "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, "viewer": { "directly_related_user_types": [ { @@ -4444,6 +4728,9 @@ "relation": "viewer" } }, + "editor": { + "this": {} + }, "viewer": { "this": {} } @@ -4478,6 +4765,32 @@ "object": "document:2" } ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "d", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "editor", + "object": "document:1" + } + ] } ], "expected_sent": [ @@ -4508,6 +4821,223 @@ } ], "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "editor", + "object": "document:1" + } + ], + "for": ["d"] + } + ] + }, + { + "name": "does not merge contextual tuples with a different userset or wildcard user", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "admin": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "admin": { + "this": {} + }, + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "type": "user", + "wildcard": {} + }, + { + "relation": "member", + "type": "team" + }, + { + "relation": "admin", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#admin", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:*", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#admin", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:*", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["d"] } ] }, From fbd127a7207302f9e242782c42ed331abbc9531d Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 27 Nov 2026 20:10:11 +0530 Subject: [PATCH 22/38] docs: say which token request failures fail the call --- README.md | 4 ++-- openfga_sdk/client/_model_cache_base.py | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 68fee720..e4fedfbc 100644 --- a/README.md +++ b/README.md @@ -990,9 +990,9 @@ To find aliases, the SDK reads the authorization model the first time it needs i - no authorization model ID is set - the model or the store doesn't exist -- the credentials can't read the model (a 401 or 403, or the token request fails). If your credentials can only run checks, leave the option off. +- the credentials can't read the model (a 401 or 403 from the read or the token request, or a token response with no usable token). If your credentials can only run checks, leave the option off. -If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. After a 429 it waits about a minute before reading the model again. After any other failure it tries again on the next call. +If reading the model fails for another reason, such as a 429, a 5xx or a timeout, including on the token request, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. After a 429 it waits about a minute before reading the model again. After any other failure it tries again on the next call. Compared with leaving the option off, a call: diff --git a/openfga_sdk/client/_model_cache_base.py b/openfga_sdk/client/_model_cache_base.py index ba05319d..1b3003ff 100644 --- a/openfga_sdk/client/_model_cache_base.py +++ b/openfga_sdk/client/_model_cache_base.py @@ -30,7 +30,8 @@ def model_read_fails_call(error: Exception | None) -> bool: """ Whether a model read error fails the BatchCheck call instead of sending the checks unmerged: the model or store doesn't exist, or the credentials can't read the model - (a 401 or 403, or the token request failed) + (a 401 or 403 from the read or the token request, or a token response with no + usable token) """ if isinstance(error, AuthenticationError): return True From 6f8957e35247b0455b91c0128547e8566f15e017 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 27 Nov 2026 20:48:33 +0530 Subject: [PATCH 23/38] fix: fail the call when the token request fails, instead of falling back The checks need the same token, so falling back couldn't send them. It also ran the token retries a second time, logged and counted a fallback that never happened, and remembered a token 429 as a model read failure for a minute. The client now gets the token before the model read, so any token failure fails the call like it would with the option off. --- README.md | 5 +- openfga_sdk/client/_batch_check_merge.py | 5 +- openfga_sdk/client/_model_cache_base.py | 8 +- openfga_sdk/client/client.py | 12 ++ openfga_sdk/sync/client/client.py | 12 ++ test/client/batch_check_merge_test.py | 126 ++++++++++++++++++--- test/client/model_cache_test.py | 2 - test/sync/client/batch_check_merge_test.py | 104 ++++++++++++++--- 8 files changed, 226 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index e4fedfbc..b06e8e1c 100644 --- a/README.md +++ b/README.md @@ -990,9 +990,10 @@ To find aliases, the SDK reads the authorization model the first time it needs i - no authorization model ID is set - the model or the store doesn't exist -- the credentials can't read the model (a 401 or 403 from the read or the token request, or a token response with no usable token). If your credentials can only run checks, leave the option off. +- the SDK can't get an access token. The checks need the same token, so the call would fail with the option off too. +- the credentials can't read the model (a 401 or 403). If your credentials can only run checks, leave the option off. -If reading the model fails for another reason, such as a 429, a 5xx or a timeout, including on the token request, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. After a 429 it waits about a minute before reading the model again. After any other failure it tries again on the next call. +If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. After a 429 it waits about a minute before reading the model again. After any other failure it tries again on the next call. Compared with leaving the option off, a call: diff --git a/openfga_sdk/client/_batch_check_merge.py b/openfga_sdk/client/_batch_check_merge.py index 5d69730b..b537472e 100644 --- a/openfga_sdk/client/_batch_check_merge.py +++ b/openfga_sdk/client/_batch_check_merge.py @@ -67,9 +67,8 @@ def checks_to_send( if lookup.aliases is None: if model_read_fails_call(lookup.error): - # BatchCheck would fail too if the model is missing or no token can be - # fetched, and falling back on a 401 or 403 would hide wrong credentials. - # Fail before sending anything. + # BatchCheck would fail too if the model is missing, and falling back on a + # 401 or 403 would hide wrong credentials. Fail before sending anything. raise lookup.error groups = unmerged(checks) metrics.fallback(getattr(lookup.error, "status", None)) diff --git a/openfga_sdk/client/_model_cache_base.py b/openfga_sdk/client/_model_cache_base.py index 1b3003ff..7ca48057 100644 --- a/openfga_sdk/client/_model_cache_base.py +++ b/openfga_sdk/client/_model_cache_base.py @@ -14,7 +14,7 @@ from dataclasses import dataclass from openfga_sdk.client._equivalent_checks import ModelAliases -from openfga_sdk.exceptions import ApiException, AuthenticationError +from openfga_sdk.exceptions import ApiException MAX_MODELS = 32 @@ -30,11 +30,9 @@ def model_read_fails_call(error: Exception | None) -> bool: """ Whether a model read error fails the BatchCheck call instead of sending the checks unmerged: the model or store doesn't exist, or the credentials can't read the model - (a 401 or 403 from the read or the token request, or a token response with no - usable token) + (a 401 or 403). Token request failures never get here: the clients get the token + before the read, and fail the call if they can't. """ - if isinstance(error, AuthenticationError): - return True return isinstance(error, ApiException) and ( error.code in NOT_FOUND_CODES or error.status in CREDENTIAL_FAILURE_STATUSES ) diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index aa159384..104fbfc4 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -932,6 +932,7 @@ async def _merged_batch_check( if not checks: return ClientBatchCheckResponse([], checks_sent=0) + await self._fetch_token() lookup = await self._read_and_cache_model_aliases( store_id, authorization_model_id, options ) @@ -955,6 +956,17 @@ async def _merged_batch_check( expand(checks, groups, results), checks_sent=len(groups) ) + async def _fetch_token(self) -> None: + """ + Get the access token before the model read, if the client uses client + credentials. The checks need the same token, so if it can't be fetched the call + fails with that error, as it would with the option off, instead of falling back + or being remembered as a model read failure. + """ + oauth2_client = self._api._oauth2_client + if oauth2_client is not None: + await oauth2_client.get_authentication_header(self._api_client.rest_client) + async def _read_and_cache_model_aliases( self, store_id: str, diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index 5372c54f..71717a57 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -926,6 +926,7 @@ def _merged_batch_check( if not checks: return ClientBatchCheckResponse([], checks_sent=0) + self._fetch_token() lookup = self._read_and_cache_model_aliases( store_id, authorization_model_id, options ) @@ -949,6 +950,17 @@ def _merged_batch_check( expand(checks, groups, results), checks_sent=len(groups) ) + def _fetch_token(self) -> None: + """ + Get the access token before the model read, if the client uses client + credentials. The checks need the same token, so if it can't be fetched the call + fails with that error, as it would with the option off, instead of falling back + or being remembered as a model read failure. + """ + oauth2_client = self._api._oauth2_client + if oauth2_client is not None: + oauth2_client.get_authentication_header(self._api_client.rest_client) + def _read_and_cache_model_aliases( self, store_id: str, diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index c8bee8ac..adc5fdc1 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -14,6 +14,7 @@ from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest from openfga_sdk.client.models.batch_check_response import ClientBatchCheckResponse from openfga_sdk.configuration import RetryParams +from openfga_sdk.credentials import CredentialConfiguration, Credentials from openfga_sdk.exceptions import ( AuthenticationError, FgaValidationException, @@ -35,6 +36,7 @@ API_URL = "http://api.fga.example" MODELS_URL = f"{API_URL}/stores/{STORE_ID}/authorization-models/" BATCH_CHECK_URL = f"{API_URL}/stores/{STORE_ID}/batch-check" +TOKEN_URL = "https://issuer.fga.example/oauth/token" # define viewer: [user], can_view: viewer, can_share: can_view, editor: [user] MODEL = { @@ -75,6 +77,36 @@ def mock_response(body, status=200): return rest.RESTResponse(obj, obj.data) +def token_issued(): + return mock_response(json.dumps({"access_token": "token", "expires_in": 3600})) + + +def no_token_issued(): + return mock_response("{}") + + +def token_configuration(): + """ + A configuration that gets a token from TOKEN_URL, and retries a failed token + request once. + """ + return ClientConfiguration( + api_url=API_URL, + store_id=STORE_ID, + authorization_model_id=MODEL_ID, + credentials=Credentials( + method="client_credentials", + configuration=CredentialConfiguration( + client_id="client-id", + client_secret="client-secret", + api_issuer=TOKEN_URL, + api_audience="audience", + ), + ), + retry_params=RetryParams(max_retry=1), + ) + + def checks(): return [ ClientBatchCheckItem( @@ -100,10 +132,15 @@ def checks(): class FakeServer: """ - Answers model reads and BatchCheck requests, and records what was sent. + Answers token requests, model reads and BatchCheck requests, and records what was + sent. """ - def __init__(self, model_error=None, answer=None, model_body=None): + def __init__( + self, model_error=None, answer=None, model_body=None, token=token_issued + ): + self.token = token + self.token_requests = 0 self.model_error = model_error self.model_body = ( {"authorization_model": MODEL} if model_body is None else model_body @@ -117,6 +154,13 @@ def __init__(self, model_error=None, answer=None, model_body=None): self.sent = [] def __call__(self, method, url, **kwargs): + if method == "POST" and url == TOKEN_URL: + self.token_requests += 1 + response = self.token() + if isinstance(response, Exception): + raise response + return response + if method == "GET" and url.startswith(MODELS_URL): self.model_reads += 1 self.model_ids_read.append(url.removeprefix(MODELS_URL)) @@ -182,8 +226,8 @@ def store_not_found(): return NotFoundException(http_resp=http_mock_response(json.dumps(body), 404)) -def token_request_failed(): - return AuthenticationError(http_resp=http_mock_response("{}", 400)) +def bad_request(): + return ValidationException(http_resp=http_mock_response("{}", 400)) UNMERGED = [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")] @@ -516,25 +560,71 @@ async def test_sends_unmerged_when_grouping_fails( ) @patch.object(rest.RESTClientObject, "request") - async def test_fails_before_sending_when_the_store_does_not_exist_or_no_token( + async def test_fails_before_sending_when_the_store_does_not_exist( self, mock_request ): - for model_error, error_type in [ - (store_not_found, NotFoundException), - (token_request_failed, AuthenticationError), + server = FakeServer(model_error=store_not_found) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs("openfga_sdk.client._batch_check_merge", "WARNING"): + with self.assertRaises(NotFoundException): + await self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_fails_like_the_option_off_when_the_token_request_fails( + self, mock_request, mock_fallback + ): + for token, error_type in [ + (unauthorized, UnauthorizedException), + (bad_request, ValidationException), + (rate_limited, RateLimitExceededError), + (server_error, ServiceException), + (connection_dropped, aiohttp.ClientConnectionError), + (no_token_issued, AuthenticationError), ]: - with self.subTest(error=model_error.__name__): - server = FakeServer(model_error=model_error) - mock_request.side_effect = server + with self.subTest(token=token.__name__): + token_requests = [] + for merge in [False, True]: + server = FakeServer(token=token) + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + with self.assertRaises(error_type): + await client.batch_check( + ClientBatchCheckRequest(checks=checks()), + options={"merge_equivalent_checks": merge}, + ) - async with OpenFgaClient(self.configuration) as client: - with self.assertNoLogs( - "openfga_sdk.client._batch_check_merge", "WARNING" - ): - with self.assertRaises(error_type): - await self.batch_check(client, checks()) + self.assertEqual(server.model_reads, 0) + self.assertEqual(server.sent, []) + token_requests.append(server.token_requests) - self.assertEqual(server.sent, []) + self.assertEqual(token_requests[1], token_requests[0]) + + mock_fallback.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_a_failed_token_request_is_not_remembered(self, mock_request): + server = FakeServer(token=rate_limited) + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + with self.assertRaises(RateLimitExceededError): + await self.batch_check(client, checks()) + + server.token = token_issued + response = await self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) + self.assertEqual(response.checks_sent, 2) @patch.object(rest.RESTClientObject, "request") async def test_fails_before_sending_when_the_model_does_not_exist( diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py index b07c7b83..0eff978c 100644 --- a/test/client/model_cache_test.py +++ b/test/client/model_cache_test.py @@ -7,7 +7,6 @@ from openfga_sdk.client._model_cache import AsyncModelCache from openfga_sdk.client._model_cache_base import model_read_fails_call from openfga_sdk.exceptions import ( - AuthenticationError, ForbiddenException, NotFoundException, RateLimitExceededError, @@ -194,7 +193,6 @@ def test_fails_when_the_model_is_missing_or_the_credentials_cannot_read_it(self) (with_code(NotFoundException(status=404), "store_id_not_found"), True), (UnauthorizedException(status=401), True), (ForbiddenException(status=403), True), - (AuthenticationError(status=500), True), (with_code(ValidationException(status=400), "validation_error"), False), (RateLimitExceededError(status=429), False), (ServiceException(status=500), False), diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 5c24bdd2..515f263e 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -14,6 +14,8 @@ FgaValidationException, ForbiddenException, NotFoundException, + RateLimitExceededError, + ServiceException, UnauthorizedException, ValidationException, ) @@ -29,7 +31,9 @@ MODELS_URL, OTHER_MODEL_ID, STORE_ID, + TOKEN_URL, UNMERGED, + bad_request, checks, forbidden, http_mock_response, @@ -39,7 +43,7 @@ server_error, store_not_found, timed_out, - token_request_failed, + token_configuration, unauthorized, ) @@ -53,12 +57,25 @@ def mock_response(body, status=200): return rest.RESTResponse(obj, obj.data) +def token_issued(): + return mock_response(json.dumps({"access_token": "token", "expires_in": 3600})) + + +def no_token_issued(): + return mock_response("{}") + + class FakeServer: """ - Answers model reads and BatchCheck requests, and records what was sent. + Answers token requests, model reads and BatchCheck requests, and records what was + sent. """ - def __init__(self, model_error=None, answer=None, model_body=None): + def __init__( + self, model_error=None, answer=None, model_body=None, token=token_issued + ): + self.token = token + self.token_requests = 0 self.model_error = model_error self.model_body = ( {"authorization_model": MODEL} if model_body is None else model_body @@ -72,6 +89,13 @@ def __init__(self, model_error=None, answer=None, model_body=None): self.sent = [] def __call__(self, method, url, **kwargs): + if method == "POST" and url == TOKEN_URL: + self.token_requests += 1 + response = self.token() + if isinstance(response, Exception): + raise response + return response + if method == "GET" and url.startswith(MODELS_URL): self.model_reads += 1 self.model_ids_read.append(url.removeprefix(MODELS_URL)) @@ -381,25 +405,69 @@ def test_sends_unmerged_when_grouping_fails( ) @patch.object(rest.RESTClientObject, "request") - def test_fails_before_sending_when_the_store_does_not_exist_or_no_token( - self, mock_request + def test_fails_before_sending_when_the_store_does_not_exist(self, mock_request): + server = FakeServer(model_error=store_not_found) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs("openfga_sdk.client._batch_check_merge", "WARNING"): + with self.assertRaises(NotFoundException): + self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_fails_like_the_option_off_when_the_token_request_fails( + self, mock_request, mock_fallback ): - for model_error, error_type in [ - (store_not_found, NotFoundException), - (token_request_failed, AuthenticationError), + for token, error_type in [ + (unauthorized, UnauthorizedException), + (bad_request, ValidationException), + (rate_limited, RateLimitExceededError), + (server_error, ServiceException), + (connection_dropped, urllib3.exceptions.ProtocolError), + (no_token_issued, AuthenticationError), ]: - with self.subTest(error=model_error.__name__): - server = FakeServer(model_error=model_error) - mock_request.side_effect = server + with self.subTest(token=token.__name__): + token_requests = [] + for merge in [False, True]: + server = FakeServer(token=token) + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + with self.assertRaises(error_type): + client.batch_check( + ClientBatchCheckRequest(checks=checks()), + options={"merge_equivalent_checks": merge}, + ) - with OpenFgaClient(self.configuration) as client: - with self.assertNoLogs( - "openfga_sdk.client._batch_check_merge", "WARNING" - ): - with self.assertRaises(error_type): - self.batch_check(client, checks()) + self.assertEqual(server.model_reads, 0) + self.assertEqual(server.sent, []) + token_requests.append(server.token_requests) - self.assertEqual(server.sent, []) + self.assertEqual(token_requests[1], token_requests[0]) + + mock_fallback.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_a_failed_token_request_is_not_remembered(self, mock_request): + server = FakeServer(token=rate_limited) + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + with self.assertRaises(RateLimitExceededError): + self.batch_check(client, checks()) + + server.token = token_issued + response = self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) + self.assertEqual(response.checks_sent, 2) @patch.object(rest.RESTClientObject, "request") def test_fails_before_sending_when_the_model_does_not_exist(self, mock_request): From d7d3b2cff23b7c9a89f2965c23f3cc5d6ca3874c Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 27 Nov 2026 21:01:50 +0530 Subject: [PATCH 24/38] fix: tell token failures apart from model read failures Fetching the token before the model read missed tokens that expire within the SDK's renewal buffer: every request renews them, so the read could still fail on a token request and fall back. --- README.md | 2 +- openfga_sdk/client/_batch_check_merge.py | 31 ++++++++++-- openfga_sdk/client/_model_cache_base.py | 19 ++++++-- openfga_sdk/client/client.py | 21 +++------ openfga_sdk/sync/client/client.py | 21 +++------ test/client/batch_check_merge_test.py | 55 ++++++++++++++++++++++ test/sync/client/batch_check_merge_test.py | 54 +++++++++++++++++++++ 7 files changed, 168 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index b06e8e1c..70f18a0c 100644 --- a/README.md +++ b/README.md @@ -990,7 +990,7 @@ To find aliases, the SDK reads the authorization model the first time it needs i - no authorization model ID is set - the model or the store doesn't exist -- the SDK can't get an access token. The checks need the same token, so the call would fail with the option off too. +- the SDK can't get an access token, after retrying as usual. The checks need the same token, so the call would fail with the option off too. - the credentials can't read the model (a 401 or 403). If your credentials can only run checks, leave the option off. If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. After a 429 it waits about a minute before reading the model again. After any other failure it tries again on the next call. diff --git a/openfga_sdk/client/_batch_check_merge.py b/openfga_sdk/client/_batch_check_merge.py index b537472e..6500ccff 100644 --- a/openfga_sdk/client/_batch_check_merge.py +++ b/openfga_sdk/client/_batch_check_merge.py @@ -11,7 +11,11 @@ resolve, unmerged, ) -from openfga_sdk.client._model_cache_base import ModelLookup, model_read_fails_call +from openfga_sdk.client._model_cache_base import ( + ModelLookup, + TokenRequestFailed, + model_read_fails_call, +) from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem from openfga_sdk.configuration import RetryParams from openfga_sdk.telemetry.attributes import TelemetryAttributes @@ -34,6 +38,24 @@ def model_read_kwargs( return kwargs +class TokenWatch: + """ + Tells whether a failed request failed because the SDK couldn't get an access token + for it. A request first gets a new token if there's none or the cached one is close + to expiring, and a successful token request always replaces the cached token. So if + the token was due for renewal before the request, and is the same one after it + failed, the token request is what failed. + """ + + def __init__(self, oauth2_client) -> None: + self._oauth2_client = oauth2_client + self._renewing = oauth2_client is not None and not oauth2_client._token_valid() + self._token = oauth2_client._token_state if self._renewing else None + + def token_request_failed(self) -> bool: + return self._renewing and self._oauth2_client._token_state is self._token + + def log_model_read_failure( error: Exception, store_id: str, authorization_model_id: str ) -> None: @@ -67,8 +89,11 @@ def checks_to_send( if lookup.aliases is None: if model_read_fails_call(lookup.error): - # BatchCheck would fail too if the model is missing, and falling back on a - # 401 or 403 would hide wrong credentials. Fail before sending anything. + # BatchCheck would fail too without a token or if the model is missing, and + # falling back on a 401 or 403 would hide wrong credentials. Fail before + # sending anything. + if isinstance(lookup.error, TokenRequestFailed): + raise lookup.error.error raise lookup.error groups = unmerged(checks) metrics.fallback(getattr(lookup.error, "status", None)) diff --git a/openfga_sdk/client/_model_cache_base.py b/openfga_sdk/client/_model_cache_base.py index 7ca48057..5ce2b83f 100644 --- a/openfga_sdk/client/_model_cache_base.py +++ b/openfga_sdk/client/_model_cache_base.py @@ -26,13 +26,26 @@ ModelCacheKey = tuple[str, str] +class TokenRequestFailed(Exception): + """ + The model read failed because the SDK couldn't get an access token for it. The call + fails with `error`, as it would with the option off, and the failure isn't + remembered. + """ + + def __init__(self, error: Exception) -> None: + super().__init__(str(error)) + self.error = error + + def model_read_fails_call(error: Exception | None) -> bool: """ Whether a model read error fails the BatchCheck call instead of sending the checks - unmerged: the model or store doesn't exist, or the credentials can't read the model - (a 401 or 403). Token request failures never get here: the clients get the token - before the read, and fail the call if they can't. + unmerged: the SDK couldn't get an access token, the model or store doesn't exist, or + the credentials can't read the model (a 401 or 403). """ + if isinstance(error, TokenRequestFailed): + return True return isinstance(error, ApiException) and ( error.code in NOT_FOUND_CODES or error.status in CREDENTIAL_FAILURE_STATUSES ) diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 104fbfc4..961d5e51 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -8,6 +8,7 @@ from openfga_sdk.api.open_fga_api import OpenFgaApi from openfga_sdk.api_client import ApiClient from openfga_sdk.client._batch_check_merge import ( + TokenWatch, checks_to_send, log_model_read_failure, model_read_kwargs, @@ -19,7 +20,7 @@ prepare_checks, ) from openfga_sdk.client._model_cache import AsyncModelCache -from openfga_sdk.client._model_cache_base import ModelLookup +from openfga_sdk.client._model_cache_base import ModelLookup, TokenRequestFailed from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( @@ -932,7 +933,6 @@ async def _merged_batch_check( if not checks: return ClientBatchCheckResponse([], checks_sent=0) - await self._fetch_token() lookup = await self._read_and_cache_model_aliases( store_id, authorization_model_id, options ) @@ -956,17 +956,6 @@ async def _merged_batch_check( expand(checks, groups, results), checks_sent=len(groups) ) - async def _fetch_token(self) -> None: - """ - Get the access token before the model read, if the client uses client - credentials. The checks need the same token, so if it can't be fetched the call - fails with that error, as it would with the option off, instead of falling back - or being remembered as a model read failure. - """ - oauth2_client = self._api._oauth2_client - if oauth2_client is not None: - await oauth2_client.get_authentication_header(self._api_client.rest_client) - async def _read_and_cache_model_aliases( self, store_id: str, @@ -975,17 +964,21 @@ async def _read_and_cache_model_aliases( ) -> ModelLookup: """ Read an authorization model through the client's model cache, and work out its - aliases for merge_equivalent_checks. The read is never retried. + aliases for merge_equivalent_checks. The read is never retried. If it fails + because the SDK couldn't get an access token, the error is a TokenRequestFailed. :param header(options) - Custom headers to send alongside the request """ async def load(): + token = TokenWatch(self._api._oauth2_client) try: response = await self._api.read_authorization_model( authorization_model_id, **model_read_kwargs(options) ) return ModelAliases(response.authorization_model) except Exception as error: + if token.token_request_failed(): + raise TokenRequestFailed(error) from error log_model_read_failure(error, store_id, authorization_model_id) raise diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index 71717a57..180b49a3 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -6,6 +6,7 @@ from typing import Any from openfga_sdk.client._batch_check_merge import ( + TokenWatch, checks_to_send, log_model_read_failure, model_read_kwargs, @@ -16,7 +17,7 @@ merge_enabled, prepare_checks, ) -from openfga_sdk.client._model_cache_base import ModelLookup +from openfga_sdk.client._model_cache_base import ModelLookup, TokenRequestFailed from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( @@ -926,7 +927,6 @@ def _merged_batch_check( if not checks: return ClientBatchCheckResponse([], checks_sent=0) - self._fetch_token() lookup = self._read_and_cache_model_aliases( store_id, authorization_model_id, options ) @@ -950,17 +950,6 @@ def _merged_batch_check( expand(checks, groups, results), checks_sent=len(groups) ) - def _fetch_token(self) -> None: - """ - Get the access token before the model read, if the client uses client - credentials. The checks need the same token, so if it can't be fetched the call - fails with that error, as it would with the option off, instead of falling back - or being remembered as a model read failure. - """ - oauth2_client = self._api._oauth2_client - if oauth2_client is not None: - oauth2_client.get_authentication_header(self._api_client.rest_client) - def _read_and_cache_model_aliases( self, store_id: str, @@ -969,17 +958,21 @@ def _read_and_cache_model_aliases( ) -> ModelLookup: """ Read an authorization model through the client's model cache, and work out its - aliases for merge_equivalent_checks. The read is never retried. + aliases for merge_equivalent_checks. The read is never retried. If it fails + because the SDK couldn't get an access token, the error is a TokenRequestFailed. :param header(options) - Custom headers to send alongside the request """ def load(): + token = TokenWatch(self._api._oauth2_client) try: response = self._api.read_authorization_model( authorization_model_id, **model_read_kwargs(options) ) return ModelAliases(response.authorization_model) except Exception as error: + if token.token_request_failed(): + raise TokenRequestFailed(error) from error log_model_read_failure(error, store_id, authorization_model_id) raise diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index adc5fdc1..19900a18 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -81,6 +81,16 @@ def token_issued(): return mock_response(json.dumps({"access_token": "token", "expires_in": 3600})) +def short_lived_token_issued(): + # Expires within the SDK's renewal buffer, so every request gets a new token + return mock_response(json.dumps({"access_token": "token", "expires_in": 300})) + + +def short_lived_tokens_then_rate_limited(count): + responses = iter([short_lived_token_issued] * count) + return lambda: next(responses, rate_limited)() + + def no_token_issued(): return mock_response("{}") @@ -626,6 +636,51 @@ async def test_a_failed_token_request_is_not_remembered(self, mock_request): self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) self.assertEqual(response.checks_sent, 2) + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_fails_when_the_model_read_cannot_renew_the_token( + self, mock_request, mock_fallback + ): + for renewals in [0, 1]: + with self.subTest(renewals_before_failing=renewals): + server = FakeServer(token=short_lived_token_issued) + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + await client.batch_check(ClientBatchCheckRequest(checks=checks())) + server.token = short_lived_tokens_then_rate_limited(renewals) + + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + with self.assertRaises(RateLimitExceededError): + await self.batch_check(client, checks()) + + server.token = short_lived_token_issued + response = await self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(response.checks_sent, 2) + + mock_fallback.assert_not_called() + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_the_read_fails_after_renewing_the_token( + self, mock_request, mock_fallback + ): + server = FakeServer(model_error=rate_limited, token=short_lived_token_issued) + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + with self.assertLogs("openfga_sdk.client._batch_check_merge", "WARNING"): + response = await self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + mock_fallback.assert_called_once() + @patch.object(rest.RESTClientObject, "request") async def test_fails_before_sending_when_the_model_does_not_exist( self, mock_request diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 515f263e..08d4c6ee 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -61,6 +61,15 @@ def token_issued(): return mock_response(json.dumps({"access_token": "token", "expires_in": 3600})) +def short_lived_token_issued(): + return mock_response(json.dumps({"access_token": "token", "expires_in": 300})) + + +def short_lived_tokens_then_rate_limited(count): + responses = iter([short_lived_token_issued] * count) + return lambda: next(responses, rate_limited)() + + def no_token_issued(): return mock_response("{}") @@ -469,6 +478,51 @@ def test_a_failed_token_request_is_not_remembered(self, mock_request): self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) self.assertEqual(response.checks_sent, 2) + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_fails_when_the_model_read_cannot_renew_the_token( + self, mock_request, mock_fallback + ): + for renewals in [0, 1]: + with self.subTest(renewals_before_failing=renewals): + server = FakeServer(token=short_lived_token_issued) + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + client.batch_check(ClientBatchCheckRequest(checks=checks())) + server.token = short_lived_tokens_then_rate_limited(renewals) + + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + with self.assertRaises(RateLimitExceededError): + self.batch_check(client, checks()) + + server.token = short_lived_token_issued + response = self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(response.checks_sent, 2) + + mock_fallback.assert_not_called() + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_the_read_fails_after_renewing_the_token( + self, mock_request, mock_fallback + ): + server = FakeServer(model_error=rate_limited, token=short_lived_token_issued) + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + with self.assertLogs("openfga_sdk.client._batch_check_merge", "WARNING"): + response = self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + mock_fallback.assert_called_once() + @patch.object(rest.RESTClientObject, "request") def test_fails_before_sending_when_the_model_does_not_exist(self, mock_request): server = FakeServer(model_error=model_not_found) From 73c5b247603db1e88dc192c7462e23884e8f5d6f Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Fri, 27 Nov 2026 23:17:43 +0530 Subject: [PATCH 25/38] test: pin the shared equivalent-checks cases to openfga/language@b7cc548 --- Makefile | 2 +- test/data/equivalent-checks-cases.json | 91 ++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index d008a69e..632b3e2b 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases # openfga/language commit to copy the shared equivalent-checks cases from -LANGUAGE_REF ?= 22e223f804fc4d2daef358f300361c9831318f78 +LANGUAGE_REF ?= b7cc548b50e1479dc4db38d208bd735653446d62 # Install/update dependencies sync: diff --git a/test/data/equivalent-checks-cases.json b/test/data/equivalent-checks-cases.json index 0702e719..6726874c 100644 --- a/test/data/equivalent-checks-cases.json +++ b/test/data/equivalent-checks-cases.json @@ -691,6 +691,97 @@ } ] }, + { + "name": "keeps a check sent as is in its place between merged groups", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_veiw", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:bob", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "e", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "c"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_veiw", + "object": "document:1", + "for": ["b"] + }, + { + "id": "merged-2", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["d", "e"] + } + ] + }, { "name": "stops the chain at a union", "model": { From bfb72a7b6935f69f4c03d7730b26ba8d939210e6 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Sat, 28 Nov 2026 13:56:02 +0530 Subject: [PATCH 26/38] refactor: stop remembering a 429 from the model read --- README.md | 4 +- openfga_sdk/client/_model_cache.py | 4 -- openfga_sdk/client/_model_cache_base.py | 53 +++------------- openfga_sdk/sync/client/_model_cache.py | 1 - test/client/batch_check_merge_test.py | 5 +- test/client/model_cache_test.py | 25 ++------ test/sync/client/batch_check_merge_test.py | 5 +- test/sync/client/model_cache_test.py | 71 ++++------------------ 8 files changed, 29 insertions(+), 139 deletions(-) diff --git a/README.md b/README.md index 70f18a0c..e201a2f9 100644 --- a/README.md +++ b/README.md @@ -993,7 +993,7 @@ To find aliases, the SDK reads the authorization model the first time it needs i - the SDK can't get an access token, after retrying as usual. The checks need the same token, so the call would fail with the option off too. - the credentials can't read the model (a 401 or 403). If your credentials can only run checks, leave the option off. -If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. After a 429 it waits about a minute before reading the model again. After any other failure it tries again on the next call. +If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. The next call reads the model again. Compared with leaving the option off, a call: @@ -1001,7 +1001,7 @@ Compared with leaving the option off, a call: - spends a little time grouping the checks and copying the answers back. This happens in memory and is small next to a request. - sends fewer checks when some of them merge, so the checks themselves can finish sooner. -Each client reads each model once. Some services rate limit model reads much lower than checks, so if many clients start at the same time, some may get a 429 and send checks unmerged for about a minute. +Each client reads each model once. Some services rate limit model reads much lower than checks, so if many clients start at the same time, some may get a 429. Those clients send checks unmerged and read the model again on each call until a read succeeds. If a merged check returns an error, every check it stands for gets that error. Correlation IDs must match `^[\w\d-]{1,36}$` (ASCII), and missing ones are generated. For metrics, see `fga-client.batch_check.*` and `fga-client.model_cache.lookup` in [OpenTelemetry](docs/opentelemetry.md). diff --git a/openfga_sdk/client/_model_cache.py b/openfga_sdk/client/_model_cache.py index f05f8836..d3c2c5f2 100644 --- a/openfga_sdk/client/_model_cache.py +++ b/openfga_sdk/client/_model_cache.py @@ -66,10 +66,6 @@ async def _load( ) -> ModelAliases: try: aliases = await load() - except Exception as error: - self._remember_failure(key, error) - raise - else: self._store(key, aliases) return aliases finally: diff --git a/openfga_sdk/client/_model_cache_base.py b/openfga_sdk/client/_model_cache_base.py index 5ce2b83f..54ef3bef 100644 --- a/openfga_sdk/client/_model_cache_base.py +++ b/openfga_sdk/client/_model_cache_base.py @@ -3,14 +3,10 @@ part of the public API. A model never changes once it's written, so a cached model never goes stale. Only -successful reads are cached. A 429 is remembered for a short time, so rate limiting -doesn't add a read to every call. Other failures aren't, so the next call reads again. +successful reads are cached, so after a failure the next call reads again. """ -import time - from collections import OrderedDict -from collections.abc import Callable from dataclasses import dataclass from openfga_sdk.client._equivalent_checks import ModelAliases @@ -18,8 +14,6 @@ MAX_MODELS = 32 -FAILURE_TTL_SECONDS = 60.0 -REMEMBERED_FAILURE_STATUSES = frozenset({429}) CREDENTIAL_FAILURE_STATUSES = frozenset({401, 403}) NOT_FOUND_CODES = frozenset({"authorization_model_not_found", "store_id_not_found"}) @@ -29,8 +23,7 @@ class TokenRequestFailed(Exception): """ The model read failed because the SDK couldn't get an access token for it. The call - fails with `error`, as it would with the option off, and the failure isn't - remembered. + fails with `error`, as it would with the option off. """ def __init__(self, error: Exception) -> None: @@ -65,52 +58,22 @@ class ModelLookup: class ModelCacheBase: """ - The cached models and remembered failures. The async and sync caches add the reads. + The cached models. The async and sync caches add the reads. """ - def __init__( - self, - max_models: int = MAX_MODELS, - failure_ttl: float = FAILURE_TTL_SECONDS, - clock: Callable[[], float] = time.monotonic, - ) -> None: + def __init__(self, max_models: int = MAX_MODELS) -> None: self._max_models = max_models - self._failure_ttl = failure_ttl - self._clock = clock self._models: OrderedDict[ModelCacheKey, ModelAliases] = OrderedDict() - self._failures: OrderedDict[ModelCacheKey, tuple[float, Exception]] = ( - OrderedDict() - ) def _cached(self, key: ModelCacheKey) -> ModelLookup | None: aliases = self._models.get(key) - if aliases is not None: - self._models.move_to_end(key) - return ModelLookup(aliases=aliases, hit=True) - - failure = self._failures.get(key) - if failure is not None: - expires_at, error = failure - if self._clock() < expires_at: - return ModelLookup(error=error) - del self._failures[key] - - return None + if aliases is None: + return None + self._models.move_to_end(key) + return ModelLookup(aliases=aliases, hit=True) def _store(self, key: ModelCacheKey, aliases: ModelAliases) -> None: - self._failures.pop(key, None) self._models[key] = aliases self._models.move_to_end(key) while len(self._models) > self._max_models: self._models.popitem(last=False) - - def _remember_failure(self, key: ModelCacheKey, error: Exception) -> None: - if not ( - isinstance(error, ApiException) - and error.status in REMEMBERED_FAILURE_STATUSES - ): - return - self._failures[key] = (self._clock() + self._failure_ttl, error) - self._failures.move_to_end(key) - while len(self._failures) > self._max_models: - self._failures.popitem(last=False) diff --git a/openfga_sdk/sync/client/_model_cache.py b/openfga_sdk/sync/client/_model_cache.py index 5b3c455a..da1a8b8d 100644 --- a/openfga_sdk/sync/client/_model_cache.py +++ b/openfga_sdk/sync/client/_model_cache.py @@ -52,7 +52,6 @@ def get( aliases = load() except Exception as error: with self._lock: - self._remember_failure(key, error) self._loading.pop(key, None) future.set_exception(error) return ModelLookup(error=error) diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index 19900a18..ecf376f0 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -486,7 +486,7 @@ async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): self.assertIn(MODEL_ID, logs.output[0]) self.assertIn(STORE_ID, logs.output[0]) self.assertIn("429", logs.output[0]) - self.assertEqual(server.model_reads, 1) + self.assertEqual(server.model_reads, 2) self.assertEqual(sent_checks(server), UNMERGED * 2) self.assertEqual(response.checks_sent, 4) self.assertEqual(second.checks_sent, 4) @@ -513,7 +513,6 @@ async def test_sends_unmerged_when_the_server_fails_or_times_out( self.assertEqual(sent_checks(server), UNMERGED * 2) self.assertEqual(response.checks_sent, 4) - # Only a 429 is remembered, so the next call reads again. self.assertEqual(server.model_reads, 2) self.assertEqual( mock_fallback.call_args.kwargs["attributes"][ @@ -621,7 +620,7 @@ async def test_fails_like_the_option_off_when_the_token_request_fails( mock_fallback.assert_not_called() @patch.object(rest.RESTClientObject, "request") - async def test_a_failed_token_request_is_not_remembered(self, mock_request): + async def test_the_next_call_works_after_a_failed_token_request(self, mock_request): server = FakeServer(token=rate_limited) mock_request.side_effect = server diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py index 0eff978c..74b86a77 100644 --- a/test/client/model_cache_test.py +++ b/test/client/model_cache_test.py @@ -19,14 +19,6 @@ KEY = ("store", "model") -class FakeClock: - def __init__(self): - self.now = 0.0 - - def __call__(self): - return self.now - - class TestAsyncModelCache(IsolatedAsyncioTestCase): async def test_parallel_lookups_share_one_read_and_later_lookups_hit(self): cache = AsyncModelCache() @@ -50,9 +42,8 @@ async def load(): later = await cache.get(KEY, load) self.assertEqual((later.aliases, later.hit, reads), ("model", True, 1)) - async def test_a_failed_read_is_remembered_for_a_short_time(self): - clock = FakeClock() - cache = AsyncModelCache(failure_ttl=60, clock=clock) + async def test_a_failed_read_is_not_cached(self): + cache = AsyncModelCache() reads = 0 error = RateLimitExceededError(status=429) @@ -62,23 +53,17 @@ async def load(): raise error first = await cache.get(KEY, load) - clock.now = 59 second = await cache.get(KEY, load) self.assertIs(first.error, error) self.assertIs(second.error, error) self.assertIsNone(second.aliases) - self.assertEqual(reads, 1) - - clock.now = 60 - await cache.get(KEY, load) self.assertEqual(reads, 2) @skipIf(sys.version_info < (3, 12), "eager tasks need Python 3.12+") async def test_retries_a_failed_read_that_finished_eagerly(self): asyncio.get_running_loop().set_task_factory(asyncio.eager_task_factory) - clock = FakeClock() - cache = AsyncModelCache(failure_ttl=60, clock=clock) + cache = AsyncModelCache() reads = 0 async def load(): @@ -89,7 +74,6 @@ async def load(): await cache.get(KEY, load) self.assertEqual(cache._loading, {}) - clock.now = 60 await cache.get(KEY, load) self.assertEqual(reads, 2) @@ -149,8 +133,7 @@ async def load(): self.assertEqual((await cache.get(KEY, load)).aliases, "model") async def test_keys_on_both_the_store_and_the_model(self): - clock = FakeClock() - cache = AsyncModelCache(clock=clock) + cache = AsyncModelCache() reads = [] async def get(store, model, error=None): diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index 08d4c6ee..a66b7175 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -330,7 +330,7 @@ def test_sends_unmerged_when_the_model_cannot_be_read( self.assertEqual(len(logs.records), 1) self.assertIn("429", logs.output[0]) - self.assertEqual(server.model_reads, 1) + self.assertEqual(server.model_reads, 2) self.assertEqual(sent_checks(server), UNMERGED * 2) self.assertEqual(response.checks_sent, 4) self.assertEqual(mock_fallback.call_count, 2) @@ -360,7 +360,6 @@ def test_sends_unmerged_when_the_server_fails_or_times_out( self.assertEqual(sent_checks(server), UNMERGED * 2) self.assertEqual(response.checks_sent, 4) - # Only a 429 is remembered, so the next call reads again. self.assertEqual(server.model_reads, 2) self.assertEqual( mock_fallback.call_args.kwargs["attributes"][ @@ -463,7 +462,7 @@ def test_fails_like_the_option_off_when_the_token_request_fails( mock_fallback.assert_not_called() @patch.object(rest.RESTClientObject, "request") - def test_a_failed_token_request_is_not_remembered(self, mock_request): + def test_the_next_call_works_after_a_failed_token_request(self, mock_request): server = FakeServer(token=rate_limited) mock_request.side_effect = server diff --git a/test/sync/client/model_cache_test.py b/test/sync/client/model_cache_test.py index 447a2b96..b610d2a8 100644 --- a/test/sync/client/model_cache_test.py +++ b/test/sync/client/model_cache_test.py @@ -16,14 +16,6 @@ KEY = ("store", "model") -class FakeClock: - def __init__(self): - self.now = 0.0 - - def __call__(self): - return self.now - - class TestModelCache(TestCase): def test_threads_share_one_read_and_later_lookups_hit(self): cache = ModelCache() @@ -56,34 +48,14 @@ def load(): self.assertEqual([r.aliases for r in results], ["model"] * 4) self.assertTrue(cache.get(KEY, load).hit) - def test_a_failed_read_is_remembered_for_a_short_time(self): - clock = FakeClock() - cache = ModelCache(failure_ttl=60, clock=clock) - reads = 0 - error = RateLimitExceededError(status=429) - - def load(): - nonlocal reads - reads += 1 - raise error - - self.assertIs(cache.get(KEY, load).error, error) - clock.now = 59 - self.assertIs(cache.get(KEY, load).error, error) - self.assertEqual(reads, 1) - - clock.now = 60 - cache.get(KEY, load) - self.assertEqual(reads, 2) - - def test_only_a_429_is_remembered(self): - for error, remembered in [ - (RateLimitExceededError(status=429), True), - (ForbiddenException(status=403), False), - (UnauthorizedException(status=401), False), - (ValidationException(status=400), False), - (ServiceException(status=500), False), - (TimeoutError(), False), + def test_a_failed_read_is_not_cached(self): + for error in [ + RateLimitExceededError(status=429), + ForbiddenException(status=403), + UnauthorizedException(status=401), + ValidationException(status=400), + ServiceException(status=500), + TimeoutError(), ]: with self.subTest(error=type(error).__name__): cache = ModelCache() @@ -94,9 +66,9 @@ def load(): reads += 1 raise error - cache.get(KEY, load) - cache.get(KEY, load) - self.assertEqual(reads, 1 if remembered else 2) + self.assertIs(cache.get(KEY, load).error, error) + self.assertIs(cache.get(KEY, load).error, error) + self.assertEqual(reads, 2) def test_drops_the_least_recently_used_model(self): cache = ModelCache(max_models=2) @@ -140,27 +112,6 @@ def load(): self.assertEqual([r.error for r in results], [error] * 4) - def test_remembers_a_bounded_number_of_failures(self): - cache = ModelCache(max_models=2) - reads = [] - - def get(key): - def load(): - reads.append(key) - raise RateLimitExceededError(status=429) - - return cache.get(key, load) - - get("a") - get("b") - get("c") - get("b") - get("c") - self.assertEqual(reads, ["a", "b", "c"]) - - get("a") - self.assertEqual(reads, ["a", "b", "c", "a"]) - def test_an_interrupted_read_is_not_cached(self): cache = ModelCache() From 46cbdfd929a927fc8c6076916a0115eb6b68c2bd Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Sat, 28 Nov 2026 20:53:58 +0530 Subject: [PATCH 27/38] docs: say alias checks need the same context, and the cache holds 32 models --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e201a2f9..f481cf58 100644 --- a/README.md +++ b/README.md @@ -971,7 +971,7 @@ If you set `merge_equivalent_checks` to `True` in the options, the SDK sends che Two kinds of checks are merged: -- Checks on a relation that is an alias of another one. With `define can_view: viewer`, a check on `can_view` and a check on `viewer` for the same user and object become one check on `viewer`. Chains like `define can_share: can_view` are followed too. +- Checks on a relation that is an alias of another one. With `define can_view: viewer`, a check on `can_view` and a check on `viewer` with the same user, object, context and contextual tuples become one check on `viewer`. Chains like `define can_share: can_view` are followed too. - Exact repeats, with the same user, relation, object, context and contextual tuples. ```python @@ -986,7 +986,7 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), The option is off by default, and nothing changes while it is off. Leaving it out or setting it to `None` keeps it off. Any other value that isn't a bool, like `"true"`, fails with a validation error. -To find aliases, the SDK reads the authorization model the first time it needs it and keeps it in memory, so create the client once and reuse it. The call fails before any check is sent when: +To find aliases, the SDK reads the authorization model the first time it needs it and keeps it in memory, so create the client once and reuse it. Each client keeps up to 32 models and drops the least recently used one. The call fails before any check is sent when: - no authorization model ID is set - the model or the store doesn't exist @@ -1001,7 +1001,7 @@ Compared with leaving the option off, a call: - spends a little time grouping the checks and copying the answers back. This happens in memory and is small next to a request. - sends fewer checks when some of them merge, so the checks themselves can finish sooner. -Each client reads each model once. Some services rate limit model reads much lower than checks, so if many clients start at the same time, some may get a 429. Those clients send checks unmerged and read the model again on each call until a read succeeds. +Each client reads each model once, unless it uses more than 32 models. Some services rate limit model reads much lower than checks, so if many clients start at the same time, some may get a 429. Those clients send checks unmerged and read the model again on each call until a read succeeds. If a merged check returns an error, every check it stands for gets that error. Correlation IDs must match `^[\w\d-]{1,36}$` (ASCII), and missing ones are generated. For metrics, see `fga-client.batch_check.*` and `fga-client.model_cache.lookup` in [OpenTelemetry](docs/opentelemetry.md). From 1f57c497e2a3ae8bcbb07d160325d911e51b5bae Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 30 Nov 2026 16:06:22 +0530 Subject: [PATCH 28/38] chore: mark the shared cases JSON as generated GitHub collapses it in PR diffs, as the language repo does. --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..0d2f8f0c --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +test/data/equivalent-checks-cases.json linguist-generated=true From 15e49a11a3a9f54dc526d6b4c5adf8874128c144 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 30 Nov 2026 16:06:22 +0530 Subject: [PATCH 29/38] refactor: read the model in the model cache, not in a callback from the client The cache's get now takes the API, store, model ID and options, and reads the model itself. The clients no longer define a nested load function. --- openfga_sdk/client/_batch_check_merge.py | 4 +- openfga_sdk/client/_model_cache.py | 51 ++++++++++-- openfga_sdk/client/client.py | 41 +-------- openfga_sdk/sync/client/_model_cache.py | 45 +++++++++- openfga_sdk/sync/client/client.py | 41 +-------- test/client/model_cache_test.py | 102 +++++++++++++---------- test/sync/client/model_cache_test.py | 87 +++++++++++-------- 7 files changed, 199 insertions(+), 172 deletions(-) diff --git a/openfga_sdk/client/_batch_check_merge.py b/openfga_sdk/client/_batch_check_merge.py index 6500ccff..f69a01cd 100644 --- a/openfga_sdk/client/_batch_check_merge.py +++ b/openfga_sdk/client/_batch_check_merge.py @@ -1,7 +1,7 @@ """ Steps of a BatchCheck call with `merge_equivalent_checks` on that are the same in the -async and sync clients. The clients only read the model and send the checks. Not part -of the public API. +async and sync clients. The model caches read the model, and the clients send the +checks. Not part of the public API. """ import logging diff --git a/openfga_sdk/client/_model_cache.py b/openfga_sdk/client/_model_cache.py index d3c2c5f2..e13ba49f 100644 --- a/openfga_sdk/client/_model_cache.py +++ b/openfga_sdk/client/_model_cache.py @@ -5,13 +5,18 @@ import asyncio -from collections.abc import Awaitable, Callable - +from openfga_sdk.api.open_fga_api import OpenFgaApi +from openfga_sdk.client._batch_check_merge import ( + TokenWatch, + log_model_read_failure, + model_read_kwargs, +) from openfga_sdk.client._equivalent_checks import ModelAliases from openfga_sdk.client._model_cache_base import ( ModelCacheBase, ModelCacheKey, ModelLookup, + TokenRequestFailed, ) @@ -26,16 +31,24 @@ def __init__(self, *args, **kwargs) -> None: async def get( self, - key: ModelCacheKey, - load: Callable[[], Awaitable[ModelAliases]], + api: OpenFgaApi, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None = None, ) -> ModelLookup: + """ + Return the aliases of an authorization model, reading the model with `api` if + it isn't cached. If the read fails, the lookup has its error. + :param header(options) - Custom headers to send alongside the model read + """ + key = (store_id, authorization_model_id) cached = self._cached(key) if cached is not None: return cached task = self._loading.get(key) if task is None: - task = asyncio.ensure_future(self._load(key, load)) + task = asyncio.ensure_future(self._load(key, api, options)) task.add_done_callback(_retrieve_exception) # An eager task can finish before it's registered, so don't keep a done one. if not task.done(): @@ -62,16 +75,40 @@ async def close(self) -> None: async def _load( self, key: ModelCacheKey, - load: Callable[[], Awaitable[ModelAliases]], + api: OpenFgaApi, + options: dict[str, int | str | dict[str, int | str]] | None, ) -> ModelAliases: try: - aliases = await load() + aliases = await self._read(api, *key, options) self._store(key, aliases) return aliases finally: if self._loading.get(key) is asyncio.current_task(): del self._loading[key] + async def _read( + self, + api: OpenFgaApi, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None, + ) -> ModelAliases: + """ + Read the model and work out its aliases. The read is never retried. If it fails + because the SDK couldn't get an access token, the error is a TokenRequestFailed. + """ + token = TokenWatch(api._oauth2_client) + try: + response = await api.read_authorization_model( + authorization_model_id, **model_read_kwargs(options) + ) + return ModelAliases(response.authorization_model) + except Exception as error: + if token.token_request_failed(): + raise TokenRequestFailed(error) from error + log_model_read_failure(error, store_id, authorization_model_id) + raise + def _retrieve_exception(task: asyncio.Task) -> None: # Marks the error as seen, so asyncio doesn't log it when no caller is left waiting. diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 961d5e51..606579fa 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -7,20 +7,13 @@ from openfga_sdk.api.open_fga_api import OpenFgaApi from openfga_sdk.api_client import ApiClient -from openfga_sdk.client._batch_check_merge import ( - TokenWatch, - checks_to_send, - log_model_read_failure, - model_read_kwargs, -) +from openfga_sdk.client._batch_check_merge import checks_to_send from openfga_sdk.client._equivalent_checks import ( - ModelAliases, expand, merge_enabled, prepare_checks, ) from openfga_sdk.client._model_cache import AsyncModelCache -from openfga_sdk.client._model_cache_base import ModelLookup, TokenRequestFailed from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( @@ -933,8 +926,8 @@ async def _merged_batch_check( if not checks: return ClientBatchCheckResponse([], checks_sent=0) - lookup = await self._read_and_cache_model_aliases( - store_id, authorization_model_id, options + lookup = await self._model_cache.get( + self._api, store_id, authorization_model_id, options ) groups = checks_to_send( self._api_client, store_id, authorization_model_id, lookup, checks @@ -956,34 +949,6 @@ async def _merged_batch_check( expand(checks, groups, results), checks_sent=len(groups) ) - async def _read_and_cache_model_aliases( - self, - store_id: str, - authorization_model_id: str, - options: dict[str, int | str | dict[str, int | str]] | None = None, - ) -> ModelLookup: - """ - Read an authorization model through the client's model cache, and work out its - aliases for merge_equivalent_checks. The read is never retried. If it fails - because the SDK couldn't get an access token, the error is a TokenRequestFailed. - :param header(options) - Custom headers to send alongside the request - """ - - async def load(): - token = TokenWatch(self._api._oauth2_client) - try: - response = await self._api.read_authorization_model( - authorization_model_id, **model_read_kwargs(options) - ) - return ModelAliases(response.authorization_model) - except Exception as error: - if token.token_request_failed(): - raise TokenRequestFailed(error) from error - log_model_read_failure(error, store_id, authorization_model_id) - raise - - return await self._model_cache.get((store_id, authorization_model_id), load) - async def expand( self, body: ClientExpandRequest, diff --git a/openfga_sdk/sync/client/_model_cache.py b/openfga_sdk/sync/client/_model_cache.py index da1a8b8d..5d0485a3 100644 --- a/openfga_sdk/sync/client/_model_cache.py +++ b/openfga_sdk/sync/client/_model_cache.py @@ -5,15 +5,21 @@ import threading -from collections.abc import Callable from concurrent.futures import Future +from openfga_sdk.client._batch_check_merge import ( + TokenWatch, + log_model_read_failure, + model_read_kwargs, +) from openfga_sdk.client._equivalent_checks import ModelAliases from openfga_sdk.client._model_cache_base import ( ModelCacheBase, ModelCacheKey, ModelLookup, + TokenRequestFailed, ) +from openfga_sdk.sync.open_fga_api import OpenFgaApi class ModelCache(ModelCacheBase): @@ -28,9 +34,17 @@ def __init__(self, *args, **kwargs) -> None: def get( self, - key: ModelCacheKey, - load: Callable[[], ModelAliases], + api: OpenFgaApi, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None = None, ) -> ModelLookup: + """ + Return the aliases of an authorization model, reading the model with `api` if + it isn't cached. If the read fails, the lookup has its error. + :param header(options) - Custom headers to send alongside the model read + """ + key = (store_id, authorization_model_id) with self._lock: cached = self._cached(key) if cached is not None: @@ -49,7 +63,7 @@ def get( return ModelLookup(error=error) try: - aliases = load() + aliases = self._read(api, store_id, authorization_model_id, options) except Exception as error: with self._lock: self._loading.pop(key, None) @@ -68,3 +82,26 @@ def get( self._loading.pop(key, None) future.set_result(aliases) return ModelLookup(aliases=aliases) + + def _read( + self, + api: OpenFgaApi, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None, + ) -> ModelAliases: + """ + Read the model and work out its aliases. The read is never retried. If it fails + because the SDK couldn't get an access token, the error is a TokenRequestFailed. + """ + token = TokenWatch(api._oauth2_client) + try: + response = api.read_authorization_model( + authorization_model_id, **model_read_kwargs(options) + ) + return ModelAliases(response.authorization_model) + except Exception as error: + if token.token_request_failed(): + raise TokenRequestFailed(error) from error + log_model_read_failure(error, store_id, authorization_model_id) + raise diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index 180b49a3..99f99750 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -5,19 +5,12 @@ from contextlib import closing from typing import Any -from openfga_sdk.client._batch_check_merge import ( - TokenWatch, - checks_to_send, - log_model_read_failure, - model_read_kwargs, -) +from openfga_sdk.client._batch_check_merge import checks_to_send from openfga_sdk.client._equivalent_checks import ( - ModelAliases, expand, merge_enabled, prepare_checks, ) -from openfga_sdk.client._model_cache_base import ModelLookup, TokenRequestFailed from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( @@ -927,8 +920,8 @@ def _merged_batch_check( if not checks: return ClientBatchCheckResponse([], checks_sent=0) - lookup = self._read_and_cache_model_aliases( - store_id, authorization_model_id, options + lookup = self._model_cache.get( + self._api, store_id, authorization_model_id, options ) groups = checks_to_send( self._api_client, store_id, authorization_model_id, lookup, checks @@ -950,34 +943,6 @@ def _merged_batch_check( expand(checks, groups, results), checks_sent=len(groups) ) - def _read_and_cache_model_aliases( - self, - store_id: str, - authorization_model_id: str, - options: dict[str, int | str | dict[str, int | str]] | None = None, - ) -> ModelLookup: - """ - Read an authorization model through the client's model cache, and work out its - aliases for merge_equivalent_checks. The read is never retried. If it fails - because the SDK couldn't get an access token, the error is a TokenRequestFailed. - :param header(options) - Custom headers to send alongside the request - """ - - def load(): - token = TokenWatch(self._api._oauth2_client) - try: - response = self._api.read_authorization_model( - authorization_model_id, **model_read_kwargs(options) - ) - return ModelAliases(response.authorization_model) - except Exception as error: - if token.token_request_failed(): - raise TokenRequestFailed(error) from error - log_model_read_failure(error, store_id, authorization_model_id) - raise - - return self._model_cache.get((store_id, authorization_model_id), load) - def expand( self, body: ClientExpandRequest, diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py index 74b86a77..1429b70e 100644 --- a/test/client/model_cache_test.py +++ b/test/client/model_cache_test.py @@ -16,22 +16,32 @@ ) +API = object() KEY = ("store", "model") +def cache_reading(read, **kwargs): + """ + A cache that reads models with read(store_id, authorization_model_id), not the API. + """ + cache = AsyncModelCache(**kwargs) + cache._read = lambda api, store_id, model_id, options: read(store_id, model_id) + return cache + + class TestAsyncModelCache(IsolatedAsyncioTestCase): async def test_parallel_lookups_share_one_read_and_later_lookups_hit(self): - cache = AsyncModelCache() release = asyncio.Event() reads = 0 - async def load(): + async def read(*_): nonlocal reads reads += 1 await release.wait() return "model" - lookups = [asyncio.ensure_future(cache.get(KEY, load)) for _ in range(3)] + cache = cache_reading(read) + lookups = [asyncio.ensure_future(cache.get(API, *KEY)) for _ in range(3)] await asyncio.sleep(0) release.set() results = await asyncio.gather(*lookups) @@ -39,21 +49,21 @@ async def load(): self.assertEqual(reads, 1) self.assertEqual([(r.aliases, r.hit) for r in results], [("model", False)] * 3) - later = await cache.get(KEY, load) + later = await cache.get(API, *KEY) self.assertEqual((later.aliases, later.hit, reads), ("model", True, 1)) async def test_a_failed_read_is_not_cached(self): - cache = AsyncModelCache() reads = 0 error = RateLimitExceededError(status=429) - async def load(): + async def read(*_): nonlocal reads reads += 1 raise error - first = await cache.get(KEY, load) - second = await cache.get(KEY, load) + cache = cache_reading(read) + first = await cache.get(API, *KEY) + second = await cache.get(API, *KEY) self.assertIs(first.error, error) self.assertIs(second.error, error) @@ -63,47 +73,44 @@ async def load(): @skipIf(sys.version_info < (3, 12), "eager tasks need Python 3.12+") async def test_retries_a_failed_read_that_finished_eagerly(self): asyncio.get_running_loop().set_task_factory(asyncio.eager_task_factory) - cache = AsyncModelCache() reads = 0 - async def load(): + async def read(*_): nonlocal reads reads += 1 raise RuntimeError("forbidden") - await cache.get(KEY, load) + cache = cache_reading(read) + await cache.get(API, *KEY) self.assertEqual(cache._loading, {}) - await cache.get(KEY, load) + await cache.get(API, *KEY) self.assertEqual(reads, 2) async def test_drops_the_least_recently_used_model(self): - cache = AsyncModelCache(max_models=2) + async def read(store, model): + return f"{store}/{model}" - async def load_for(key): - async def load(): - return f"model-{key}" + cache = cache_reading(read, max_models=2) - return await cache.get(key, load) + await cache.get(API, "a", "1") + await cache.get(API, "b", "1") + self.assertTrue((await cache.get(API, "a", "1")).hit) + await cache.get(API, "c", "1") - await load_for("a") - await load_for("b") - self.assertTrue((await load_for("a")).hit) - await load_for("c") - - self.assertTrue((await load_for("a")).hit) - self.assertFalse((await load_for("b")).hit) + self.assertTrue((await cache.get(API, "a", "1")).hit) + self.assertFalse((await cache.get(API, "b", "1")).hit) async def test_a_cancelled_caller_does_not_cancel_the_shared_read(self): - cache = AsyncModelCache() release = asyncio.Event() - async def load(): + async def read(*_): await release.wait() return "model" - cancelled = asyncio.ensure_future(cache.get(KEY, load)) - waiting = asyncio.ensure_future(cache.get(KEY, load)) + cache = cache_reading(read) + cancelled = asyncio.ensure_future(cache.get(API, *KEY)) + waiting = asyncio.ensure_future(cache.get(API, *KEY)) await asyncio.sleep(0) cancelled.cancel() release.set() @@ -113,37 +120,40 @@ async def load(): await cancelled async def test_close_cancels_in_flight_reads_without_caching_them(self): - cache = AsyncModelCache() started = asyncio.Event() + hang = True - async def hang(): - started.set() - await asyncio.Event().wait() + async def read(*_): + if hang: + started.set() + await asyncio.Event().wait() + return "model" - lookup = asyncio.ensure_future(cache.get(KEY, hang)) + cache = cache_reading(read) + lookup = asyncio.ensure_future(cache.get(API, *KEY)) await started.wait() await cache.close() with self.assertRaises(asyncio.CancelledError): await lookup - async def load(): - return "model" - - self.assertEqual((await cache.get(KEY, load)).aliases, "model") + hang = False + self.assertEqual((await cache.get(API, *KEY)).aliases, "model") async def test_keys_on_both_the_store_and_the_model(self): - cache = AsyncModelCache() reads = [] + errors = {("c", "1"): RateLimitExceededError(status=429)} + + async def read(store, model): + reads.append((store, model)) + if (store, model) in errors: + raise errors[(store, model)] + return f"{store}/{model}" - async def get(store, model, error=None): - async def load(): - reads.append((store, model)) - if error is not None: - raise error - return f"{store}/{model}" + cache = cache_reading(read) - return await cache.get((store, model), load) + async def get(store, model): + return await cache.get(API, store, model) self.assertEqual((await get("a", "1")).aliases, "a/1") self.assertEqual((await get("b", "1")).aliases, "b/1") @@ -153,7 +163,7 @@ async def load(): self.assertTrue((await get("a", "2")).hit) self.assertEqual(reads, [("a", "1"), ("b", "1"), ("a", "2")]) - await get("c", "1", RateLimitExceededError(status=429)) + await get("c", "1") self.assertEqual((await get("d", "1")).aliases, "d/1") self.assertEqual((await get("c", "2")).aliases, "c/2") self.assertEqual(reads[3:], [("c", "1"), ("d", "1"), ("c", "2")]) diff --git a/test/sync/client/model_cache_test.py b/test/sync/client/model_cache_test.py index b610d2a8..1e1f9ee8 100644 --- a/test/sync/client/model_cache_test.py +++ b/test/sync/client/model_cache_test.py @@ -13,29 +13,39 @@ from openfga_sdk.sync.client._model_cache import ModelCache +API = object() KEY = ("store", "model") +def cache_reading(read, **kwargs): + """ + A cache that reads models with read(store_id, authorization_model_id), not the API. + """ + cache = ModelCache(**kwargs) + cache._read = lambda api, store_id, model_id, options: read(store_id, model_id) + return cache + + class TestModelCache(TestCase): def test_threads_share_one_read_and_later_lookups_hit(self): - cache = ModelCache() started = threading.Event() release = threading.Event() reads = 0 - def load(): + def read(*_): nonlocal reads reads += 1 started.set() release.wait() return "model" + cache = cache_reading(read) results = [] - owner = threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + owner = threading.Thread(target=lambda: results.append(cache.get(API, *KEY))) owner.start() started.wait() waiters = [ - threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + threading.Thread(target=lambda: results.append(cache.get(API, *KEY))) for _ in range(3) ] for waiter in waiters: @@ -46,7 +56,7 @@ def load(): self.assertEqual(reads, 1) self.assertEqual([r.aliases for r in results], ["model"] * 4) - self.assertTrue(cache.get(KEY, load).hit) + self.assertTrue(cache.get(API, *KEY).hit) def test_a_failed_read_is_not_cached(self): for error in [ @@ -58,49 +68,46 @@ def test_a_failed_read_is_not_cached(self): TimeoutError(), ]: with self.subTest(error=type(error).__name__): - cache = ModelCache() reads = 0 - def load(): + def read(*_): nonlocal reads reads += 1 raise error - self.assertIs(cache.get(KEY, load).error, error) - self.assertIs(cache.get(KEY, load).error, error) + cache = cache_reading(read) + self.assertIs(cache.get(API, *KEY).error, error) + self.assertIs(cache.get(API, *KEY).error, error) self.assertEqual(reads, 2) def test_drops_the_least_recently_used_model(self): - cache = ModelCache(max_models=2) - - def get(key): - return cache.get(key, lambda: f"model-{key}") + cache = cache_reading(lambda store, model: f"{store}/{model}", max_models=2) - get("a") - get("b") - self.assertTrue(get("a").hit) - get("c") + cache.get(API, "a", "1") + cache.get(API, "b", "1") + self.assertTrue(cache.get(API, "a", "1").hit) + cache.get(API, "c", "1") - self.assertTrue(get("a").hit) - self.assertFalse(get("b").hit) + self.assertTrue(cache.get(API, "a", "1").hit) + self.assertFalse(cache.get(API, "b", "1").hit) def test_threads_waiting_on_a_failed_read_get_its_error(self): - cache = ModelCache() started = threading.Event() release = threading.Event() error = RuntimeError("forbidden") - def load(): + def read(*_): started.set() release.wait() raise error + cache = cache_reading(read) results = [] - owner = threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + owner = threading.Thread(target=lambda: results.append(cache.get(API, *KEY))) owner.start() started.wait() waiters = [ - threading.Thread(target=lambda: results.append(cache.get(KEY, load))) + threading.Thread(target=lambda: results.append(cache.get(API, *KEY))) for _ in range(3) ] for waiter in waiters: @@ -113,28 +120,34 @@ def load(): self.assertEqual([r.error for r in results], [error] * 4) def test_an_interrupted_read_is_not_cached(self): - cache = ModelCache() + interrupt = True - def interrupt(): - raise KeyboardInterrupt() + def read(*_): + if interrupt: + raise KeyboardInterrupt() + return "model" + cache = cache_reading(read) with self.assertRaises(KeyboardInterrupt): - cache.get(KEY, interrupt) + cache.get(API, *KEY) - self.assertEqual(cache.get(KEY, lambda: "model").aliases, "model") + interrupt = False + self.assertEqual(cache.get(API, *KEY).aliases, "model") def test_keys_on_both_the_store_and_the_model(self): - cache = ModelCache() reads = [] + errors = {("c", "1"): RateLimitExceededError(status=429)} - def get(store, model, error=None): - def load(): - reads.append((store, model)) - if error is not None: - raise error - return f"{store}/{model}" + def read(store, model): + reads.append((store, model)) + if (store, model) in errors: + raise errors[(store, model)] + return f"{store}/{model}" + + cache = cache_reading(read) - return cache.get((store, model), load) + def get(store, model): + return cache.get(API, store, model) self.assertEqual(get("a", "1").aliases, "a/1") self.assertEqual(get("b", "1").aliases, "b/1") @@ -144,7 +157,7 @@ def load(): self.assertTrue(get("a", "2").hit) self.assertEqual(reads, [("a", "1"), ("b", "1"), ("a", "2")]) - get("c", "1", RateLimitExceededError(status=429)) + get("c", "1") self.assertEqual(get("d", "1").aliases, "d/1") self.assertEqual(get("c", "2").aliases, "c/2") self.assertEqual(reads[3:], [("c", "1"), ("d", "1"), ("c", "2")]) From 9341f8d0bfce0993ce7bf855cdae8cb15d0a201b Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 30 Nov 2026 17:04:14 +0530 Subject: [PATCH 30/38] perf: resolve model aliases in linear time Following a long alias chain re-walked it for every relation and kept a set of each relation's chain, so one long chain was cubic in time and quadratic in memory. Memoize each relation's final relation in a loop, and number each alias tree once so the self-userset rule is two comparisons. --- openfga_sdk/client/_equivalent_checks.py | 106 ++++++++++++++++------- test/client/equivalent_checks_test.py | 43 +++++++++ 2 files changed, 119 insertions(+), 30 deletions(-) diff --git a/openfga_sdk/client/_equivalent_checks.py b/openfga_sdk/client/_equivalent_checks.py index 4fe16942..650e0ad3 100644 --- a/openfga_sdk/client/_equivalent_checks.py +++ b/openfga_sdk/client/_equivalent_checks.py @@ -116,14 +116,13 @@ def __init__(self, model: AuthorizationModel | None) -> None: if model is None: raise ValueError("The authorization model response is empty") - # type -> relation -> (final relation, every relation in the chain), or None - # if the chain points to a missing relation or loops. - self._types: dict[str, dict[str, tuple[str, frozenset[str]] | None]] = {} + # type -> relation -> where it ends, or None if its chain points to a missing + # relation or loops. + self._types: dict[str, dict[str, _ResolvedRelation | None]] = {} for type_definition in model.type_definitions or []: - relations = type_definition.relations or {} - self._types[type_definition.type] = { - relation: _resolved_chain(relations, relation) for relation in relations - } + self._types[type_definition.type] = _resolve_aliases( + type_definition.relations or {} + ) def final_relation(self, check: ClientBatchCheckItem) -> str | None: """ @@ -151,14 +150,13 @@ def final_relation(self, check: ClientBatchCheckItem) -> str | None: resolved = relations[check.relation] if resolved is None: return None - final_relation, chain = resolved # The server says a userset always has its own relation on its own object, at # every step of a chain, so a merged check could get a different answer. if ( userset_separator and (user_type, user_id) == (object_type, object_id) - and user_relation in chain + and resolved.passes_through(relations[user_relation]) ): return None @@ -170,7 +168,7 @@ def final_relation(self, check: ClientBatchCheckItem) -> str | None: if len(set(tuple_keys)) != len(tuple_keys): return None - return final_relation + return resolved.final def resolve( @@ -313,33 +311,81 @@ def _alias_target(rewrite: Userset | None) -> str | None: return target.relation -def _alias_chain(relations: dict[str, Userset], relation: str) -> list[str] | None: +@dataclass(frozen=True) +class _ResolvedRelation: """ - Follow aliases from `relation`. Return every relation on the way, ending at the final - relation, or None if the chain points to a missing relation or loops. + Where a relation ends after following its aliases. + + The relations that end at the same final relation form a tree, with each relation + under the one it aliases. `start` and `end` number the relation in a walk of that + tree, so the relations under it, and only those, have a `start` in [start, end). """ - chain = [relation] - while True: - if chain[-1] not in relations: - return None - target = _alias_target(relations[chain[-1]]) - if target is None: - return chain + final: str + start: int + end: int - if target in chain: - return None + def passes_through(self, other: "_ResolvedRelation | None") -> bool: + """ + Return whether following this relation's aliases reaches `other`. + """ + return other is not None and other.start <= self.start < other.end - chain.append(target) +def _resolve_aliases( + relations: dict[str, Userset], +) -> dict[str, _ResolvedRelation | None]: + """ + Follow the aliases of every relation of a type. A relation is None if its chain + points to a missing relation or loops. Each relation is visited a fixed number of + times and nothing recurses, so a long chain can't make this slow or run out of stack. + """ + targets = { + relation: _alias_target(rewrite) for relation, rewrite in relations.items() + } + + # Follow each chain until it reaches a relation that's already been followed. + finals: dict[str, str | None] = {} + for relation in relations: + path: set[str] = set() + current = relation + while current not in finals: + if current not in relations or current in path: + break + path.add(current) + if targets[current] is None: + finals[current] = current + break + current = targets[current] + final = finals.get(current) + for step in path: + finals[step] = final + + aliased_by: dict[str, list[str]] = {} + for relation, target in targets.items(): + if target is not None and finals[relation] is not None: + aliased_by.setdefault(target, []).append(relation) + + resolved: dict[str, _ResolvedRelation | None] = dict.fromkeys(relations) + starts: dict[str, int] = {} + position = 0 + for final in relations: + if finals[final] != final: + continue + stack = [final] + while stack: + relation = stack[-1] + if relation in starts: + stack.pop() + resolved[relation] = _ResolvedRelation( + final, starts[relation], position + ) + else: + starts[relation] = position + position += 1 + stack.extend(aliased_by.get(relation, [])) -def _resolved_chain( - relations: dict[str, Userset], relation: str -) -> tuple[str, frozenset[str]] | None: - chain = _alias_chain(relations, relation) - if chain is None: - return None - return chain[-1], frozenset(chain) + return resolved def _context_key(context) -> tuple: diff --git a/test/client/equivalent_checks_test.py b/test/client/equivalent_checks_test.py index 21b2ddf9..27b92401 100644 --- a/test/client/equivalent_checks_test.py +++ b/test/client/equivalent_checks_test.py @@ -288,6 +288,49 @@ def test_rewrites_that_only_look_like_aliases_are_not_merged(can_view): assert sent(groups) == [("a", "viewer", ["a"]), ("b", "can_view", ["b"])] +def test_a_long_alias_chain_is_resolved(): + # r0 -> r1 -> ... -> r4999, deeper than Python's recursion limit. + length = 5000 + relations = { + f"r{i}": Userset( + computed_userset=ObjectRelation(object="", relation=f"r{i + 1}") + ) + for i in range(length - 1) + } + relations[f"r{length - 1}"] = Userset(this={}) + model = AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", + schema_version="1.1", + type_definitions=[ + TypeDefinition(type="user"), + TypeDefinition(type="document", relations=relations), + ], + ) + + def userset_check(correlation_id, user_relation, relation): + return ClientBatchCheckItem( + user=f"document:1#{user_relation}", + relation=relation, + object="document:1", + correlation_id=correlation_id, + ) + + groups = resolve( + ModelAliases(model), + [ + check("a", relation="r0"), + userset_check("b", "r2500", "r0"), + userset_check("c", "r0", "r2500"), + ], + ) + + assert sent(groups) == [ + ("a", "r4999", ["a"]), + ("b", "r0", ["b"]), + ("c", "r4999", ["c"]), + ] + + def test_model_aliases_rejects_an_empty_model(): with pytest.raises(ValueError, match="The authorization model response is empty"): ModelAliases(None) From 8009f4e39271d2a2c2f11d2cb8b564cc55e54f3e Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 30 Nov 2026 19:04:28 +0530 Subject: [PATCH 31/38] test: cover more alias trees and document how aliases are numbered --- openfga_sdk/client/_equivalent_checks.py | 39 ++++++++++-- test/client/equivalent_checks_test.py | 79 ++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 5 deletions(-) diff --git a/openfga_sdk/client/_equivalent_checks.py b/openfga_sdk/client/_equivalent_checks.py index 650e0ad3..c040aeaf 100644 --- a/openfga_sdk/client/_equivalent_checks.py +++ b/openfga_sdk/client/_equivalent_checks.py @@ -317,8 +317,21 @@ class _ResolvedRelation: Where a relation ends after following its aliases. The relations that end at the same final relation form a tree, with each relation - under the one it aliases. `start` and `end` number the relation in a walk of that - tree, so the relations under it, and only those, have a `start` in [start, end). + under the one it aliases. A depth-first walk of the tree gives each relation a + `start` when the walk reaches it, and an `end` when the walk has finished + everything under it. So the relations under a relation, and only those, have a + `start` in its [start, end). + + For example, with `define owner: [user]`, `define writer: owner`, + `define admin: owner` and `define member: writer`, the walk gives: + + owner [0, 4) + admin [1, 2) + writer [2, 4) + member [3, 4) + + Following member's aliases reaches writer, because 2 <= 3 < 4, and owner, because + 0 <= 3 < 4. It doesn't reach admin, because 3 isn't in [1, 2). """ final: str @@ -337,14 +350,25 @@ def _resolve_aliases( ) -> dict[str, _ResolvedRelation | None]: """ Follow the aliases of every relation of a type. A relation is None if its chain - points to a missing relation or loops. Each relation is visited a fixed number of - times and nothing recurses, so a long chain can't make this slow or run out of stack. + points to a missing relation or loops. + + It works in two steps: + + 1. Find each relation's final relation. Each chain is followed only until it + reaches a relation whose final relation is already known, so every relation is + followed once, whatever order the relations are in. + 2. Walk each final relation's tree of aliases to number it, as described in + `_ResolvedRelation`. Relations whose chain is broken aren't in any tree. + + Each relation is visited a fixed number of times and nothing recurses, so a long + chain can't make this slow or run out of stack. """ targets = { relation: _alias_target(rewrite) for relation, rewrite in relations.items() } - # Follow each chain until it reaches a relation that's already been followed. + # Step 1: follow each chain until it reaches a relation that's already been + # followed, then give every relation on the way the same final relation. finals: dict[str, str | None] = {} for relation in relations: path: set[str] = set() @@ -361,11 +385,15 @@ def _resolve_aliases( for step in path: finals[step] = final + # The aliases of each relation, leaving out broken chains. aliased_by: dict[str, list[str]] = {} for relation, target in targets.items(): if target is not None and finals[relation] is not None: aliased_by.setdefault(target, []).append(relation) + # Step 2: walk each tree depth-first from its final relation to set each + # relation's [start, end). A relation stays on the stack until everything under + # it is done, so it's seen twice: first to set its start, then its end. resolved: dict[str, _ResolvedRelation | None] = dict.fromkeys(relations) starts: dict[str, int] = {} position = 0 @@ -376,6 +404,7 @@ def _resolve_aliases( while stack: relation = stack[-1] if relation in starts: + # Everything under it is done. stack.pop() resolved[relation] = _ResolvedRelation( final, starts[relation], position diff --git a/test/client/equivalent_checks_test.py b/test/client/equivalent_checks_test.py index 27b92401..b087bfb7 100644 --- a/test/client/equivalent_checks_test.py +++ b/test/client/equivalent_checks_test.py @@ -331,6 +331,85 @@ def userset_check(correlation_id, user_relation, relation): ] +def alias(relation): + return Userset(computed_userset=ObjectRelation(object="", relation=relation)) + + +# Aliases are listed before the relations they point to, and there are two trees and a +# broken chain in the same type. +# define member: writer +# define writer: owner +# define admin: owner +# define owner: [user] +# define can_edit: editor +# define editor: [user] +# define via_stale: stale +# define stale: removed (missing) +ALIAS_TREES = ModelAliases( + AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", + schema_version="1.1", + type_definitions=[ + TypeDefinition(type="user"), + TypeDefinition( + type="document", + relations={ + "member": alias("writer"), + "writer": alias("owner"), + "admin": alias("owner"), + "owner": Userset(this={}), + "can_edit": alias("editor"), + "editor": Userset(this={}), + "via_stale": alias("stale"), + "stale": alias("removed"), + }, + ), + ], + ) +) + + +@pytest.mark.parametrize( + "user, relation, final", + [ + ("user:anne", "member", "owner"), + ("user:anne", "can_edit", "editor"), + ("document:1#admin", "writer", "owner"), + ("document:1#admin", "member", "owner"), + ("document:1#member", "writer", "owner"), + ("document:1#writer", "member", None), + ("document:1#writer", "writer", None), + ("document:1#owner", "admin", None), + ("document:1#editor", "member", "owner"), + ("document:1#member", "can_edit", "editor"), + ("user:anne", "via_stale", None), + ("user:anne", "stale", None), + ("document:1#stale", "member", "owner"), + ], + ids=[ + "alias-listed-before-its-target", + "second-tree", + "userset-on-a-sibling-branch", + "userset-on-a-sibling-branch-of-a-chain", + "userset-under-the-relation-checked", + "userset-in-the-chain", + "userset-is-the-relation-checked", + "userset-is-the-final-relation", + "userset-in-another-tree", + "check-in-another-tree", + "alias-of-a-broken-chain", + "broken-chain", + "userset-on-a-broken-chain", + ], +) +def test_final_relation_with_several_alias_trees(user, relation, final): + item = ClientBatchCheckItem( + user=user, relation=relation, object="document:1", correlation_id="a" + ) + + assert ALIAS_TREES.final_relation(item) == final + + def test_model_aliases_rejects_an_empty_model(): with pytest.raises(ValueError, match="The authorization model response is empty"): ModelAliases(None) From 0f1425d4dab7c22cb10a44bca183dc0ec9c58b1c Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 30 Nov 2026 20:05:57 +0530 Subject: [PATCH 32/38] test: pin shared cases to the openfga/language#718 merge commit --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 632b3e2b..f5f5d58f 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases # openfga/language commit to copy the shared equivalent-checks cases from -LANGUAGE_REF ?= b7cc548b50e1479dc4db38d208bd735653446d62 +LANGUAGE_REF ?= 41f78349717678d97aade591cf12c78541fae77f # Install/update dependencies sync: From 0c73f59a87a360dc595e62eee7359c3c96125646 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 30 Nov 2026 20:15:05 +0530 Subject: [PATCH 33/38] docs: drop a redundant sentence about the option being off --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f481cf58..c9855787 100644 --- a/README.md +++ b/README.md @@ -984,7 +984,7 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), # response.checks_sent is how many checks were sent to the server ``` -The option is off by default, and nothing changes while it is off. Leaving it out or setting it to `None` keeps it off. Any other value that isn't a bool, like `"true"`, fails with a validation error. +The option is off by default. Leaving it out or setting it to `None` keeps it off. Any other value that isn't a bool, like `"true"`, fails with a validation error. To find aliases, the SDK reads the authorization model the first time it needs it and keeps it in memory, so create the client once and reuse it. Each client keeps up to 32 models and drops the least recently used one. The call fails before any check is sent when: From bf9eccce725de776836308ff88b7e75c3873db4d Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Mon, 30 Nov 2026 21:52:15 +0530 Subject: [PATCH 34/38] fix: catch token failures where the model read gets its token --- openfga_sdk/client/_batch_check_merge.py | 18 -------- openfga_sdk/client/_model_cache.py | 41 ++++++++++++++--- openfga_sdk/sync/client/_model_cache.py | 41 ++++++++++++++--- test/client/batch_check_merge_test.py | 51 ++++++++++++++++++++++ test/sync/client/batch_check_merge_test.py | 51 ++++++++++++++++++++++ 5 files changed, 170 insertions(+), 32 deletions(-) diff --git a/openfga_sdk/client/_batch_check_merge.py b/openfga_sdk/client/_batch_check_merge.py index f69a01cd..1cc06407 100644 --- a/openfga_sdk/client/_batch_check_merge.py +++ b/openfga_sdk/client/_batch_check_merge.py @@ -38,24 +38,6 @@ def model_read_kwargs( return kwargs -class TokenWatch: - """ - Tells whether a failed request failed because the SDK couldn't get an access token - for it. A request first gets a new token if there's none or the cached one is close - to expiring, and a successful token request always replaces the cached token. So if - the token was due for renewal before the request, and is the same one after it - failed, the token request is what failed. - """ - - def __init__(self, oauth2_client) -> None: - self._oauth2_client = oauth2_client - self._renewing = oauth2_client is not None and not oauth2_client._token_valid() - self._token = oauth2_client._token_state if self._renewing else None - - def token_request_failed(self) -> bool: - return self._renewing and self._oauth2_client._token_state is self._token - - def log_model_read_failure( error: Exception, store_id: str, authorization_model_id: str ) -> None: diff --git a/openfga_sdk/client/_model_cache.py b/openfga_sdk/client/_model_cache.py index e13ba49f..734f22d1 100644 --- a/openfga_sdk/client/_model_cache.py +++ b/openfga_sdk/client/_model_cache.py @@ -4,10 +4,10 @@ """ import asyncio +import copy from openfga_sdk.api.open_fga_api import OpenFgaApi from openfga_sdk.client._batch_check_merge import ( - TokenWatch, log_model_read_failure, model_read_kwargs, ) @@ -94,22 +94,49 @@ async def _read( options: dict[str, int | str | dict[str, int | str]] | None, ) -> ModelAliases: """ - Read the model and work out its aliases. The read is never retried. If it fails - because the SDK couldn't get an access token, the error is a TokenRequestFailed. + Read the model and work out its aliases. The read is never retried. If the SDK + can't get an access token for it, the error is a TokenRequestFailed. """ - token = TokenWatch(api._oauth2_client) try: - response = await api.read_authorization_model( + response = await _model_reader(api).read_authorization_model( authorization_model_id, **model_read_kwargs(options) ) return ModelAliases(response.authorization_model) + except TokenRequestFailed: + raise except Exception as error: - if token.token_request_failed(): - raise TokenRequestFailed(error) from error log_model_read_failure(error, store_id, authorization_model_id) raise +class _TokenRequests: + """ + Gets access tokens with an OAuth2 client, and raises a TokenRequestFailed if it + can't, so the failure isn't mistaken for a failed model read. + """ + + def __init__(self, oauth2_client) -> None: + self._oauth2_client = oauth2_client + + async def get_authentication_header(self, client): + try: + return await self._oauth2_client.get_authentication_header(client) + except Exception as error: + raise TokenRequestFailed(error) from error + + +def _model_reader(api: OpenFgaApi) -> OpenFgaApi: + """ + Return a copy of `api` that gets its access token through _TokenRequests. It shares + the OAuth2 client, and so the token, with `api`. + """ + if api._oauth2_client is None: + return api + reader = copy.copy(api) + reader._oauth2_client = _TokenRequests(api._oauth2_client) + return reader + + def _retrieve_exception(task: asyncio.Task) -> None: # Marks the error as seen, so asyncio doesn't log it when no caller is left waiting. if not task.cancelled(): diff --git a/openfga_sdk/sync/client/_model_cache.py b/openfga_sdk/sync/client/_model_cache.py index 5d0485a3..162762fd 100644 --- a/openfga_sdk/sync/client/_model_cache.py +++ b/openfga_sdk/sync/client/_model_cache.py @@ -3,12 +3,12 @@ `merge_equivalent_checks` option. Calls for the same model share one in-flight read. """ +import copy import threading from concurrent.futures import Future from openfga_sdk.client._batch_check_merge import ( - TokenWatch, log_model_read_failure, model_read_kwargs, ) @@ -91,17 +91,44 @@ def _read( options: dict[str, int | str | dict[str, int | str]] | None, ) -> ModelAliases: """ - Read the model and work out its aliases. The read is never retried. If it fails - because the SDK couldn't get an access token, the error is a TokenRequestFailed. + Read the model and work out its aliases. The read is never retried. If the SDK + can't get an access token for it, the error is a TokenRequestFailed. """ - token = TokenWatch(api._oauth2_client) try: - response = api.read_authorization_model( + response = _model_reader(api).read_authorization_model( authorization_model_id, **model_read_kwargs(options) ) return ModelAliases(response.authorization_model) + except TokenRequestFailed: + raise except Exception as error: - if token.token_request_failed(): - raise TokenRequestFailed(error) from error log_model_read_failure(error, store_id, authorization_model_id) raise + + +class _TokenRequests: + """ + Gets access tokens with an OAuth2 client, and raises a TokenRequestFailed if it + can't, so the failure isn't mistaken for a failed model read. + """ + + def __init__(self, oauth2_client) -> None: + self._oauth2_client = oauth2_client + + def get_authentication_header(self, client): + try: + return self._oauth2_client.get_authentication_header(client) + except Exception as error: + raise TokenRequestFailed(error) from error + + +def _model_reader(api: OpenFgaApi) -> OpenFgaApi: + """ + Return a copy of `api` that gets its access token through _TokenRequests. It shares + the OAuth2 client, and so the token, with `api`. + """ + if api._oauth2_client is None: + return api + reader = copy.copy(api) + reader._oauth2_client = _TokenRequests(api._oauth2_client) + return reader diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py index ecf376f0..5bc091f9 100644 --- a/test/client/batch_check_merge_test.py +++ b/test/client/batch_check_merge_test.py @@ -1,6 +1,8 @@ import asyncio import json +from dataclasses import replace +from datetime import datetime from unittest import IsolatedAsyncioTestCase from unittest.mock import patch @@ -8,6 +10,7 @@ import urllib3 from openfga_sdk import rest +from openfga_sdk.api_client import ApiClient from openfga_sdk.client import ClientConfiguration from openfga_sdk.client.client import OpenFgaClient from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem @@ -95,6 +98,23 @@ def no_token_issued(): return mock_response("{}") +def token_due_for_renewal_when_used(client): + """ + Make the client's token due for renewal right when a request gets it, as if it got + there just after any earlier check. + """ + oauth2_client = client._api._oauth2_client + update_params_for_auth = ApiClient.update_params_for_auth + + async def renewal_due(api_client, *args, **kwargs): + oauth2_client._token_state = replace( + oauth2_client._token_state, expiry_time=datetime.now() + ) + return await update_params_for_auth(api_client, *args, **kwargs) + + return patch.object(ApiClient, "update_params_for_auth", renewal_due) + + def token_configuration(): """ A configuration that gets a token from TOKEN_URL, and retries a failed token @@ -663,6 +683,37 @@ async def test_fails_when_the_model_read_cannot_renew_the_token( mock_fallback.assert_not_called() + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_fails_like_the_option_off_when_the_token_is_due_just_before_the_read( + self, mock_request, mock_fallback + ): + token_requests = [] + for merge in [False, True]: + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + await client.batch_check(ClientBatchCheckRequest(checks=checks())) + server.token = rate_limited + + with token_due_for_renewal_when_used(client): + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + with self.assertRaises(RateLimitExceededError): + await client.batch_check( + ClientBatchCheckRequest(checks=checks()), + options={"merge_equivalent_checks": merge}, + ) + + self.assertEqual(server.model_reads, 0) + self.assertEqual(len(server.sent), 1) + token_requests.append(server.token_requests) + + self.assertEqual(token_requests[1], token_requests[0]) + mock_fallback.assert_not_called() + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") @patch.object(rest.RESTClientObject, "request") async def test_sends_unmerged_when_the_read_fails_after_renewing_the_token( diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py index a66b7175..01e306c3 100644 --- a/test/sync/client/batch_check_merge_test.py +++ b/test/sync/client/batch_check_merge_test.py @@ -1,6 +1,8 @@ import json from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from datetime import datetime from unittest import TestCase from unittest.mock import patch @@ -20,6 +22,7 @@ ValidationException, ) from openfga_sdk.sync import rest +from openfga_sdk.sync.api_client import ApiClient from openfga_sdk.sync.client.client import OpenFgaClient from openfga_sdk.telemetry.attributes import TelemetryAttributes from openfga_sdk.telemetry.metrics import TelemetryMetrics @@ -74,6 +77,23 @@ def no_token_issued(): return mock_response("{}") +def token_due_for_renewal_when_used(client): + """ + Make the client's token due for renewal right when a request gets it, as if it got + there just after any earlier check. + """ + oauth2_client = client._api._oauth2_client + update_params_for_auth = ApiClient.update_params_for_auth + + def renewal_due(api_client, *args, **kwargs): + oauth2_client._token_state = replace( + oauth2_client._token_state, expiry_time=datetime.now() + ) + return update_params_for_auth(api_client, *args, **kwargs) + + return patch.object(ApiClient, "update_params_for_auth", renewal_due) + + class FakeServer: """ Answers token requests, model reads and BatchCheck requests, and records what was @@ -505,6 +525,37 @@ def test_fails_when_the_model_read_cannot_renew_the_token( mock_fallback.assert_not_called() + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_fails_like_the_option_off_when_the_token_is_due_just_before_the_read( + self, mock_request, mock_fallback + ): + token_requests = [] + for merge in [False, True]: + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + client.batch_check(ClientBatchCheckRequest(checks=checks())) + server.token = rate_limited + + with token_due_for_renewal_when_used(client): + with self.assertNoLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ): + with self.assertRaises(RateLimitExceededError): + client.batch_check( + ClientBatchCheckRequest(checks=checks()), + options={"merge_equivalent_checks": merge}, + ) + + self.assertEqual(server.model_reads, 0) + self.assertEqual(len(server.sent), 1) + token_requests.append(server.token_requests) + + self.assertEqual(token_requests[1], token_requests[0]) + mock_fallback.assert_not_called() + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") @patch.object(rest.RESTClientObject, "request") def test_sends_unmerged_when_the_read_fails_after_renewing_the_token( From 8a3389ad5711d27033b335fff264fa0464e5f036 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Tue, 1 Dec 2026 23:16:15 +0530 Subject: [PATCH 35/38] ci: check the equivalent-checks cases match LANGUAGE_REF --- .github/workflows/main.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 2295db83..8fb4e5fa 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -60,6 +60,20 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} slug: openfga/python-sdk + equivalent-checks-cases: + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Check the equivalent-checks cases match openfga/language at LANGUAGE_REF + run: | + make update-equivalent-checks-cases + git diff --exit-code test/data/ + verify-version: runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/v') From ab8b129c1ca6c509d0cc735abd59395d4ef76af8 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Tue, 1 Dec 2026 23:16:15 +0530 Subject: [PATCH 36/38] refactor: address review comments --- README.md | 2 ++ openfga_sdk/client/_equivalent_checks.py | 19 ++++++++++++------- openfga_sdk/client/_model_cache.py | 6 ++++-- openfga_sdk/sync/client/_model_cache.py | 3 ++- 4 files changed, 20 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index c9855787..ccab8032 100644 --- a/README.md +++ b/README.md @@ -993,6 +993,8 @@ To find aliases, the SDK reads the authorization model the first time it needs i - the SDK can't get an access token, after retrying as usual. The checks need the same token, so the call would fail with the option off too. - the credentials can't read the model (a 401 or 403). If your credentials can only run checks, leave the option off. +Calls running at the same time share one read, sent with the headers of the call that started it. If your calls pass different credentials in `headers`, a call can fail with the 401 or 403 of another call's read. + If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. The next call reads the model again. Compared with leaving the option off, a call: diff --git a/openfga_sdk/client/_equivalent_checks.py b/openfga_sdk/client/_equivalent_checks.py index c040aeaf..738f3ffc 100644 --- a/openfga_sdk/client/_equivalent_checks.py +++ b/openfga_sdk/client/_equivalent_checks.py @@ -24,6 +24,8 @@ from openfga_sdk.models.userset import Userset +# Same rule the server applies to BatchCheckItem.correlation_id: +# https://github.com/openfga/api/blob/c0650ce2169bcb39a72d73841fb531c200e32248/openfga/v1/openfga_service.proto#L1447 CORRELATION_ID_PATTERN = re.compile(r"^[\w\d-]{1,36}$", re.ASCII) _MISSING = ("missing",) @@ -151,8 +153,11 @@ def final_relation(self, check: ClientBatchCheckItem) -> str | None: if resolved is None: return None - # The server says a userset always has its own relation on its own object, at - # every step of a chain, so a merged check could get a different answer. + # The legacy Check algorithm says a userset always has its own relation on its + # own object, at every step of a chain, so a merged check could get a different + # answer. The weighted graph algorithm drops this rule, so this check can go once + # supported servers no longer use the legacy one: + # https://openfga.dev/blog/weighted-graph-upcoming-changes#5-self-referential-usersets if ( userset_separator and (user_type, user_id) == (object_type, object_id) @@ -161,6 +166,8 @@ def final_relation(self, check: ClientBatchCheckItem) -> str | None: return None # The server's answer can depend on which of these tuples it reads first. + # https://github.com/openfga/openfga/pull/3410 makes the server reject copies + # with different conditions, but servers without it still accept them. tuple_keys = [ (contextual_tuple.user, contextual_tuple.relation, contextual_tuple.object) for contextual_tuple in check.contextual_tuples or [] @@ -180,22 +187,20 @@ def resolve( The result is deterministic: the same model and checks, in the same order, give the same groups and IDs. Each group is placed at the position of its first check. """ - finals = [aliases.final_relation(check) for check in checks] + checks_with_finals = [(aliases.final_relation(check), check) for check in checks] # Comparing context and contextual tuples is the slow part, so only do it for checks # that share a final relation, user and object with another check. shared = Counter( (final_relation, check.user, check.object) - for final_relation, check in zip(finals, checks, strict=True) + for final_relation, check in checks_with_finals if final_relation is not None ) entries: list[tuple[str, ClientBatchCheckItem | tuple]] = [] groups: dict[tuple, list[ClientBatchCheckItem]] = {} - for position, (final_relation, check) in enumerate( - zip(finals, checks, strict=True) - ): + for position, (final_relation, check) in enumerate(checks_with_finals): if final_relation is None: entries.append(("as_is", check)) continue diff --git a/openfga_sdk/client/_model_cache.py b/openfga_sdk/client/_model_cache.py index 734f22d1..a11dc2d6 100644 --- a/openfga_sdk/client/_model_cache.py +++ b/openfga_sdk/client/_model_cache.py @@ -38,7 +38,8 @@ async def get( ) -> ModelLookup: """ Return the aliases of an authorization model, reading the model with `api` if - it isn't cached. If the read fails, the lookup has its error. + it isn't cached. If the read fails, the lookup has its error. Calls that overlap + share one read, sent with the options of the call that started it. :param header(options) - Custom headers to send alongside the model read """ key = (store_id, authorization_model_id) @@ -138,6 +139,7 @@ def _model_reader(api: OpenFgaApi) -> OpenFgaApi: def _retrieve_exception(task: asyncio.Task) -> None: - # Marks the error as seen, so asyncio doesn't log it when no caller is left waiting. + # Marks the error as seen, so asyncio doesn't warn that it was never retrieved + # when every caller timed out before the shared read failed. if not task.cancelled(): task.exception() diff --git a/openfga_sdk/sync/client/_model_cache.py b/openfga_sdk/sync/client/_model_cache.py index 162762fd..c1e4af3d 100644 --- a/openfga_sdk/sync/client/_model_cache.py +++ b/openfga_sdk/sync/client/_model_cache.py @@ -41,7 +41,8 @@ def get( ) -> ModelLookup: """ Return the aliases of an authorization model, reading the model with `api` if - it isn't cached. If the read fails, the lookup has its error. + it isn't cached. If the read fails, the lookup has its error. Calls that overlap + share one read, sent with the options of the call that started it. :param header(options) - Custom headers to send alongside the model read """ key = (store_id, authorization_model_id) From d72aa55d697c6f1ce52372e1b5af7d11d6747ba5 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Wed, 2 Dec 2026 11:05:27 +0530 Subject: [PATCH 37/38] chore: check the equivalent-checks cases with make instead of CI --- .github/workflows/main.yaml | 14 -------------- Makefile | 7 ++++++- 2 files changed, 6 insertions(+), 15 deletions(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 8fb4e5fa..2295db83 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -60,20 +60,6 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} slug: openfga/python-sdk - equivalent-checks-cases: - runs-on: ubuntu-latest - permissions: - contents: read - - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Check the equivalent-checks cases match openfga/language at LANGUAGE_REF - run: | - make update-equivalent-checks-cases - git diff --exit-code test/data/ - verify-version: runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/v') diff --git a/Makefile b/Makefile index f5f5d58f..724dcb89 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases +.PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases check-equivalent-checks-cases # openfga/language commit to copy the shared equivalent-checks cases from LANGUAGE_REF ?= 41f78349717678d97aade591cf12c78541fae77f @@ -34,6 +34,10 @@ fix: update-equivalent-checks-cases: curl -fsSL https://raw.githubusercontent.com/openfga/language/$(LANGUAGE_REF)/tests/data/equivalent-checks-cases.json -o test/data/equivalent-checks-cases.json +# Check that the committed equivalent-checks cases match openfga/language at LANGUAGE_REF +check-equivalent-checks-cases: + curl -fsSL https://raw.githubusercontent.com/openfga/language/$(LANGUAGE_REF)/tests/data/equivalent-checks-cases.json | diff -q - test/data/equivalent-checks-cases.json + # Run checks (lint + test) check: lint fmt test @@ -48,4 +52,5 @@ doc: @echo " fix - Fix fixable linting and formatting issues" @echo " check - Run both linting and tests" @echo " update-equivalent-checks-cases - Copy the shared equivalent-checks cases from openfga/language (LANGUAGE_REF=)" + @echo " check-equivalent-checks-cases - Check the committed cases match openfga/language at LANGUAGE_REF" @echo " doc - Show this help message" From 427ff3f296dc0991bc3b3e4e3414358c13707265 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Wed, 2 Dec 2026 13:30:41 +0530 Subject: [PATCH 38/38] docs: say checks_sent is None when off, and how cache misses are counted --- README.md | 2 +- docs/opentelemetry.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ccab8032..b06adca2 100644 --- a/README.md +++ b/README.md @@ -981,7 +981,7 @@ options = { "merge_equivalent_checks": True, } response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), options) -# response.checks_sent is how many checks were sent to the server +# response.checks_sent is how many checks were sent to the server, or None when the option is off ``` The option is off by default. Leaving it out or setting it to `None` keeps it off. Any other value that isn't a bool, like `"true"`, fails with a validation error. diff --git a/docs/opentelemetry.md b/docs/opentelemetry.md index c534a796..630ba08e 100644 --- a/docs/opentelemetry.md +++ b/docs/opentelemetry.md @@ -30,7 +30,7 @@ If you configure the OpenTelemetry SDK, these metrics will be exported and sent | `fga-client.batch_check.checks_requested` | Counter | Yes | Checks passed to `batch_check` with `merge_equivalent_checks` on | | `fga-client.batch_check.checks_sent` | Counter | Yes | Checks actually sent by `batch_check` with `merge_equivalent_checks` on | | `fga-client.batch_check.merge_fallback` | Counter | Yes | `batch_check` calls sent unmerged because the model read failed with an error that doesn't fail the call (such as a 429, a 5xx or a timeout), or the checks couldn't be grouped. Has the `http.response.status_code` of the failed read, when there is one | -| `fga-client.model_cache.lookup` | Counter | Yes | Authorization model cache lookups by `merge_equivalent_checks`, with a `hit` or `miss` result | +| `fga-client.model_cache.lookup` | Counter | Yes | Authorization model cache lookups by `merge_equivalent_checks`, one per `batch_check` call, with a `hit` or `miss` result. Calls that wait for the same model read each count a miss, so there can be more misses than reads | ### Supported Attributes