"""Exact invented heartbeat cohorts, not a running detector. License: CC0-1.0.""" from fractions import Fraction from hashlib import sha256 import json from pathlib import Path import sys def seconds(value, *, allow_zero=False): """Accept exact rational seconds; reject ambiguous floats and bools.""" if isinstance(value, bool) or not isinstance(value, (int, str, Fraction)): raise ValueError("seconds must be an integer or exact rational string") try: result = Fraction(value) except (ValueError, ZeroDivisionError) as error: raise ValueError("invalid rational seconds") from error if result < 0 or (result == 0 and not allow_zero): raise ValueError("seconds must be nonnegative" if allow_zero else "seconds must be positive") return result def summarize(groups, threshold): """Groups are (count, complete interval seconds); every process stays alive. Suspicion starts only when age > threshold and resets immediately on arrival. These finite-record identities do not require independence or an arrival model. """ threshold = seconds(threshold) count, episodes = 0, 0 duration, suspected = Fraction(0), Fraction(0) for multiplicity, interval in groups: if isinstance(multiplicity, bool) or not isinstance(multiplicity, int) or multiplicity <= 0: raise ValueError("multiplicity must be a positive integer") interval = seconds(interval) count += multiplicity if count > 2**53 - 1: raise ValueError("interval count must remain JSON-safe") duration += multiplicity * interval if interval > threshold: episodes += multiplicity suspected += multiplicity * (interval - threshold) if count == 0: raise ValueError("at least one complete interval is required") return { "intervalCount": count, "thresholdSecondsExact": str(threshold), "totalSecondsExact": str(duration), "meanSecondsExact": str(duration / count), "exceedanceCount": episodes, "exceedanceFractionExact": str(Fraction(episodes, count)), "episodesPerSecondExact": str(episodes / duration), "suspectedSecondsExact": str(suspected), "suspectedTimeFractionExact": str(suspected / duration), "suspectedPercentDisplay": format(float(100 * suspected / duration), ".2f"), } def observed_window(arrivals, end, threshold, *, initial_age): """Clip suspicion to [0, end) with a known starting age and always-alive subject. Arrival offsets are strictly increasing in (0, end]. A threshold crossing at the left boundary counts only if positive-duration suspicion follows. An already-suspected initial state contributes time, not a new onset. """ end, threshold = seconds(end), seconds(threshold) initial_age = seconds(initial_age, allow_zero=True) arrivals = [seconds(value) for value in arrivals] previous = Fraction(0) for arrival in arrivals: if not previous < arrival <= end: raise ValueError("arrivals must increase strictly within (0, end]") previous = arrival last_arrival, segment_start = -initial_age, Fraction(0) suspected, onsets = Fraction(0), 0 for segment_end in arrivals + [end]: crossing = last_arrival + threshold duration = max(segment_end - max(segment_start, crossing), Fraction(0)) suspected += duration if duration > 0 and crossing >= segment_start: onsets += 1 last_arrival = segment_end segment_start = segment_end return { "windowSecondsExact": str(end), "initialAgeSecondsExact": str(initial_age), "thresholdSecondsExact": str(threshold), "arrivalsSecondsExact": [str(value) for value in arrivals], "carriedInSuspicion": initial_age > threshold, "observedOnsetCount": onsets, "onsetsPerSecondExact": str(onsets / end), "suspectedSecondsExact": str(suspected), "suspectedTimeFractionExact": str(suspected / end), } CASES = [ ("A", [(99, "1"), (1, "11")]), ("B", [(99, "10/11"), (1, "20")]), ] def result(): return { "schemaVersion": 1, "evidenceType": "synthetic-exact-accounting", "license": "CC0-1.0", "sourceCodeSha256": sha256(Path(__file__).read_bytes()).hexdigest(), "sourcesReviewedOn": "2026-11-06", "assumptions": [ "Invented complete intervals; every process independently stipulated alive.", "Fixed 2-second delay threshold; immediate reset at every arrival.", "One positive-duration episode per interval strictly longer than the threshold.", "Continuous observation, no polling delay, pause guard or adaptive fitting.", "Not telemetry, a confidence interval, a recommended threshold or a Cassandra replay.", ], "assumptionScopes": {"cohorts": "assumptions", "observationWindows": "windowAssumptions"}, "windowAssumptions": [ "Fixed positive threshold, continuous observation, immediate reset at every arrival.", "Known initial heartbeat age; subject independently stipulated alive throughout.", "Half-open [0, end) window; no unobserved future arrival is invented.", "Strict age > threshold; equality at an arrival or the right edge adds no episode.", "A crossing at zero counts if positive duration follows; carried-in suspicion is not a new onset.", ], "observationWindows": [ {"label": "unfinished-gap", **observed_window([1, 2], 5, 2, initial_age=0)}, {"label": "carried-in", **observed_window([], 1, 2, initial_age=3)}, ], "cohorts": [ {"label": label, "groups": [{"count": count, "secondsExact": interval} for count, interval in groups], **summarize(groups, "2")} for label, groups in CASES ], } if __name__ == "__main__": payload = json.dumps(result(), indent=2, allow_nan=False) + "\n" if sys.argv[1:] == ["--check"]: if Path(__file__).with_name("renewal.json").read_text() != payload: raise SystemExit("renewal.json differs from exact regeneration") print("Exact renewal packet matches.") elif not sys.argv[1:]: print(payload, end="") else: raise SystemExit("usage: python3 -B renewal.py [--check]")