Skip to content

fix: reject boolean values for integer flags - #621

Open
Hexecu wants to merge 3 commits into
open-feature:mainfrom
Hexecu:fix/reject-boolean-integer-flags
Open

fix: reject boolean values for integer flags#621
Hexecu wants to merge 3 commits into
open-feature:mainfrom
Hexecu:fix/reject-boolean-integer-flags

Conversation

@Hexecu

@Hexecu Hexecu commented Aug 30, 2026

Copy link
Copy Markdown

This PR

I reproduced the behavior reported by @aepfli in #619: requesting a boolean flag through get_integer_details returns the boolean as a successful evaluation, instead of returning the integer default with TYPE_MISMATCH.

The caller gets neither the expected type nor an indication that the flag is misconfigured for that request. The fallback is silently bypassed because Python considers bool a subclass of int, so isinstance(True, int) passes the client's type check.

Reproducing the problem

This example uses the built-in provider; no flag server or credentials are needed. Run it with uv run --frozen python repro.py after saving it as repro.py in the checkout:

import asyncio

from openfeature import api
from openfeature.provider.in_memory_provider import InMemoryFlag, InMemoryProvider


async def main():
    api.set_provider_and_wait(
        InMemoryProvider({"flag": InMemoryFlag("on", {"on": True})})
    )
    try:
        client = api.get_client()
        for mode, details in (
            ("sync", client.get_integer_details("flag", 1)),
            ("async", await client.get_integer_details_async("flag", 1)),
        ):
            error = details.error_code.value if details.error_code else None
            print(
                f"{mode}: {details.value!r} ({type(details.value).__name__}), "
                f"{details.reason.value}, {error}"
            )
    finally:
        api.shutdown()


asyncio.run(main())

On the base commit, 371aca1:

sync: True (bool), STATIC, None
async: True (bool), STATIC, None

With this patch, the same example returns the supplied default and reports the mismatch:

sync: 1 (int), ERROR, TYPE_MISMATCH
async: 1 (int), ERROR, TYPE_MISMATCH

I also checked False with a default of 0. The type matters here: a test that only checks equality would pass even before the fix, since True == 1 and False == 0.

Why there are two changes

The shared type check now excludes booleans when the requested type is INTEGER. I kept isinstance for everything else so this doesn't also reject valid integer subclasses or change how other flag types are handled.

That change alone wasn't enough for the async API. While checking it, I found that the async type-mismatch branch still constructed its result with resolution.value. It reported an error, but returned the rejected value anyway. The second change uses default_value in that branch, matching the sync behavior.

This also corrects the async fallback for other client-detected type mismatches, which is why the tests cover more than bool-to-int. It doesn't change provider implementations or introduce type coercion. Boolean flags and objects containing booleans continue to work as before.

Related Issues

Fixes #619. Thanks @aepfli for the reproduction and the conformance test that caught this.

How to test

The added tests exercise both value and details getters through the real InMemoryProvider. They check the exact return type as well as the value, error details and hook behavior: a mismatch must run the error hook, skip the after hook, and give the finally hook the fallback value. There are also passing cases for valid flag values and an integer subclass, to check that the stricter bool handling doesn't affect them.

To run just these tests:

uv run --frozen pytest tests/test_client.py -q \
  -k 'client_returns_default_on_type_mismatch or client_preserves_matching_flag_types or typecheck_flag_value_accepts_integer_subclasses'

I ran the same 39 cases against the unmodified base and this patch. Before the fix, 11 failed and 28 passed: the failures were the two sync bool-to-int cases and the nine async mismatch cases. After the fix, all 39 passed.

The full suite passed on Python 3.10 through 3.14, with 211 tests on each version. The repository's Gherkin suite also passed on each version: 21 scenarios / 84 steps, using its pinned spec and in-memory provider. Ruff, mypy, the remaining pre-commit hooks, and the wheel/sdist build passed locally as well.

UV_FROZEN=1 uv run --frozen poe test-all
UV_FROZEN=1 uv run --frozen poe e2e
UV_FROZEN=1 uv run --frozen prek run --all-files --show-diff-on-failure
uv build --no-sources

Notes

For a check independent of the tests added here, I ran the in-memory self-test from python-sdk-contrib#409, at d6de5dc, against both SDK versions. The case marked as a known failure for #619 becomes XPASS(strict) with this patch. Running that unchanged test file with --runxfail, so the assertions run normally, gives 24 passed and 5 skipped. The skips are unsupported provider capabilities; the strict marker will need updating when that suite adopts the fixed SDK.

All results above are local macOS runs. I haven't tested against live flagd/OFREP servers, and these results don't replace hosted CI.

@Hexecu
Hexecu requested review from a team as code owners August 30, 2026 05:50
@coderabbitai

coderabbitai Bot commented Aug 30, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b51ac1fb-e544-47c1-abdd-2e831e040d24

📥 Commits

Reviewing files that changed from the base of the PR and between 10f26c1 and a153f93.

📒 Files selected for processing (1)
  • openfeature/client.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • openfeature/client.py

Included review availability: Your plan provides up to 2 included reviews per hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

The client now rejects booleans for integer flags and returns the caller’s default value for asynchronous type mismatches. Tests cover matching and mismatched values across synchronous and asynchronous getters.

Changes

Flag type validation

Layer / File(s) Summary
Type mismatch validation
openfeature/client.py, tests/test_client.py
Integer checks reject boolean values while accepting integer subclasses. Tests cover matching and mismatched flag types.
Evaluation default handling
openfeature/client.py, tests/test_client.py
Asynchronous mismatches return the caller’s default value. Tests verify error details, hooks, and sync/async getters.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to a153f

The change correctly rejects boolean values for integer flags and returns the configured default for synchronous and asynchronous mismatches; no actionable merge-blocking risk remains beyond normal checks and review.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: rejecting boolean values for integer flag requests.
Description check ✅ Passed The description directly explains the boolean-to-integer mismatch, the asynchronous fallback correction, tests, and validation results.
Linked Issues check ✅ Passed The changes satisfy issue #619 by rejecting booleans for integer requests, returning the default with TYPE_MISMATCH, and preserving valid integer subclasses.
Out of Scope Changes check ✅ Passed The implementation, asynchronous fallback correction, documentation, and regression tests directly support the stated objectives. No unrelated code changes are identified.
  • Fix all pre-merge checks with AI

Comment @coderabbitai help to get the list of available commands.

Exclude bool from integer flag type checks while preserving other integer subclasses. Return the caller default when the async client detects a type mismatch, matching the sync path.

Cover sync and async value/details getters, exact fallback types, hook behavior, and valid flag values with regression tests for open-feature#619.

Signed-off-by: Hexecu <vaingloryhex@gmail.com>
@Hexecu
Hexecu force-pushed the fix/reject-boolean-integer-flags branch from e530620 to 71fe148 Compare August 30, 2026 06:08
Document the boolean/integer distinction, async type-mismatch fallback, and the regression cases. Keep the evaluation logic and test assertions unchanged.

Signed-off-by: Hexecu <vaingloryhex@gmail.com>

@gruebel gruebel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for the PR, i added a few comments, nothing critical

Comment thread openfeature/client.py Outdated
Comment thread openfeature/client.py Outdated
Comment thread tests/test_client.py Outdated
@codecov

codecov Bot commented Aug 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.40%. Comparing base (371aca1) to head (a153f93).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #621      +/-   ##
==========================================
+ Coverage   98.36%   98.40%   +0.03%     
==========================================
  Files          45       45              
  Lines        2514     2574      +60     
==========================================
+ Hits         2473     2533      +60     
  Misses         41       41              
Flag Coverage Δ
unittests 98.40% <100.00%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Hexecu

Hexecu commented Aug 30, 2026

Copy link
Copy Markdown
Author

Thanks for the review! Removed the added docstrings and moved the bool/int explanation next to the condition. Re-ran the full test suite and Gherkin tests on Python 3.10–3.14; all pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A boolean flag satisfies an Integer request: bool is a subclass of int

2 participants