Probe Python peer health

This commit is contained in:
Meta Vens 2026-06-14 13:44:57 +01:00
commit 031d879695
5 changed files with 206 additions and 6 deletions

View file

@ -81,9 +81,10 @@ CultCache, CultNet, and CultMesh. It is evidence, not confetti.
discovery from endpoints already advertised in local Verse and peer catalogs,
fan out raw snapshot fetches and simulation observations to peer-card
endpoints, apply peer snapshots through a caller-owned database, run
lightweight scheduled snapshot and simulation-observation fanout loops, and
upsert results into local catalogs with the same count-returning ergonomics
as the C# discovery clients.
lightweight scheduled snapshot and simulation-observation fanout loops, probe
peer-card endpoints for hello-level reachability, and upsert results into
local catalogs with the same count-returning ergonomics as the C# discovery
clients.
- Python CultMesh facade:
Exposes C#-matching client entrypoints for Verse discovery, peer exchange,
raw CultNet client construction, local nodes, catalogs, sessions, streams,

View file

@ -1,6 +1,8 @@
from .client import (
CultMeshDiscoveryClient,
CultMeshPeerExchangeClient,
CultMeshPeerHealth,
CultMeshPeerHealthMonitor,
CultMeshSimulationObservationFanout,
CultMeshSnapshotFanout,
CultMeshVerseDiscoveryClient,
@ -69,6 +71,8 @@ __all__ = [
"AuthorityLeaseVerifier",
"CultMeshDiscoveryClient",
"CultMeshPeerExchangeClient",
"CultMeshPeerHealth",
"CultMeshPeerHealthMonitor",
"CultMeshSimulationObservationFanout",
"CultMeshSnapshotFanout",
"CultMeshVerseDiscoveryClient",

View file

@ -2,10 +2,11 @@ from __future__ import annotations
import threading
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Any, Callable
from urllib.parse import urlparse
from cultnet_py import CultNetRawClient, CultNetRawSnapshotResponse
from cultnet_py import CultNetRawClient, CultNetRawSnapshotResponse, hello
from .wire import (
PEER_EXCHANGE_RESPONSE,
@ -484,6 +485,128 @@ class CultMeshSnapshotFanout:
self.sync_once()
@dataclass(frozen=True)
class CultMeshPeerHealth:
peer_id: str
endpoint: str
checked_at: datetime
is_reachable: bool
runtime_id: str | None = None
error: str | None = None
@dataclass
class CultMeshPeerHealthMonitor:
runtime_id: str
timeout_seconds: float = 2.0
interval_seconds: float = 5.0
on_update: Callable[[CultMeshPeerHealth], None] | None = None
_latest: dict[tuple[str, str], CultMeshPeerHealth] = field(default_factory=dict, init=False, repr=False)
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
_stop: threading.Event = field(default_factory=threading.Event, init=False, repr=False)
_thread: threading.Thread | None = field(default=None, init=False, repr=False)
def probe_peer(self, peer: CultMeshPeerCard) -> list[CultMeshPeerHealth]:
return [
self._record(self._probe_endpoint(peer.peer_id, endpoint))
for endpoint in _distinct_non_empty(list(peer.endpoints))
]
def probe_catalog(
self,
catalog: CultMeshPeerCatalog,
*,
verse_id: str,
roles: list[str] | None = None,
) -> list[CultMeshPeerHealth]:
requested_roles = set(roles or [])
results = []
for peer in catalog.find(verse_id):
if requested_roles and not requested_roles.intersection(peer.roles):
continue
results.extend(self.probe_peer(peer))
return results
def latest(self) -> tuple[CultMeshPeerHealth, ...]:
with self._lock:
return tuple(
self._latest[key]
for key in sorted(self._latest)
)
def start(
self,
catalog: CultMeshPeerCatalog,
*,
verse_id: str,
roles: list[str] | None = None,
) -> "CultMeshPeerHealthMonitor":
if self._thread is not None:
return self
self._stop.clear()
self._thread = threading.Thread(
target=self._run,
args=(catalog, verse_id, roles),
daemon=True,
)
self._thread.start()
return self
def stop(self) -> None:
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=max(2.0, self.interval_seconds * 2.0))
self._thread = None
def __enter__(self) -> "CultMeshPeerHealthMonitor":
if self._thread is None:
raise RuntimeError("CultMeshPeerHealthMonitor.start(...) must be called before entering context")
return self
def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
self.stop()
def _run(
self,
catalog: CultMeshPeerCatalog,
verse_id: str,
roles: list[str] | None,
) -> None:
while not self._stop.wait(self.interval_seconds):
self.probe_catalog(catalog, verse_id=verse_id, roles=roles)
def _probe_endpoint(self, peer_id: str, endpoint: str) -> CultMeshPeerHealth:
checked_at = datetime.now(UTC)
try:
host, port = _parse_endpoint(endpoint)
response = CultNetRawClient(host, port, self.timeout_seconds).request(
hello(runtime_id=self.runtime_id),
expected_schema_version="cultnet.hello.v0",
)
return CultMeshPeerHealth(
peer_id=peer_id,
endpoint=endpoint,
checked_at=checked_at,
is_reachable=True,
runtime_id=str(response.get("runtimeId") or ""),
)
except Exception as error:
return CultMeshPeerHealth(
peer_id=peer_id,
endpoint=endpoint,
checked_at=checked_at,
is_reachable=False,
error=str(error),
)
def _record(self, health: CultMeshPeerHealth) -> CultMeshPeerHealth:
with self._lock:
self._latest[(health.peer_id, health.endpoint)] = health
if self.on_update is not None:
self.on_update(health)
return health
def _parse_endpoint(endpoint: str) -> tuple[str, int]:
if not endpoint or not endpoint.strip():
raise ValueError("endpoint must be non-empty")

View file

@ -90,6 +90,7 @@ from cultmesh_py import (
CultMeshHmacAuthorityLeaseVerifier,
CultMeshDiscoveryClient,
CultMeshPeerExchangeClient,
CultMeshPeerHealthMonitor,
CultMeshSimulationObservationFanout,
CultMeshSnapshotFanout,
CultMeshStreamCatalog,
@ -2785,6 +2786,75 @@ class CultCacheTests(unittest.TestCase):
self.assertTrue(seen)
self.assertEqual(target.database.get_required(document, "note:background")["body"], "from-background")
def test_cultmesh_peer_health_monitor_probes_reachable_and_failed_endpoints(self) -> None:
server = CultMesh.serve_node(CultMesh.create_node(runtime_id="health-peer"))
closed_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
closed_socket.bind(("127.0.0.1", 0))
closed_port = closed_socket.getsockname()[1]
closed_socket.close()
try:
peers = CultMeshPeerCatalog()
peers.upsert(CultMeshPeerCard(
peer_id="health-peer",
verse_id="mesh",
endpoints=(f"cultnet://127.0.0.1:{server.port}",),
roles=("read-replica",),
))
peers.upsert(CultMeshPeerCard(
peer_id="closed-peer",
verse_id="mesh",
endpoints=(f"cultnet://127.0.0.1:{closed_port}",),
roles=("read-replica",),
))
seen: list[tuple[str, bool]] = []
monitor = CultMeshPeerHealthMonitor(
runtime_id="health-prober",
timeout_seconds=0.2,
on_update=lambda health: seen.append((health.peer_id, health.is_reachable)),
)
results = monitor.probe_catalog(peers, verse_id="mesh", roles=["read-replica"])
finally:
server.stop()
by_peer = {result.peer_id: result for result in results}
self.assertTrue(by_peer["health-peer"].is_reachable)
self.assertEqual(by_peer["health-peer"].runtime_id, "health-peer")
self.assertFalse(by_peer["closed-peer"].is_reachable)
self.assertTrue(by_peer["closed-peer"].error)
self.assertEqual({peer_id for peer_id, _ in seen}, {"health-peer", "closed-peer"})
self.assertEqual(len(monitor.latest()), 2)
def test_cultmesh_peer_health_monitor_runs_background_probe_loop(self) -> None:
server = CultMesh.serve_node(CultMesh.create_node(runtime_id="health-loop-peer"))
try:
peers = CultMeshPeerCatalog()
peers.upsert(CultMeshPeerCard(
peer_id="health-loop-peer",
verse_id="mesh",
endpoints=(f"cultnet://127.0.0.1:{server.port}",),
roles=("read-replica",),
))
seen: list[str] = []
monitor = CultMeshPeerHealthMonitor(
runtime_id="health-loop-prober",
timeout_seconds=0.2,
interval_seconds=0.05,
on_update=lambda health: seen.append(health.peer_id),
)
monitor.start(peers, verse_id="mesh", roles=["read-replica"])
deadline = time.monotonic() + 2.0
while not seen and time.monotonic() < deadline:
time.sleep(0.01)
monitor.stop()
finally:
server.stop()
self.assertTrue(seen)
latest = monitor.latest()
self.assertEqual(latest[0].peer_id, "health-loop-peer")
self.assertTrue(latest[0].is_reachable)
def test_cultmesh_local_server_serves_node_and_catalogs_over_clients(self) -> None:
document = define_database_entry_type(
"mesh.server_note",

View file

@ -92,7 +92,8 @@ Implemented:
Not implemented yet:
- membership/failure detection
- SWIM-style membership/failure detection beyond Python's hello-level health
monitor
- leader election or automatic shard failover
- cross-runtime scheduled peer-to-peer snapshot fanout beyond Python's local
fanout loop
@ -145,7 +146,8 @@ Not implemented yet:
Add discovery fanout and operational polish:
- add periodic gossip fanout over known peer cards
- standardize periodic gossip fanout over known peer cards beyond Python's
local schedulers and health monitor
- standardize cross-runtime authority lease signature algorithms beyond the
package-local Python HMAC verifier
- standardize cross-runtime simulation-frame rollback/resimulation helpers beyond