KatInterview

Replay-Safe Versioned Record Updates Simulator

Data Structure DesignAuto-graded · 22 test cases
MediumAuto-gradedData Structure Designdesignhash-mapidempotency

Last updated

Simulate a record store that applies updates with optimistic version checks and per-record idempotency keys, replaying cached results for retries and rejecting reused keys.

Replay-Safe Versioned Record Updates

Clients of a data store often retry requests that appear to have failed, and several clients may try to modify the same record at once. A well-behaved store must make retries harmless (idempotency) and must refuse writes made against an outdated view of a record (optimistic concurrency).

You are given a script of operations to run against a fresh, empty in-memory store. Simulate the store and return the result of every operation, in order.

Records

A record is a dictionary with these fields:

  • "record_id": the string identifier
  • "version": an integer, which is 1 when the record is created and goes up by exactly 1 per successful update
  • "data": a dictionary of string keys to primitive values
  • "updated_at": a number, 0.0 at creation, and later the current_time of the latest successful update

Operations

operations[i] is the name of the i-th operation, and arguments[i] is its list of arguments.

"put_initial" with arguments [record_id, data]

  • Creates the record with version 1, a copy of data, and updated_at = 0.0.
  • If a record with this id already exists, it is replaced entirely by the new version-1 record. Idempotency history already stored for that id is not cleared.
  • The result is the newly created record (a dictionary).

"update_record" with arguments [record_id, expected_version, updates, idempotency_key, current_time]

The result is a three-element list [success, record, message]. Evaluate these checks in exactly this order and stop at the first one that applies:

  1. Unknown record. If no record with record_id exists, return [False, None, "NOT_FOUND"].
  2. Key already used on this record. Idempotency keys are scoped per record, so the same key on two different records is two unrelated requests. If idempotency_key was previously stored for this record:
    • If the earlier request had the same expected_version and an equal updates dictionary (ordinary equality, so key order is irrelevant), return [True, saved_record, "IDEMPOTENT_REPLAY"]. Here saved_record is the record exactly as it was returned by that earlier successful call. Nothing in the store changes, even if the record has been updated several times since.
    • Otherwise return [False, None, "IDEMPOTENCY_CONFLICT"].
  3. Stale version. If expected_version differs from the record's current version, return [False, current_record, "VERSION_MISMATCH"], where current_record is the record as it stands now. Nothing is stored for this key, so a later request reusing the key is evaluated from scratch.
  4. Apply. Otherwise:
    • Merge updates into the record's data (top-level keys are overwritten or added; there is no deep merge).
    • Increase version by 1.
    • Set updated_at to current_time.
    • Remember the request (its expected_version and updates) together with a snapshot of the new record under idempotency_key for this record.
    • Return [True, new_record, "OK"].

An empty updates dictionary is a valid update: the version and timestamp still change.

Only successful updates ("OK") are remembered. Rejected requests leave no trace.

Errors

  • Raise ValueError if an "update_record" operation does not have exactly five arguments.
  • Raise ValueError if an operation name is neither "put_initial" nor "update_record".

Output

Return a list with one entry per operation: a record dictionary for "put_initial", and a [success, record, message] list for "update_record". Results must be independent of the store's internal state, so later operations must not change a result that was already returned.

Constraints

  • operations and arguments have the same length.
  • record_id and idempotency_key are non-empty strings of length at most 128.
  • updates and data have string keys and primitive values (numbers, strings, booleans, null).
  • expected_version is an integer and current_time is a number.

Examples

Example 1

Input: simulate_record_store(['put_initial', 'update_record', 'update_record', 'update_record'], [['user_1', {'name': 'Alice', 'role': 'member'}], ['user_1', 1, {'role': 'admin'}, 'key-100', 1000], ['user_1', 1, {'role': 'admin'}, 'key-100', 1005], ['user_1', 1, {'role': 'editor'}, 'key-200', 1010]])

Output: [{'record_id': 'user_1', 'version': 1, 'data': {'name': 'Alice', 'role': 'member'}, 'updated_at': 0}, [True, {'record_id': 'user_1', 'version': 2, 'data': {'name': 'Alice', 'role': 'admin'}, 'updated_at': 1000}, 'OK'], [True, {'record_id': 'user_1', 'version': 2, 'data': {'name': 'Alice', 'role': 'admin'}, 'updated_at': 1000}, 'IDEMPOTENT_REPLAY'], [False, {'record_id': 'user_1', 'version': 2, 'data': {'name': 'Alice', 'role': 'admin'}, 'updated_at': 1000}, 'VERSION_MISMATCH']]

Example 2

Input: simulate_record_store(['update_record'], [['missing', 1, {'x': 1}, 'key', 1]])

Output: [[False, None, 'NOT_FOUND']]

Example 3

Input: simulate_record_store(['put_initial', 'update_record', 'update_record'], [['r', {'n': 0}], ['r', 1, {'n': 1}, 'k', 10], ['r', 1, {'n': 2}, 'k', 11]])

Output: [{'record_id': 'r', 'version': 1, 'data': {'n': 0}, 'updated_at': 0}, [True, {'record_id': 'r', 'version': 2, 'data': {'n': 1}, 'updated_at': 10}, 'OK'], [False, None, 'IDEMPOTENCY_CONFLICT']]

Example 4

Input: simulate_record_store(['put_initial', 'update_record', 'update_record'], [['r', {'x': 1}], ['r', 1, {'x': 2}, 'k', 1], ['r', 2, {'x': 3}, 'k2', 2]])

Output: [{'record_id': 'r', 'version': 1, 'data': {'x': 1}, 'updated_at': 0}, [True, {'record_id': 'r', 'version': 2, 'data': {'x': 2}, 'updated_at': 1}, 'OK'], [True, {'record_id': 'r', 'version': 3, 'data': {'x': 3}, 'updated_at': 2}, 'OK']]

Hints

Hint 1

Process the operations one by one while keeping two dictionaries: the current record for each id, and for each id a map from idempotency key to (request fingerprint, saved result).

Hint 2

Order of the checks matters: a retry carries the old expected version, so the idempotency lookup must happen before the version comparison, otherwise valid retries would look like version mismatches.

Hint 3

Store a deep-copied snapshot at commit time and return deep copies everywhere, so a replay returns the old record rather than the live one and callers cannot alias internal state.