We are going to build an event-time correctness verifier. This verifier will check for:
Watermark shifts: It should detect when the watermark moves backward (which is a sign of out-of-orderness or system issues).
Late data contracts: It should check if events are arriving later than a defined lateness threshold (which might be defined by the allowed lateness in windowing or by a service level agreement).
Alerts: It should be able to raise alerts when either of the above conditions are violated.
We assume we are processing a stream of events with event time and we are maintaining a watermark (which is an estimate of the maximum event time seen so far, minus some allowed lateness).
Steps:
We will maintain:
currentWatermark: the current watermark (as a timestamp, in milliseconds since epoch).
previousWatermark: to compare with the current one to detect backward shifts.
allowedLateness: the maximum lateness allowed for events (in milliseconds). This can be set per window or globally.
For each event, we have:
eventTime: the event time of the event (in milliseconds since epoch).
We will check:
a. Watermark shift: if currentWatermark < previousWatermark, then we have a backward shift.
b. Late data: if eventTime < (currentWatermark - allowedLateness), then the event is too late.
We will also consider that the watermark might be updated periodically (not necessarily for every event). So we need to update the watermark and then check the conditions.
However, note that in practice, the watermark is updated by the system based on the events seen. We are going to simulate a stream of events and watermark updates.
Let's design:
We have two types of inputs:
Event: (eventTime, other data)
WatermarkUpdate: (newWatermark)
We can design a class that can process both.
Alternatively, we can design the verifier to be called on every event and also when the watermark updates.
But note: the watermark might be updated without an event (by a periodic watermark generator). So we need to handle both.
Let's create:
class EventTimeVerifier:
def init(self, allowed_lateness):
self.allowed_lateness = allowed_lateness
self.current_watermark = None
self.previous_watermark = None
self.late_events = [] # to store late events (or just count? we might want to report)
self.backward_shifts = [] # to store backward shift events (timestamp of when detected, and the shift)
code
def on_watermark_update(self, new_watermark):
# Check for backward shift
if self.current_watermark is not None and new_watermark < self.current_watermark:
# Record backward shift: from current_watermark to new_watermark
self.backward_shifts.append({
'timestamp': time.time(), # current processing time
'previous_watermark': self.current_watermark,
'new_watermark': new_watermark
})
self.previous_watermark = self.current_watermark
self.current_watermark = new_watermark
def on_event(self, event_time):
# Check if the event is late
if self.current_watermark is not None:
if event_time < self.current_watermark - self.allowed_lateness:
self.late_events.append({
'event_time': event_time,
'watermark_at_arrival': self.current_watermark,
'lateness': self.current_watermark - event_time
})
# Note: if watermark is None, we cannot determine lateness, so we skip.
def get_report(self):
return {
'late_events': self.late_events,
'backward_shifts': self.backward_shifts
}
However, note that the event might arrive at a time when the watermark is not set? In practice, the watermark is set by the system and we assume we get updates.
But what if we get an event before any watermark? We cannot check lateness until we have a watermark.
Also, note that the watermark update might happen after the event? In a streaming system, the watermark is updated based on the events, so typically we see events and then the watermark updates.
But the order of calls to on_event and on_watermark_update might be interleaved.
We have to be cautious: the watermark at the time of event arrival is the current_watermark at that moment.
However, if we get an event and then the watermark updates, we might not have checked that event against the new watermark? Actually, the event is processed with the watermark at the time of arrival. So we are okay.
But what if the watermark updates and then we get an event? We check with the updated watermark.
So the above design is okay.
However, note that in some systems, the watermark is computed from the events and then we might have:
Event arrives -> update state -> then watermark updates (based on the new state)
So the event is processed with the old watermark, and then the watermark updates to a new value that might be after the event time.
But the event is already processed. So we are only checking the event against the watermark at the time of arrival.
This is the typical behavior.
But note: what if the event is very early and then the watermark jumps? We don't recheck old events.
So we are only checking the event at the time it arrives.
However, the problem of late data is defined as: event time is before (watermark - allowedLateness). And the watermark at the time of the event is the one we use.
This is correct.
We might also want to check for events that are too far in the future? That is, event time > currentWatermark?
Actually, that is allowed because the watermark is a lower bound on the event time of future events?
But note: the watermark is defined as an estimate of the maximum event time seen so far, minus some threshold.
So it's possible to have events with event time > currentWatermark (these are early events). We don't consider them late.
We might also want to check for watermark gaps? For example, if the watermark jumps from t1 to t3 and skips t2? That might be okay if no events in between, but could be a sign of problem?
We are only concerned with backward shifts.
We might want to set a threshold for how much the watermark can jump forward? That is system specific.
Let's stick to the requirements.
We also might want to have a way to reset the verifier (for a new window of time, or for testing).
9. We might also want to have a way to set the allowed lateness dynamically? Maybe per window? Then we would need to change the allowed_lateness for each window.
But the requirement says "late data contracts", which might be defined per window. So we might need to update the allowed_lateness.
10. However, note that the allowed lateness might be different for different windows. But our verifier is for a single stream? Or for a pipeline?
code
We can design it to be per key? But the requirement doesn't specify.
Let's assume we are verifying a single stream (or a single partition) for simplicity.
11. We might also want to track the number of events and the number of late events, etc.
We might want to have an alerting mechanism. The requirement says "alerts". We can have:
def check_and_alert(self):
# This function can be called periodically to check the conditions and raise alerts.
# But we are already recording the events. We can have a separate function that, given the recorded events, decides if we need to alert.
code
Revised design:
class EventTimeVerifier:
def init(self, allowed_lateness):
self.allowed_lateness = allowed_lateness
self.current_watermark = None
self.previous_watermark = None
self.late_events = [] # list of late event info dicts
self.backward_shifts = [] # list of backward shift info dicts
self.backward_shift_handlers = []
self.late_event_handlers = []
code
def set_allowed_lateness(self, allowed_lateness):
self.allowed_lateness = allowed_lateness
def register_backward_shift_handler(self, handler):
self.backward_shift_handlers.append(handler)
def register_late_event_handler(self, handler):
self.late_event_handlers.append(handler)
def on_watermark_update(self, new_watermark):
# Check for backward shift
if self.current_watermark is not None and new_watermark < self.current_watermark:
shift_info = {
'timestamp': time.time(),
'previous_watermark': self.current_watermark,
'new_watermark': new_watermark
}
self.backward_shifts.append(shift_info)
for handler in self.backward_shift_handlers:
handler(shift_info)
self.previous_watermark = self.current_watermark
self.current_watermark = new_watermark
def on_event(self, event_time):
if self.current_watermark is not None:
if event_time < self.current_watermark - self.allowed_lateness:
late_event_info = {
'event_time': event_time,
'watermark_at_arrival': self.current_watermark,
'lateness': self.current_watermark - event_time
}
self.late_events.append(late_event_info)
for handler in self.late_event_handlers:
handler(late_event_info)
def reset(self):
self.current_watermark = None
self.previous_watermark = None
self.late_events = []
self.backward_shifts = []
# Note: we don't reset the handlers because they are callbacks and might be set by the user.
def get_report(self):
return {
'late_events': self.late_events,
'backward_shifts': self.backward_shifts
}
18. We might also want to have a way to get the current state (current_watermark, etc.) for monitoring.
We assume that the event_time and watermark are in milliseconds since epoch (or any comparable numeric type).
We use time.time() for the timestamp of the shift? That is the processing time when we detected the shift.
We might also want to record the processing time of the event? We don't have that in the late_event_info. We can add:
'arrival_time': time.time()
But the requirement doesn't specify.
We'll leave it as is.
We must be cautious: the watermark might be updated frequently and we might get a backward shift and then later a forward shift that recovers? We record every backward shift.
We might also want to check for watermark stagnation? That is, the watermark doesn't advance? That could be a problem too.
But the requirement doesn't specify.
We'll stick to the requirements.
Let's write the code accordingly.
However, note: the requirement says "watermark shifts", and we are only checking backward shifts. But a forward shift that is too small? That might be a problem too? Not necessarily.
We are only concerned with backward shifts.
Let's code accordingly.
We'll also add a method to get the current watermark and allowed lateness for monitoring.
We'll also add a method to get the number of late events and backward shifts.
We'll write the class in a way that it can be used in a streaming system.
Let's code accordingly.
But note: the problem says "Build an event-time correctness verifier". We are building a verifier that can be used in a streaming pipeline.
We assume that the streaming system will call on_watermark_update when the watermark advances (or retreats) and on_event for every event.
We might also want to handle the case when the watermark is None initially? We set it to None and then when we get the first watermark update, we set it.
We are done.
Let's write the code.
However, note: the allowed_lateness might be a function of the window? We are not handling that. We are using a fixed allowed_lateness.
If the allowed_lateness changes (for example, for different windows), then we need to update the allowed_lateness and then we might need to re-evaluate the events? But that is not possible because the event's lateness is determined at the time of arrival with the allowed_lateness at that time.
So if the allowed_lateness changes, we are using the new allowed_lateness for new events.
This is acceptable.
Let's code accordingly.
We'll write the class in Python.
We'll also add some documentation.
Note: We are using time.time() which returns seconds in float (since epoch). We assume event_time and watermark are in the same unit (milliseconds?).
We must be consistent: if event_time is in milliseconds, then allowed_lateness is in milliseconds, and watermark is in milliseconds.
We'll assume that.
But time.time() returns seconds. We can convert to milliseconds? Or we can leave as seconds? We'll leave as is and assume the user uses the same unit.
We can change to use time.time() * 1000 if we want milliseconds.
But the problem doesn't specify.
Let's assume the user uses milliseconds for event_time and watermark, and we record the shift timestamp in milliseconds too? Or we can leave it as seconds.
We'll record the shift timestamp in the same unit as the event_time? Not necessarily.
We'll record the shift timestamp as the processing time (in seconds since epoch) and the event_time and watermark in their own unit.
It's okay.
Let's code.
We'll also add a method to get the current state (watermark and allowed_lateness) for monitoring.
Let's write the code.
I'll build a comprehensive Event-Time Correctness Verifier that monitors watermark behavior, late data contracts, and generates alerts. This is crucial for streaming systems using event-time processing.
Architecture Overview
python
"""
Event-Time Correctness Verifier
Monitors: Watermark shifts, late data contracts, and alerting
"""
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Callable, Any
from collections import deque, defaultdict
import statistics
import json
from dataclasses import dataclass, asdict
from enum import Enum
import time
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
1. Core Data Structures
python
class AlertSeverity(Enum):
INFO = "INFO"
WARNING = "WARNING"
CRITICAL = "CRITICAL"
EMERGENCY = "EMERGENCY"
@dataclass
class WatermarkObservation:
"""Single watermark observation"""
timestamp: datetime # processing time when observed
watermark_value: datetime # event-time watermark value
source_id: str # which source/partition produced this
lateness_estimate_ms: Optional[int] = None # estimated max lateness
@dataclass
class LateEvent:
"""Late event detection"""
event_id: str
event_time: datetime
processing_time: datetime
watermark_at_arrival: datetime
lateness_ms: int # positive = late, negative = early
allowed_lateness_ms: int
source_id: str
window_id: Optional[str] = None
@dataclass
class Alert:
"""Alert generated by verifier"""
alert_id: str
severity: AlertSeverity
timestamp: datetime
rule_name: str
description: str
metadata: Dict[str, Any]
count: int = 1 # for rate-based alerts
@dataclass
class ContractViolation:
"""Contract violation record"""
contract_name: str
violation_time: datetime
observed_value: Any
threshold: Any
source_id: str
details: Dict[str, Any]
2. Watermark Monitor
python
class WatermarkMonitor:
"""Detects watermark regressions and anomalies"""
def __init__(self,
min_watermark_advance_ms: int = 1000,
max_watermark_gap_ms: int = 300000, # 5 minutes
regression_threshold_ms: int = 100):
self.min_advance = min_watermark_advance_ms
self.max_gap = max_watermark_gap_ms
self.regression_threshold = regression_threshold_ms
self.history: Dict[str, deque] = defaultdict(
lambda: deque(maxlen=1000)
) # source_id -> deque of WatermarkObservation
self.last_watermark: Dict[str, datetime] = {}
def add_observation(self, observation: WatermarkObservation):
"""Add new watermark observation and check for issues"""
source_id = observation.source_id
history = self.history[source_id]
issues = []
if len(history) > 0:
last_obs = history[-1]
# 1. Check for watermark regression
if observation.watermark_value < last_obs.watermark_value:
regression_ms = (
last_obs.watermark_value - observation.watermark_value
).total_seconds() * 1000
if regression_ms > self.regression_threshold_ms:
issues.append({
'type': 'watermark_regression',
'regression_ms': regression_ms,
'previous': last_obs.watermark_value,
'current': observation.watermark_value
})
# 2. Check for stagnant watermark
time_diff = (observation.timestamp - last_obs.timestamp).total_seconds() * 1000
watermark_diff = (
observation.watermark_value - last_obs.watermark_value
).total_seconds() * 1000
if time_diff > self.max_gap and watermark_diff < self.min_advance:
issues.append({
'type': 'stagnant_watermark',
'gap_ms': time_diff,
'advance_ms': watermark_diff
})
history.append(observation)
self.last_watermark[source_id] = observation.watermark_value
return issues
3. Late Data Contract Verifier
python
4. Alert Manager
python
class AlertManager:
"""Generates and manages alerts based on verifier outputs"""
def __init__(self,
alert_handlers: Optional[List[Callable]] = None,
rate_limit_secs: int = 300,
max_alerts_per_rule: int = 1000):
self.alert_handlers = alert_handlers or []
self.rate_limit_secs = rate_limit_secs
self.max_alerts_per_rule = max_alerts_per_rule
self.active_alerts: Dict[str, List[Alert]] = defaultdict(list)
self.alert_counts: Dict[str, int] = defaultdict(int)
self.last_alert_time: Dict[str, datetime] = {}
def generate_alert(self,
severity: AlertSeverity,
rule_name: str,
description: str,
metadata: Optional[Dict] = None,
count: int = 1) -> Optional[Alert]:
"""Generate new alert if not rate-limited"""
now = datetime.now()
metadata = metadata or {}
# Check rate limiting
last_time = self.last_alert_time.get(rule_name)
if last_time and (now - last_time).total_seconds() < self.rate_limit_secs:
return None
# Check max alerts per rule
if self.alert_counts[rule_name] >= self.max_alerts_per_rule:
return None
alert = Alert(
alert_id=f"{rule_name}_{int(now.timestamp() * 1000)}",
severity=severity,
timestamp=now,
rule_name=rule_name,
description=description,
metadata=metadata,
count=count
)
self._dispatch_alert(alert)
self.active_alerts[rule_name].append(alert)
self.alert_counts[rule_name] += 1
self.last_alert_time[rule_name] = now
# Clean old alerts
self._clean_old_alerts()
return alert
def _dispatch_alert(self, alert: Alert):
"""Send alert to all handlers"""
for handler in self.alert_handlers:
try:
handler(alert)
except Exception as e:
logger.error(f"Alert handler failed: {e}")
def _clean_old_alerts(self, max_age_hours: int = 24):
"""Clean alerts older than max_age_hours"""
cutoff = datetime.now() - timedelta(hours=max_age_hours)
for rule, alerts in list(self.active_alerts.items()):
self.active_alerts[rule] = [
a for a in alerts if a.timestamp > cutoff
]
self.alert_counts[rule] = len(self.active_alerts[rule])
def get_active_alerts(self, severity: Optional[AlertSeverity] = None) -> List[Alert]:
"""Get currently active alerts"""
all_alerts = []
for alerts in self.active_alerts.values():
all_alerts.extend(alerts)
if severity:
all_alerts = [a for a in all_alerts if a.severity == severity]
return sorted(all_alerts, key=lambda x: x.timestamp, reverse=True)
5. Main Verifier Class
python
6. Usage Example
python
def example_usage():
"""Example of how to use the verifier"""
# Initialize verifier
verifier = EventTimeCorrectnessVerifier(
default_allowed_lateness_ms=5000, # 5 seconds default
watermark_regression_threshold_ms=100 # 100ms regression threshold
)
# Register contracts
verifier.register_contract(
contract_name="tumbling_1min",
allowed_lateness_ms=2000, # 2 seconds allowed lateness
max_lateness_ms=10000, # 10 seconds max before critical
window_duration_ms=60000 # 1 minute windows
)
verifier.register_contract(
contract_name="session_30min",
allowed_lateness_ms=10000, # 10 seconds allowed
apply_to_sources=["session_events"]
)
# Simulate watermark updates
verifier.add_watermark(
watermark=datetime(2024, 1, 1, 12, 0, 0),
source_id="input_stream_1"
)
# Simulate events
base_time = datetime(2024, 1, 1, 12, 0, 0)
# On-time event
verifier.process_event(
event_time=base_time - timedelta(seconds=1), # 1 second late
processing_time=datetime.now(),
source_id="input_stream_1",
event_id="event_001"
)
# Very late event
verifier.process_event(
event_time=base_time - timedelta(minutes=2), # 2 minutes late
processing_time=datetime.now(),
source_id="input_stream_1",
event_id="event_002"
)
# Check health
report = verifier.get_health_report()
print(json.dumps(report, indent=2, default=str))
# Export metrics
print("\n=== Prometheus Metrics ===")
print(verifier.export_metrics(format='prometheus'))
Multiple handler support (Slack, PagerDuty, email, etc.)
Alert deduplication and cleanup
Monitoring & Observability:
Health reports with key metrics
Watermark trend analysis
Export to Prometheus format
JSON exports for dashboards
Production Ready:
Thread-safe design assumptions
Configurable thresholds
Memory limits (deque maxlen)
Comprehensive logging
10. Integration Patterns
python
# In a Flink/Spark streaming job:
class StreamingJobWithVerifier:
def process_element(self, element):
# Extract event time
event_time = element.get_event_time()
# Check with verifier
violation = verifier.process_event(
event_time=event_time,
processing_time=datetime.now(),
source_id=self.source_name,
event_id=element.get_id(),
window_id=element.get_window_id()
)
if violation:
# Could route late events to side output
self.side_output.collect(element)
else:
self.main_output.collect(element)
def on_watermark(self, watermark, source_id):
verifier.add_watermark(watermark, source_id)
This verifier provides comprehensive event-time correctness monitoring with:
Real-time detection of watermark issues
Contract-based late data validation
Flexible alerting with rate limiting
Production-ready metrics export
Easy integration with streaming frameworks
The system helps maintain event-time guarantees in distributed streaming systems and quickly detects issues like:
Clock skew between sources
Processing bottlenecks causing watermark stalls
Service degradations increasing lateness
Configuration issues with allowed lateness settings
# For example, if there are more than X late events in the last Y minutes, or if there is a backward shift.
# But the requirement doesn't specify the alerting policy.
# We can leave the alerting to the user of this class? Or we can have a callback?
# Alternatively, we can have:
# on_backward_shift_callback
# on_late_event_callback
# But the requirement says "alerts", so we might want to have a way to trigger alerts.
# Since the requirement is vague, we can just record and let the user decide.
# However, the problem says "build an event-time correctness verifier: ... and alerts."
# So we should have a way to raise alerts.
# Let's change the design to have:
# alert_handlers: a list of callables that will be called when an alert condition is met.
# We can have:
# on_backward_shift(shift_info)
# on_late_event(late_event_info)
# Then the user can register handlers that, for example, log or send an email.
# We'll modify the class to have:
# self.backward_shift_handlers = []
# self.late_event_handlers = []
# And when we detect a backward shift, we call each handler in backward_shift_handlers.
# Similarly for late events.
# But note: late events might be many, so we might want to batch them? The requirement doesn't specify.
# Alternatively, we can have a policy: only alert if the number of late events in a time window exceeds a threshold.
# Since the requirement is open, let's stick to per-event alerts for late events? But that might be too noisy.
# We can change the design to:
# For backward shifts: we alert every time.
# For late events: we can have a threshold and a time window.
# But let's keep it simple and just record. The user can then check the recorded lists and decide.
# However, the requirement says "alerts", so we must have some alerting.
# We can do:
# In on_backward_shift: call the backward_shift_handlers immediately.
# In on_event: for late events, we don't call immediately, but we can have a separate function that checks the late_events list and if the count in the last 5 minutes (for example) exceeds 10, then alert.
# But then we need to keep track of the time of late events? We are already storing the event_time and the watermark_at_arrival.
# We can store the arrival time (current processing time) of the event? We didn't. We only stored event_time and watermark_at_arrival.
# We need to store the arrival time to compute the rate? Alternatively, we can have the user provide a function that, given the list of late events, decides when to alert.
# Given the complexity, let's just record and let the user implement the alerting policy by examining the recorded lists.
# But the requirement says we must build the verifier with alerts. So we must include an alerting mechanism.
# We can do:
# alert_on_backward_shift: bool (default True) and alert_on_late_events: bool (default True) and then thresholds?
# Alternatively, we can have:
# self.late_event_threshold = None # if set, then when the number of late events in the last minute (or some window) exceeds this, we alert.
# But we don't have a time window defined.
# Let's change the design to:
# We will have:
# backward_shift_alert: always alert (by calling handlers) when a backward shift is detected.
# late_event_alert: we will batch late events and alert if the number of late events in a sliding window (of fixed size) exceeds a threshold.
# We can have:
# late_event_window_seconds: the size of the sliding window (in seconds) for late events.
# late_event_threshold: the number of late events in the window that triggers an alert.
# We will maintain a deque of late event arrival times (or we can store the arrival time in the late_events list?).
# We change on_event for late events:
# record the current time (when the event arrived) and then when the number of late events in the last `late_event_window_seconds` exceeds `late_event_threshold`, we alert.
# But note: the allowed lateness might change? We are using the current allowed_lateness at the time of the event.
# This is getting complex.
# Given the open-ended requirement, I think we should stick to the simple recording and let the user decide.
# But the requirement says "alerts", so we must have at least a way to trigger alerts.
# Let's do:
# We will have:
# self.backward_shift_handlers = []
# self.late_event_handlers = []
# And when we detect a backward shift, we call each handler with the shift info.
# For late events, we call the handler for every late event? That might be too many.
# We can have:
# self.late_event_handlers are called for every late event? Or we can have a separate mechanism.
# Alternatively, we can have:
# on_backward_shift_callback(shift_info)
# on_late_event_callback(late_event_info) # for every late event
# But then the user can decide to throttle.
# Given that the requirement doesn't specify, we'll do:
# We will provide a way to register callbacks for backward shifts and for late events (per event).
# Then the user can implement their own throttling.
# We change the class:
# def register_backward_shift_handler(self, handler):
# self.backward_shift_handlers.append(handler)
# def register_late_event_handler(self, handler):
# self.late_event_handlers.append(handler)
# Then in on_backward_shift, we call each handler with the shift_info.
# In on_event, when we detect a late event, we call each late_event_handler with the late_event_info.
# But note: the late_event_info we stored in the list is a dict. We can pass that.
# However, we are already storing in the lists. So we can do:
# self.late_events.append(late_event_info)
# for handler in self.late_event_handlers:
# handler(late_event_info)
# Similarly for backward shifts.
# But note: the backward shift is detected in on_watermark_update, and we call the handlers there.
# 13. We might also want to have a way to unregister? Not required by the problem.
# Let's change the class accordingly.
We also need to consider that the allowed_lateness might be updated, and then we might want to re-evaluate past events? But that doesn't make sense because the event's lateness is determined at the time of arrival.
So we don't re-evaluate.
We also note that the watermark might be updated multiple times and we might get events in between.
We must be thread-safe? The problem doesn't specify. We assume single-threaded (as in a streaming operator).
Let's code accordingly.
class LateDataContractVerifier:
"""Validates late data against configured contracts"""
def __init__(self,
default_allowed_lateness_ms: int = 2000,
max_lateness_threshold_ms: int = 60000): # 1 minute
self.default_lateness = default_allowed_lateness_ms
self.max_lateness = max_lateness_threshold_ms
self.contracts: Dict[str, Dict] = {} # contract_name -> config
self.violations: List[ContractViolation] = []
self.late_events: List[LateEvent] = []
# Statistics
self.stats: Dict[str, Dict] = defaultdict(
lambda: {
'total_events': 0,
'late_events': 0,
'very_late_events': 0, # > max_lateness
'lateness_ms': []
}
)
def register_contract(self,
contract_name: str,
allowed_lateness_ms: int,
max_lateness_ms: Optional[int] = None,
window_duration_ms: Optional[int] = None,
apply_to_sources: Optional[List[str]] = None):
"""Register a late data contract"""
self.contracts[contract_name] = {
'allowed_lateness_ms': allowed_lateness_ms,
'max_lateness_ms': max_lateness_ms or self.max_lateness,
'window_duration_ms': window_duration_ms,
'apply_to_sources': apply_to_sources
}
def check_event(self,
event_time: datetime,
processing_time: datetime,
watermark: datetime,
source_id: str,
event_id: str,
window_id: Optional[str] = None) -> Optional[LateEvent]:
"""Check if event is late and violates contracts"""
# Calculate lateness (positive = late)
lateness_ms = (processing_time - event_time).total_seconds() * 1000
# Get applicable contracts
applicable_contracts = self._get_applicable_contracts(source_id, window_id)
violation = None
for contract_name, contract_config in applicable_contracts.items():
allowed = contract_config['allowed_lateness_ms']
max_late = contract_config['max_lateness_ms']
if lateness_ms > allowed:
# This is a late event
late_event = LateEvent(
event_id=event_id,
event_time=event_time,
processing_time=processing_time,
watermark_at_arrival=watermark,
lateness_ms=lateness_ms,
allowed_lateness_ms=allowed,
source_id=source_id,
window_id=window_id
)
self.late_events.append(late_event)
# Update statistics
stats = self.stats[source_id]
stats['total_events'] += 1
stats['late_events'] += 1
stats['lateness_ms'].append(lateness_ms)
if lateness_ms > max_late:
stats['very_late_events'] += 1
violation = ContractViolation(
contract_name=contract_name,
violation_time=processing_time,
observed_value=lateness_ms,
threshold=max_late,
source_id=source_id,
details={
'event_time': event_time.isoformat(),
'allowed_lateness_ms': allowed,
'max_lateness_ms': max_late,
'lateness_ms': lateness_ms
}
)
self.violations.append(violation)
return violation
def _get_applicable_contracts(self, source_id: str, window_id: Optional[str]) -> Dict[str, Dict]:
"""Get contracts applicable to this source/window"""
applicable = {}
for name, config in self.contracts.items():
sources = config.get('apply_to_sources')
if sources is None or source_id in sources:
applicable[name] = config
return applicable
def get_statistics(self, source_id: Optional[str] = None) -> Dict:
"""Get late data statistics"""
if source_id:
return dict(self.stats.get(source_id, {}))
# Aggregate across all sources
agg = {
'total_events': 0,
'late_events': 0,
'very_late_events': 0,
'sources': {}
}
for sid, stats in self.stats.items():
agg['total_events'] += stats['total_events']
agg['late_events'] += stats['late_events']
agg['very_late_events'] += stats['very_late_events']
agg['sources'][sid] = dict(stats)
# Calculate percentiles if we have data
if stats['lateness_ms']:
agg['sources'][sid]['p50_lateness_ms'] = statistics.quantiles(
stats['lateness_ms'], n=10
)[4] # 50th percentile
agg['sources'][sid]['p99_lateness_ms'] = statistics.quantiles(
stats['lateness_ms'], n=100
)[98] # 99th percentile
if agg['total_events'] > 0:
agg['late_rate'] = agg['late_events'] / agg['total_events']
return agg
class EventTimeCorrectnessVerifier:
"""Main verifier that orchestrates all checks"""
def __init__(self,
default_allowed_lateness_ms: int = 2000,
watermark_regression_threshold_ms: int = 100,
alert_rate_limit_secs: int = 300):
self.watermark_monitor = WatermarkMonitor(
regression_threshold_ms=watermark_regression_threshold_ms
)
self.late_data_verifier = LateDataContractVerifier(
default_allowed_lateness_ms=default_allowed_lateness_ms
)
self.alert_manager = AlertManager(
rate_limit_secs=alert_rate_limit_secs
)
# Register default alert handlers
self._setup_default_alert_handlers()
# Statistics
self.start_time = datetime.now()
self.total_events_processed = 0
def _setup_default_alert_handlers(self):
"""Setup default logging handler"""
def log_handler(alert: Alert):
logger.log(
logging.WARNING if alert.severity != AlertSeverity.INFO else logging.INFO,
f"[{alert.severity.value}] {alert.rule_name}: {alert.description}"
)
self.alert_manager.alert_handlers.append(log_handler)
def register_alert_handler(self, handler: Callable[[Alert], None]):
"""Register custom alert handler"""
self.alert_manager.alert_handlers.append(handler)
# ========== Watermark Methods ==========
def add_watermark(self,
watermark: datetime,
source_id: str,
timestamp: Optional[datetime] = None):
"""Process new watermark observation"""
timestamp = timestamp or datetime.now()
observation = WatermarkObservation(
timestamp=timestamp,
watermark_value=watermark,
source_id=source_id
)
issues = self.watermark_monitor.add_observation(observation)
for issue in issues:
self._handle_watermark_issue(issue, source_id)
def _handle_watermark_issue(self, issue: Dict, source_id: str):
"""Handle detected watermark issue"""
if issue['type'] == 'watermark_regression':
self.alert_manager.generate_alert(
severity=AlertSeverity.CRITICAL,
rule_name='watermark_regression',
description=(
f"Watermark regressed by {issue['regression_ms']:.0f}ms "
f"on source {source_id}. "
f"Previous: {issue['previous'].isoformat()}, "
f"Current: {issue['current'].isoformat()}"
),
metadata={
'source_id': source_id,
'regression_ms': issue['regression_ms'],
'previous_watermark': issue['previous'].isoformat(),
'current_watermark': issue['current'].isoformat()
}
)
elif issue['type'] == 'stagnant_watermark':
self.alert_manager.generate_alert(
severity=AlertSeverity.WARNING,
rule_name='stagnant_watermark',
description=(
f"Watermark stagnant for {issue['gap_ms']/1000:.1f}s "
f"on source {source_id}. Advanced only {issue['advance_ms']:.0f}ms."
),
metadata={
'source_id': source_id,
'gap_seconds': issue['gap_ms'] / 1000,
'advance_ms': issue['advance_ms']
}
)
# ========== Event Processing Methods ==========
def process_event(self,
event_time: datetime,
processing_time: Optional[datetime] = None,
source_id: str = "default",
event_id: Optional[str] = None,
window_id: Optional[str] = None) -> Optional[Dict]:
"""
Process an event and check for lateness violations
Returns:
None if no violation, or violation dict if late
"""
processing_time = processing_time or datetime.now()
event_id = event_id or f"event_{self.total_events_processed}"
# Get current watermark for this source
current_watermark = self.watermark_monitor.last_watermark.get(source_id)
if current_watermark is None:
# No watermark yet, can't check lateness
self.total_events_processed += 1
return None
violation = self.late_data_verifier.check_event(
event_time=event_time,
processing_time=processing_time,
watermark=current_watermark,
source_id=source_id,
event_id=event_id,
window_id=window_id
)
self.total_events_processed += 1
if violation:
self._handle_violation(violation)
return asdict(violation)
return None
def _handle_violation(self, violation: ContractViolation):
"""Handle contract violation"""
self.alert_manager.generate_alert(
severity=AlertSeverity.WARNING,
rule_name='late_data_violation',
description=(
f"Event violated contract '{violation.contract_name}' "
f"on source {violation.source_id}. "
f"Lateness: {violation.details['lateness_ms']:.0f}ms, "
f"max allowed: {violation.details['max_lateness_ms']}ms"
),
metadata=violation.details,
count=1
)
# ========== Contract Management ==========
def register_contract(self,
contract_name: str,
allowed_lateness_ms: int,
**kwargs):
"""Register a late data contract"""
self.late_data_verifier.register_contract(
contract_name=contract_name,
allowed_lateness_ms=allowed_lateness_ms,
**kwargs
)
# ========== Reporting Methods ==========
def get_health_report(self) -> Dict:
"""Generate comprehensive health report"""
stats = self.late_data_verifier.get_statistics()
# Get recent alerts
recent_alerts = self.alert_manager.get_active_alerts()
recent_alerts = [a for a in recent_alerts
if (datetime.now() - a.timestamp).total_seconds() < 3600]
return {
'timestamp': datetime.now().isoformat(),
'uptime_seconds': (datetime.now() - self.start_time).total_seconds(),
'total_events_processed': self.total_events_processed,
'late_data_statistics': stats,
'active_alerts': len(recent_alerts),
'recent_alerts': [
{
'severity': a.severity.value,
'rule': a.rule_name,
'description': a.description,
'timestamp': a.timestamp.isoformat()
}
for a in recent_alerts[:10] # Top 10 recent
],
'watermark_sources': list(self.watermark_monitor.history.keys()),
'registered_contracts': list(self.late_data_verifier.contracts.keys())
}
def get_watermark_trends(self, source_id: str, hours: int = 1) -> Dict:
"""Get watermark progression trends for a source"""
if source_id not in self.watermark_monitor.history:
return {'error': f'No data for source {source_id}'}
history = self.watermark_monitor.history[source_id]
cutoff = datetime.now() - timedelta(hours=hours)
recent = [obs for obs in history if obs.timestamp > cutoff]
if len(recent) < 2:
return {'error': 'Insufficient data'}
# Calculate advancement rate
time_span = (recent[-1].timestamp - recent[0].timestamp).total_seconds()
watermark_advance = (
recent[-1].watermark_value - recent[0].watermark_value
).total_seconds()
return {
'source_id': source_id,
'sample_count': len(recent),
'time_span_seconds': time_span,
'watermark_advance_seconds': watermark_advance,
'advance_rate_per_second': watermark_advance / time_span if time_span > 0 else 0,
'current_watermark': recent[-1].watermark_value.isoformat(),
'first_observation': recent[0].timestamp.isoformat(),
'last_observation': recent[-1].timestamp.isoformat()
}
def export_metrics(self, format: str = 'json') -> str:
"""Export metrics in specified format"""
data = {
'health': self.get_health_report(),
'watermark_trends': {
source: self.get_watermark_trends(source)
for source in self.watermark_monitor.history.keys()
},
'late_events': [
asdict(event) for event in self.late_data_verifier.late_events[-100:]
][-100:], # Last 100 late events
'contract_violations': [
asdict(v) for v in self.late_data_verifier.violations[-100:]
][-100:]
}
if format == 'json':
return json.dumps(data, default=str, indent=2)
elif format == 'prometheus':
return self._format_prometheus(data)
else:
raise ValueError(f"Unsupported format: {format}")
def _format_prometheus(self, data: Dict) -> str:
"""Format metrics for Prometheus exposition"""
lines = []
# Help text
lines.append("# HELP event_time_verifier_events_total Total events processed")
lines.append("# TYPE event_time_verifier_events_total gauge")
lines.append(f"event_time_verifier_events_total {data['health']['total_events_processed']}")
lines.append("# HELP event_time_verifier_late_events_total Total late events")
lines.append("# TYPE event_time_verifier_late_events_total gauge")
lines.append(f"event_time_verifier_late_events_total {data['health']['late_data_statistics'].get('late_events', 0)}")
lines.append("# HELP event_time_verifier_active_alerts Total active alerts")
lines.append("# TYPE event_time_verifier_active_alerts gauge")
lines.append(f"event_time_verifier_active_alerts {data['health']['active_alerts']}")
return "\n".join(lines)