Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 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
688c812
Merge remote-tracking branch 'origin/main' into siddhant-k-code-optim…
Siddhant-K-code Nov 27, 2026
60aa1e8
test: check the model read isn't retried on network errors
Siddhant-K-code Nov 27, 2026
7550d14
refactor: make the merge modules private
Siddhant-K-code Nov 27, 2026
77a90b1
refactor: return the responses from _send_batch_checks and share the …
Siddhant-K-code Nov 27, 2026
429aeac
docs: say when batch_check calls are sent unmerged
Siddhant-K-code Nov 27, 2026
70d49d7
test: update the shared equivalent-checks cases to 67
Siddhant-K-code Nov 27, 2026
fbd127a
docs: say which token request failures fail the call
Siddhant-K-code Nov 27, 2026
6f8957e
fix: fail the call when the token request fails, instead of falling back
Siddhant-K-code Nov 27, 2026
d7d3b2c
fix: tell token failures apart from model read failures
Siddhant-K-code Nov 27, 2026
73c5b24
test: pin the shared equivalent-checks cases to openfga/language@b7cc548
Siddhant-K-code Nov 27, 2026
bfb72a7
refactor: stop remembering a 429 from the model read
Siddhant-K-code Nov 28, 2026
46cbdfd
docs: say alias checks need the same context, and the cache holds 32 …
Siddhant-K-code Nov 28, 2026
1f57c49
chore: mark the shared cases JSON as generated
Siddhant-K-code Nov 30, 2026
15e49a1
refactor: read the model in the model cache, not in a callback from t…
Siddhant-K-code Nov 30, 2026
9341f8d
perf: resolve model aliases in linear time
Siddhant-K-code Nov 30, 2026
9a0fce5
Merge branch 'main' into siddhant-k-code-optimize-relation-aliases
Siddhant-K-code Nov 30, 2026
8009f4e
test: cover more alias trees and document how aliases are numbered
Siddhant-K-code Nov 30, 2026
0f1425d
test: pin shared cases to the openfga/language#718 merge commit
Siddhant-K-code Nov 30, 2026
0c73f59
docs: drop a redundant sentence about the option being off
Siddhant-K-code Nov 30, 2026
bf9eccc
fix: catch token failures where the model read gets its token
Siddhant-K-code Nov 30, 2026
8a3389a
ci: check the equivalent-checks cases match LANGUAGE_REF
Siddhant-K-code Dec 1, 2026
ab8b129
refactor: address review comments
Siddhant-K-code Dec 1, 2026
d72aa55
chore: check the equivalent-checks cases with make instead of CI
Siddhant-K-code Dec 2, 2026
427ff3f
docs: say checks_sent is None when off, and how cache misses are counted
Siddhant-K-code Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
test/data/equivalent-checks-cases.json linguist-generated=true
16 changes: 15 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 check-equivalent-checks-cases

# openfga/language commit to copy the shared equivalent-checks cases from
LANGUAGE_REF ?= 41f78349717678d97aade591cf12c78541fae77f

# Install/update dependencies
sync:
Expand Down Expand Up @@ -26,6 +29,15 @@ 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

# 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

Expand All @@ -39,4 +51,6 @@ 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 " check-equivalent-checks-cases - Check the committed cases match openfga/language at LANGUAGE_REF"
@echo " doc - Show this help message"
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,48 @@ 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` 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
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, 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.

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
- 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:

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

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 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`, 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

| 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
133 changes: 133 additions & 0 deletions openfga_sdk/client/_batch_check_merge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
"""
Steps of a BatchCheck call with `merge_equivalent_checks` on that are the same in the
async and sync clients. The model caches read the model, and the clients send the
checks. Not part of the public API.
"""

import logging

from openfga_sdk.client._equivalent_checks import (
EquivalentCheckGroup,
resolve,
unmerged,
)
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


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)}
Comment thread
Siddhant-K-code marked this conversation as resolved.
Resolved
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:
"""
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). "
Comment thread
Siddhant-K-code marked this conversation as resolved.
Resolved
"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):
Comment thread
Siddhant-K-code marked this conversation as resolved.
Resolved
# 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))
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
)
Loading