Workspace/Coding labs
Loading progress

Enforce lease ownership with fencing tokens

Advanced70 min

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

  1. 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.
  2. Require action claim or complete, finite numeric now excluding booleans, a nonempty worker string, and positive finite ttl excluding booleans. Invalid arguments raise ValueError.
  3. 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.
  4. Claiming an actively leased or done job returns an equal copy without changing ownership or extending the lease.
  5. 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.
  6. 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

The old worker must not be able to commit using token 1.
solution.pyPython 3.12