"""Integrate contiguous CPU-counter intervals without averaging sample rates.""" from fractions import Fraction def summarize_intervals(intervals): previous = None first = None count = 0 rate_sum = Fraction() for row in intervals: for key in ("scope", "counter_epoch"): if not isinstance(row[key], str) or not row[key].strip(): raise ValueError(key + " must identify one stable counter") for key in ("start_ns", "end_ns", "cpu_start_ns", "cpu_end_ns"): if type(row[key]) is not int: raise TypeError(key + " must be an integer") if row[key] < 0: raise ValueError(key + " must be nonnegative") duration = row["end_ns"] - row["start_ns"] cpu = row["cpu_end_ns"] - row["cpu_start_ns"] if duration <= 0 or cpu < 0: raise ValueError("elapsed time must increase; CPU counter must not decrease") if previous is not None: if any(row[key] != previous[key] for key in ("scope", "counter_epoch")): raise ValueError("counter scope or epoch changed") if row["start_ns"] != previous["end_ns"]: raise ValueError("intervals must be ordered, contiguous and nonoverlapping") if row["cpu_start_ns"] != previous["cpu_end_ns"]: raise ValueError("CPU counter boundary is discontinuous") else: first = dict(row) rate_sum += Fraction(cpu, duration) count += 1 # Copy because an iterator may reuse its mutable row buffer. previous = dict(row) if first is None: raise ValueError("at least one interval is required") elapsed = previous["end_ns"] - first["start_ns"] cpu = previous["cpu_end_ns"] - first["cpu_start_ns"] return { "scope": first["scope"], "counter_epoch": first["counter_epoch"], "interval_count": count, "elapsed_ns": elapsed, "cpu_ns": cpu, "time_weighted_average_cores": str(Fraction(cpu, elapsed)), "unweighted_interval_mean_cores": str(rate_sum / count), "unweighted_mean_times_elapsed_ns": str(rate_sum * elapsed / count), } def examples(): def row(start, end, before, after): return {"scope": "constructed-worker-group", "counter_epoch": "one-run", "start_ns": start * 10**9, "end_ns": end * 10**9, "cpu_start_ns": before * 10**9, "cpu_end_ns": after * 10**9} coarse = [row(0, 1, 0, 4), row(1, 10, 4, 4)] split_idle = [coarse[0], row(1, 5, 4, 4), row(5, 10, 4, 4)] return { "schema_version": 1, "kind": "synthetic-counter-intervals", "cases": [{"case": name, "input": rows, "result": summarize_intervals(rows)} for name, rows in (("irregular", coarse), ("split-idle", split_idle))], "limits": "Constructed cumulative counters, not cache measurements. Interval average cores are CPU deltas divided by elapsed deltas, not instantaneous samples or host-normalized percentages. Matching labels and monotone counters cannot detect all hidden resets or prove instrumentation scope.", } if __name__ == "__main__": import json print(json.dumps(examples(), indent=2))