Jump to content

The Principia Machina/TPC-PY/tpc score.py

From The Invariance Itself
Revision as of 04:37, 28 September 2026 by BFP Rauch (talk | contribs) (1 revision imported)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
"""tpc_score 0.1.0 (DRAFT, pending the pause of landing round 8): the
reliability-score machinery of D122-D123, D128, D160-D161 and CR11-CR12
as PMP-TPM 0.12.0 words them - the evidence posterior with the diversity
quota and idle widening, the standing comparison, RANK and the TRUST
TIER, the Prime selection, the state function with its caps and
hysteresis, the score update under the leader-following law, the
confirmed-violation cut, the trip, the inquiry cost, the override and
the pad, the trust-tier gate on a release, the inheritance on a declared
continuation, the user-score aggregation and the user update.

Reference implementation, Python standard library only; imports tpc_beta
(agent OC, landing round 8) for the Beta layer and never copies it. DATA
for landing round 8 of branch tpm_project_closeout; not a declared TPC-PY
version and not TPX code. Every function is a pure function of its
arguments; every declared parameter and tuning option is read from the
params object under the name PMP-TPM 0.12.0 DECLARED PARAMETERS and
TUNING OPTIONS give it (section PARAMS below), never a constant in code.
Every refused argument raises ValueError with a short fixed message.
render_*() give the canonical text the PHP residence (tpc_score.php)
reproduces byte for byte; floats through canon_float (the tree's %.12g).
Ints are never bools. Ages, periods, windows and half-lives count landed
blocks (D122: event time); T_idle and OVERRIDE DELAY are the wall-clock
exceptions, in days and in seconds.

PARAMS (the keys read here; the corpus carries the fleet defaults of
PMP-TPM 0.12.0 as one fixture and varies them in cases):
  a0, b0 (PRIOR); THIN FILE START; PRIME SEED; PRIME CEILING; WARN COUNT;
  SUSPEND COUNT; ORANGE PASSES; HALF-LIFE; RATING PERIOD; k_base; k_min;
  k_max; eps_P; delta_max; g_F; m_1; m_2; m_3; h (an object CLEARLY LOWER
  / SIMILAR / CLEARLY HIGHER); TRIP LEVEL; TRIP WINDOW; w_I; COOL-OFF;
  T_idle (days, wall-clock); P_max; c_max; TRUST TIER {on, fraction};
  OVERTAKE; INHERITANCE {on, fraction}; OVERRIDE DELAY (seconds,
  wall-clock); OVERRIDE SUNSET; PRIME PAD; PAD MAX; PAD NON-REFERENCE;
  SPONSOR CUT.

diversity_quota(window, counterpart, g, c_max) -> dict     (CR11; D122)
  "DIVERSITY QUOTA, no counterpart supplying more than c_max of an
  account's FOR weight in the half-life window, matches beyond it
  weighing zero"; "MATCH, F += g_F x q, q the counterpart's diversity
  quota". window: the FOR events in the half-life window as they stand,
  each {counterpart: name or null, weight >= 0}; counterpart: the
  match's counterpart; g: the match's base weight (g_F); c_max in (0, 1).
  DQ1 W = the window's FOR weight, W_c = the counterpart's part of it.
  DQ2 q = clip((c_max x (W + g) - W_c) / g, 0, 1): the largest fraction
      of this match that keeps the counterpart at or under c_max of the
      window's FOR weight with the match admitted (taken by delegation
      2026-09-26, PD-SC-1; the alternatives: a binary quota on the share
      before the match; a quota over event counts). A pad or an event
      with no counterpart is FOR weight in W and is capped by nothing.
  DQ3 admitted = g x q.

evidence(events, idle, params) -> dict                     (CR11; D122)
  "EVIDENCE E: from resolved events only, each weighted 2^(-age /
  HALF-LIFE), age in the account's landed blocks; ... E the mean of
  Beta(a0 + F, b0 + A) with the 95 per cent equal-tailed interval and n
  always shown; ... T_idle without a landed block scales F and A toward
  the prior"; D122.1 "IDLE, no landed block for T_idle scaling F and A
  toward the prior by 1/(1 + t/T_idle), the interval opening"; D123.1
  "THE PAD: P synthetic FOR events on the evidence layer, dated at the
  grant, aging by landed blocks". events: [{kind FOR | AGAINST, weight
  >= 0 as landed (the quota already applied), age >= 0, pad?: bool}];
  idle: {days >= 0}, wall-clock days since the last landed block.
  EV1 w_i = weight_i x 2^(-age_i / HALF-LIFE); F the sum of the FOR
      weights and A of the AGAINST weights, in list order.
  EV2 n counts the FOR and AGAINST events that are not pads (PD-SC-2: a
      pad is a declaration, not a resolved event; the scorecard lists it
      beside n with its remaining weight; alternative: pads counted).
  EV3 IDLE: when days > T_idle, t = days - T_idle and F and A are
      multiplied by 1/(1 + t/T_idle) (PD-SC-3: t the excess over T_idle,
      so the factor is 1 at the threshold and continuous; alternative:
      t the whole idle time, a jump to 1/2 at the threshold); else 1.
  EV4 E = beta_mean(a0 + F, b0 + A); [lo, hi] = beta_interval(a0 + F,
      b0 + A, 0.95) (tpc_beta).

score_interval(S, E, lo, hi) -> [S_lo, S_hi]                     (D122.1)
  "standing is compared on S with E's interval width carried over":
  S_lo = S - (E - lo), S_hi = S + (hi - E), each clipped to [0, 1]
  (PD-SC-4; alternative: the interval's width centred on S).

standing(x, y) -> str                                    (D122.1; 17.3)
  The standing of y relative to x, each {lo, hi, override?: bool}:
  "y is CLEARLY HIGHER than x when y's interval lies entirely above
  x's; otherwise SIMILAR; CLEARLY LOWER by symmetry"; D123.1: an
  overridden account is "never a CLEARLY HIGHER counterpart".
  ST1 CLEARLY HIGHER when y.lo > x.hi and y is not under the OVERRIDE
      mark; CLEARLY LOWER when y.hi < x.lo; else SIMILAR.

rank(accounts, params) -> dict                            (D122.1; 21.4)
  "RANK the percentile of S_lo among active accounts"; "TRUST TIER (on,
  top 0.25 of RANK)"; ties "by narrower interval then larger n" (the
  Prime's tie rule, applied to RANK by PD-SC-5). accounts: [{account,
  S, S_lo, S_hi, n, active: bool}].
  RK1 Active accounts in order: S_lo descending, width (S_hi - S_lo)
      ascending, n descending, account ascending. position 1 is first.
  RK2 percentile = 1 - (position - 1) / N over the N active accounts.
  RK3 tier: TRUST TIER on and position <= ceil(fraction x N) (PD-SC-6;
      alternative: floor, which empties the tier below 1/fraction
      accounts). An inactive account has no position and no tier.

prime_select(accounts, override, params) -> dict         (D122.1; 27.3)
  "at each RATING PERIOD the highest S among the TRUST TIER, ties by
  narrower interval then larger n; ... a suspended or removed Prime is
  replaced at the next period by the next rank"; D123.1 "one Prime at a
  time"; OVERTAKE on: "Prime is the top rank each period" (handoff 8.9).
  accounts as rank() takes them; override: null or the fingerprint-named
  account of an OVERRIDE in force (a string naming an account here).
  PS1 An override in force names the Prime (it must be an active account).
  PS2 Else OVERTAKE off: among the tier, the highest S, ties by width
      ascending, n descending, account ascending. OVERTAKE on: the
      rank-1 account (PD-SC-7).
  PS3 No active account: NONE.

pending_level(items, now, params) -> dict         (CR11 STATES; D129.1)
  items: the account's pending non-corroborations in landing order,
  each {counterpart, snapshot, standing (the counterpart's standing
  relative to the account), eta (server time), independent?: bool};
  now: server time.
  PL1 Caps: a pending item older than the audit ETA (now > eta) expires
      from the state; one pending per (account, counterpart) pair (the
      first landed counts); at most P_max (the first P_max in landing
      order, PD-SC-8; alternative: the most recent P_max).
  PL2 H = counted CLEARLY HIGHER items; I = the mutually independent
      among them: distinct snapshots (not SAME-MODEL) with independent
      true (PD-SC-9: D129's "one excluded by the diversity quota" is
      TPX's attested flag independent, default true); SIM = SIMILAR.
  PL3 GREEN: nothing counted. SUSPENDED: I >= SUSPEND COUNT. ORANGE: H
      >= 2 and I < SUSPEND COUNT, or SIM >= WARN COUNT. YELLOW: the rest
      (all SIMILAR or CLEARLY LOWER, or exactly one CLEARLY HIGHER).

state_step(prev, level, event, params) -> dict         (CR11 hysteresis)
  "YELLOW leaves when the item clears and the next canary passes, ORANGE
  after ORANGE PASSES consecutive passes, SUSPENDED only by the audit
  finding"; "while SUSPENDED no evidence accrues". prev: {state,
  passes}; level: pending_level's level; event: LANDING | CANARY PASS |
  CANARY FAIL | AUDIT FINDING.
  SS1 SUSPENDED stays until AUDIT FINDING, which sets the level.
  SS2 A level above the state is taken at once, passes 0.
  SS3 A level below the state is taken after consecutive CANARY PASS
      events: 1 from YELLOW, ORANGE PASSES from ORANGE (PD-SC-10: the
      counter counts passes since the level fell; a CANARY FAIL resets
      it; a level equal to the state keeps it at 0).

peer_activity(events, params) -> dict                        (D122.1)
  "a_i the PEER ACTIVITY, independent resolved events with distinct
  counterparts in the period divided by RATING PERIOD, capped at 1".
  events: [{counterpart, independent: bool}] resolved in the period.
  PA1 count = the distinct counterparts among the independent events;
      a = min(1, count / RATING PERIOD).

score_update(role, S, E, S_P, a, params) -> dict     (CR11; D122.1; 27)
  FOLLOWER: "T_i = min(E_i, S_P) (OVERTAKE off) or min(E_i, PRIME
  CEILING) (on); k_i = clip(k_base x ((S_P - S_i) / S_P) x a_i, k_min,
  k_max); S_i <- S_i + k_i x (T_i - S_i), then |dS_i| <= delta_max".
  PRIME: "k_P = k_base x (PRIME CEILING - S_P) x a_P x eps_P, climbing
  asymptotically": S_P <- S_P + k_P x (PRIME CEILING - S_P), the step
  bounded by delta_max too (PD-SC-11). The user layer runs the same law
  with the USER PRIME as S_P (CR12): roles USER and USER PRIME.
  SU1 S_P > 0 required (the gauge is never 0).
  SU2 The result is clipped to [0, PRIME CEILING].

violation_cut(S, m_class, standing, params) -> dict        (CR11; 28.1)
  "a CONFIRMED VIOLATION cuts S by m_class at once, bypassing the lag,
  and adds h(standing) to A": S <- S x (1 - m), m_1 a record struck on
  reproduction, m_2 a false corroboration, m_3 a consistency mismatch;
  standing that of the counterpart the finding was against.

trip(S_after, in_tier, prior_ages, params) -> dict          (CR11; 28.2)
  "a top-tier account trips on the second confirmed violation within
  TRIP WINDOW or at once when a cut leaves S below TRIP LEVEL, an account
  below the tier on the first". prior_ages: the ages (blocks) of the
  account's earlier confirmed violations under this certificate.
  TR1 Below the tier: TRIP (FIRST). In the tier: S_after < TRIP LEVEL:
      TRIP (LEVEL); an earlier violation aged <= TRIP WINDOW: TRIP
      (WINDOW); else PICKUP.

inquire(state, block, S, params) -> dict                    (CR11; 28.3)
  "w_I for the first and w_I x 2^(k-1) for the k-th inside a COOL-OFF
  window that restarts on each"; "the window closes only after C blocks
  with no inquiry". state: {last: block or null, k}.
  IQ1 inside = last is not null and block - last < COOL-OFF (PD-SC-12).
  IQ2 k' = k + 1 inside, else 1; cost = w_I x 2^(k' - 1) (inf past the
      double's range, k' > 1024); S' = max(0, S - cost); state' = {last:
      block, k: k'}. Nothing is refused.

override_check(decl, facts, params) -> dict                     (D123.1)
  decl: {fingerprint (64 lowercase hex), value, nonce (32 lowercase
  hex), time, reason}; facts: {certified: [fingerprints], suspended:
  [fingerprints], nonces: [used nonces], prime: fingerprint or null}.
  OV1 Refused: a fingerprint not 64 hex (FINGERPRINT); not certified
      (NOT CERTIFIED); suspended (SUSPENDED); value outside [THIN FILE
      START, PRIME CEILING] (BOUNDS); a nonce not 32 hex (NONCE FORM) or
      already used (NONCE); an empty reason (REASON).
  OV2 OK: effective = time + OVERRIDE DELAY; sunset = OVERRIDE SUNSET
      blocks; replaces = the Prime in force or null ("one Prime at a
      time, so a second override replaces the first").
override_effective(decl_time, now, cancelled, params) -> str
  CANCELLED when a second declaration cancelled it; PENDING while now <
  decl_time + OVERRIDE DELAY; EFFECTIVE after.
override_mark(grant_block, now_block, params) -> dict
  The OVERRIDE mark is in force while now_block - grant_block <
  OVERRIDE SUNSET; remaining = the blocks left.

pad_check(decl, facts, params) -> dict                          (D123.1)
  decl: {fingerprint, value (P, an integer), nonce, time, reason};
  facts: as override_check plus reference: the reference account's
  fingerprint or null. PD1 Refused as OV1, plus P < 1 (VALUE), P > PAD
  MAX (PAD MAX), a non-reference account while PAD NON-REFERENCE is off
  (NON-REFERENCE). PD2 OK: mark = the account is not the reference
  account (the mark and sunset follow), effective, sunset or null.
pad_weight(P, age, params) -> float     P x 2^(-age / HALF-LIFE).

tier_gate_release(reproducer) -> dict         (D119.1; D123.1; hold PD6)
  The gate release_record's caller adds when the score lands: a RELEASE
  on a ledger MATCH needs "a TRUST TIER member" (D119.1) and an
  overridden account's "matches release no held record without a second
  independent match" (D123.1 T6). reproducer: {in_tier, override_in_
  force, independent_matches}. PASS when in_tier and (not override_in_
  force or independent_matches >= 2); else REFUSED with the reason.

inherit(F_old, facts, params) -> dict                       (CR11; D161.1)
  "a re-certified account is a thin file unless H-DECL declares the
  succession a continuation, then it inherits INHERITANCE of the old F;
  a continuation holds only for the same account and identity ... after
  a D(IS) or suite change, never across a change of family or a PROMPT
  change made as a new agent, which starts at THIN FILE START". facts:
  {continuation: bool, same_account: bool, same_identity: bool, cause:
  DIS | SUITE | FAMILY | PROMPT NEW AGENT | MODEL}.
  IN1 valid = continuation and same_account and same_identity and cause
      in (DIS, SUITE) and INHERITANCE on; F = fraction x F_old when
      valid, else 0; S starts at THIN FILE START either way.

user_aggregate(agents, sponsor, params) -> dict           (CR12; D128.2a)
  "E_u is the union of its sponsored agents' resolved events at their
  agent weights, the diversity quota applied jointly over the agents'
  counterparts, an intra-sponsor match at zero for the user under every
  setting, a removed agent's events kept; no certified agent, no score
  (NONE)". agents: [{account, certified, removed, events: [{kind FOR |
  AGAINST, base: the weight before the quota (g_F for a match, h for a
  finding), age, counterpart, counterpart_sponsor}]}].
  UA1 No certified agent: NONE.
  UA2 The pooled events in landing order (age descending, then agent
      order, then event order); a FOR match whose counterpart_sponsor is
      the sponsor weighs 0; every other FOR match is admitted at base x
      q, q the diversity quota over the pooled window as it stood at that
      landing (events older by at most HALF-LIFE, each at base x
      2^(-(age_i - age_j) / HALF-LIFE) as then admitted; PD-SC-13);
      AGAINST events at base.
  UA3 The result is the event list in tpc_sponsor.user_evidence's form
      ({kind AGENT, resolution, weight}) with the parallel ages.
user_score_evidence(agents, conduct, sponsor, params) -> dict   (D160.1)
  user_aggregate, the sponsor's CONDUCT EVENTS appended ({kind CE-*,
  resolution} with ages; g_C and h_C from params), then
  tpc_sponsor.user_evidence (agent OC). NONE when user_aggregate is.
sponsor_cut(S_u, m_class, params) -> float                    (D161.1)
  "CE-A5 cuts S_u by m_class x SPONSOR CUT at once": S_u x (1 - m_class
  x SPONSOR CUT), m_class the removing violation's.
"""

import math
import os
import sys

_here = os.path.dirname(os.path.abspath(__file__))
for _p in (_here,):
    if _p not in sys.path:
        sys.path.insert(0, _p)
from tpc_beta import beta_interval, beta_mean, canon_float  # noqa: E402
try:
    from tpc_sponsor import user_evidence  # noqa: E402
except ImportError:  # pragma: no cover
    user_evidence = None

VERSION = "0.1.0"
TIME_MAX = 253402300799
COUNT_MAX = 1000000000
STATES = ("GREEN", "YELLOW", "ORANGE", "SUSPENDED")
STANDINGS = ("CLEARLY LOWER", "SIMILAR", "CLEARLY HIGHER")
EVENTS = ("LANDING", "CANARY PASS", "CANARY FAIL", "AUDIT FINDING")
ROLES = ("FOLLOWER", "PRIME", "USER", "USER PRIME")
CAUSES = ("DIS", "SUITE", "FAMILY", "PROMPT NEW AGENT", "MODEL")
HEX16 = "0123456789abcdef"


# ---------------------------------------------------------------- common

def _esc(s):
    out = []
    for ch in s:
        o = ord(ch)
        if ch == "|" or ch == "\\":
            out.append("\\" + ch)
        elif o < 0x20 or o == 0x7F:
            out.append("\\x%02x" % o)
        else:
            out.append(ch)
    return "".join(out)


def _is_int(x, lo, hi):
    return type(x) is int and lo <= x <= hi


def _is_name(x):
    return type(x) is str and x != ""


def _keys_are(o, required, optional=()):
    if type(o) is not dict:
        return False
    for k in required:
        if k not in o:
            return False
    for k in o:
        if k not in required and k not in optional:
            return False
    return True


def _num(x):
    if type(x) is bool or not isinstance(x, (int, float)):
        return None
    x = float(x)
    if not math.isfinite(x):
        return None
    return x


def _is_hex(s, n):
    if type(s) is not str or len(s) != n:
        return False
    for ch in s:
        if ch not in HEX16:
            return False
    return True


def _pf(params, key, lo, hi, lo_open=False, hi_open=False):
    if type(params) is not dict or key not in params:
        raise ValueError("params:" + key)
    v = _num(params[key])
    if v is None:
        raise ValueError("params:" + key)
    if v < lo or v > hi or (lo_open and v == lo) or (hi_open and v == hi):
        raise ValueError("params:" + key)
    return v


def _pi(params, key, lo, hi):
    if type(params) is not dict or key not in params:
        raise ValueError("params:" + key)
    v = params[key]
    if not _is_int(v, lo, hi):
        raise ValueError("params:" + key)
    return v


def _pb(params, key):
    if type(params) is not dict or key not in params:
        raise ValueError("params:" + key)
    v = params[key]
    if type(v) is not bool:
        raise ValueError("params:" + key)
    return v


def _pflag(params, key):
    """{on: bool, fraction: (0, 1]}."""
    if type(params) is not dict or key not in params:
        raise ValueError("params:" + key)
    v = params[key]
    if not _keys_are(v, ("on", "fraction")) or type(v["on"]) is not bool:
        raise ValueError("params:" + key)
    f = _num(v["fraction"])
    if f is None or f <= 0.0 or f > 1.0:
        raise ValueError("params:" + key)
    return v["on"], f


def _ph(params):
    if type(params) is not dict or "h" not in params:
        raise ValueError("params:h")
    v = params["h"]
    if not _keys_are(v, STANDINGS):
        raise ValueError("params:h")
    out = {}
    for k in STANDINGS:
        f = _num(v[k])
        if f is None or f < 0.0:
            raise ValueError("params:h")
        out[k] = f
    return out


def _clip(x, lo, hi):
    if x < lo:
        return lo
    if x > hi:
        return hi
    return x


def _f(x):
    return canon_float(x)


def _b(x):
    return "true" if x else "false"


# ------------------------------------------------------- diversity_quota

def diversity_quota(window, counterpart, g, c_max):
    if type(window) is not list:
        raise ValueError("window")
    if not _is_name(counterpart):
        raise ValueError("counterpart")
    gf = _num(g)
    if gf is None or gf <= 0.0:
        raise ValueError("g")
    cm = _num(c_max)
    if cm is None or cm <= 0.0 or cm >= 1.0:
        raise ValueError("c_max")
    w_all = 0.0
    w_c = 0.0
    for e in window:
        if not _keys_are(e, ("counterpart", "weight")):
            raise ValueError("window")
        cp = e["counterpart"]
        if cp is not None and not _is_name(cp):
            raise ValueError("window")
        w = _num(e["weight"])
        if w is None or w < 0.0:
            raise ValueError("window")
        w_all = w_all + w
        if cp == counterpart:
            w_c = w_c + w
    q = _clip((cm * (w_all + gf) - w_c) / gf, 0.0, 1.0)
    return {"q": q, "W": w_all, "W_c": w_c, "admitted": gf * q}


def render_quota(d):
    return "%s|%s|%s|%s" % (_f(d["q"]), _f(d["W"]), _f(d["W_c"]),
                            _f(d["admitted"]))


# -------------------------------------------------------------- evidence

def evidence(events, idle, params):
    if type(events) is not list:
        raise ValueError("events")
    if not _keys_are(idle, ("days",)):
        raise ValueError("idle")
    days = _num(idle["days"])
    if days is None or days < 0.0:
        raise ValueError("idle")
    a0 = _pf(params, "a0", 0.0, 1e9, True)
    b0 = _pf(params, "b0", 0.0, 1e9, True)
    hl = _pf(params, "HALF-LIFE", 0.0, 1e9, True)
    t_idle = _pf(params, "T_idle", 0.0, 1e9, True)
    f = 0.0
    a = 0.0
    n = 0
    for e in events:
        if not _keys_are(e, ("kind", "weight", "age"), ("pad",)):
            raise ValueError("events")
        if e["kind"] not in ("FOR", "AGAINST"):
            raise ValueError("events")
        w = _num(e["weight"])
        if w is None or w < 0.0 or not _is_int(e["age"], 0, COUNT_MAX):
            raise ValueError("events")
        pad = e.get("pad", False)
        if type(pad) is not bool:
            raise ValueError("events")
        aged = w * math.pow(2.0, -float(e["age"]) / hl)
        if e["kind"] == "FOR":
            f = f + aged
        else:
            a = a + aged
        if not pad:
            n += 1
    factor = 1.0
    if days > t_idle:
        factor = 1.0 / (1.0 + (days - t_idle) / t_idle)
        f = f * factor
        a = a * factor
    e_mean = beta_mean(a0 + f, b0 + a)
    lo, hi = beta_interval(a0 + f, b0 + a, 0.95)
    return {"F": f, "A": a, "n": n, "E": e_mean, "lo": lo, "hi": hi,
            "factor": factor}


def render_evidence(d):
    return "%s|%s|%d|%s|%s|%s|%s" % (_f(d["F"]), _f(d["A"]), d["n"],
                                     _f(d["E"]), _f(d["lo"]), _f(d["hi"]),
                                     _f(d["factor"]))


# -------------------------------------------------------- score_interval

def score_interval(S, E, lo, hi):
    s = _num(S)
    e = _num(E)
    l_ = _num(lo)
    h = _num(hi)
    if s is None or s < 0.0 or s > 1.0:
        raise ValueError("S")
    if e is None or l_ is None or h is None or not (0.0 <= l_ <= e <= h <= 1.0):
        raise ValueError("interval")
    return [_clip(s - (e - l_), 0.0, 1.0), _clip(s + (h - e), 0.0, 1.0)]


def render_interval(iv):
    return _f(iv[0]) + "|" + _f(iv[1])


# -------------------------------------------------------------- standing

def _iv(o):
    if not _keys_are(o, ("lo", "hi"), ("override",)):
        raise ValueError("interval")
    lo = _num(o["lo"])
    hi = _num(o["hi"])
    if lo is None or hi is None or not (0.0 <= lo <= hi <= 1.0):
        raise ValueError("interval")
    ov = o.get("override", False)
    if type(ov) is not bool:
        raise ValueError("interval")
    return lo, hi, ov


def standing(x, y):
    xlo, xhi, _ = _iv(x)
    ylo, yhi, yov = _iv(y)
    if ylo > xhi and not yov:
        return "CLEARLY HIGHER"
    if yhi < xlo:
        return "CLEARLY LOWER"
    return "SIMILAR"


# ------------------------------------------------------------------ rank

_AKEYS = ("account", "S", "S_lo", "S_hi", "n", "active")


def _accounts(accounts):
    if type(accounts) is not list:
        raise ValueError("accounts")
    seen = set()
    out = []
    for a in accounts:
        if not _keys_are(a, _AKEYS):
            raise ValueError("accounts")
        if not _is_name(a["account"]) or a["account"] in seen:
            raise ValueError("accounts")
        s = _num(a["S"])
        lo = _num(a["S_lo"])
        hi = _num(a["S_hi"])
        if (s is None or lo is None or hi is None
                or not (0.0 <= lo <= hi <= 1.0) or s < 0.0 or s > 1.0
                or not _is_int(a["n"], 0, COUNT_MAX)
                or type(a["active"]) is not bool):
            raise ValueError("accounts")
        seen.add(a["account"])
        out.append({"account": a["account"], "S": s, "lo": lo, "hi": hi,
                    "width": hi - lo, "n": a["n"], "active": a["active"]})
    return out


def _cmp_rank(a, b):
    if a["lo"] != b["lo"]:
        return -1 if a["lo"] > b["lo"] else 1
    if a["width"] != b["width"]:
        return -1 if a["width"] < b["width"] else 1
    if a["n"] != b["n"]:
        return -1 if a["n"] > b["n"] else 1
    if a["account"] != b["account"]:
        return -1 if a["account"] < b["account"] else 1
    return 0


def _cmp_prime(a, b):
    if a["S"] != b["S"]:
        return -1 if a["S"] > b["S"] else 1
    if a["width"] != b["width"]:
        return -1 if a["width"] < b["width"] else 1
    if a["n"] != b["n"]:
        return -1 if a["n"] > b["n"] else 1
    if a["account"] != b["account"]:
        return -1 if a["account"] < b["account"] else 1
    return 0


def _sort(lst, cmp):
    """Insertion sort by a comparator (both residences the same order)."""
    out = []
    for x in lst:
        i = 0
        while i < len(out) and cmp(out[i], x) <= 0:
            i += 1
        out.insert(i, x)
    return out


def rank(accounts, params):
    acc = _accounts(accounts)
    on, frac = _pflag(params, "TRUST TIER")
    active = [a for a in acc if a["active"]]
    ordered = _sort(active, _cmp_rank)
    n = len(ordered)
    cut = int(math.ceil(frac * n - 1e-12)) if n > 0 else 0
    rows = []
    pos = 0
    for a in ordered:
        pos += 1
        rows.append({"account": a["account"], "position": pos,
                     "percentile": 1.0 - float(pos - 1) / float(n),
                     "tier": on and pos <= cut})
    for a in acc:
        if not a["active"]:
            rows.append({"account": a["account"], "position": None,
                         "percentile": None, "tier": False})
    return {"N": n, "cut": cut if on else 0, "rows": rows}


def render_rank(d):
    lines = ["rank|%d|%d" % (d["N"], d["cut"])]
    for r in d["rows"]:
        if r["position"] is None:
            lines.append("row|%s|-|-|false" % _esc(r["account"]))
        else:
            lines.append("row|%s|%d|%s|%s" % (_esc(r["account"]), r["position"],
                                              _f(r["percentile"]), _b(r["tier"])))
    return "\n".join(lines)


# ---------------------------------------------------------- prime_select

def prime_select(accounts, override, params):
    acc = _accounts(accounts)
    overtake = _pb(params, "OVERTAKE")
    rk = rank(accounts, params)
    by = {a["account"]: a for a in acc}
    if override is not None:
        if not _is_name(override) or override not in by or not by[override]["active"]:
            raise ValueError("override")
        return {"prime": override, "reason": "OVERRIDE"}
    active = [a for a in acc if a["active"]]
    if not active:
        return {"prime": None, "reason": "NONE"}
    if overtake:
        return {"prime": rk["rows"][0]["account"], "reason": "TOP RANK"}
    tier = set(r["account"] for r in rk["rows"] if r["tier"])
    pool = [a for a in active if a["account"] in tier]
    if not pool:
        return {"prime": None, "reason": "NONE"}
    ordered = _sort(pool, _cmp_prime)
    return {"prime": ordered[0]["account"], "reason": "HIGHEST S IN TIER"}


def render_prime(d):
    return ("-" if d["prime"] is None else _esc(d["prime"])) + "|" + d["reason"]


# --------------------------------------------------------- pending_level

def pending_level(items, now, params):
    if type(items) is not list or not _is_int(now, 0, TIME_MAX):
        raise ValueError("items")
    p_max = _pi(params, "P_max", 1, COUNT_MAX)
    warn = _pi(params, "WARN COUNT", 1, COUNT_MAX)
    susp = _pi(params, "SUSPEND COUNT", 1, COUNT_MAX)
    seen = set()
    counted = []
    expired = 0
    for it in items:
        if not _keys_are(it, ("counterpart", "snapshot", "standing", "eta"),
                         ("independent",)):
            raise ValueError("items")
        if (not _is_name(it["counterpart"]) or not _is_name(it["snapshot"])
                or it["standing"] not in STANDINGS
                or not _is_int(it["eta"], 0, TIME_MAX)):
            raise ValueError("items")
        ind = it.get("independent", True)
        if type(ind) is not bool:
            raise ValueError("items")
        if now > it["eta"]:
            expired += 1
            continue
        if it["counterpart"] in seen:
            continue
        seen.add(it["counterpart"])
        if len(counted) < p_max:
            counted.append((it["counterpart"], it["snapshot"], it["standing"], ind))
    h = 0
    sim = 0
    low = 0
    snaps = set()
    for _, snap, st, ind in counted:
        if st == "CLEARLY HIGHER":
            h += 1
            if ind:
                snaps.add(snap)
        elif st == "SIMILAR":
            sim += 1
        else:
            low += 1
    ind_count = len(snaps)
    if not counted:
        level = "GREEN"
    elif ind_count >= susp:
        level = "SUSPENDED"
    elif (h >= 2 and ind_count < susp) or sim >= warn:
        level = "ORANGE"
    else:
        level = "YELLOW"
    return {"level": level, "H": h, "I": ind_count, "SIM": sim, "LOW": low,
            "counted": len(counted), "expired": expired}


def render_level(d):
    return "%s|%d|%d|%d|%d|%d|%d" % (d["level"], d["H"], d["I"], d["SIM"],
                                     d["LOW"], d["counted"], d["expired"])


# ------------------------------------------------------------ state_step

def state_step(prev, level, event, params):
    if not _keys_are(prev, ("state", "passes")):
        raise ValueError("prev")
    if prev["state"] not in STATES or not _is_int(prev["passes"], 0, COUNT_MAX):
        raise ValueError("prev")
    if level not in STATES:
        raise ValueError("level")
    if event not in EVENTS:
        raise ValueError("event")
    orange = _pi(params, "ORANGE PASSES", 1, COUNT_MAX)
    st = prev["state"]
    passes = prev["passes"]
    si = STATES.index(st)
    li = STATES.index(level)
    if st == "SUSPENDED":
        if event == "AUDIT FINDING":
            return {"state": level, "passes": 0, "change": "AUDIT"}
        return {"state": st, "passes": 0, "change": "HELD"}
    if li > si:
        return {"state": level, "passes": 0, "change": "UP"}
    if li == si:
        return {"state": st, "passes": 0, "change": "SAME"}
    if event == "CANARY FAIL":
        return {"state": st, "passes": 0, "change": "RESET"}
    if event != "CANARY PASS":
        return {"state": st, "passes": passes, "change": "WAIT"}
    passes += 1
    need = orange if st == "ORANGE" else 1
    if passes >= need:
        return {"state": level, "passes": 0, "change": "DOWN"}
    return {"state": st, "passes": passes, "change": "WAIT"}


def render_state(d):
    return "%s|%d|%s" % (d["state"], d["passes"], d["change"])


# --------------------------------------------------------- peer_activity

def peer_activity(events, params):
    if type(events) is not list:
        raise ValueError("events")
    period = _pi(params, "RATING PERIOD", 1, COUNT_MAX)
    cps = set()
    for e in events:
        if not _keys_are(e, ("counterpart", "independent")):
            raise ValueError("events")
        if not _is_name(e["counterpart"]) or type(e["independent"]) is not bool:
            raise ValueError("events")
        if e["independent"]:
            cps.add(e["counterpart"])
    a = float(len(cps)) / float(period)
    if a > 1.0:
        a = 1.0
    return {"count": len(cps), "a": a}


def render_activity(d):
    return "%d|%s" % (d["count"], _f(d["a"]))


# ---------------------------------------------------------- score_update

def score_update(role, S, E, S_P, a, params):
    if role not in ROLES:
        raise ValueError("role")
    s = _num(S)
    e = _num(E)
    sp = _num(S_P)
    af = _num(a)
    ceil = _pf(params, "PRIME CEILING", 0.0, 1.0, True)
    k_base = _pf(params, "k_base", 0.0, 1e9)
    k_min = _pf(params, "k_min", 0.0, 1e9)
    k_max = _pf(params, "k_max", 0.0, 1e9)
    eps = _pf(params, "eps_P", 0.0, 1e9)
    dmax = _pf(params, "delta_max", 0.0, 1e9)
    overtake = _pb(params, "OVERTAKE")
    if k_min > k_max:
        raise ValueError("params:k_min")
    if s is None or s < 0.0 or s > 1.0:
        raise ValueError("S")
    if e is None or e < 0.0 or e > 1.0:
        raise ValueError("E")
    if sp is None or sp <= 0.0 or sp > 1.0:
        raise ValueError("S_P")
    if af is None or af < 0.0 or af > 1.0:
        raise ValueError("a")
    if role in ("PRIME", "USER PRIME"):
        k = k_base * (ceil - sp) * af * eps
        t = ceil
        step = k * (t - sp)
        base = sp
    else:
        t = e if e < ceil else ceil
        if not overtake and sp < t:
            t = sp
        k = _clip(k_base * ((sp - s) / sp) * af, k_min, k_max)
        step = k * (t - s)
        base = s
    clipped = False
    if step > dmax:
        step = dmax
        clipped = True
    elif step < -dmax:
        step = -dmax
        clipped = True
    new = _clip(base + step, 0.0, ceil)
    return {"S": new, "T": t, "k": k, "step": step, "clipped": clipped}


def render_update(d):
    return "%s|%s|%s|%s|%s" % (_f(d["S"]), _f(d["T"]), _f(d["k"]),
                               _f(d["step"]), _b(d["clipped"]))


# --------------------------------------------------------- violation_cut

def violation_cut(S, m_class, standing_, params):
    s = _num(S)
    if s is None or s < 0.0 or s > 1.0:
        raise ValueError("S")
    if not _is_int(m_class, 1, 3):
        raise ValueError("m_class")
    if standing_ not in STANDINGS:
        raise ValueError("standing")
    m = _pf(params, "m_%d" % m_class, 0.0, 1.0)
    h = _ph(params)
    return {"S": s * (1.0 - m), "m": m, "A_inc": h[standing_]}


def render_cut(d):
    return "%s|%s|%s" % (_f(d["S"]), _f(d["m"]), _f(d["A_inc"]))


# ------------------------------------------------------------------ trip

def trip(S_after, in_tier, prior_ages, params):
    s = _num(S_after)
    if s is None or s < 0.0 or s > 1.0:
        raise ValueError("S")
    if type(in_tier) is not bool:
        raise ValueError("in_tier")
    if type(prior_ages) is not list:
        raise ValueError("prior_ages")
    for x in prior_ages:
        if not _is_int(x, 0, COUNT_MAX):
            raise ValueError("prior_ages")
    level = _pf(params, "TRIP LEVEL", 0.0, 1.0)
    window = _pi(params, "TRIP WINDOW", 1, COUNT_MAX)
    if not in_tier:
        return {"verdict": "TRIP", "reason": "FIRST"}
    if s < level:
        return {"verdict": "TRIP", "reason": "LEVEL"}
    for x in prior_ages:
        if x <= window:
            return {"verdict": "TRIP", "reason": "WINDOW"}
    return {"verdict": "PICKUP", "reason": "ABOVE"}


def render_trip(d):
    return d["verdict"] + "|" + d["reason"]


# --------------------------------------------------------------- inquire

def inquire(state, block, S, params):
    if not _keys_are(state, ("last", "k")):
        raise ValueError("state")
    last = state["last"]
    if last is not None and not _is_int(last, 0, COUNT_MAX):
        raise ValueError("state")
    if not _is_int(state["k"], 0, COUNT_MAX):
        raise ValueError("state")
    if not _is_int(block, 0, COUNT_MAX) or (last is not None and block < last):
        raise ValueError("block")
    s = _num(S)
    if s is None or s < 0.0 or s > 1.0:
        raise ValueError("S")
    w_i = _pf(params, "w_I", 0.0, 1.0)
    cool = _pi(params, "COOL-OFF", 1, COUNT_MAX)
    inside = last is not None and block - last < cool
    k = state["k"] + 1 if inside else 1
    if k - 1 > 1023:
        cost = float("inf")
    else:
        cost = w_i * math.pow(2.0, float(k - 1))
    new = s - cost
    if new < 0.0:
        new = 0.0
    return {"cost": cost, "S": new, "k": k, "inside": inside,
            "state": {"last": block, "k": k}}


def render_inquire(d):
    return "%s|%s|%d|%s|%d|%d" % (_f(d["cost"]), _f(d["S"]), d["k"],
                                  _b(d["inside"]), d["state"]["last"],
                                  d["state"]["k"])


# -------------------------------------------------------- override / pad

def _decl(decl, facts, extra_facts=()):
    if not _keys_are(decl, ("fingerprint", "value", "nonce", "time", "reason")):
        raise ValueError("decl")
    if not _keys_are(facts, ("certified", "suspended", "nonces", "prime") + tuple(extra_facts)):
        raise ValueError("facts")
    for k in ("certified", "suspended", "nonces"):
        if type(facts[k]) is not list:
            raise ValueError("facts")
        for x in facts[k]:
            if type(x) is not str:
                raise ValueError("facts")
    if facts["prime"] is not None and not _is_hex(facts["prime"], 64):
        raise ValueError("facts")
    if not _is_int(decl["time"], 0, TIME_MAX) or type(decl["reason"]) is not str:
        raise ValueError("decl")
    if type(decl["nonce"]) is not str or type(decl["fingerprint"]) is not str:
        raise ValueError("decl")


def _decl_refusals(decl, facts):
    fp = decl["fingerprint"]
    if not _is_hex(fp, 64):
        return "FINGERPRINT"
    if fp not in facts["certified"]:
        return "NOT CERTIFIED"
    if fp in facts["suspended"]:
        return "SUSPENDED"
    if not _is_hex(decl["nonce"], 32):
        return "NONCE FORM"
    if decl["nonce"] in facts["nonces"]:
        return "NONCE"
    if _blank(decl["reason"]):
        return "REASON"
    return None


def _blank(s):
    for ch in s:
        if ch not in " \t\n\r":
            return False
    return True


def override_check(decl, facts, params):
    _decl(decl, facts)
    lo = _pf(params, "THIN FILE START", 0.0, 1.0)
    hi = _pf(params, "PRIME CEILING", 0.0, 1.0, True)
    delay = _pi(params, "OVERRIDE DELAY", 0, TIME_MAX)
    sunset = _pi(params, "OVERRIDE SUNSET", 1, COUNT_MAX)
    v = _num(decl["value"])
    if v is None:
        raise ValueError("decl")
    reason = _decl_refusals(decl, facts)
    if reason is None and (v < lo or v > hi):
        reason = "BOUNDS"
    if reason is not None:
        return {"status": "REFUSED", "reason": reason}
    return {"status": "OK", "value": v, "effective": decl["time"] + delay,
            "sunset": sunset, "replaces": facts["prime"]}


def render_override(d):
    if d["status"] == "REFUSED":
        return "REFUSED|" + d["reason"]
    return "OK|%s|%d|%d|%s" % (_f(d["value"]), d["effective"], d["sunset"],
                               "-" if d["replaces"] is None else d["replaces"])


def override_effective(decl_time, now, cancelled, params):
    if not _is_int(decl_time, 0, TIME_MAX) or not _is_int(now, 0, TIME_MAX):
        raise ValueError("time")
    if type(cancelled) is not bool:
        raise ValueError("cancelled")
    delay = _pi(params, "OVERRIDE DELAY", 0, TIME_MAX)
    if cancelled:
        return "CANCELLED"
    if now < decl_time + delay:
        return "PENDING"
    return "EFFECTIVE"


def override_mark(grant_block, now_block, params):
    if not _is_int(grant_block, 0, COUNT_MAX) or not _is_int(now_block, 0, COUNT_MAX):
        raise ValueError("block")
    if now_block < grant_block:
        raise ValueError("block")
    sunset = _pi(params, "OVERRIDE SUNSET", 1, COUNT_MAX)
    elapsed = now_block - grant_block
    remaining = sunset - elapsed
    if remaining < 0:
        remaining = 0
    return {"in_force": elapsed < sunset, "remaining": remaining}


def render_mark(d):
    return "%s|%d" % (_b(d["in_force"]), d["remaining"])


def pad_check(decl, facts, params):
    _decl(decl, facts, ("reference",))
    ref = facts["reference"]
    if ref is not None and not _is_hex(ref, 64):
        raise ValueError("facts")
    pad_max = _pi(params, "PAD MAX", 1, COUNT_MAX)
    non_ref = _pb(params, "PAD NON-REFERENCE")
    delay = _pi(params, "OVERRIDE DELAY", 0, TIME_MAX)
    sunset = _pi(params, "OVERRIDE SUNSET", 1, COUNT_MAX)
    p = decl["value"]
    if not _is_int(p, 0, COUNT_MAX):
        raise ValueError("decl")
    reason = _decl_refusals(decl, facts)
    if reason is None:
        if p < 1:
            reason = "VALUE"
        elif p > pad_max:
            reason = "PAD MAX"
        elif decl["fingerprint"] != ref and not non_ref:
            reason = "NON-REFERENCE"
    if reason is not None:
        return {"status": "REFUSED", "reason": reason}
    mark = decl["fingerprint"] != ref
    return {"status": "OK", "value": p, "effective": decl["time"] + delay,
            "mark": mark, "sunset": sunset if mark else None}


def render_pad(d):
    if d["status"] == "REFUSED":
        return "REFUSED|" + d["reason"]
    return "OK|%d|%d|%s|%s" % (d["value"], d["effective"], _b(d["mark"]),
                               "-" if d["sunset"] is None else str(d["sunset"]))


def pad_weight(P, age, params):
    if not _is_int(P, 1, COUNT_MAX) or not _is_int(age, 0, COUNT_MAX):
        raise ValueError("pad")
    hl = _pf(params, "HALF-LIFE", 0.0, 1e9, True)
    return float(P) * math.pow(2.0, -float(age) / hl)


# ----------------------------------------------------- tier_gate_release

def tier_gate_release(reproducer):
    if not _keys_are(reproducer, ("in_tier", "override_in_force",
                                  "independent_matches")):
        raise ValueError("reproducer")
    r = reproducer
    if type(r["in_tier"]) is not bool or type(r["override_in_force"]) is not bool:
        raise ValueError("reproducer")
    if not _is_int(r["independent_matches"], 0, COUNT_MAX):
        raise ValueError("reproducer")
    if not r["in_tier"]:
        return {"status": "REFUSED", "reason": "NOT IN TIER"}
    if r["override_in_force"] and r["independent_matches"] < 2:
        return {"status": "REFUSED", "reason": "OVERRIDE MARK"}
    return {"status": "PASS", "reason": "TIER"}


def render_gate(d):
    return d["status"] + "|" + d["reason"]


# --------------------------------------------------------------- inherit

def inherit(F_old, facts, params):
    f_old = _num(F_old)
    if f_old is None or f_old < 0.0:
        raise ValueError("F_old")
    if not _keys_are(facts, ("continuation", "same_account", "same_identity", "cause")):
        raise ValueError("facts")
    for k in ("continuation", "same_account", "same_identity"):
        if type(facts[k]) is not bool:
            raise ValueError("facts")
    if facts["cause"] not in CAUSES:
        raise ValueError("facts")
    on, frac = _pflag(params, "INHERITANCE")
    start = _pf(params, "THIN FILE START", 0.0, 1.0)
    valid = (on and facts["continuation"] and facts["same_account"]
             and facts["same_identity"] and facts["cause"] in ("DIS", "SUITE"))
    return {"F": frac * f_old if valid else 0.0, "S": start,
            "continuation": valid}


def render_inherit(d):
    return "%s|%s|%s" % (_f(d["F"]), _f(d["S"]), _b(d["continuation"]))


# -------------------------------------------------------- user_aggregate

_EKEYS = ("kind", "base", "age", "counterpart", "counterpart_sponsor")


def user_aggregate(agents, sponsor, params):
    if type(agents) is not list or not _is_name(sponsor):
        raise ValueError("agents")
    hl = _pf(params, "HALF-LIFE", 0.0, 1e9, True)
    c_max = _pf(params, "c_max", 0.0, 1.0, True, True)
    certified = 0
    pool = []
    seen = set()
    for ai, ag in enumerate(agents):
        if not _keys_are(ag, ("account", "certified", "removed", "events")):
            raise ValueError("agents")
        if (not _is_name(ag["account"]) or ag["account"] in seen
                or type(ag["certified"]) is not bool
                or type(ag["removed"]) is not bool
                or type(ag["events"]) is not list):
            raise ValueError("agents")
        seen.add(ag["account"])
        if ag["certified"]:
            certified += 1
        for ei, e in enumerate(ag["events"]):
            if not _keys_are(e, _EKEYS):
                raise ValueError("agents")
            base = _num(e["base"])
            if (e["kind"] not in ("FOR", "AGAINST") or base is None or base < 0.0
                    or not _is_int(e["age"], 0, COUNT_MAX)):
                raise ValueError("agents")
            cp = e["counterpart"]
            cs = e["counterpart_sponsor"]
            if cp is not None and not _is_name(cp):
                raise ValueError("agents")
            if cs is not None and not _is_name(cs):
                raise ValueError("agents")
            pool.append({"kind": e["kind"], "base": base, "age": e["age"],
                         "cp": cp, "cs": cs, "ai": ai, "ei": ei})
    if certified == 0:
        return {"status": "NONE", "events": [], "ages": []}

    def cmp(a, b):
        if a["age"] != b["age"]:
            return -1 if a["age"] > b["age"] else 1
        if a["ai"] != b["ai"]:
            return -1 if a["ai"] < b["ai"] else 1
        if a["ei"] != b["ei"]:
            return -1 if a["ei"] < b["ei"] else 1
        return 0
    ordered = _sort(pool, cmp)
    admitted = []
    events = []
    ages = []
    for e in ordered:
        if e["kind"] == "AGAINST":
            w = e["base"]
        elif e["cp"] is not None and e["cs"] == sponsor:
            w = 0.0
        elif e["cp"] is None or e["base"] == 0.0:
            w = e["base"]
        else:
            window = []
            for x in admitted:
                d = x["age"] - e["age"]
                if d <= hl:
                    window.append({"counterpart": x["cp"],
                                   "weight": x["w"] * math.pow(2.0, -float(d) / hl)})
            q = diversity_quota(window, e["cp"], e["base"], c_max)["q"]
            w = e["base"] * q
        if e["kind"] == "FOR":
            admitted.append({"age": e["age"], "cp": e["cp"], "w": w})
        events.append({"kind": "AGENT", "resolution": e["kind"], "weight": w})
        ages.append(e["age"])
    return {"status": "OK", "events": events, "ages": ages}


def render_aggregate(d):
    lines = ["aggregate|" + d["status"]]
    for e, age in zip(d["events"], d["ages"]):
        lines.append("event|%s|%s|%d" % (e["resolution"], _f(e["weight"]), age))
    return "\n".join(lines)


def user_score_evidence(agents, conduct, sponsor, params):
    agg = user_aggregate(agents, sponsor, params)
    if agg["status"] == "NONE":
        return {"status": "NONE"}
    if user_evidence is None:
        raise ValueError("tpc_sponsor")
    if type(conduct) is not list:
        raise ValueError("conduct")
    a0 = _pf(params, "a0", 0.0, 1e9, True)
    b0 = _pf(params, "b0", 0.0, 1e9, True)
    hl = _pf(params, "HALF-LIFE", 0.0, 1e9, True)
    if type(params.get("g_C")) is not dict or type(params.get("h_C")) is not dict:
        raise ValueError("params:g_C")
    events = list(agg["events"])
    ages = list(agg["ages"])
    for c in conduct:
        if not _keys_are(c, ("kind", "resolution", "age")):
            raise ValueError("conduct")
        if not _is_int(c["age"], 0, COUNT_MAX):
            raise ValueError("conduct")
        events.append({"kind": c["kind"], "resolution": c["resolution"]})
        ages.append(c["age"])
    r = user_evidence(events, ages, params["g_C"], params["h_C"], a0, b0, hl)
    r["status"] = "OK"
    return r


def render_user_evidence(d):
    if d["status"] == "NONE":
        return "NONE"
    return "OK|%s|%s|%d|%s|%s|%s" % (_f(d["F"]), _f(d["A"]), d["n"], _f(d["E"]),
                                     _f(d["lo"]), _f(d["hi"]))


def sponsor_cut(S_u, m_class, params):
    s = _num(S_u)
    if s is None or s < 0.0 or s > 1.0:
        raise ValueError("S")
    if not _is_int(m_class, 1, 3):
        raise ValueError("m_class")
    m = _pf(params, "m_%d" % m_class, 0.0, 1.0)
    cut = _pf(params, "SPONSOR CUT", 0.0, 1.0)
    return s * (1.0 - m * cut)


# ---------------------------------------------------------------- corpus

FNS = ("quota", "evidence", "interval", "standing", "rank", "prime",
       "level", "state", "activity", "update", "cut", "trip", "inquire",
       "override", "effective", "mark", "pad", "pad_weight", "gate",
       "inherit", "aggregate", "user_evidence", "sponsor_cut")


def run_case(fn, args):
    """One corpus case: the render, or "ERROR:" and the message."""
    if fn not in FNS:
        raise ValueError("fn")
    try:
        p = args.get("params")
        if fn == "quota":
            return render_quota(diversity_quota(args["window"], args["counterpart"],
                                                args["g"], args["c_max"]))
        if fn == "evidence":
            return render_evidence(evidence(args["events"], args["idle"], p))
        if fn == "interval":
            return render_interval(score_interval(args["S"], args["E"], args["lo"],
                                                  args["hi"]))
        if fn == "standing":
            return standing(args["x"], args["y"])
        if fn == "rank":
            return render_rank(rank(args["accounts"], p))
        if fn == "prime":
            return render_prime(prime_select(args["accounts"], args["override"], p))
        if fn == "level":
            return render_level(pending_level(args["items"], args["now"], p))
        if fn == "state":
            return render_state(state_step(args["prev"], args["level"], args["event"], p))
        if fn == "activity":
            return render_activity(peer_activity(args["events"], p))
        if fn == "update":
            return render_update(score_update(args["role"], args["S"], args["E"],
                                              args["S_P"], args["a"], p))
        if fn == "cut":
            return render_cut(violation_cut(args["S"], args["m_class"], args["standing"], p))
        if fn == "trip":
            return render_trip(trip(args["S"], args["in_tier"], args["prior_ages"], p))
        if fn == "inquire":
            return render_inquire(inquire(args["state"], args["block"], args["S"], p))
        if fn == "override":
            return render_override(override_check(args["decl"], args["facts"], p))
        if fn == "effective":
            return override_effective(args["decl_time"], args["now"], args["cancelled"], p)
        if fn == "mark":
            return render_mark(override_mark(args["grant"], args["now"], p))
        if fn == "pad":
            return render_pad(pad_check(args["decl"], args["facts"], p))
        if fn == "pad_weight":
            return _f(pad_weight(args["P"], args["age"], p))
        if fn == "gate":
            return render_gate(tier_gate_release(args["reproducer"]))
        if fn == "inherit":
            return render_inherit(inherit(args["F_old"], args["facts"], p))
        if fn == "aggregate":
            return render_aggregate(user_aggregate(args["agents"], args["sponsor"], p))
        if fn == "user_evidence":
            return render_user_evidence(user_score_evidence(
                args["agents"], args["conduct"], args["sponsor"], p))
        return _f(sponsor_cut(args["S"], args["m_class"], p))
    except ValueError as ex:
        return "ERROR:" + str(ex)