Files
NODEDC_MISSION_CORE/tests/test_board_monitor.py
T
DCCONSTRUCTIONS bec20d63e2 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.
2026-10-29 09:10:01 +03:00

299 lines
12 KiB
Python

import importlib.util
import sqlite3
import time
from pathlib import Path
from uuid import uuid4
import pytest
from k1link.fleet.monitor import MAX_NODES, SCHEMA, LiveMonitor, MonitorReceiver
ROOT = Path(__file__).resolve().parents[1]
def module(name):
spec = importlib.util.spec_from_file_location(
name, ROOT / "apps/node-agent/monitor" / (name + ".py")
)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
def record(seq, at, boot, value=25):
return dict(seq=seq, at=at, boot_id=boot, uptime=seq, values={"cpu.usage": value}, events=[])
def envelope(source, rows, latest=None):
return dict(
schema=SCHEMA,
source_id=source,
storage="ready",
latest=latest or rows[-1],
definitions={
"cpu.usage": dict(label="CPU", group="CPU", resource="cpu", unit="%", reason=None)
},
batch=dict(schema=SCHEMA, source_id=source, samples=rows),
)
def test_linux_rates_distinguish_absent_initial_reset_and_gap(tmp_path):
now = [100]
def write(path, text):
target = tmp_path / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text)
def counters(cpu, idle, rx):
write("proc/stat", f"cpu {cpu} 0 0 {idle} 0 0 0 0\ncpu0 {cpu} 0 0 {idle} 0 0 0 0\n")
write("sys/class/net/eth0/statistics/rx_bytes", str(rx))
write("sys/class/net/eth0/speed", "-1")
write("sys/bus/usb/devices/1-2/idVendor", "0000")
write("sys/bus/usb/devices/1-2/speed", "480")
write(
"sys/fs/cgroup/system.slice/mission-core-node.service/memory.events", "oom 3\noom_kill 2\n"
)
metrics = module("linux_metrics").LinuxMetrics(tmp_path, lambda: now[0])
counters(100, 100, 1000)
first = metrics.sample()
assert first["cpu.usage"] is None and first["net.eth0.rx_bytes"] is None
now[0] += 1
counters(150, 150, 1512)
second = metrics.sample()
assert second["cpu.usage"] == 50 and second["net.eth0.rx_bytes"] == 512
assert second["net.eth0.speed"] is None
assert second["usb.1-2.speed"] == 480 and second["usb.1-2.traffic"] is None
assert second["service.mission-core-node.service.oom"] == 2
now[0] += 1
counters(5, 5, 100)
assert metrics.sample()["net.eth0.rx_bytes"] is None
now[0] += 11
counters(25, 25, 900)
assert metrics.sample()["cpu.usage"] is None
def test_journal_retains_classification_without_freeform_data():
classify = module("journal_events").classify
value = classify(
{
"__REALTIME_TIMESTAMP": "123000000",
"_TRANSPORT": "kernel",
"MESSAGE": "Out of memory: Killed process 23 secret argument",
}
)
assert value == dict(code="system-oom", kind="Kernel", at=123, locations=[])
assert classify({"MESSAGE": "private Wi-Fi password"}) is None
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())
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