The customer replays older events after an outage. How would you keep downstream state correct?

Instruction: Explain whether the events are snapshots or incremental changes before choosing ordering logic. Include deletions and non-state side effects in the replay plan.

Context:

Implement and test a pure versioned-snapshot transition for fictional service visits, including duplicates, deletion replay and equal-version conflicts. Explain what remains outside the function.

Practice task

Implement apply_snapshot(current, incoming) for this fictional customer event contract. The function tracks one record, returns an independent snapshot, and must not mutate either input. current is None before the first accepted snapshot.

Input contract

  • Every event is a complete current-state snapshot or a deletion marker, not an incremental adjustment.
  • Each snapshot has exactly record_id, version, deleted and payload.
  • Record IDs are nonempty strings. Source versions are monotonically increasing, nonnegative integers for each record; booleans and other numeric representations are invalid versions.
  • deleted must be a boolean. A live payload contains exactly {"status": <nonempty string>}; a blank or whitespace-only status is invalid. A deletion's payload is None.
  • Both current and incoming snapshots must obey this contract. Different records require separate state.
  • An older snapshot must not replace newer state. A repeated identical snapshot has no additional effect. Different contents at an equal version are an explicit conflict; do not choose one silently.
  • A deletion remains part of the versioned state while older events may be replayed. Raise ValueError for invalid inputs or conflicts.

Fictional inputs

v1 = {"record_id": "visit-7", "version": 1, "deleted": False,
      "payload": {"status": "draft"}}
v2 = {"record_id": "visit-7", "version": 2, "deleted": False,
      "payload": {"status": "scheduled"}}
v3_deleted = {"record_id": "visit-7", "version": 3, "deleted": True,
              "payload": None}

events = [v2, v1, v2, v3_deleted, v1]
conflicting_v2 = {**v2, "payload": {"status": "cancelled"}}

Process events in that delivery order. Separately test conflicting_v2 against an accepted v2, invalid boolean and integer status values, invalid versions, extra fields, another record ID and input immutability.

Explain the guarantee of this pure state-transition function and the destination-level concurrency, persistence and customer-scoping checks a real deployment would still need. State why this contract would not safely process inventory adjustments merely by discarding older versions.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

I'd confirm that these events are full snapshots with the source versions defined in the task. That lets a newer version replace older state...

Related Questions