Implement a scoped idempotent inventory operation
Implement reserve_inventory(stock, ledger, principal, key, sku, quantity). It mutates in-memory stock once per tenant-scoped key and returns a copied result for identical replays.
Your task
- Require a nonempty string tenant and inventory:reserve in principal scopes on every call, including replays; otherwise raise PermissionError.
- Require nonempty string key and SKU and an exact integer quantity from 1 through 20; reject invalid input with ValueError before changing state.
- Use (tenant, key) for the ledger identity and (sku, quantity) as the payload fingerprint. Return a copy for an identical replay and raise ValueError for a conflicting replay.
- For a fresh operation, reject unknown or insufficient stock with ValueError; otherwise decrement stock and store the result. The initial stock mapping contains nonnegative integer counts.
- Keep this a sequential simulation. Document the transaction and unique constraint required in production.
Examples
EXAMPLE 1
Inputstock={'A':10}, tenant='north', key='K', sku='A', quantity=3
Output{'sku':'A','reserved':3,'remaining':7}
Implement the function, then run the tests.
Ctrl / ⌘ + Enter to test · Shift + Tab leaves editor