Workspace/Coding labs
Loading progress

Apply and reverse a versioned edit

Intermediate50 min

Implement apply_transaction(state, expected_version, changes) and rollback(state, receipt). State has an integer version and a fields dictionary of immutable scalar values. Applying requires a matching version and known fields, returns a new state at version+1 plus a receipt containing a copy of prior fields and after_version. Even an empty changes dictionary is a committed transaction. Rollback requires the state's version to equal receipt.after_version; it restores prior fields in a new state and increments the version again. Never mutate inputs. Reject stale versions and unknown fields with ValueError.

Your task

  1. Complete the starter function using the contract above.
  2. Use the examples and visible tests to check normal inputs, boundaries, and rejected inputs.
  3. Run tests to record your result, then compare with the explained reference solution.

Examples

EXAMPLE 1

Inputversion 3, title Alpha; change title to Beta

Outputversion 4, title Beta, receipt stores Alpha

The edit creates a restoration record.
EXAMPLE 2

InputRollback that receipt at version 5

OutputValueError

An intervening change prevents unsafe restoration.
solution.pyPython 3.12