feat(monitor): keep operator telemetry live and retire local replicas

Keep operator monitoring in bounded live snapshots and provide scoped replica retirement. Update the board dashboard and retirement regressions.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent 7878937691
commit bec20d63e2
9 changed files with 940 additions and 429 deletions
+209 -287
View File
@@ -1,15 +1,25 @@
"""Idempotent local replica of a board-owned Timescale history, behind fleet mTLS."""
"""Bounded live operator snapshots; the board owns its independent archive.
Nothing in this module opens or migrates monitor.sqlite3. The v1 transport ACK
advances past the accepted latest observation in live mode; it is NOT a durable
replication receipt. Node's collector retention is independent of this cursor.
"""
import json
import math
import re
import sqlite3
import threading
import time
from uuid import UUID
SCHEMA = "missioncore.node-system-monitor/v1"
KEY = re.compile(r"^[A-Za-z0-9_.:-]{1,180}$")
MAX_NODES = 32
MAX_SNAPSHOT_BYTES = 196608
TTL_SECONDS = 30
SAMPLE_FRESH_SECONDS = 10
RECEIVE_FRESH_SECONDS = 15
FUTURE_SKEW_SECONDS = 5
def checked_sample(value):
@@ -24,7 +34,7 @@ def checked_sample(value):
raise ValueError("Invalid sample")
if type(value["seq"]) is not int or not 0 < value["seq"] < 2**53:
raise ValueError("Invalid sequence")
if str(UUID(value["boot_id"])) != value["boot_id"]:
if not isinstance(value["boot_id"], str) or str(UUID(value["boot_id"])) != value["boot_id"]:
raise ValueError("Invalid boot")
for name in ["at", "uptime"]:
if (
@@ -36,8 +46,13 @@ def checked_sample(value):
if not isinstance(value["values"], dict) or len(value["values"]) > 384:
raise ValueError("Metric budget")
for key, number in value["values"].items():
if not KEY.fullmatch(key) or (
number is not None and (type(number) not in (int, float) or not math.isfinite(number))
if (
not isinstance(key, str)
or not KEY.fullmatch(key)
or (
number is not None
and (type(number) not in (int, float) or not math.isfinite(number))
)
):
raise ValueError("Invalid metric")
if not isinstance(value["events"], list) or len(value["events"]) > 64:
@@ -79,312 +94,219 @@ def checked_sample(value):
return json.dumps(value, allow_nan=False, separators=(",", ":"), sort_keys=True)
class MonitorReplica:
def __init__(self, root):
path = root / "monitor.sqlite3"
if path.is_symlink():
raise ValueError("Invalid monitor store")
self.db = sqlite3.connect(path, check_same_thread=False, timeout=2)
try:
path.chmod(0o600)
self.lock = threading.RLock()
self.maintenance = 0
self.db.execute("PRAGMA journal_mode=WAL")
self.db.execute("PRAGMA synchronous=FULL")
self.db.execute("PRAGMA max_page_count=524288")
self.db.execute(
"CREATE TABLE IF NOT EXISTS samples(node TEXT,source TEXT,seq INTEGER,at REAL,"
"body TEXT,PRIMARY KEY(node,source,seq))"
)
self.db.execute("CREATE INDEX IF NOT EXISTS samples_time ON samples(node,at)")
self.db.execute(
"CREATE TABLE IF NOT EXISTS minutes(node TEXT,at INTEGER,body TEXT,"
"PRIMARY KEY(node,at))"
)
self.db.execute(
"CREATE TABLE IF NOT EXISTS events(node TEXT,source TEXT,seq INTEGER,at REAL,"
"body TEXT,PRIMARY KEY(node,source,seq))"
)
self.db.execute("CREATE INDEX IF NOT EXISTS events_time ON events(node,at)")
self.db.execute(
"CREATE TABLE IF NOT EXISTS states(node TEXT PRIMARY KEY,source TEXT,"
"body TEXT,received REAL,ack INTEGER)"
)
self.db.commit()
except Exception:
self.db.close()
raise
def checked_snapshot(value):
if not isinstance(value, dict) or value.get("schema") != SCHEMA:
return None
source = value.get("source_id")
if not isinstance(source, str) or str(UUID(source)) != source:
raise ValueError("Invalid source")
definitions = value.get("definitions")
if not isinstance(definitions, dict) or len(definitions) > 384:
raise ValueError("Definition budget")
for key, definition in definitions.items():
if (
not isinstance(key, str)
or not KEY.fullmatch(key)
or not isinstance(definition, dict)
or set(definition) != {"label", "group", "resource", "unit", "reason"}
):
raise ValueError("Invalid definition")
if any(
(name != "reason" or v is not None) and (not isinstance(v, str) or len(v) > 256)
for name, v in definition.items()
):
raise ValueError("Invalid definition")
if value.get("latest") is None:
return None
sample = checked_sample(value["latest"])
if len(sample.encode()) > 32768:
raise ValueError("Sample budget")
# Projection precedes serialization: backfill, archive metadata and unknown
# extensions are neither walked nor retained on the operator machine.
snapshot = {
"schema": SCHEMA,
"source_id": source,
"definitions": definitions,
"latest": value["latest"],
}
payload = json.dumps(snapshot, allow_nan=False, separators=(",", ":"), sort_keys=True)
if len(payload.encode()) > MAX_SNAPSHOT_BYTES:
raise ValueError("Live snapshot budget")
return payload, sample
def unavailable():
return dict(
available=False,
fresh=False,
mode="live",
history_available=False,
ttl_seconds=TTL_SECONDS,
source_id=None,
latest=None,
definitions={},
events=[],
received_at=None,
sample_age_seconds=None,
received_age_seconds=None,
expires_in_seconds=0,
)
class LiveMonitor:
"""One serialized snapshot per node, with monotonic expiry and UTC day reset."""
def __init__(self, *, clock=None, monotonic=None):
self.clock = clock or time.time
self.monotonic = monotonic or time.monotonic
self.lock = threading.RLock()
self.entries = {}
self.day = int(self.clock() // 86400)
def _prune(self):
now, tick = self.clock(), self.monotonic()
day = int(now // 86400)
if day != self.day:
self.entries.clear()
self.day = day
for node, entry in list(self.entries.items()):
age = now - entry["at"]
if (
tick - entry["tick"] >= TTL_SECONDS
or age >= TTL_SECONDS
or age < -FUTURE_SKEW_SECONDS
):
del self.entries[node]
def prune(self):
with self.lock:
self._prune()
def ingest(self, node, value):
if not isinstance(value, dict) or value.get("schema") != SCHEMA:
if not isinstance(node, str) or not KEY.fullmatch(node):
raise ValueError("Invalid node")
checked = checked_snapshot(value)
if checked is None:
return None
source = value.get("source_id")
if not isinstance(source, str) or str(UUID(source)) != source:
raise ValueError("Invalid source")
definitions = value.get("definitions")
if not isinstance(definitions, dict) or len(definitions) > 384:
raise ValueError("Definition budget")
for key, definition in definitions.items():
if (
not KEY.fullmatch(key)
or not isinstance(definition, dict)
or set(definition) != {"label", "group", "resource", "unit", "reason"}
):
raise ValueError("Invalid definition")
if any(
v is not None and (not isinstance(v, str) or len(v) > 256)
for v in definition.values()
):
raise ValueError("Invalid definition")
if value.get("latest") is not None:
checked_sample(value["latest"])
batch = value.get("batch") or {}
rows = batch.get("samples", [])
if (
not isinstance(rows, list)
or len(rows) > 32
or (rows and (batch.get("source_id") != source or batch.get("schema") != SCHEMA))
):
raise ValueError("Invalid batch")
serialized = [(row, checked_sample(row)) for row in rows]
if sum(len(text.encode()) for _, text in serialized) > 196608:
raise ValueError("Batch budget")
if any(
a[0]["seq"] >= b[0]["seq"] for a, b in zip(serialized, serialized[1:], strict=False)
):
raise ValueError("Unordered batch")
snapshot = {
key: item
for key, item in value.items()
if key
in {
"schema",
"source_id",
"latest",
"definitions",
"storage",
"database_bytes",
"sample_interval_seconds",
"retention_days",
"database_budget_bytes",
"free_reserve_bytes",
}
}
snapshot.update(
retained_since=batch.get("retained_since"), first_seq=batch.get("first_seq")
)
with self.lock, self.db:
previous = self.db.execute(
"SELECT source,ack FROM states WHERE node=?", (node,)
).fetchone()
ack = previous[1] if previous and previous[0] == source else 0
minutes = {}
for row, text in serialized:
old = self.db.execute(
"SELECT body FROM samples WHERE node=? AND source=? AND seq=?",
(node, source, row["seq"]),
).fetchone()
if old and old[0] != text:
raise ValueError("Conflicting history sequence")
self.db.execute(
"INSERT OR IGNORE INTO samples VALUES(?,?,?,?,?)",
(node, source, row["seq"], row["at"], text),
)
if not old:
minute = int(row["at"] // 60) * 60
if minute not in minutes:
saved = self.db.execute(
"SELECT body FROM minutes WHERE node=? AND at=?", (node, minute)
).fetchone()
minutes[minute] = json.loads(saved[0]) if saved else {}
for key, number in row["values"].items():
if number is not None:
aggregate = minutes[minute].setdefault(key, [number, number, 0, 0])
aggregate[0] = min(aggregate[0], number)
aggregate[1] = max(aggregate[1], number)
aggregate[2] += number
aggregate[3] += 1
if row["events"]:
self.db.execute(
"INSERT INTO events VALUES(?,?,?,?,?)",
(node, source, row["seq"], row["at"], json.dumps(row["events"])),
)
ack = max(ack, row["seq"])
for minute, aggregate in minutes.items():
self.db.execute(
"INSERT INTO minutes VALUES(?,?,?) ON CONFLICT(node,at) "
"DO UPDATE SET body=excluded.body",
(node, minute, json.dumps(aggregate)),
)
self.db.execute(
"INSERT INTO states VALUES(?,?,?,?,?) ON CONFLICT(node) DO UPDATE SET "
"source=excluded.source,body=excluded.body,received=excluded.received,ack=excluded.ack",
(node, source, json.dumps(snapshot), time.time(), ack),
payload, sample = checked
snapshot = json.loads(payload)
latest, source = snapshot["latest"], snapshot["source_id"]
with self.lock:
self._prune()
now, tick = self.clock(), self.monotonic()
previous = self.entries.get(node)
ack = dict(source_id=source, after=latest["seq"], mode="live")
# Consuming a stale live observation advances transport only; it
# cannot populate the current view or trigger historical backfill.
if not -FUTURE_SKEW_SECONDS <= now - latest["at"] < TTL_SECONDS:
return ack
if previous and previous["source"] == source:
if latest["seq"] < previous["seq"]:
return dict(source_id=source, after=previous["seq"], mode="live")
if latest["seq"] == previous["seq"]:
if sample != previous["sample"]:
raise ValueError("Conflicting live sequence")
# Repeated packets never extend freshness or expiry.
return ack
if previous and latest["at"] < previous["at"]:
return None
if previous is None and len(self.entries) >= MAX_NODES:
return None
self.entries[node] = dict(
payload=payload,
sample=sample,
source=source,
seq=latest["seq"],
at=latest["at"],
tick=tick,
received=now,
)
if time.time() - self.maintenance > 60:
self.db.execute("DELETE FROM samples WHERE at<?", (time.time() - 7 * 86400,))
self.db.execute("DELETE FROM minutes WHERE at<?", (time.time() - 7 * 86400,))
self.db.execute("DELETE FROM events WHERE at<?", (time.time() - 7 * 86400,))
self.maintenance = time.time()
return dict(source_id=source, after=ack)
return ack
def query(self, node, metric="cpu.usage", window=900, end=None):
if not KEY.fullmatch(metric) or window not in (900, 3600, 21600, 86400, 604800):
raise ValueError("Invalid range")
end = time.time() if end is None else end
if not math.isfinite(end) or end < 0:
raise ValueError("Invalid time")
coarse = window >= 21600
width = math.ceil(window / 300 / 60) * 60 if coarse else max(1, window // 300)
if coarse:
end = math.floor(end / 60) * 60
start = end - window
path = '$.values."' + metric + '"'
def query(self, node):
with self.lock:
row = self.db.execute(
"SELECT body,received,ack FROM states WHERE node=?", (node,)
).fetchone()
if not row:
return dict(available=False, series=[], events=[])
snapshot = json.loads(row[0])
if coarse:
aggregate = '$."' + metric + '"'
points = self.db.execute(
"SELECT CAST(at/? AS INTEGER),min(json_extract(body,?)), "
"max(json_extract(body,?)),sum(json_extract(body,?))*1.0/"
"nullif(sum(json_extract(body,?)),0),sum(json_extract(body,?)) "
"FROM minutes WHERE node=? AND at>=? AND at<? "
"GROUP BY CAST(at/? AS INTEGER) ORDER BY 1",
(
width,
aggregate + "[0]",
aggregate + "[1]",
aggregate + "[2]",
aggregate + "[3]",
aggregate + "[3]",
node,
start,
end,
width,
),
).fetchall()
else:
points = self.db.execute(
"SELECT CAST(at/? AS INTEGER),min(json_extract(body,?)), "
"max(json_extract(body,?)),avg(json_extract(body,?)),"
"count(json_extract(body,?)) FROM samples "
"WHERE node=? AND at>=? AND at<=? GROUP BY CAST(at/? AS INTEGER) ORDER BY 1",
(width, path, path, path, path, node, start, end, width),
).fetchall()
event_rows = self.db.execute(
"SELECT body FROM events WHERE node=? AND at>=? AND at<=? "
"ORDER BY at DESC LIMIT 64",
(node, start, end),
).fetchall()
earliest = self.db.execute(
"SELECT min(at) FROM samples WHERE node=?", (node,)
).fetchone()[0]
latest = snapshot.get("latest")
fresh = bool(latest and -5 <= time.time() - latest["at"] < 10 and time.time() - row[1] < 15)
return dict(
available=True,
**snapshot,
fresh=fresh,
received_at=row[1],
replicated_after=row[2],
archive_since=earliest,
backlog=max(0, (latest or {}).get("seq", 0) - row[2]),
start=start,
end=end,
bucket_seconds=width,
series=[
dict(at=bucket * width, min=minimum, max=maximum, mean=mean, count=count)
for bucket, minimum, maximum, mean, count in points
],
events=[event for record in event_rows for event in json.loads(record[0])][:64],
)
self._prune()
entry = self.entries.get(node)
if entry is None:
return unavailable()
now = self.clock()
sample_age = now - entry["at"]
received_age = self.monotonic() - entry["tick"]
snapshot = json.loads(entry["payload"])
events = [
e
for e in snapshot["latest"]["events"]
if -FUTURE_SKEW_SECONDS <= now - e["at"] < TTL_SECONDS
]
# Do not leave expired events accessible via the nested sample.
snapshot["latest"]["events"] = events
return dict(
**snapshot,
available=True,
mode="live",
history_available=False,
ttl_seconds=TTL_SECONDS,
fresh=sample_age < SAMPLE_FRESH_SECONDS and received_age < RECEIVE_FRESH_SECONDS,
received_at=entry["received"],
sample_age_seconds=sample_age,
received_age_seconds=received_age,
expires_in_seconds=max(
0, min(TTL_SECONDS - sample_age, TTL_SECONDS - received_age)
),
events=events,
)
def close(self):
def clear(self):
with self.lock:
self.db.close()
self.entries.clear()
class MonitorReceiver:
"""Replica I/O never runs under the fleet/control lock, including startup.
"""Bounded in-memory admission only; no disk I/O under the fleet lock.
Heartbeats may repeat a batch until this worker commits it. Replacing a
queued retry is safe: the sender advances only from the returned commit ACK.
An idle sweeper expires snapshots even when nobody polls the API. Invalid
optional monitor payloads are rejected without disrupting control traffic.
"""
def __init__(self, root):
self.root = root
def __init__(self, root=None, *, clock=None, monotonic=None):
# root remains an accepted constructor argument for FleetRegistry. It is
# deliberately never read, created, or retained as a storage destination.
self.live = LiveMonitor(clock=clock, monotonic=monotonic)
self.lock = threading.Lock()
self.pending = {}
self.acks = {}
self.archive = None
self.worker = None
self.wake = threading.Event()
self.stop = threading.Event()
self.worker = None
def _start(self):
with self.lock:
if self.stop.is_set():
return False
if self.worker is None:
self.worker = threading.Thread(
target=self.run, name="fleet-monitor-expiry", daemon=True
)
self.worker.start()
return True
def submit(self, node, value):
if not isinstance(value, dict) or value.get("schema") != SCHEMA:
if not self._start():
return None
with self.lock:
if node not in self.pending and len(self.pending) >= 32:
if self.stop.is_set():
return None
self.pending[node] = value
if self.worker is None:
self.worker = threading.Thread(
target=self.run, name="fleet-monitor-replica", daemon=True
)
self.worker.start()
self.wake.set()
ack = self.acks.get(node)
return ack if ack and ack["source_id"] == value.get("source_id") else None
return self.live.ingest(node, value)
def run(self):
try:
while not self.stop.is_set():
self.wake.wait(1)
with self.lock:
pending, self.pending = self.pending, {}
self.wake.clear()
if self.archive is None:
try:
self.archive = MonitorReplica(self.root)
except (OSError, ValueError, sqlite3.Error):
continue
for node, value in pending.items():
try:
if self.archive is None:
self.archive = MonitorReplica(self.root)
ack = self.archive.ingest(node, value)
with self.lock:
self.acks[node] = ack
except (OSError, ValueError, TypeError, KeyError, sqlite3.Error):
# No ACK: the board retains and retries its own archive.
continue
finally:
if self.archive is not None:
self.archive.close()
while not self.stop.wait(1):
self.live.prune()
def query(self, *args, **kwargs):
with self.lock:
if self.worker is None:
self.worker = threading.Thread(
target=self.run, name="fleet-monitor-replica", daemon=True
)
self.worker.start()
self.wake.set()
try:
if self.archive is not None:
return self.archive.query(*args, **kwargs)
except sqlite3.Error:
pass
return dict(available=False, series=[], events=[])
def query(self, node):
if self.stop.is_set():
return unavailable()
return self.live.query(node)
def close(self):
self.stop.set()
self.wake.set()
with self.lock:
self.stop.set()
if self.worker is not None:
self.worker.join(5)
self.worker.join(2)
self.live.clear()