Align Asynchronous Cycle-Count Traces Onto Shared Timestamps
Medium · Software Engineering Fundamentals · Member of Technical Staff, ML Systems · Onsite
Problem Statement
Two hardware telemetry traces, series_a and series_b, capture [timestamp, value] pairs stamped against CPU cycle counters at independent, uncoordinated times. Given both traces together with a sorted list of query cycle counts boundaries, evaluate both traces on boundaries under a shared piecewise-linear alignment contract.
def align_cpu_series(
series_a: List[List[float]],
series_b: List[List[float]],
boundaries: List[float],
) -> List[List[Optional[float]]]:
Enforce the following alignment and validation rules:
- Input ordering (
ValueError): Within each trace, consecutive sample timestamps must strictly increase (curr_ts > prev_ts). Entries inboundariesmust appear in non-decreasing order (boundaries[i] >= boundaries[i - 1]; identical consecutive query timestamps are permitted and produce duplicate output rows). RaiseValueErrorwhenever either ordering requirement fails. - Exact hits & linear interpolation: A non-empty trace covers the closed span
[first_ts, last_ts]from its earliest sample timestamp to its latest sample timestamp:- If query timestamp
tcoincides with a recorded sample[ts, val], its aligned value isval(including when the trace has only a single sample). - If
tlies strictly inside an adjacent sample pair[t0, v0]and[t1, v1](t0 < t < t1), computev0 + (v1 - v0) * (t - t0) / (t1 - t0).
- If query timestamp
- Missing values outside observed bounds: Never extrapolate beyond observed data. Whenever a trace is empty (
[]),t < first_ts, ort > last_ts, reportNonefor that trace att. - Output structure: Return a list of
[t, value_a, value_b]rows—one per elementtofboundaries, in matching order.
Examples
Example 1
Input:
series_a = [[100, 10], [200, 30]]
series_b = [[150, 50], [250, 10]]
boundaries = [100, 150, 200, 250]
Output:
[[100, 10, None], [150, 20.0, 50], [200, 30, 30.0], [250, None, 10]]
At cycle 100, series_a begins at 10 while series_b has not started (None). At 150, series_a is halfway across [100, 200] (20.0) and series_b hits 50. At 200, series_a reaches 30 and series_b is halfway between 50 and 10 (30.0). At 250, series_a has already ended (None) and series_b hits 10.
Example 2
Input:
series_a = [[0, 4], [6, 16], [12, 10]]
series_b = [[3, 20], [9, 32]]
boundaries = [2, 3, 6, 9, 12]
Output:
[[2, 8.0, None], [3, 10.0, 20], [6, 16, 26.0], [9, 13.0, 32], [12, 10, None]]
series_a rises at +2 per cycle on [0, 6] (giving 8.0 at t = 2, 10.0 at t = 3, and 16 at t = 6) and falls at -1 per cycle on [6, 12] (giving 13.0 at t = 9 and 10 at t = 12). Meanwhile series_b spans [3, 9], producing None at t = 2 and t = 12, exact values 20 and 32 at its endpoints, and midpoint 26.0 at t = 6.
Example 3
Input:
series_a = [[10, 6], [14, 14]]
series_b = [[8, 0], [16, 24]]
boundaries = [6, 8, 10, 12, 16]
Output:
[[6, None, None], [8, None, 0], [10, 6, 6.0], [12, 10.0, 12.0], [16, None, 24]]
Query 6 precedes both traces ([6, None, None]). Across [10, 14], both traces overlap and produce interpolated pairs, before series_a ends prior to t = 16.
Constraints
0 <= len(series_a), len(series_b), len(boundaries) <= 10^5- Valid traces satisfy
series[i][0] > series[i - 1][0]for alli >= 1; non-increasing timestamps must raiseValueError. - Valid query grids satisfy
boundaries[i] >= boundaries[i - 1]for alli >= 1; unsortedboundariesmust raiseValueError. - The two traces may share zero timestamps, overlap partially, or be completely disjoint.
Step-by-step walkthrough
Lock down the alignment contract
Before coding, let's summarize the exact rules that govern every query timestamp in
boundaries:- Target timestamps: Supplied by the caller in
boundaries, sorted in non-decreasing order (boundaries[i] >= boundaries[i - 1]). - Instantaneous value via linear segments: Each query
treads an instantaneous value off the straight-line segments connecting consecutive[timestamp, value]samples (piecewise-linear interpolation). - No extrapolation outside observed spans: A non-empty trace is defined only across
[first_ts, last_ts], both endpoints included. Queries strictly belowfirst_tsor strictly abovelast_tsevaluate toNone. - Exact sample matches: Whenever
tequals a sample's timestamp, return that sample's recorded value directly. - Row layout: Emit
[t, value_a, value_b]for eachtinboundaries, preserving order.
Here is Example 1 (
series_a = [[100, 10], [200, 30]],series_b = [[150, 50], [250, 10]],boundaries = [100, 150, 200, 250]) plotted on a shared cycle axis:Cycle t: 100 150 200 250 | | | | Series A: (100,10)------[t=150]-----(200,30) None (A ends at 200) val=10 val=20.0 val=30 Series B: None (150,50)----[t=200]-----(250,10) (B starts at 150) val=50 val=30.0 val=10 Output rows: [100,10,None] [150,20,50] [200,30,30] [250,None,10]We also guard against malformed inputs by raising
ValueErrorwhenever timestamps inside a trace fail to strictly increase (curr_ts <= prev_ts) orboundariesdecreases (boundaries[i] < boundaries[i - 1]).- Target timestamps: Supplied by the caller in
Why scanning from scratch per boundary is too slow
When a query
tfalls inside[left_ts, right_ts], how far across the interval(right_ts - left_ts)doestsit?fraction = (t - left_ts) / (right_ts - left_ts) interpolated = left_val + (right_val - left_val) * fractionAt
t == left_ts,fractionis0(left_val); halfway across,fractionis0.5(the midpoint value).If we searched from index
0on every single querytto locate its bracketing segment,Bboundaries acrossnsamples would takeO(B * n)work. Hardware cycle traces routinely contain hundreds of thousands of readings and thousands of query points, turningB * ninto billions of redundant comparisons.Key idea: advance one segment pointer forward
Both
seriesandboundariesare ordered in non-decreasing time. Onceboundaries[i]lands in segmentseg_idx, the next queryboundaries[i + 1] >= boundaries[i]can only land in segmentseg_idxor a later segment—never an earlier one.Keeping a single index
seg_idxper trace that only steps rightward eliminates all backtracking:series_a: [0]---------[6]---------[12] boundaries: 2 3 6 9 12 seg_idx: 0 0 1 --> 1 --> 2 (never resets to 0!)Across all
Bqueries,seg_idxincrements at mostn - 1times total, cutting the runtime per trace fromO(B * n)down toO(n + B). Evaluatingseries_aandseries_bindependently with the same helper also handles completely disjoint or unshared timestamps automatically.Validate timestamps and boundary order
Before sweeping,
_check_seriesverifies strictly increasing sample timestamps. Rejectingcurr_ts <= prev_tsprevents both zero-width division (right_ts - left_ts == 0) on duplicate timestamps and silent corruption when a hardware cycle register wraps or resets backward.def _check_series(series: List[List[float]], name: str) -> None: """Verify timestamps strictly increase; equal or decreasing timestamps break segments.""" # series: list of [timestamp, value] pairs, e.g. [[0, 4], [6, 16], [12, 10]] for i in range(1, len(series)): prev_ts = series[i - 1][0] curr_ts = series[i][0] # Reject <= (not just <): duplicate timestamps make segment width 0 (division by zero), # and decreasing timestamps typically signal a CPU cycle counter reset or wraparound. if curr_ts <= prev_ts: raise ValueError(f"{name}: timestamps must strictly increase (index {i})")Interpolate one trace in a single pass
Inside
_values_at(series, boundaries), an empty trace immediately returns[None] * len(boundaries). Otherwise each querytruns through four clean stages:- Range check (
t < first_ts or t > last_ts): AppendNone. Any query reaching stage 2 is guaranteed to satisfyfirst_ts <= t <= last_ts. - Advance
seg_idx: Whileseg_idx + 1 < len(series)andseries[seg_idx + 1][0] <= t, incrementseg_idx. Using<=stepsseg_idxdirectly onto a sample whenevertmatches that sample's timestamp. - Exact sample hit (
t == left_ts): Appendleft_valverbatim. This avoids floating-point rounding drift and safely handlest == last_ts(whereseg_idx == len(series) - 1, soseries[seg_idx + 1]does not exist). - Linear interpolation: Because
t <= last_tsandt != left_ts,seg_idx + 1is guaranteed to exist withleft_ts < t < right_ts. Computefractionandinterpolated.
def _values_at(series: List[List[float]], boundaries: List[float]) -> List[Optional[float]]: """Interpolate `series` at each sorted boundary; return None outside [first_ts, last_ts].""" if len(series) == 0: return [None] * len(boundaries) first_ts = series[0][0] last_ts = series[-1][0] # values: one interpolated float (or None if out of range) per boundary timestamp values: List[Optional[float]] = [] # seg_idx: index of the left sample [left_ts, left_val] bracketing the current boundary; # only moves forward because both `series` and `boundaries` are sorted. seg_idx = 0 for t in boundaries: # Phase 1: Out-of-range check. Strict < and > keep exact endpoints [first_ts, last_ts] valid, # while reporting None outside the observed span instead of extrapolating. if t < first_ts or t > last_ts: values.append(None) continue # Phase 2: Advance seg_idx while the next sample is at or before t. # Using <= lands seg_idx directly on the sample whenever t matches a sample timestamp. while seg_idx + 1 < len(series) and series[seg_idx + 1][0] <= t: seg_idx += 1 left_ts, left_val = series[seg_idx] # Phase 3: Exact sample hit. Returning left_val directly avoids floating-point rounding # and safely handles t == last_ts (where series[seg_idx + 1] does not exist). if t == left_ts: values.append(left_val) continue # Phase 4: Linear interpolation inside (left_ts, right_ts). # Invariant: left_ts < t < right_ts and seg_idx + 1 < len(series) because t <= last_ts and t != left_ts. right_ts, right_val = series[seg_idx + 1] fraction = (t - left_ts) / (right_ts - left_ts) interpolated = left_val + (right_val - left_val) * fraction values.append(interpolated) return values- Range check (
Trace Example 2 and assemble the aligned rows
Let's walk through Example 2 (
series_a = [[0, 4], [6, 16], [12, 10]],series_b = [[3, 20], [9, 32]],boundaries = [2, 3, 6, 9, 12]):Boundary t | Series A (span [0, 12]) | Series B (span [3, 9]) -----------+----------------------------------------------+------------------------------------- t = 2 | seg_idx=0, seg [0,6]: 4 + 12*(2/6) = 8.0 | 2 < first_ts (3) -> None t = 3 | seg_idx=0, seg [0,6]: 4 + 12*(3/6) = 10.0 | seg_idx=0, exact hit t==3 -> 20 t = 6 | seg_idx->1, exact hit t==6 -> 16 | seg_idx=0, seg [3,9]: 20 + 12*(3/6) = 26.0 t = 9 | seg_idx=1, seg [6,12]: 16 + (-6)*(3/6) = 13.0| seg_idx->1, exact hit t==9 -> 32 t = 12 | seg_idx->2, exact hit t==12 -> 10 | 12 > last_ts (9) -> NonePairing
[boundaries[i], values_a[i], values_b[i]]yields[[2, 8.0, None], [3, 10.0, 20], [6, 16, 26.0], [9, 13.0, 32], [12, 10, None]], matching Example 2.def align_cpu_series( series_a: List[List[float]], series_b: List[List[float]], boundaries: List[float], ) -> List[List[Optional[float]]]: # Ensure boundaries are non-decreasing so the single forward pointer in _values_at stays valid. # Equal consecutive boundaries (curr < prev is False) are allowed and simply repeat the row. for i in range(1, len(boundaries)): if boundaries[i] < boundaries[i - 1]: raise ValueError("boundaries must be sorted in non-decreasing order") _check_series(series_a, "series_a") _check_series(series_b, "series_b") # Evaluate both series independently on the shared boundary timestamps. values_a = _values_at(series_a, boundaries) values_b = _values_at(series_b, boundaries) # rows: list of [boundary_ts, val_a_or_None, val_b_or_None] aligned to `boundaries` rows: List[List[Optional[float]]] = [] for i in range(len(boundaries)): rows.append([boundaries[i], values_a[i], values_b[i]]) return rowsComplete solution
from typing import Any, Dict, List, Optional, Set, Tuple def _check_series(series: List[List[float]], name: str) -> None: """Verify timestamps strictly increase; equal or decreasing timestamps break segments.""" # series: list of [timestamp, value] pairs, e.g. [[0, 4], [6, 16], [12, 10]] for i in range(1, len(series)): prev_ts = series[i - 1][0] curr_ts = series[i][0] # Reject <= (not just <): duplicate timestamps make segment width 0 (division by zero), # and decreasing timestamps typically signal a CPU cycle counter reset or wraparound. if curr_ts <= prev_ts: raise ValueError(f"{name}: timestamps must strictly increase (index {i})") def _values_at(series: List[List[float]], boundaries: List[float]) -> List[Optional[float]]: """Interpolate `series` at each sorted boundary; return None outside [first_ts, last_ts].""" if len(series) == 0: return [None] * len(boundaries) first_ts = series[0][0] last_ts = series[-1][0] # values: one interpolated float (or None if out of range) per boundary timestamp values: List[Optional[float]] = [] # seg_idx: index of the left sample [left_ts, left_val] bracketing the current boundary; # only moves forward because both `series` and `boundaries` are sorted. seg_idx = 0 for t in boundaries: # Phase 1: Out-of-range check. Strict < and > keep exact endpoints [first_ts, last_ts] valid, # while reporting None outside the observed span instead of extrapolating. if t < first_ts or t > last_ts: values.append(None) continue # Phase 2: Advance seg_idx while the next sample is at or before t. # Using <= lands seg_idx directly on the sample whenever t matches a sample timestamp. while seg_idx + 1 < len(series) and series[seg_idx + 1][0] <= t: seg_idx += 1 left_ts, left_val = series[seg_idx] # Phase 3: Exact sample hit. Returning left_val directly avoids floating-point rounding # and safely handles t == last_ts (where series[seg_idx + 1] does not exist). if t == left_ts: values.append(left_val) continue # Phase 4: Linear interpolation inside (left_ts, right_ts). # Invariant: left_ts < t < right_ts and seg_idx + 1 < len(series) because t <= last_ts and t != left_ts. right_ts, right_val = series[seg_idx + 1] fraction = (t - left_ts) / (right_ts - left_ts) interpolated = left_val + (right_val - left_val) * fraction values.append(interpolated) return values def align_cpu_series( series_a: List[List[float]], series_b: List[List[float]], boundaries: List[float], ) -> List[List[Optional[float]]]: # Ensure boundaries are non-decreasing so the single forward pointer in _values_at stays valid. # Equal consecutive boundaries (curr < prev is False) are allowed and simply repeat the row. for i in range(1, len(boundaries)): if boundaries[i] < boundaries[i - 1]: raise ValueError("boundaries must be sorted in non-decreasing order") _check_series(series_a, "series_a") _check_series(series_b, "series_b") # Evaluate both series independently on the shared boundary timestamps. values_a = _values_at(series_a, boundaries) values_b = _values_at(series_b, boundaries) # rows: list of [boundary_ts, val_a_or_None, val_b_or_None] aligned to `boundaries` rows: List[List[Optional[float]]] = [] for i in range(len(boundaries)): rows.append([boundaries[i], values_a[i], values_b[i]]) return rows✅ Submit now — all tests should pass.
Intuition & how it works
Picture two hardware probes logging CPU metrics at uncoordinated moments, and plotting both traces on shared graph paper by drawing straight lines dot-to-dot between consecutive samples. This dot-to-dot model is piecewise-linear interpolation, which estimates a metric at any intermediate timestamp along the straight line joining its nearest left and right samples. To compare both probes on one schedule, we place vertical markers at every timestamp in boundaries and read off where each curve crosses the marker—returning None wherever a trace has not started yet or has already finished, instead of extrapolating (projecting lines past the first or last recorded reading).
Scanning an entire n-sample trace from index 0 for every one of the B query timestamps repeats nearly the entire search each time, costing O(B * n) operations. Instead, we use a two-pointer scan—an algorithm that walks two sorted sequences with an index that only moves forward—so our segment pointer seg_idx never backtracks from one query timestamp to the next.
Trace Example 1 with series_a = [[100, 10], [200, 30]], series_b = [[150, 50], [250, 10]], and boundaries = [100, 150, 200, 250]:
1. At t = 100: series_a hits its initial sample (10), whereas series_b has not begun (100 < 150 -> None), yielding [100, 10, None].
2. At t = 150: series_a sits halfway across [100, 200], giving 10 + (30 - 10) * (50 / 100) = 20.0; series_b hits (150, 50), yielding [150, 20.0, 50].
3. At t = 200: series_a advances seg_idx to (200, 30) for 30; series_b sits halfway across [150, 250], giving 50 + (10 - 50) * (50 / 100) = 30.0, yielding [200, 30, 30.0].
4. At t = 250: series_a has ended (250 > 200 -> None), whereas series_b hits (250, 10), yielding [250, None, 10].
Complexity
Let n_a be len(series_a), n_b be len(series_b), and B be len(boundaries).
- Time:
O(n_a + n_b + B). Validating ordering scans each input once, and inside_values_atthe pointerseg_idxincrements at mostn - 1times total across allBqueries while each query performsO(1)arithmetic. - Space:
O(B)to holdvalues_a,values_b, and theBoutput rows (only scalar variables are used during the sweep).
Edge cases
- Empty trace (
[]): Contains no samples, so every query timestamp receivesNonefor that trace. - Single-sample trace (
[[5, 7]]): Defined solely att = 5(returning7); any queryt != 5falls outside[5, 5]and receivesNone. - Queries matching
first_tsorlast_ts: Both endpoints are inclusive and return the exact recorded value without indexingseries[seg_idx + 1]. - Queries outside
[first_ts, last_ts]: ProduceNonerather than extending the edge slope. - Unshared or disjoint spans: Handled seamlessly because
series_aandseries_bare evaluated independently onboundaries. - Duplicate entries in
boundaries: Permitted (boundaries[i] < boundaries[i - 1]isFalseon ties) and emit identical consecutive rows. - Large cycle counts (
10^12+): Pythonintarithmetic computest - left_tsandright_ts - left_tsexactly; when ingesting 64-bit float arrays (float64, which represents integers exactly only up to2^53), subtract an integer base cycle offset before converting to float. - Non-increasing trace timestamps or unsorted boundaries: Raise
ValueErrorupfront instead of dividing by zero or misplacingseg_idx.
Common mistakes
- Extrapolating past
first_tsorlast_ts: Extending the first or last segment's slope invents unmeasured values instead of returningNone. - Using
<=/>=in the out-of-bounds guard (t <= first_ts): Wrongly turns exact endpoint hits intoNone. - Resetting
seg_idx = 0per query: Degrades theO(n + B)sweep back toO(B * n). - Evaluating the division formula when
t == left_ts: Introduces unnecessary float rounding and triggersIndexErroronseries[seg_idx + 1]whent == last_ts. - Outputting at the union of sample timestamps: Ignores the caller-supplied
boundariesschedule.
Alternative approaches
- Per-query binary search (
bisect): Binary search repeatedly halves a sorted array to locate a target position inO(log n)comparisons. Running it per query takesO(B log n)time, works even on unsortedboundaries, and beats a linear scan whenBis tiny relative ton(such as 5 queries across 10 million samples). - NumPy
np.interp: Runs in vectorized C, thoughnp.interpclamps out-of-bounds queries to endpoint values by default, requiringleft=np.nan, right=np.nanplus NaN-to-Noneconversion.
Follow-up questions
- How would you modify the pass if each interval [b_i, b_{i+1}] required a time-weighted mean instead of an instantaneous value at b_i? The time-weighted mean of a continuous curve across
[b_i, b_{i+1}]equals the area under the curve divided byb_{i+1} - b_i. Because each piece is linear, compute the area via the trapezoidal rule—where the area under a line segment over[lo, hi]is(hi - lo) * (val_lo + val_hi) / 2—clipped to[b_i, b_{i+1}], advancing a single segment pointer across adjacent windows inO(n + B)time (returningNonewhenever[b_i, b_{i+1}]is not fully covered by[first_ts, last_ts]).
def window_average(series, start, end):
"""Time-weighted mean of piecewise-linear `series` on [start, end], or None if uncovered."""
if len(series) == 0 or end <= start or start < series[0][0] or end > series[-1][0]:
return None
total_area = 0.0
for i in range(len(series) - 1):
left_ts, left_val = series[i]
right_ts, right_val = series[i + 1]
lo = max(left_ts, start)
hi = min(right_ts, end)
if lo < hi:
slope = (right_val - left_val) / (right_ts - left_ts)
val_lo = left_val + slope * (lo - left_ts)
val_hi = left_val + slope * (hi - left_ts)
total_area += (hi - lo) * (val_lo + val_hi) / 2.0
return total_area / (end - start)
- How would you adapt this into a streaming operator when interpolating at timestamp t must wait for the next sample after t to arrive? Keep only the latest observed sample
(prev_ts, prev_val)per stream alongside a FIFO queue of pending query timestamps. Each time a new sample(curr_ts, curr_val)arrives, every queued queryt <= curr_tsnow has its right endpoint and resolves immediately (Noneiftpreceded the stream's very first sample, or interpolated across[prev_ts, curr_ts]), emitting[t, val_a, val_b]once both streams resolvet. To prevent unbounded memory growth if one probe goes silent, enforce a watermark—a timestamp cutoff declaring no valid readings older than a timeout will arrive—to flush stalled queries withNone. - How can an ingestion pipeline tell apart fixed-width cycle-counter wraparound from an unexpected counter reset? Whenever
curr_ts <= prev_ts, test whether counter wraparound—where aW-bit hardware register overflows past2^W - 1back through0—explains the drop by checking whether(curr_ts + 2^W) - prev_tsmatches the expected sampling cadence in cycles. If it matches, add2^Wto unwrap subsequent timestamps into a continuous monotone timeline; if the delta is erratic (caused by a reboot or thread migration across unsynchronized cores), split the trace at the discontinuity and reportNoneacross the gap instead of interpolating across invalid data. Note that a 32-bit counter at 4 GHz wraps roughly every1.07seconds, whereas a 64-bit counter runs for ~146 years.
Follow-up questions
- How would you modify the pass if each interval [b_i, b_{i+1}] required a time-weighted mean instead of an instantaneous value at b_i?
- How would you adapt this into a streaming operator when interpolating at timestamp t must wait for the next sample after t to arrive?
- How can an ingestion pipeline tell apart fixed-width cycle-counter wraparound from an unexpected counter reset?
Similar questions
- Natural-Language Image Search Architecture
- Batch LLM Inference with Heterogeneous Hardware Routing
- LRU Cache Implementation
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination