Log Record Dedup: Batch Merge and Watermarked Replay
Data Structure DesignAuto-graded · 17 test casesLast 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 smallesttimestamp. If several share that timestamp, keep the one that appears earliest inrecords."KEEP_LATEST": keep the record with the largesttimestamp. If several share that timestamp, keep the one that appears latest inrecords.
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
ingestcontributesNoneto 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 withtimestamp < threshold(strictly older) is finalized: it is removed from the active set entirely and emitted. - The emitted records are listed sorted by
timestampascending, ties byevent_idascending. - 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;opsmay be empty.- Timestamps are non-negative integers that fit in 64 bits.
event_idis a non-empty ASCII string of at most 64 characters.policyis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both parts rely on the same comparison. Because records are always examined in arrival order, the newcomer is the later record. So:
KEEP_FIRST: replace the current winner only if the newcomer's timestamp is strictly smaller. On a tie the earlier arrival stays.KEEP_LATEST: replace if the newcomer's timestamp is greater than or equal. On a tie the later arrival wins.
Batch. Scan records once, keeping a dictionary from event_id to its current winner and applying the rule above. Then sort the winners by (timestamp, event_id). After deduplication every event_id is unique, so this ordering is total.
Stream. Keep two pieces of state: now (the highest time seen so far, or None) and active, a dictionary from event_id to its current record.
- On
ingest, drop the record ifnowis set and the timestamp is strictly belownow - lateness_ms. Otherwise insert it, or replace the active record using the same rule. - On
advance_watermark, raisenowif the new value is larger, compute the thresholdnow - lateness_ms, collect all active records strictly below it, sort them by(timestamp, event_id), delete them fromactive, and return them.
Why it is correct
- The batch dictionary invariant is that after each record, the stored entry is the best one among all records seen for that id under the policy, including the tie rule. Scanning in input order makes "newcomer is later" always true.
- Because
nownever decreases, the threshold never decreases. A record that was too late stays too late, and a record that is finalized is below every future threshold, so emitting it once is consistent. - Deleting emitted entries means a later non-late record with the same id starts fresh, exactly as the statement requires.
- Sorting the emitted list by
(timestamp, event_id)gives the required order, and ids are unique within one emission.
Complexity
- Batch:
O(n + k log k)time forkdistinct ids (at mostO(n log n)),O(k)space. - Stream: each
ingestisO(1). Eachadvance_watermarkscans the active set, so it costsO(W + e log e), whereWis the number of active records andethe number emitted. Space isO(W), since finalized entries are removed. A min-heap with lazy deletion would avoid the full scan if advances are frequent.
Reference solution
from typing import Dict, List
def dedupe_and_replay_logs(records, policy, ops, lateness_ms):
def better(candidate, current):
# candidate always arrives after current
if policy == "KEEP_FIRST":
return candidate["timestamp"] < current["timestamp"]
return candidate["timestamp"] >= current["timestamp"]
# Batch part
winners = {}
for rec in records:
eid = rec["event_id"]
if eid not in winners or better(rec, winners[eid]):
winners[eid] = rec
batch = sorted(winners.values(), key=lambda r: (r["timestamp"], r["event_id"]))
# Stream part
active = {}
now = None
stream = []
for op in ops:
name, args = op[0], op[1]
if name == "ingest":
ts, eid, payload = args
if now is not None and ts < now - lateness_ms:
stream.append(None)
continue
rec = {"timestamp": ts, "event_id": eid, "payload": payload}
if eid not in active or better(rec, active[eid]):
active[eid] = rec
stream.append(None)
elif name == "advance_watermark":
if now is None or args[0] > now:
now = args[0]
threshold = now - lateness_ms
done = [r for r in active.values() if r["timestamp"] < threshold]
done.sort(key=lambda r: (r["timestamp"], r["event_id"]))
for r in done:
del active[r["event_id"]]
stream.append(done)
else:
raise ValueError("Unknown operation")
return {"batch": batch, "stream": stream}