Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions sdk/python/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
15 changes: 12 additions & 3 deletions sdk/python/src/b2a_sdk/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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,
Expand Down
85 changes: 85 additions & 0 deletions sdk/python/tests/test_sdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import asyncio
import json
import warnings
from typing import Any
from unittest.mock import AsyncMock, MagicMock

import httpx
Expand Down Expand Up @@ -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(
Expand Down