Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion apps/api/src/sibyl/services/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,27 @@
_ROLLUP_INTERVAL_SECONDS = 60
_ROLLUP_RETENTION_HOURS = 24
_ROLLUP_FAILURE_BACKOFF_SECONDS = 60.0
_ROLLUP_FIELDS = (
"uuid",
"bucket_key",
"bucket_start",
"window_seconds",
"uptime_seconds",
"summaries",
"trends",
"metrics",
"recent_events",
"updated_at",
)
# Every API process writes the row for the current minute, so a second replica
# (or a restart inside the minute) finds it already there. SET replaces the
# listed fields and leaves created_at alone; CONTENT replaced the whole row,
# and created_at only defaults on create, so the second writer was refused.
_ROLLUP_UPSERT = (
"UPSERT telemetry_rollups SET "
+ ", ".join(f"{field} = $record.{field}" for field in _ROLLUP_FIELDS)
+ " WHERE bucket_key = $bucket_key;"
)
_last_persisted_bucket: int | None = None
_logged_failure_buckets: dict[str, int] = {}
_next_scheduled_rollup_at = 0.0
Expand Down Expand Up @@ -78,7 +99,7 @@ async def persist_runtime_rollup(
try:
client = await get_shared_surreal_content_client()
result = await client.execute_query(
"UPSERT telemetry_rollups CONTENT $record WHERE bucket_key = $bucket_key;",
_ROLLUP_UPSERT,
bucket_key=bucket_key,
record=record,
)
Expand Down
66 changes: 65 additions & 1 deletion apps/api/tests/test_surreal_live_nested_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from __future__ import annotations

import asyncio
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
Expand Down Expand Up @@ -42,7 +43,7 @@
reason="live SurrealDB runtime smoke tests are disabled",
)

_ROLLUP_UPSERT = "UPSERT telemetry_rollups CONTENT $record WHERE bucket_key = $bucket_key;"
_ROLLUP_UPSERT = telemetry_service._ROLLUP_UPSERT


def _live_surreal_url() -> str:
Expand Down Expand Up @@ -146,6 +147,67 @@ async def shared_client() -> SurrealContentClient:
assert "api_p95_ms" in rows[0]["trends"][0]


@pytest.mark.asyncio
async def test_live_runtime_rollup_accepts_every_replica_in_the_same_minute(monkeypatch) -> None:
async with _content_store() as first_replica:
second_replica = _client(first_replica._namespace)
try:
bucket = telemetry_service._current_bucket()

async def persist(client: SurrealContentClient, uptime: float) -> dict | None:
async def shared_client() -> SurrealContentClient:
return client

snapshot = {**_runtime_snapshot(), "uptime_seconds": uptime}
monkeypatch.setattr(
telemetry_service, "get_shared_surreal_content_client", shared_client
)
monkeypatch.setattr(telemetry_service, "_last_persisted_bucket", None)
monkeypatch.setattr(telemetry_service, "runtime_summary", lambda **_: snapshot)
return await telemetry_service.persist_runtime_rollup(bucket=bucket)

async def stored() -> list[dict]:
return normalize_records(
await first_replica.execute_query(
"SELECT created_at, uptime_seconds FROM telemetry_rollups;"
)
)

assert await persist(first_replica, 10.0) is not None
created_at = (await stored())[0]["created_at"]

assert await persist(second_replica, 20.0) is not None, "the second write was refused"
rows = await stored()
assert len(rows) == 1
assert rows[0]["uptime_seconds"] == 20.0
assert rows[0]["created_at"] == created_at

# Two replicas that tick over in the same instant, on a fresh minute.
record = {
"uuid": str(uuid4()),
"bucket_key": "209901010000",
"bucket_start": datetime(2099, 1, 1, tzinfo=UTC),
"window_seconds": 900,
"uptime_seconds": 1.0,
"summaries": {},
"trends": [],
"metrics": [],
"recent_events": [],
"updated_at": datetime.now(UTC),
}
await asyncio.gather(
*(
client.execute_query(
_ROLLUP_UPSERT, record=record, bucket_key=record["bucket_key"]
)
for client in (first_replica, second_replica)
)
)
assert len(await stored()) == 2
finally:
await second_replica.close()


@pytest.mark.asyncio
async def test_live_source_import_keeps_skipped_and_error_entries() -> None:
async with _content_store() as client:
Expand Down Expand Up @@ -225,11 +287,13 @@ async def test_live_migration_59_opens_rollup_entries_on_an_upgraded_database()
"uuid": str(uuid4()),
"bucket_key": "209901010000",
"bucket_start": datetime(2099, 1, 1, tzinfo=UTC),
"window_seconds": 900,
"uptime_seconds": snapshot["uptime_seconds"],
"summaries": snapshot["summaries"],
"trends": snapshot["trends"],
"metrics": snapshot["metrics"],
"recent_events": snapshot["recent_events"],
"updated_at": datetime.now(UTC),
}
if index_engine_of(info) is not None:
# The failure this migration exists for: 4.0 refuses nested keys
Expand Down
42 changes: 42 additions & 0 deletions apps/api/tests/test_telemetry_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from sibyl.api.routes import telemetry as telemetry_routes
from sibyl.jobs import worker as worker_module
from sibyl.services import telemetry as telemetry_service
from sibyl_core.backends.surreal import SurrealContentClient, bootstrap_content_schema
from sibyl_core.backends.surreal.records import normalize_records
from sibyl_core.observability import telemetry_registry


Expand Down Expand Up @@ -330,3 +332,43 @@ async def failing_client() -> FailingClient:

# One entry per interval, not one per error class ever seen.
assert len(telemetry_service._logged_failure_buckets) == 1


@pytest.mark.asyncio
async def test_rollup_for_a_minute_that_already_has_a_row_updates_it(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client = SurrealContentClient(url="memory://")
await bootstrap_content_schema(client, reset=True)

async def shared_client() -> SurrealContentClient:
return client

monkeypatch.setattr(telemetry_service, "get_shared_surreal_content_client", shared_client)
monkeypatch.setattr(telemetry_service, "_logged_failure_buckets", {})
bucket = telemetry_service._current_bucket()

async def persist_as_a_fresh_process(uptime: float) -> dict[str, object] | None:
snapshot = {**telemetry_service.runtime_summary(), "uptime_seconds": uptime}
monkeypatch.setattr(telemetry_service, "runtime_summary", lambda **_: snapshot)
monkeypatch.setattr(telemetry_service, "_last_persisted_bucket", None)
return await telemetry_service.persist_runtime_rollup(bucket=bucket)

async def stored() -> list[dict[str, object]]:
return normalize_records(
await client.execute_query("SELECT created_at, uptime_seconds FROM telemetry_rollups;")
)

try:
assert await persist_as_a_fresh_process(10.0) is not None
created_at = (await stored())[0]["created_at"]

# A second replica, or the same daemon restarted inside the minute.
assert await persist_as_a_fresh_process(20.0) is not None, "the second write was refused"

rows = await stored()
assert len(rows) == 1
assert rows[0]["uptime_seconds"] == 20.0
assert rows[0]["created_at"] == created_at
finally:
await client.close()
Loading