#!/usr/bin/env python3
"""Reference implementation of the node's own ceiling and the shed ladder.
Standard library only. Every constant is read from schema/constants.json rather
than hardcoded, so this file and the protocol version digest cannot disagree.
A grant bounds one peer. Nothing bounded the node. `Meter` is per peer and the
tick loops them, so twenty anchor peerings each perfectly inside its grant is
960,000 events an hour with nobody at fault anywhere: every branch within its
limit, and the trunk with none. That is the fragility this file answers.
Two decisions worth stating here rather than leaving to a reader.
**The total is the operator's number and this file states no default.** The
specification says connectivity and not capability is what separates one
deployment from another, so a Raspberry Pi and a forty-core gateway both declare
anchor and no per-class table could be honest about either. What is normative is
the ladder. A node with no declared total measures its pressure and reports it
and sheds nothing, because refusing an honest peer against a limit nobody chose
is worse than the overload it would be avoiding. `suggest` exists so an operator
has a number to start from rather than a blank.
**Shedding is announced, and it is not adverse.** Every rung says what it is
doing - a decline code, a republished coverage claim, an amend carrying
`cause: capacity`. A node that shed quietly would be read as partitioned, which
is the one conclusion this protocol keeps having to unlearn, and a subject that
read a capacity shed as a remedy would price its issuer for owning a small
machine.
"""
from __future__ import annotations
from typing import Iterable, Mapping, Optional, Sequence
from . import window
from ..wire import schema_files# window.as_limits: a grant carries integers
from ..wire.interfaces import CapacitySummary
C = schema_files.load_constants()['capacity']
COUNTERS: tuple[str, ...] = tuple(C['counters'])
LADDER: tuple[tuple[float, str], ...] = tuple((r['at'], r['action']) for r in C['shed'])
ACTIONS: tuple[str, ...] = tuple(a for _, a in LADDER)
[docs]def pressure(measured: Mapping[str, int | float], total: Mapping[str, int | float]) -> tuple[float, Optional[str]]:
"""(fraction, binding counter) for one window's aggregate against a total.
The fraction is the max over counters, not a mean: a node that has run out
of one thing has run out. `total` is a dict of the same counter names; a
counter the operator did not declare is not measured, and a total of zero or
less is not a declaration.
"""
worst: float = 0.0
binding: Optional[str] = None
for name in COUNTERS:
cap = total.get(name)
if not cap or cap <= 0:
continue
share = measured.get(name, 0) / float(cap)
if share > worst:
worst, binding = share, name
return worst, binding
[docs]def rungs(p: float) -> list[str]:
"""Every shed action engaged at pressure p, in ladder order."""
return [a for at, a in LADDER if p >= at]
[docs]def engaged(p: float, held: Sequence[str] = ()) -> list[str]:
"""The rungs a node should be holding now, given what it holds already.
Rungs engage each at its own threshold and release together below
`restore_below`. Releasing each at the threshold that engaged it would flap
a node sitting on a boundary, and each flap costs its peers an amend.
"""
if p < C['restore_below']:
return []
now = set(rungs(p)) | set(held)
return [a for a in ACTIONS if a in now]
[docs]def shed_floor(probation: Mapping[str, int | float]) -> dict[str, int]:
"""The lowest a capacity shed may take a limit, from the probation ceilings.
Deliberately not the probation ceiling itself. A peering opens at that
ceiling, so a floor there would make the amend_down rung do nothing at all
for exactly the peers a busy node has most of - declared and never read,
which is a shape this specification keeps finding in itself. Deliberately
not zero either: zero for 24 hours is what S3 does to an offender, and a
shed is not a remedy. What is left is enough for a receipt and a trickle,
which is what keeps a small peering accountable rather than silent.
"""
f: float = C['shed_floor_fraction']
# Floored, like every other limit. A fractional floor and an integer result
# do not compare the way anyone expects: max(335544.3, x) written into a
# grant becomes 335544, which is below the floor it was just held to.
return window.as_limits({k: v * f for k, v in probation.items()})
[docs]def reduce(limits: Mapping[str, int | float], floor: Mapping[str, int | float], fraction: Optional[float] = None) -> dict[str, int]:
"""Scale a grant's limits for a capacity shed, never below the floor.
A capacity shed makes a peer smaller and never makes it a stranger: the tier
does not move and the peering is not ended. That is what separates it from
an S2, which is the ladder's business and not this file's. Pass the floor
from `shed_floor`.
"""
f = C['amend_down_fraction'] if fraction is None else fraction
return window.as_limits({k: max(floor.get(k, 0), v * f) if k in floor else v * f
for k, v in limits.items()})
[docs]def suggest(windows: Iterable[Mapping[str, int | float]]) -> dict[str, int | float]:
"""A total to start from, per counter: the largest window observed.
`windows` is an iterable of aggregate measurements, one per closed window.
This is a report of what the machine has already carried and not a claim
about what it can. An operator raises it deliberately or lowers it after
watching the box, and either way the number is theirs.
"""
out: dict[str, int | float] = {}
for w in windows:
for name in COUNTERS:
v = w.get(name, 0)
if v > out.get(name, 0):
out[name] = v
return out
[docs]def summary(measured: Mapping[str, int | float], total: Mapping[str, int | float]) -> CapacitySummary:
"""What the health block prints. Undeclared is a state, not a zero."""
if not any(total.get(n) for n in COUNTERS):
return {'declared': False, 'pressure': None, 'binding': None,
'rungs': [], 'measured': {k: measured.get(k, 0) for k in COUNTERS
if measured.get(k)}}
p, binding = pressure(measured, total)
return {'declared': True, 'pressure': round(p, 4), 'binding': binding,
'rungs': rungs(p),
'measured': {k: measured.get(k, 0) for k in COUNTERS if measured.get(k)}}