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 -79
View File
@@ -6,7 +6,7 @@ from uuid import uuid4
import pytest
from k1link.fleet.monitor import SCHEMA, MonitorReceiver, MonitorReplica
from k1link.fleet.monitor import MAX_NODES, SCHEMA, LiveMonitor, MonitorReceiver
ROOT = Path(__file__).resolve().parents[1]
@@ -37,70 +37,6 @@ def envelope(source, rows, latest=None):
)
def test_replica_retries_restart_backfill_and_latest_are_separate(tmp_path):
source, boot = str(uuid4()), str(uuid4())
now = time.time()
rows = [record(i, now - 40 + i, boot) for i in range(1, 41)]
archive = MonitorReplica(tmp_path)
assert archive.ingest("board", envelope(source, rows[:32], rows[-1]))["after"] == 32
result = archive.query("board")
assert result["latest"]["seq"] == 40 and result["backlog"] == 8
assert archive.db.execute("SELECT count(*) FROM samples").fetchone()[0] == 32
archive.close()
archive = MonitorReplica(tmp_path)
# A lost reply cannot duplicate history; ACK comes from the durable commit.
assert archive.ingest("board", envelope(source, rows[:32], rows[-1]))["after"] == 32
assert archive.ingest("board", envelope(source, rows[32:]))["after"] == 40
assert archive.db.execute("SELECT count(*) FROM samples").fetchone()[0] == 40
assert archive.query("board")["backlog"] == 0
# Retention on the board can leave a real gap; no zero samples are invented.
assert archive.ingest("board", envelope(source, [record(51, now + 11, boot)]))["after"] == 51
archive.close()
def test_conflicting_or_nonfinite_batch_rolls_back_and_missing_values_are_null(tmp_path):
source, boot = str(uuid4()), str(uuid4())
now = time.time()
archive = MonitorReplica(tmp_path)
original = record(2, now - 20, boot)
archive.ingest("board", envelope(source, [original]))
bad = envelope(source, [record(1, now - 21, boot), {**original, "values": {"cpu.usage": 99}}])
with pytest.raises(ValueError):
archive.ingest("board", bad)
assert archive.db.execute("SELECT count(*) FROM samples").fetchone()[0] == 1
with pytest.raises(ValueError):
archive.ingest("board", envelope(source, [record(3, now, boot, float("nan"))]))
archive.ingest("board", envelope(source, [record(3, now, boot, None)]))
point = archive.query("board")["series"][-1]
assert point["max"] is None and point["count"] == 0
archive.close()
def test_receiver_failure_isolated_and_offline_history_reopens(tmp_path, monkeypatch):
source, boot = str(uuid4()), str(uuid4())
archive = MonitorReplica(tmp_path)
archive.ingest("board", envelope(source, [record(1, time.time(), boot)]))
archive.close()
receiver = MonitorReceiver(tmp_path)
try:
deadline = time.monotonic() + 2
while not receiver.query("board")["available"] and time.monotonic() < deadline:
time.sleep(0.01)
assert receiver.query("board")["available"]
monkeypatch.setattr(
receiver.archive,
"ingest",
lambda *_: (_ for _ in ()).throw(sqlite3.OperationalError("synthetic full disk")),
)
start = time.monotonic()
assert receiver.submit("board", envelope(source, [record(2, time.time(), boot)])) is None
assert time.monotonic() - start < 0.1
time.sleep(0.05)
assert receiver.acks.get("board") is None
finally:
receiver.close()
def test_linux_rates_distinguish_absent_initial_reset_and_gap(tmp_path):
now = [100]
@@ -151,18 +87,212 @@ def test_journal_retains_classification_without_freeform_data():
assert classify({"MESSAGE": "private Wi-Fi password"}) is None
def test_long_range_aggregates_keep_peaks_counts_and_exclude_incomplete_minute(tmp_path):
class Clock:
def __init__(self):
self.wall = 1_000_000.0
self.tick = 100.0
def advance(self, seconds):
self.wall += seconds
self.tick += seconds
@pytest.fixture
def live():
clock = Clock()
state = LiveMonitor(clock=lambda: clock.wall, monotonic=lambda: clock.tick)
return state, clock, str(uuid4()), str(uuid4())
def test_latest_is_accepted_without_replicating_backfill_or_creating_files(live, tmp_path):
state, clock, source, boot = live
old = [record(i, clock.wall - 100 + i, boot) for i in range(1, 33)]
value = envelope(source, old, record(1000, clock.wall, boot))
value["unrelated"] = object() # Unknown fields/backfill are not serialized.
ack = state.ingest("board", value)
assert ack == dict(source_id=source, after=1000, mode="live")
result = state.query("board")
assert result["fresh"] and result["latest"]["seq"] == 1000
assert result["mode"] == "live" and result["history_available"] is False
assert not {"series", "batch", "backlog", "archive_since", "database_bytes"} & result.keys()
assert list(tmp_path.iterdir()) == []
def test_duplicates_never_extend_freshness_or_expiry(live):
state, clock, source, boot = live
value = envelope(source, [record(1, clock.wall, boot)])
state.ingest("board", value)
clock.advance(11)
assert state.ingest("board", value)["after"] == 1
result = state.query("board")
assert result["available"] and not result["fresh"]
assert result["received_age_seconds"] == 11 and result["expires_in_seconds"] == 19
clock.advance(19)
assert not state.query("board")["available"] and not state.entries
state.ingest("board", value)
assert not state.entries
def test_utc_day_reset_and_monotonic_expiry(live):
state, clock, source, boot = live
clock.wall = (int(clock.wall // 86400) + 1) * 86400 - 2
state.ingest("board", envelope(source, [record(1, clock.wall, boot)]))
clock.advance(3)
assert not state.query("board")["available"]
state.ingest("board", envelope(source, [record(2, clock.wall, boot)]))
assert state.query("board")["fresh"]
clock.tick += 30 # Wall time can freeze/adjust; monotonic time still expires RAM.
assert not state.query("board")["available"]
def test_out_of_order_conflicting_and_changed_source_cannot_restore_old_values(live):
state, clock, source, boot = live
current = record(10, clock.wall, boot, 50)
state.ingest("board", envelope(source, [current]))
assert state.ingest("board", envelope(source, [record(9, clock.wall - 1, boot)]))["after"] == 10
with pytest.raises(ValueError, match="Conflicting"):
state.ingest("board", envelope(source, [{**current, "values": {"cpu.usage": 99}}]))
assert state.query("board")["latest"]["values"]["cpu.usage"] == 50
newer = str(uuid4())
clock.advance(1)
state.ingest("board", envelope(newer, [record(1, clock.wall, boot, 60)]))
assert state.ingest("board", envelope(source, [current])) is None
assert state.query("board")["source_id"] == newer
@pytest.mark.parametrize("age", [30, 3600, -6])
def test_stale_or_future_clock_snapshots_do_not_populate_live_state(live, age):
state, clock, source, boot = live
assert (
state.ingest("board", envelope(source, [record(1, clock.wall - age, boot)]))["mode"]
== "live"
)
assert not state.query("board")["available"]
def test_node_capacity_is_bounded_and_released_by_expiry(live):
state, clock, source, boot = live
value = envelope(source, [record(1, clock.wall, boot)])
for i in range(MAX_NODES):
assert state.ingest(f"board-{i}", value)
assert state.ingest("overflow", value) is None
assert len(state.entries) == MAX_NODES
clock.advance(31)
assert state.ingest("overflow", envelope(source, [record(2, clock.wall, boot)]))
assert len(state.entries) == 1
def test_snapshot_size_and_metric_validation_leave_previous_state_untouched(live):
state, clock, source, boot = live
value = envelope(source, [record(1, clock.wall, boot)])
state.ingest("board", value)
huge = envelope(source, [record(2, clock.wall, boot)])
huge["definitions"] = {
f"metric{i}": dict(
label="x" * 256, group="x" * 256, resource="x" * 256, unit="x" * 256, reason="x" * 256
)
for i in range(384)
}
with pytest.raises(ValueError, match="budget"):
state.ingest("board", huge)
for invalid in [float("nan"), float("inf"), True, "private text"]:
with pytest.raises(ValueError):
state.ingest("board", envelope(source, [record(2, clock.wall, boot, invalid)]))
assert state.query("board")["latest"]["seq"] == 1
def test_sample_budget_and_invalid_ids_are_rejected(live):
state, clock, source, boot = live
row = record(1, clock.wall, boot)
row["values"] = {"m" * 175 + str(i): 1 for i in range(384)}
with pytest.raises(ValueError, match="budget"):
state.ingest("board", envelope(source, [row]))
for bad in [None, 23, False, {}, "not-a-uuid"]:
with pytest.raises((ValueError, TypeError)):
state.ingest("board", envelope(source, [record(1, clock.wall, bad)]))
def test_snapshot_is_detached_and_missing_values_remain_null(live):
state, clock, source, boot = live
value = envelope(source, [record(1, clock.wall, boot, None)])
state.ingest("board", value)
value["latest"]["values"]["cpu.usage"] = 100
result = state.query("board")
assert result["latest"]["values"]["cpu.usage"] is None
result["latest"]["values"]["cpu.usage"] = 99
assert state.query("board")["latest"]["values"]["cpu.usage"] is None
def test_only_events_in_latest_unexpired_observation_are_visible(live):
state, clock, source, boot = live
row = record(1, clock.wall, boot)
row["events"] = [
dict(code="usb-error", kind="Kernel", locations=[], at=clock.wall),
dict(code="system-oom", kind="Kernel", locations=[], at=clock.wall - 60),
]
state.ingest("board", envelope(source, [row]))
assert [e["code"] for e in state.query("board")["events"]] == ["usb-error"]
assert len(state.query("board")["latest"]["events"]) == 1
clock.advance(1)
state.ingest("board", envelope(source, [record(2, clock.wall, boot)]))
assert state.query("board")["events"] == []
def test_receiver_never_opens_legacy_db_and_restart_has_no_history(tmp_path, monkeypatch):
path = tmp_path / "monitor.sqlite3"
path.write_bytes(b"old telemetry, preserved until explicit retirement")
source, boot = str(uuid4()), str(uuid4())
now = int(time.time()//60)*60
archive = MonitorReplica(tmp_path)
rows = [record(1, now-120, boot, 10), record(2, now-110, boot, 90),
record(3, now-60, boot, 30), record(4, now+1, boot, 100)]
value = envelope(source, rows)
archive.ingest('board', value)
archive.ingest('board', value) # Duplicate delivery cannot inflate aggregates.
result = archive.query('board', window=21600, end=now+10)
assert result['end'] == now
assert sum(point['count'] for point in result['series']) == 3
assert max(point['max'] for point in result['series']) == 90
assert min(point['min'] for point in result['series']) == 10
archive.close()
monkeypatch.setattr(
sqlite3, "connect", lambda *args, **kwargs: pytest.fail("monitor opened SQLite")
)
receiver = MonitorReceiver(tmp_path)
assert receiver.submit("board", envelope(source, [record(1, time.time(), boot)]))["after"] == 1
assert receiver.query("board")["available"]
receiver.close()
assert not receiver.worker.is_alive()
assert receiver.submit("board", envelope(source, [record(2, time.time(), boot)])) is None
assert path.read_bytes() == b"old telemetry, preserved until explicit retirement"
another = MonitorReceiver(tmp_path)
assert not another.query("board")["available"]
assert list(tmp_path.iterdir()) == [path]
another.close()
def test_idle_sweeper_expires_without_api_reads(tmp_path):
clock = Clock()
receiver = MonitorReceiver(tmp_path, clock=lambda: clock.wall, monotonic=lambda: clock.tick)
try:
source, boot = str(uuid4()), str(uuid4())
receiver.submit("board", envelope(source, [record(1, clock.wall, boot)]))
clock.advance(31)
deadline = time.monotonic() + 2
while receiver.live.entries and time.monotonic() < deadline:
time.sleep(0.01)
assert not receiver.live.entries
finally:
receiver.close()
def test_live_api_refuses_historical_queries_and_returns_no_store(live):
import threading
from types import SimpleNamespace
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web import fleet_api
state, clock, source, boot = live
state.ingest("board", envelope(source, [record(1, clock.wall, boot)]))
fleet = SimpleNamespace(
lock=threading.RLock(), find=lambda _: {"node_id": "board"}, monitor=state
)
app = FastAPI()
app.include_router(fleet_api.router)
app.dependency_overrides[fleet_api.local_operator] = lambda: fleet
with TestClient(app) as client:
response = client.get("/api/v1/fleet/vehicle/monitor")
assert response.status_code == 200 and response.headers["cache-control"] == "no-store"
assert response.json()["mode"] == "live"
for query in ["window=900", "end=1000000", "metric=cpu.usage"]:
assert client.get("/api/v1/fleet/vehicle/monitor?" + query).status_code == 400