Log and Metric Processing
Thirty original Python problems on telemetry identity, counter and histogram support, exact rollups, log structure, trace duration, alert evidence, time-series alignment and constrained retention. Process explicitly supplied models without hiding missing or ambiguous data.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Canonicalize series labels without hiding duplicate keys
Write
metric_series(rows). Rows[metric_name,label_pairs], strings only. A row repeating ANY label key is invalid, even equal values. Valid series identity is metric name plus sorted label pairs. Return[groups,invalid_indices]; each group[name,sorted_pairs,input_indices], sorted by identity, retaining all valid occurrences. Invalid indices in input order. No mutation.2.Keep counter deltas unsupported across epoch changes
Write
counter_deltas(samples), rows [strictly_increasing_integer_time,string_epoch,nonnegative_integer_count]. Return[previous_time,time,delta_or_None,reason_or_None]for each adjacent pair. Different epochs give reason"epoch"; otherwise a decreasing count gives"decrease"; otherwise delta=current-previous and reasonNone. Do not assume a reset or wrap amount. No mutation.3.Recover disjoint mass from cumulative histogram evidence
Write
bucket_counts(rows). Rows[upper_bound,cumulative_count], bound integer orNone(overflow), count nonnegative integer. Require exactly oneNone, no repeated bound, and cumulative counts nondecreasing after sorting finite bounds then overflow. Return[bound,disjoint_count]in that order by adjacent differences from zero; returnNoneif invalid. Finite bounds may be negative. No mutation.4.Return the bin supporting a histogram quantile rank
Write
quantile_interval(bins,num,den). Ordered disjoint rows[low,high,count], integer low<high and count>=0; 0<num<=den integers. For total N>0, nearest rank isceil(num*N/den), one-based. Return[low,high]of the bin containing that rank, skipping zero counts. If N=0 returnNone. Do not interpolate or invent an exact observation within a bin. No mutation.5.Join metric ratios with explicit ambiguity and zero support
Write
metric_ratios(numerator,denominator), rows[string_key,integer_value]. For every key in either side, return[key,reduced_fraction_or_None,reason_or_None], sorted. Reason priority:"ambiguous"if either side has >1 row, else"missing"if either is absent, else"zero"if denominator=0, else ratio as[numerator,positive_denominator]. Identical duplicates remain ambiguous. No mutation.6.Find distinct series merged by a label projection
Write
projection_collisions(rows,keep), rows string->string label maps. Project onto PRESENT keys in keep. Report projections with >=2 DISTINCT full original maps. Return[sorted_projected_pairs,input_indices]per collision, sorted by projection. Include every occurrence index in a colliding group. Repeated identical originals alone are not collisions. Missing differs from empty. No mutation.7.Aggregate integers while preserving missing support
Write
nullable_rollup(rows),[string_key,integer_or_None]. Return sorted [key,row_count,valid_count,sum_or_None,min_or_None,max_or_None].Noneis missing; zero is valid. If a group has no valid value all three aggregates areNone. Count every row occurrence, including repeated samples. Empty rows returns []. No mutation.8.Query half-open telemetry windows with occurrence support
Write
window_totals(events,queries). Events[integer_time,string_key,integer_delta], arbitrary order; duplicate rows are separate events. Queries[start,end,key], start<=end, select start<=time<end. Return[sum_of_deltas,event_count]per query. No matching events gives[0,0], which differs from a supported zero total. Do not mutate. Support many queries without rescanning every event per query.9.Union incident evidence inside a supplied time horizon
Write
incident_duration(spans,horizon). Spans[string_kind,integer_start,integer_end], start<end; horizon[a,b], a<b. Clip to [a,b), union overlap/adjacency PER kind, and return sorted[kind,covered_duration]. Every kind appearing in input remains listed, even if coverage is zero. Repeated overlapping evidence counts once. No mutation.10.Pair unique request endpoints without inventing duration
Write
request_pairs(events), rows[string_request,"start"/"end",integer_time], arbitrary order. Return sorted[request,duration_or_None,reason_or_None]. Reason priority:"ambiguous"if >1 start OR >1 end, else"missing"if either side absent, else"time"if end<start, otherwise end-start. Identical duplicate events are still ambiguous; zero duration is valid. No mutation.11.Subtract direct child coverage once from span time
Write
exclusive_times(spans), unique-ID rows[id,parent_or_None,start,end], integer start<=end. ReturnNonefor missing parent, parent cycle, or child outside parent interval. Otherwise return sorted[id,own_duration-UNION_duration_of_direct_children]. Children may overlap; grandchildren are not subtracted again. Zero-duration spans valid. No tracing API claim or mutation.12.Look up typed JSON paths without confusing null and absence
Write
path_values(queries),[JSON_value,path_tokens]. String tokens index objects by exact key; integer tokens index arrays only, 0<=index<len. Wrong container type or missing key/index fails. Return[found_bool,detached_value_or_None]per query. Empty path finds root. Explicit null is found; numeric strings are not array indices. Tokens are strings or integers, never booleans. No mutation.13.Assemble log continuations and report orphan lines
Write
continuation_records(lines), strings without newline characters. A nonempty unindented line starts a record. A line starting ASCII space/tab appends to the active record with a newline, retaining all whitespace; without an active record report its index as orphan. An empty line ends the active record and is not stored. Return[record_strings,orphan_indices]. No mutation.14.Replace matching JSON nodes using exact-depth path patterns
Write
redact_paths(value,patterns). Token-list patterns use string object keys, integer array indices, or"*"for ANY single key/index. Match the node's ENTIRE path. Replace matching node by"[redacted]"without visiting children; [] matches root. Return detached JSON; unmatched data unchanged. Supplied transform only, no comprehensive privacy claim. No mutation.15.Report exact observed latency quantiles with support counts
Write
latency_quantiles(rows,num,den),[string_endpoint,nonnegative_latency_or_None], 0<num<=den integers. IgnoreNonefor order statistics but keep every endpoint represented. Return sorted[endpoint,valid_count,nearest_rank_latency_or_None], rankceil(num*valid_count/den), one-based. Repeated samples each count. No interpolation, missing-to-zero coercion or mutation.16.Reconcile sample revisions with typed conflict evidence
Write
reconcile_samples(rows),[string_series,integer_time,nonnegative_revision,JSON_value]. Per (series,time), consider ONLY maximum-revision rows. If their values differ under typed JSON equality, emit[series,time,None,True]; otherwise[series,time,detached_value,False]. Bool differs from number; numeric values compare by value, object key order irrelevant. Sort by series/time. No mutation.17.Attach the first matching time-and-label silence witness
Write
silence_matches(alerts,silences). Alerts[id,time,label_map]; silences[start,end,required_labels], start<end; times integers, IDs/labels strings. Match iff start<=time<end AND all required keys exist with equal values. Return[alert_id,first_matching_silence_index_or_None]per occurrence. Empty requirements match any labels in time. No notification actions or mutation.18.Preserve clear, unknown and open endings of alert episodes
Write
alert_episodes(samples),[strictly_increasing_integer_time,status], firing/clear/unknown. Firing starts/continues an episode. Clear ends it at that time; unknown ends evidence WITHOUT a known clear time. Return[start,last_firing_time,clear_time_or_None,reason], reason clear/unknown/open (input ended). Clear/unknown without an active episode do nothing. No mutation.19.Compute exact means with time-decayed sample mass
Write
decayed_means(samples),[nondecreasing_integer_time,integer_value], total time span<=20. Before each observation, multiply all existing sample weights by 2**(-elapsed_time); add the new observation with weight 1. Return the weighted mean after each insertion as reduced[numerator,positive_denominator]. Equal-time observations cause no decay. Empty input returns []. No mutation.20.Interpolate interior gaps between supported anchors
Write
interpolate_samples(samples),[strictly_increasing_integer_time,integer_or_None]. Replace a missing value ONLY if there is a nearest known sample on both sides, using linear interpolation by time. Return values as reduced[numerator,positive_denominator], keeping unsupported leading/trailingNone. Known zero values are anchors. Do not extrapolate or mutate.21.Locate a supported telemetry split using exact squared loss
Write
change_point(values,minimum), <=12 integers, minimum>=1. Consider split k with >=minimum observations on EACH side. Score=sum((x-left_mean)**2 on left)+sum((x-right_mean)**2 on right), using exact rational means. Return [best_k,[score_numerator,positive_denominator]], ties smaller k, orNoneif no supported split. No statistical significance claim or mutation.22.Retain alarm state between distinct high and low thresholds
Write
hysteresis(values,low,high), low<high integers, values integers orNone. Start stateFalse. A known value>=high setsTrue; <=low setsFalse; between thresholds orNoneretains state. Return[state_after_each_sample,indices_where_state_changed]. Equality triggers its threshold. Missing evidence never invents a transition. No mutation.23.List bounded increments consistent with counter wraps
Write
wrap_candidates(old,new,modulus,max_delta). modulus>=1, 0<=old,new<modulus, 0<=max_delta<=1000 integers. Return ALL integer increments d in[0,max_delta]with (old+d)%modulus==new, sorted. Multiple wraps are possible; do not choose one supported increment when several fit. Empty list means no bounded support. No mutation.24.Rename labels simultaneously and report collisions
Write
rename_labels(rows,mapping), rows string->string label maps; mappingold_key->new_keyapplies SIMULTANEOUSLY. Unmapped keys retain their name. If >=2 source keys target one destination, return[None,sorted_collision_keys]for that row, even equal values. Otherwise [renamed_map,[]]. Preserve row order and do not mutate. Mapping entries absent from a row have no effect.25.Attach exemplars only to unique recent prior samples
Write
attach_exemplars(samples,exemplars,max_age). Samples[series,time]; exemplars[trace,series,time]; names strings, times integers,max_age>=0. Find same-series samples at time<=exemplar time; choose latest time.Nonegives"missing"; >1 latest sample"ambiguous"; else age>max_age"stale"; else use original sample index. Return[trace,index_or_None,reason_or_None]. No mutation.26.Find intervals lacking enough distinct telemetry sources
Write
coverage_gaps(spans,horizon,minimum). Rows[string_source,start,end], integer start<end; horizon[a,b], a<b; minimum>=0 integer. Clip spans to [a,b). At each instant count DISTINCT active sources, not overlapping reports. Return maximal half-open intervals where count<minimum, sorted. Adjacent insufficient intervals merge even if source identities change. No mutation.27.Merge supported moment summaries with exact variance
Write
moment_rollup(chunks), integer rows[count,sum,square_sum], count>=0. Valid support: count=0 requires sum=square_sum=0; count=1 requiressquare_sum=sum**2; count>1 requires count*square_sum>=sum**2. Any invalid chunk returnsNone. Otherwise merge and return[N,mean_fraction,variance_fraction], population variance Q/N-(S/N)**2. Fractions reduced; N=0 gives[0,None,None]. No mutation.28.Align telemetry without crossing or reusing observations
Write
align_telemetry(left,right,tolerance), strictly increasing integer time lists of length<=8, tolerance>=0. Choose index pairs[i,j]withabs(left[i]-right[j])<=tolerance; both indices must increase strictly. Maximize pair count, then minimize total absolute lag, then lexical pair-list order. Return the chosen pairs. An observation cannot be reused; empty support returns []. No mutation.29.Choose log records under a byte budget while honoring pins
Write
retain_logs(records,budget), <=12 rows[nonnegative_bytes,nonnegative_priority,pinned_bool], budget>=0 integer. Keep EVERY pinned record. Among feasible subsets maximize total priority, then record count, then prefer the lexicographically smallest sorted index list. Return those indices, orNoneif pins alone exceed budget. Count every record occurrence. No actual deletion or mutation.30.Capture log substrings with shortest-first star lengths
Write
glob_captures(tokens,text), <=20 tokens/text characters.["lit",s]consumes exact literal s;["one"]one character;["star"]any substring, even empty, and captures it. Match ENTIRE text. Return captures in star order, choosing lexicographically smallest capture-LENGTH vector, orNonefor no match. A successful match without stars gives []. No full regex equivalence or mutation.