diff --git a/sdk/python/CHANGELOG.md b/sdk/python/CHANGELOG.md index 8a365db96..c0ae3ec44 100644 --- a/sdk/python/CHANGELOG.md +++ b/sdk/python/CHANGELOG.md @@ -145,6 +145,11 @@ unreleased. 402 response with valid x402 headers is parsed as a payment requirement, not a billing error. `InsufficientFundsError` is raised only when the response body signals `insufficient_funds`. +- **`@billable` and `@combined` with an `idempotency_key_factory`**: a factory + that returns `None` now raises `ValueError` before any charge and before the + decorated function runs. Previously `None` reached `charge()`, which minted a + fresh key, so a retry was billed again. Calling `charge(idempotency_key=None)` + directly is unchanged. ### Deprecations diff --git a/sdk/python/src/b2a_sdk/decorators.py b/sdk/python/src/b2a_sdk/decorators.py index 338468f0b..528d84bf4 100644 --- a/sdk/python/src/b2a_sdk/decorators.py +++ b/sdk/python/src/b2a_sdk/decorators.py @@ -336,8 +336,8 @@ async def generate_video(url: str): Raises: InsufficientFundsError: If wallet balance is insufficient IdempotencyConflictError: If the key was used for a different charge - ValueError: If the factory returns a blank or overlong key (nothing is - charged and the function does not run) + ValueError: If the factory returns None, or a blank or overlong key + (nothing is charged and the function does not run) """ def decorator( @@ -362,7 +362,16 @@ async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> T: if idempotency_key_factory is not None: # Passed only when configured, so a client whose charge() # predates the keyword keeps working. - charge_kwargs["idempotency_key"] = idempotency_key_factory(*args, **kwargs) + factory_key = idempotency_key_factory(*args, **kwargs) + if factory_key is None: + # charge() reads None as "no key" and mints a fresh one, so + # a retry would be billed again. A configured factory that + # yields no key is a bug in the caller: fail before any + # charge and before the function runs. + raise ValueError( + "idempotency_key_factory must return a non-blank string, got None" + ) + charge_kwargs["idempotency_key"] = factory_key await client.charge( wallet_id=wallet_id, service_category=service_category, diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py index f0ae20a46..902dc7ec0 100644 --- a/sdk/python/tests/test_sdk.py +++ b/sdk/python/tests/test_sdk.py @@ -5,6 +5,7 @@ import asyncio import json import warnings +from typing import Any from unittest.mock import AsyncMock, MagicMock import httpx @@ -669,6 +670,90 @@ async def my_function(): assert seen == [] assert ran is False + @pytest.mark.asyncio + @pytest.mark.parametrize("decorator", ["billable", "combined"]) + async def test_factory_returning_none_fails_before_charge_or_execution(self, decorator): + """A configured factory that yields None must not fall back to a minted key.""" + client, seen = _recording_client(_CHARGE_OK) + ran = False + options: dict[str, Any] = { + "wallet_id": "wallet-123", + "service_category": "iot_bridge", + "idempotency_key_factory": lambda job_id: None, + } + wrap = ( + billable(client, **options) + if decorator == "billable" + else combined(client, service_name="svc", **options) + ) + + @wrap + async def run_job(job_id): + nonlocal ran + ran = True + + async with client: + with pytest.raises(ValueError, match="must return a non-blank string, got None"): + await run_job("7") + + assert seen == [] + assert ran is False + + @pytest.mark.asyncio + @pytest.mark.parametrize("decorator", ["billable", "combined"]) + @pytest.mark.parametrize( + ("bad_key", "message"), + [ + ("", "must not be blank"), + (" ", "must not be blank"), + (42, "must be a string"), + ], + ) + async def test_factory_blank_or_non_str_key_fails_before_charge_or_execution( + self, decorator, bad_key, message + ): + """Regression pin: client.charge() already rejects these (PR #86).""" + client, seen = _recording_client(_CHARGE_OK) + ran = False + options: dict[str, Any] = { + "wallet_id": "wallet-123", + "service_category": "iot_bridge", + "idempotency_key_factory": lambda job_id: bad_key, + } + wrap = ( + billable(client, **options) + if decorator == "billable" + else combined(client, service_name="svc", **options) + ) + + @wrap + async def run_job(job_id): + nonlocal ran + ran = True + + async with client: + with pytest.raises(ValueError, match=message): + await run_job("7") + + assert seen == [] + assert ran is False + + @pytest.mark.asyncio + async def test_charge_without_factory_still_mints_a_key_and_warns(self): + """Only a configured factory returning None is an error; charge() is unchanged.""" + client, seen = _recording_client(_CHARGE_OK) + + @billable(client, wallet_id="wallet-123", service_category="iot_bridge") + async def run_job(): + return "ok" + + async with client: + with pytest.warns(UserWarning, match="not replay-safe"): + assert await run_job() == "ok" + + assert len(seen) == 1 + assert seen[0].headers["idempotency-key"] + @pytest.mark.asyncio async def test_combined_passes_idempotency_key_factory_through(self, mock_client): @combined(