Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
f490b44
feat: merge equivalent checks in BatchCheck (beta)
Siddhant-K-code Nov 12, 2026
3f707aa
fix: tighten merge_equivalent_checks validation
Siddhant-K-code Nov 12, 2026
e07c07f
test: cover an empty model response and the checks_sent setter
Siddhant-K-code Nov 12, 2026
fae9939
docs: note that merge_equivalent_checks may change while in beta
Siddhant-K-code Nov 13, 2026
4805d23
fix: count merged checks even when a request fails
Siddhant-K-code Nov 13, 2026
45d733c
fix: don't keep a model read that finished before it was registered
Siddhant-K-code Nov 13, 2026
d579913
test: check the sent context and contextual tuples in shared cases
Siddhant-K-code Nov 22, 2026
ccf64fb
test: update shared cases to declare contextual tuple condition params
Siddhant-K-code Nov 23, 2026
23b945e
fix: send checks with deeply nested context as is when merging
Siddhant-K-code Nov 23, 2026
1d4d01a
test: check that merged batch checks send the consistency option
Siddhant-K-code Nov 23, 2026
882d25e
fix: fail early when the model doesn't exist and retry transient mode…
Siddhant-K-code Nov 23, 2026
ce0957a
fix: fail the call when the credentials can't read the model
Siddhant-K-code Nov 24, 2026
16a29a2
docs: drop beta wording from merge_equivalent_checks
Siddhant-K-code Nov 24, 2026
f74eac1
test: update shared equivalent-checks cases to openfga/language@153c7a9
Siddhant-K-code Nov 24, 2026
c1f6de3
refactor: address review on merge_equivalent_checks
Siddhant-K-code Nov 25, 2026
8d27822
Merge remote-tracking branch 'origin/main' into siddhant-k-code-optim…
Siddhant-K-code Nov 25, 2026
56574bc
fix: don't retry the model read for merge_equivalent_checks
Siddhant-K-code Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -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 ?= 153c7a93ef8775b81ef1e53a5a6a3fa04d469803

# Install/update dependencies
sync:
Expand Down Expand Up @@ -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=<commit>
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

Expand All @@ -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=<commit>)"
@echo " doc - Show this help message"
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,45 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks),
# ]
```

###### Merge equivalent checks

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.

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 = {
# 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 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.

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. 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).

Comment thread
Siddhant-K-code marked this conversation as resolved.
Resolved
##### Client Batch Check


Expand Down
17 changes: 11 additions & 6 deletions docs/opentelemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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

| 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 |
Expand Down
112 changes: 112 additions & 0 deletions openfga_sdk/client/_batch_check_merge.py
Original file line number Diff line number Diff line change
@@ -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
)
104 changes: 104 additions & 0 deletions openfga_sdk/client/_model_cache_base.py
Original file line number Diff line number Diff line change
@@ -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)
Loading