Log Test Executions and Query Failure Recovery and Concurrent Failures
Data Structure DesignModel answerLast updated
Design an event-driven system to track test statuses, calculate minimum recovery durations, and identify the longest continuous window of high concurrent failures.
You are tasked with building a monitoring service that tracks automated test suite execution logs over time.
Each incoming log entry records a test_id, a numeric timestamp, and a status which is either "PASS" or "FAIL". Timestamps arrive in strictly monotonically increasing order across all operations.
Implement a class TestTracker with the following methods:
-
log_run(test_id: str, timestamp: int, status: str) -> None:- Records an execution log entry.
- Timestamps are guaranteed to be strictly strictly increasing ($t_i > t_{i-1}$).
- A test transitions to a failing state upon receiving a
"FAIL"log. Consecutive"FAIL"entries for the same test belong to the same continuous failure sequence; the recovery clock starts at the timestamp of the first"FAIL"in this sequence. - A test exits the failing state upon receiving a
"PASS"log.
-
get_min_time_to_pass(test_id: str) -> Optional[int]:- Computes the minimum time taken for
test_idto recover from a failing state to a passing state across all recorded failure-to-pass transitions. - The elapsed time for a transition is defined as $t_{\text{pass}} - t_{\text{first_fail}}$.
- Returns
Noneif the test has never successfully recovered from a failure (or was never logged/failed).
- Computes the minimum time taken for
-
get_longest_failure_window(min_tests: int) -> Optional[Dict[str, int]]:- Finds the maximal continuous time interval $[start_timestamp, end_timestamp]$ during which at least
min_testsdistinct tests were simultaneously in a failing state. - A window opens at the timestamp when the count of currently failing tests reaches or exceeds
min_tests. - A window closes at the timestamp when the count of failing tests drops below
min_tests. - If a window remains open at the end of all logged events, it implicitly closes at the timestamp of the very last recorded event.
- If multiple valid windows share the maximum duration ($end_timestamp - start_timestamp$), return the one with the earliest start timestamp.
- If
min_testsis never reached, returnNone. - Returns a dictionary format:
{"start_timestamp": start_ts, "end_timestamp": end_ts}.
- Finds the maximal continuous time interval $[start_timestamp, end_timestamp]$ during which at least
Hints
Hint 1
For `get_min_time_to_pass`, store state per `test_id`. Remember to track whether an active failure streak is ongoing and record only the timestamp of the *first* failure in that streak.
Hint 2
Since timestamps arrive in strictly increasing order, the global log history is already ordered by time. You do not need to sort events.
Hint 3
For `get_longest_failure_window`, evaluate the state of all tests using a sweep-line technique over the logged events. Maintain a active set of failing test IDs as you iterate through the events.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Architecture
This problem can be split into two parts: per-key online aggregation (get_min_time_to_pass) and multi-key interval analysis over a time series (get_longest_failure_window).
1. Per-Test Failure Recovery Tracking (get_min_time_to_pass)
To evaluate the minimum recovery duration in $O(1)$ time, we process transitions eagerly inside log_run:
- State per test:
active_fail_start: The timestamp of the first failure in the current unbroken streak of"FAIL"logs for this test. If the test is currently passing or has no history, this isNone.min_recovery_time: The smallest duration $(t_{\text{pass}} - t_{\text{first_fail}})$ observed so far for this test.
- State Transitions:
- On
"FAIL": Ifactive_fail_startisNone, set it to the currenttimestamp. If it is already set (consecutive failure), ignore it—the recovery clock must measure from the first failure. - On
"PASS": Ifactive_fail_startis set, calculateduration = timestamp - active_fail_start, updatemin_recovery_time = min(min_recovery_time, duration), and resetactive_fail_start = None.
- On
2. Multi-Test Concurrent Failure Sweep (get_longest_failure_window)
Because timestamps arrive strictly increasing, all recorded events form a naturally sorted stream.
We can evaluate the concurrent failure count using a sweep-line approach over the event stream:
- Maintain a set
failing_testscontaining all test IDs currently in a failing state. - Iterate through all logged events ordered by timestamp:
- If event is
"FAIL", addtest_idtofailing_tests. - If event is
"PASS", removetest_idfromfailing_tests(if present). - Check if
len(failing_tests) >= min_tests:- If the threshold was just met/exceeded (i.e., we were not currently inside an active window), record the current timestamp as
window_start.
- If the threshold was just met/exceeded (i.e., we were not currently inside an active window), record the current timestamp as
- If
len(failing_tests) < min_tests:- If we were currently inside an active window, the window ends at the current timestamp. Calculate
duration = timestamp - window_start, update the best window found so far, and clearwindow_start.
- If we were currently inside an active window, the window ends at the current timestamp. Calculate
- If event is
- After processing all events, if
window_startis still active, close the open window at the timestamp of the last logged event.
Python Source Code
from typing import Dict, List, Optional, Tuple
class TestTracker:
def __init__(self) -> None:
# Chronological list of events: (test_id, timestamp, status)
self.events: List[Tuple[str, int, str]] = []
# Per-test recovery metrics
self.active_fail_start: Dict[str, Optional[int]] = {}
self.min_recovery_time: Dict[str, int] = {}
self.last_timestamp: Optional[int] = None
def log_run(self, test_id: str, timestamp: int, status: str) -> None:
status_upper = status.upper()
if status_upper not in ("PASS", "FAIL"):
raise ValueError(f"Invalid status: {status}")
if self.last_timestamp is not None and timestamp <= self.last_timestamp:
raise ValueError("Timestamps must be strictly monotonically increasing.")
self.last_timestamp = timestamp
self.events.append((test_id, timestamp, status_upper))
if status_upper == "FAIL":
# Only record start time if starting a new failure sequence
if self.active_fail_start.get(test_id) is None:
self.active_fail_start[test_id] = timestamp
else: # PASS
start_time = self.active_fail_start.get(test_id)
if start_time is not None:
duration = timestamp - start_time
current_min = self.min_recovery_time.get(test_id)
if current_min is None or duration < current_min:
self.min_recovery_time[test_id] = duration
# Clear active failure status
self.active_fail_start[test_id] = None
def get_min_time_to_pass(self, test_id: str) -> Optional[int]:
return self.min_recovery_time.get(test_id)
def get_longest_failure_window(self, min_tests: int) -> Optional[Dict[str, int]]:
if not self.events:
return None
failing_tests = set()
best_window: Optional[Tuple[int, int]] = None
best_duration: int = -1
window_start: Optional[int] = None
for test_id, ts, status in self.events:
if status == "FAIL":
failing_tests.add(test_id)
elif status == "PASS":
failing_tests.discard(test_id)
is_threshold_met = len(failing_tests) >= min_tests
if is_threshold_met and window_start is None:
# Open window
window_start = ts
elif not is_threshold_met and window_start is not None:
# Close window
duration = ts - window_start
if duration > best_duration:
best_duration = duration
best_window = (window_start, ts)
window_start = None
# Handle window still open at end of stream
if window_start is not None:
last_ts = self.events[-1][1]
duration = last_ts - window_start
if duration > best_duration:
best_duration = duration
best_window = (window_start, last_ts)
if best_window is None:
return None
return {
"start_timestamp": best_window[0],
"end_timestamp": best_window[1]
}
Complexity Analysis
-
log_run:- Time Complexity: $O(1)$ amortized per call. Dictionary operations and list appends take $O(1)$ time.
- Space Complexity: $O(1)$ per event for storing history, plus $O(T)$ space for tracking per-test metrics where $T$ is the number of distinct
test_ids.
-
get_min_time_to_pass:- Time Complexity: $O(1)$ lookup in the precomputed dictionary.
- Space Complexity: $O(1)$ auxiliary space.
-
get_longest_failure_window:- Time Complexity: $O(N)$ where $N$ is the total number of logged events. The algorithm performs a single linear pass over
self.events, doing $O(1)$ set additions and updates per event. - Space Complexity: $O(T)$ auxiliary space to track
failing_testsset.
- Time Complexity: $O(N)$ where $N$ is the total number of logged events. The algorithm performs a single linear pass over
Edge Cases & Scalability Considerations
- Repeated Fails/Passes:
FAILfollowed by anotherFAIL: Ignored for clock-start computation.PASSfollowed by anotherPASS: Ignored if no active failure exists.
- Window Active at End of Logs:
- Closed at
self.events[-1][1]. If threshold is first reached at the final event $t_{\text{last}}$, the algorithm produces a zero-length window $[t_{\text{last}}, t_{\text{last}}]$ with duration0, which is valid.
- Closed at
- Threshold never met: Returns
None. - Optimizing Read Heavy Workloads:
- If
get_longest_failure_windowis queried frequently relative tolog_run, we can maintain dynamic aggregated counts or precalculate interval endpoints upon every log ingestion, trading off $O(1)$ write time for faster query times.
- If