KatInterview

Log Record Dedup: Batch Merge and Watermarked Replay

Data Structure DesignAuto-graded · 17 test cases
MediumAuto-gradedData Structure Designhash-mapsortingstreaming

Last updated

Deduplicate log records by event id under a first or latest policy, then replay an operation list through a watermark-based stream deduplicator that drops late data and evicts finalized entries.

You are building a small log-cleaning component that must work in two modes: over a complete batch, and as a simulated stream with a lateness allowance.

A log record is a dictionary with three keys:

  • timestamp: a non-negative integer (milliseconds).
  • event_id: a non-empty string identifying the underlying event.
  • payload: a string.

Retries can produce several records with the same event_id, possibly with different timestamp or payload values.

Implement one function that does both jobs and returns both results.

Inputs

  • records: a list of record dictionaries (the batch input).
  • policy: either "KEEP_FIRST" or "KEEP_LATEST".
  • ops: a list of stream operations, each a two-element list [name, args]:
    • ["ingest", [timestamp, event_id, payload]]
    • ["advance_watermark", [current_time_ms]]
  • lateness_ms: a non-negative integer, the allowed lateness for the stream.

Batch part

For each event_id, keep exactly one record from records:

  • "KEEP_FIRST": keep the record with the smallest timestamp. If several share that timestamp, keep the one that appears earliest in records.
  • "KEEP_LATEST": keep the record with the largest timestamp. If several share that timestamp, keep the one that appears latest in records.

Return the kept records sorted by timestamp ascending, with ties broken by event_id in ascending lexicographic order.

Stream part

Process ops in order, starting with no active records and with no current time set. The same policy applies to the stream. Every operation produces one entry in the stream result list.

ingest

  • If a current time has been set and timestamp < current_time - lateness_ms, the record is late and is discarded.
  • Otherwise, if no active record exists for that event_id, the new record becomes the active record.
  • Otherwise, the new record replaces the active one only if it is preferred under the policy. It is preferred under "KEEP_FIRST" when its timestamp is strictly smaller than the active one's. It is preferred under "KEEP_LATEST" when its timestamp is greater than or equal to the active one's, so a tie goes to the newer arrival.
  • An ingest contributes None to the result list.

advance_watermark

  • Set the current time to the given value, but never move it backwards: if the given value is not greater than the current time, the current time stays as it is. The first call always sets it.
  • Let threshold = current_time - lateness_ms. Every active record with timestamp < threshold (strictly older) is finalized: it is removed from the active set entirely and emitted.
  • The emitted records are listed sorted by timestamp ascending, ties by event_id ascending.
  • This operation contributes that list (possibly empty) to the result list.

A removed event leaves no memory behind. If a later record for the same event_id is not late, it starts a fresh active entry.

Any other operation name must raise ValueError.

Output

Return a dictionary:

{"batch": <list of records>, "stream": <list with one entry per operation>}

Records in the output are dictionaries with the keys timestamp, event_id and payload.

Constraints

  • 0 <= len(records) <= 10^5; ops may be empty.
  • Timestamps are non-negative integers that fit in 64 bits.
  • event_id is a non-empty ASCII string of at most 64 characters.
  • policy is always one of the two listed values.
  • lateness_ms >= 0.
  • Finalized records must be removed from the stream's internal state.

Examples

Example 1

Input: dedupe_and_replay_logs([{'timestamp': 100, 'event_id': 'A', 'payload': 'v1'}, {'timestamp': 150, 'event_id': 'B', 'payload': 'v1'}, {'timestamp': 90, 'event_id': 'A', 'payload': 'v2'}, {'timestamp': 150, 'event_id': 'C', 'payload': 'v1'}], 'KEEP_FIRST', [], 0)

Output: {'batch': [{'timestamp': 90, 'event_id': 'A', 'payload': 'v2'}, {'timestamp': 150, 'event_id': 'B', 'payload': 'v1'}, {'timestamp': 150, 'event_id': 'C', 'payload': 'v1'}], 'stream': []}

Example 2

Input: dedupe_and_replay_logs([{'timestamp': 100, 'event_id': 'A', 'payload': 'v1'}, {'timestamp': 150, 'event_id': 'B', 'payload': 'v1'}, {'timestamp': 90, 'event_id': 'A', 'payload': 'v2'}, {'timestamp': 150, 'event_id': 'C', 'payload': 'v1'}], 'KEEP_LATEST', [['ingest', [100, 'A', 'v1']], ['ingest', [150, 'B', 'v1']], ['ingest', [90, 'A', 'v2']], ['advance_watermark', [200]]], 10)

Output: {'batch': [{'timestamp': 100, 'event_id': 'A', 'payload': 'v1'}, {'timestamp': 150, 'event_id': 'B', 'payload': 'v1'}, {'timestamp': 150, 'event_id': 'C', 'payload': 'v1'}], 'stream': [None, None, None, [{'timestamp': 100, 'event_id': 'A', 'payload': 'v1'}, {'timestamp': 150, 'event_id': 'B', 'payload': 'v1'}]]}

Hints

Hint 1

Both parts share the same 'is the new record better than the current one?' rule. Write it once as a small helper, using a strict comparison for KEEP_FIRST and a non-strict one for KEEP_LATEST so that ties fall out of arrival order.

Hint 2

For the batch, one scan with a dictionary from event_id to the current winner is enough. Sort the winners once at the end by (timestamp, event_id).

Hint 3

For the stream, track the current time (never decreasing) and a dictionary of active records. On advance, collect the records strictly below current_time - lateness_ms, sort them, and delete them from the dictionary. Remember that late records are dropped on ingest only when a time has already been set.