Enforce lease ownership with fencing tokens
Implement lease_transition(state, action, now, worker, ttl=10, token=None, result=None). State contains id, status, owner, lease_until, token, and result. Return a new dictionary for claim or complete while rejecting stale ownership through unchanged state.
Your task
- Assume state is well formed, with status pending, running, or done, a nonnegative integer token, and a numeric lease_until whenever running. Do not mutate it.
- Require action claim or complete, finite numeric now excluding booleans, a nonempty worker string, and positive finite ttl excluding booleans. Invalid arguments raise ValueError.
- Claim a pending job or a running job whose lease_until <= now. Set running, owner to worker, lease_until to now + ttl, and increment the fencing token by one.
- Claiming an actively leased or done job returns an equal copy without changing ownership or extending the lease.
- Complete only a running job with matching owner, exact integer token, and now strictly less than lease_until. Set done, result to the provided value, owner to None, and lease_until to None. Preserve its token.
- A stale, expired, mismatched, or repeated completion returns an equal copy. This pure state machine simulates an atomic store operation; a real database must enforce the condition atomically.
Examples
EXAMPLE 1
Inputlease_transition(running_with_token_1_until_10, "claim", 10, "B")
Outputrunning state owned by B with token 2 and lease_until 20
Implement the function, then run the tests.
Ctrl / ⌘ + Enter to test · Shift + Tab leaves editor