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:
+209
-79
@@ -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
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"retire_monitor_replica",
|
||||
Path(__file__).resolve().parents[1] / "scripts/retire_monitor_replica.py",
|
||||
)
|
||||
retire = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(retire)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def root(tmp_path):
|
||||
fleet = tmp_path / ".runtime/mission-core/fleet"
|
||||
fleet.mkdir(parents=True)
|
||||
with closing(sqlite3.connect(fleet / "monitor.sqlite3")) as db:
|
||||
for table, columns in retire.TABLES.items():
|
||||
db.execute(f"CREATE TABLE {table} ({', '.join(columns)})")
|
||||
db.commit()
|
||||
(fleet / "monitor.sqlite3-wal").write_bytes(b"closed legacy sidecar")
|
||||
(fleet / "monitor.sqlite3-shm").write_bytes(b"closed legacy sidecar")
|
||||
return tmp_path
|
||||
|
||||
|
||||
def accepted():
|
||||
return {"mode": "live", "core_operational": True, "verified_vehicles": 1}
|
||||
|
||||
|
||||
def test_only_exact_obsolete_files_removed_after_live_acceptance(root):
|
||||
fleet = root / ".runtime/mission-core/fleet"
|
||||
unrelated = fleet / "registry.json"
|
||||
unrelated.write_text("durable fleet data")
|
||||
snapshot = retire.plan(root)
|
||||
receipt = retire.apply(snapshot, probe=accepted, closed=lambda _: None)
|
||||
assert receipt["status"] == "complete" and len(receipt["removed"]) == 3
|
||||
assert unrelated.read_text() == "durable fleet data"
|
||||
assert retire.plan(root)["files"] == []
|
||||
assert json.loads(Path(receipt["receipt"]).read_text())["removed"] == receipt["removed"]
|
||||
|
||||
|
||||
def test_stale_plan_does_not_remove_any_files(root):
|
||||
snapshot = retire.plan(root)
|
||||
fleet = root / ".runtime/mission-core/fleet"
|
||||
(fleet / "monitor.sqlite3-wal").write_bytes(b"changed")
|
||||
with pytest.raises(ValueError, match="Stale"):
|
||||
retire.apply(snapshot, probe=accepted, closed=lambda _: None)
|
||||
assert all((fleet / name).exists() for name in retire.FILES)
|
||||
|
||||
|
||||
def test_open_reader_or_old_running_core_blocks_retirement(root):
|
||||
snapshot = retire.plan(root)
|
||||
|
||||
def blocked(*_):
|
||||
raise ValueError("not accepted")
|
||||
|
||||
with pytest.raises(ValueError, match="accepted"):
|
||||
retire.apply(snapshot, probe=blocked, closed=lambda _: None)
|
||||
with pytest.raises(ValueError, match="accepted"):
|
||||
retire.apply(snapshot, probe=accepted, closed=blocked)
|
||||
assert len(retire.plan(root)["files"]) == 3
|
||||
|
||||
|
||||
def test_unexpected_schema_or_symlink_is_never_deleted(root):
|
||||
fleet = root / ".runtime/mission-core/fleet"
|
||||
with closing(sqlite3.connect(fleet / "monitor.sqlite3")) as db:
|
||||
db.execute("CREATE TABLE recordings (id)")
|
||||
db.commit()
|
||||
with pytest.raises(ValueError, match="tables"):
|
||||
retire.plan(root)
|
||||
side = fleet / "monitor.sqlite3-wal"
|
||||
side.unlink(missing_ok=True)
|
||||
side.symlink_to(fleet / "monitor.sqlite3")
|
||||
with pytest.raises(ValueError, match="regular"):
|
||||
retire.plan(root)
|
||||
|
||||
|
||||
def test_partial_retirement_keeps_main_last_and_can_be_replanned(root):
|
||||
snapshot = retire.plan(root)
|
||||
unlink = Path.unlink
|
||||
|
||||
def fail(path, *args, **kwargs):
|
||||
if path.name == "monitor.sqlite3-wal":
|
||||
raise OSError("simulated interruption")
|
||||
return unlink(path, *args, **kwargs)
|
||||
|
||||
with patch.object(Path, "unlink", fail), pytest.raises(OSError, match="interruption"):
|
||||
retire.apply(snapshot, probe=accepted, closed=lambda _: None)
|
||||
fleet = root / ".runtime/mission-core/fleet"
|
||||
assert (fleet / "monitor.sqlite3").exists()
|
||||
assert not (fleet / "monitor.sqlite3-shm").exists()
|
||||
receipt = json.loads(
|
||||
next((root / ".runtime/storage-maintenance/monitor-retirement").glob("*.json")).read_text()
|
||||
)
|
||||
assert receipt["status"] == "interrupted" and len(receipt["removed"]) == 1
|
||||
assert (
|
||||
len(retire.apply(retire.plan(root), probe=accepted, closed=lambda _: None)["removed"]) == 2
|
||||
)
|
||||
|
||||
|
||||
def test_orphan_sidecar_is_not_assumed_disposable(root):
|
||||
(root / ".runtime/mission-core/fleet/monitor.sqlite3").unlink()
|
||||
with pytest.raises(ValueError, match="orphan"):
|
||||
retire.plan(root)
|
||||
|
||||
|
||||
def test_actual_open_file_check_refuses_a_reader_and_accepts_closed_file(root):
|
||||
target = root / ".runtime/mission-core/fleet/monitor.sqlite3"
|
||||
with target.open("rb"), pytest.raises(ValueError, match="open"):
|
||||
retire.assert_closed([target])
|
||||
retire.assert_closed([target])
|
||||
Reference in New Issue
Block a user