diff --git a/PRIVACY.md b/PRIVACY.md index f05f294d..b021c1bb 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -212,6 +212,9 @@ default. It keeps the calls, tokens, and spend of each day per Agent, owner alias, AI Gateway user ID, Team, and model. Since CetiRun v0.2.0, this user ID is the owner's Entra tenant and object IDs. The view `GatewayDailyUsage` of earlier cluster templates keeps its rows until an administrator drops it. +The materialized view `GatewayCoverage` keeps, for the same time, the number of +AI Gateway heartbeats and request lines in 5 minutes per cluster and Pod, and +when the first of these lines arrived. It has no user data. Successful collection still depends on the deployed collectors, permissions, and settings. Source configuration alone does not prove that a live cluster collects data. diff --git a/app/cetirun-ai-gateway/cetirun_ai_gateway/request_log.py b/app/cetirun-ai-gateway/cetirun_ai_gateway/request_log.py index 3d0371cd..86f7a7eb 100644 --- a/app/cetirun-ai-gateway/cetirun_ai_gateway/request_log.py +++ b/app/cetirun-ai-gateway/cetirun_ai_gateway/request_log.py @@ -34,18 +34,37 @@ loads its configuration, when CETIRUN_REQUEST_LOG is set, rather than listing it in litellm_settings.callbacks, which settings saved in LiteLLM's database can replace. + +A time without request lines can be a time without calls, or a time whose +lines did not reach the logs. To tell them apart, the entrypoint also starts +``heartbeat`` with the request log: a heartbeat line every +HEARTBEAT_INTERVAL_SECONDS, on stdout like the request lines, so that it takes +their way to the logs. The logs database counts the heartbeats per 5 minutes +(GatewayCoverage), and GatewayCoverageGaps() names the intervals whose request +lines can be missing. """ import datetime import json import math import sys +import threading +import time from urllib.parse import urlsplit from litellm.integrations.custom_logger import CustomLogger LOG_TYPE = "cetirun.ai_gateway.request" SCHEMA_VERSION = 1 +HEARTBEAT_LOG_TYPE = "cetirun.ai_gateway.heartbeat" +HEARTBEAT_SCHEMA_VERSION = 1 +# The logs database counts the heartbeats per 5 minutes. On a fixed schedule of +# 5 minutes, a running Pod writes one in each interval. +HEARTBEAT_INTERVAL_SECONDS = 300 + +# The request log and the heartbeat write to stdout from different threads. +# Each line goes out whole, as one write. +WRITE_LOCK = threading.Lock() # The container runtime splits a line longer than 16 KiB, and a collector that # does not join the pieces again stores each as its own line, none of them @@ -247,9 +266,7 @@ def write(self, kwargs): payload = kwargs.get("standard_logging_object") if not isinstance(payload, dict): return - stream = self.stream or sys.stdout - stream.write(self.line(payload, call_origin(kwargs), fallback(kwargs)) + "\n") - stream.flush() + write_line(self.stream or sys.stdout, self.line(payload, call_origin(kwargs), fallback(kwargs))) def record(self, payload, origin=None, fallback_details=None): metadata = as_dict(payload.get("metadata")) @@ -358,4 +375,65 @@ def line(self, payload, origin=None, fallback_details=None): return dump(shortened(record)) +def write_line(stream, text): + """Writes one line whole, also while another thread writes to the stream.""" + with WRITE_LOCK: + stream.write(text + "\n") + stream.flush() + + +def heartbeat_line(now, interval=HEARTBEAT_INTERVAL_SECONDS): + """A heartbeat as one line of JSON: the request log was on at this time.""" + return dump({ + "log_type": HEARTBEAT_LOG_TYPE, + "schema_version": HEARTBEAT_SCHEMA_VERSION, + "time": iso_time(now), + "interval_seconds": interval, + }) + + +class Heartbeat: + """Writes a heartbeat line when it starts, then on a fixed schedule, from a + daemon thread of its own: it writes also while no call comes.""" + + def __init__(self, stream=None, interval=HEARTBEAT_INTERVAL_SECONDS, clock=time.time): + self.stream = stream + self.interval = interval + self.clock = clock + self.stopped = threading.Event() + self.thread = None + + def beat(self): + write_line(self.stream or sys.stdout, heartbeat_line(self.clock(), self.interval)) + + def run(self): + due = time.monotonic() + while True: + try: + self.beat() + except (OSError, ValueError): + # stdout is closed or broken; the next beat tries again. + pass + due += self.interval + now = time.monotonic() + if due < now: + # A write took longer than an interval: no burst of late beats. + due = now + self.interval + if self.stopped.wait(due - now): + return + + def start(self): + """Starts the thread, once.""" + if self.thread is None: + self.thread = threading.Thread(target=self.run, name="cetirun-request-log-heartbeat", daemon=True) + self.thread.start() + return self + + def stop(self, timeout=None): + self.stopped.set() + if self.thread is not None: + self.thread.join(timeout) + + handler = RequestLog() +heartbeat = Heartbeat() diff --git a/app/cetirun-ai-gateway/chart/README.md b/app/cetirun-ai-gateway/chart/README.md index ea904c97..d727e260 100644 --- a/app/cetirun-ai-gateway/chart/README.md +++ b/app/cetirun-ai-gateway/chart/README.md @@ -2979,6 +2979,18 @@ response IDs are long. The CetiRun operator puts `cetirun_agent` in the metadata of the keys that it issues. For other keys, group by `KeyAlias` instead. +The request log also writes a heartbeat line every five minutes, also while no +call comes: + +```json +{"log_type":"cetirun.ai_gateway.heartbeat","schema_version":1,"time":"2026-11-26T00:05:00.000Z","interval_seconds":300} +``` + +A heartbeat takes the same way as the request lines. A time without heartbeats +can lack request lines. With the ADX-Mon collection, the view `GatewayCoverage` +counts the heartbeats in intervals of 5 minutes, and the function +`GatewayCoverageGaps()` lists the intervals whose request lines can be missing. + The cluster must collect container logs. `make deploy` installs the ADX-Mon collection with the platform. diff --git a/app/cetirun-ai-gateway/entrypoint.py b/app/cetirun-ai-gateway/entrypoint.py index eb5a5f0d..0dcce9ed 100644 --- a/app/cetirun-ai-gateway/entrypoint.py +++ b/app/cetirun-ai-gateway/entrypoint.py @@ -252,6 +252,10 @@ def gateway(args, environ=None): The callbacks are registered in this process, so the proxy has to run in it: one uvicorn server, as LiteLLM starts by default. + + With the request log, a thread of this process also writes a heartbeat line + every five minutes, also while no call comes (cetirun_ai_gateway/request_log.py). + It starts last, so that its lines do not fall among the lines printed here. """ environ = os.environ if environ is None else environ request_log = environ.get(REQUEST_LOG_ENV, "").strip().lower() == "true" @@ -293,6 +297,11 @@ def gateway(args, environ=None): from litellm.proxy.proxy_cli import run_server + if request_log: + from cetirun_ai_gateway.request_log import heartbeat + + print(f"request log heartbeat: one line every {heartbeat.interval} seconds", flush=True) + heartbeat.start() run_server.main(args=list(args), prog_name="litellm") diff --git a/infra/cluster/main.bicep b/infra/cluster/main.bicep index fd2440f1..cd3e70c6 100644 --- a/infra/cluster/main.bicep +++ b/infra/cluster/main.bicep @@ -155,7 +155,7 @@ param platformNamespace string = 'cetirun-system' param adxContentViewers array = [] @minValue(1) -@description('Days of the daily AI Gateway usage view GatewayDailyUsageV2 in the logs database.') +@description('Days of the daily AI Gateway usage view GatewayDailyUsageV2 and of the coverage view GatewayCoverage in the logs database.') param adxGatewayUsageRetentionDays int = 400 @description('Create the managed identity of the ADX-Mon alerter, with the Viewer role on the logs and metrics databases. Needs adxMode create or existing.') diff --git a/infra/cluster/modules/adx.bicep b/infra/cluster/modules/adx.bicep index dd1e91f0..2de627b9 100644 --- a/infra/cluster/modules/adx.bicep +++ b/infra/cluster/modules/adx.bicep @@ -97,7 +97,7 @@ param contentWriterClientId string = '' param contentViewers array = [] @minValue(1) -@description('Days of the daily AI Gateway usage view GatewayDailyUsageV2 in the logs database. It can be longer than the logs retention.') +@description('Days of the daily AI Gateway usage view GatewayDailyUsageV2 and of the coverage view GatewayCoverage in the logs database. It can be longer than the logs retention.') param gatewayUsageRetentionDays int = 400 @description('Client (application) ID of the ADX-Mon alerter identity, which runs alert queries. Empty skips its Viewer roles on the logs and metrics databases.') @@ -117,9 +117,9 @@ param auditViewers array = [] // The query functions of the databases. Their files are scripts of management // commands that can also run on a Kusto cluster made without this module; -// their comment lines are left out here. The daily usage view follows the -// functions, after the logs script has created its table. -var logsFunctions = join(filter(split('${loadTextContent('adx/cetirun-logs.kql')}\n${replace(loadTextContent('adx/cetirun-gateway-usage.kql'), '__RETENTION_DAYS__', string(gatewayUsageRetentionDays))}', '\n'), line => !startsWith(line, '//')), '\n') +// their comment lines are left out here. The daily usage view and the coverage +// view follow the functions, after the logs script has created their table. +var logsFunctions = join(filter(split('${loadTextContent('adx/cetirun-logs.kql')}\n${replace(loadTextContent('adx/cetirun-gateway-usage.kql'), '__RETENTION_DAYS__', string(gatewayUsageRetentionDays))}\n${replace(loadTextContent('adx/cetirun-gateway-coverage.kql'), '__RETENTION_DAYS__', string(gatewayUsageRetentionDays))}', '\n'), line => !startsWith(line, '//')), '\n') var metricsFunctions = join(filter(split('${loadTextContent('adx/cetirun-metrics.kql')}\n${replace(loadTextContent('adx/cetirun-health.kql'), '__LOGS_DATABASE__', logsDatabaseName)}\n${loadTextContent('adx/adxmon-functions.kql')}', '\n'), line => !startsWith(line, '//')), '\n') // Each CetiRun cluster's ingestor alters ADX-Mon's functions at start, which // needs it to be their admin; a second cluster's deployment adds its own. diff --git a/infra/cluster/modules/adx/cetirun-gateway-coverage.kql b/infra/cluster/modules/adx/cetirun-gateway-coverage.kql new file mode 100644 index 00000000..da7bde9a --- /dev/null +++ b/infra/cluster/modules/adx/cetirun-gateway-coverage.kql @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +// +// Coverage of the AI Gateway request log: the times when the request lines of +// each cluster reached the CetiRun logs database. A time without request lines +// can be a time without calls, or a time whose lines did not arrive. With the +// request log, each AI Gateway Pod also writes a heartbeat line every 5 +// minutes, on stdout like the request lines, so that it takes their way to this +// database (app/cetirun-ai-gateway/cetirun_ai_gateway/request_log.py). +// +// GatewayCoverage is a materialized view of the Gateway table with the +// heartbeats per 5 minutes, cluster and Pod: a Pod writes one in each +// interval. It also counts the request lines, at the completion time of the +// call, which GatewayRequests() uses, and keeps the earliest ingestion time of +// the lines that it counted. The heartbeats sample the collection. An interval +// counts as observed when the heartbeats of a Pod arrived before it, in it and +// after it, and no Pod that ran then lacks one of its heartbeats there. +// GatewayCoverageGaps() lists the other intervals of a period, with the +// reason, and the intervals of which the table holds fewer request lines than +// the view counted: the retention of the logs database or a deletion removed +// some of them. +// +// __RETENTION_DAYS__ is the retention of the view, the one of the daily usage +// view. The ADX module of the cluster template replaces it and runs this script +// after cetirun-gateway-usage.kql. +// +// The view counts the lines that arrive after its creation, without backfill: +// Kusto refuses a backfill while some rows of the table are outside the hot +// cache. Times before the AI Gateway image that writes heartbeats, and the +// times up to the interval in which the view started, have no coverage. +.create ifnotexists materialized-view with (folder = "CetiRun", docString = "AI Gateway heartbeats per 5 minutes, cluster and Pod, and request lines at their completion time, from the creation of the view: each Pod writes one heartbeat in each interval. Arrived is the earliest ingestion time of the lines that a row counts.") GatewayCoverage on table Gateway { + Gateway + | where Container == "gateway" + | extend LogType = tostring(Body['log_type']) + | where LogType in ("cetirun.ai_gateway.heartbeat", "cetirun.ai_gateway.request") + // A request line counts at the completion time of its call, the time of + // GatewayRequests(); a heartbeat at the time when it was written. + | extend At = iff(LogType == "cetirun.ai_gateway.request", todatetime(Body['time']), Timestamp) + | summarize + Heartbeats = countif(LogType == "cetirun.ai_gateway.heartbeat"), + Requests = countif(LogType == "cetirun.ai_gateway.request"), + Arrived = min(ingestion_time()) + by Interval = bin(At, 5m), Cluster, Pod +} + +.alter materialized-view GatewayCoverage policy retention '{"SoftDeletePeriod": "__RETENTION_DAYS__.00:00:00", "Recoverability": "Enabled"}' + +.alter materialized-view GatewayCoverage policy caching hot = 31d + +.create-or-alter function with (folder = "CetiRun", docstring = "The 5-minute intervals from fromTime to toTime whose AI Gateway request lines can be missing, with the reason: collection not observed, missed heartbeat, or request lines removed. For the other intervals, a usage of zero means that no calls were recorded and no heartbeat gap was detected. The daily usage views keep their totals after the request lines expire: for them, only the first two reasons count.", skipvalidation = "true") GatewayCoverageGaps(cluster:string, fromTime:datetime, toTime:datetime) { + let step = 5m; + let firstInterval = bin(fromTime, step); + let lastEnd = bin(toTime - 1tick, step) + step; + let intervals = range Interval from firstInterval to toTime - 1tick step step; + // The view counts the lines that arrived after its creation. The interval + // in which it started, and the intervals before, can have lines that + // arrived before: they stay unobserved. + let firstCounted = toscalar(GatewayCoverage | summarize Start = bin(min(Arrived), step) + step); + // Each Pod ran from its first heartbeat to its last in the whole view, + // also through days without its heartbeats, whatever the period. + let spans = GatewayCoverage + | where Cluster == cluster and Heartbeats > 0 + | summarize First = min(Interval), Last = max(Interval) by Pod + | where First < toTime and Last >= firstInterval; + // The heartbeats in the period and next to it. + let beats = GatewayCoverage + | where Cluster == cluster and Heartbeats > 0 and Interval >= firstInterval - step and Interval < toTime + step + | distinct Pod, Interval; + // Each Pod in each interval of the period from its first heartbeat to its + // last, with its heartbeats in that interval and next to it. + let pods = spans + | mv-expand Interval = range(max_of(First, firstInterval), min_of(Last, toTime - 1tick), step) to typeof(datetime) + | where isnotnull(Interval) + | join kind=leftouter (beats | project Pod, Interval, Here = true) on Pod, Interval + | join kind=leftouter (beats | project Pod, Interval = Interval + step, Before = true) on Pod, Interval + | join kind=leftouter (beats | project Pod, Interval = Interval - step, After = true) on Pod, Interval + | project Pod, Interval, First, Last, Here = isnotnull(Here), Before = isnotnull(Before), After = isnotnull(After); + // The heartbeats of a Pod surround the interval. + let observed = pods | where Here and Before and After and Interval >= firstCounted | distinct Interval; + // A Pod that ran in the interval lacks a heartbeat in it or next to it. A + // Pod's first interval needs none before it, and its last none after it. + // In the first interval after the start of the view, a heartbeat before it + // can have arrived before the view. + let missed = pods + | where Interval >= firstCounted + | where not(Here) or (not(Before) and Interval != First and Interval != firstCounted) or (not(After) and Interval != Last) + | distinct Interval; + // GatewayRequests() reads the request lines of the Gateway table at the + // completion time of each call. A line leaves the table at the end of the + // retention of the logs database, counted from its ingestion, or with a + // deletion, while the view keeps its count. An interval of which the table + // holds fewer request lines can lack calls, also after the retention + // changed. A line is written after its call completed. + let present = Gateway + | where Timestamp >= firstInterval - step and Timestamp < lastEnd + 1h + | where Cluster == cluster and Container == "gateway" + | where tostring(Body['log_type']) == "cetirun.ai_gateway.request" + | extend At = todatetime(Body['time']) + | where At >= firstInterval and At < lastEnd + | summarize Present = count() by Interval = bin(At, step); + let removed = GatewayCoverage + | where Cluster == cluster and Interval >= firstInterval and Interval >= firstCounted and Interval < toTime + | summarize Counted = sum(Requests) by Interval + | where Counted > 0 + | join kind=leftouter present on Interval + | where coalesce(Present, 0) < Counted + | project Interval; + union + (intervals | join kind=leftanti observed on Interval | extend Reason = "collection not observed"), + (missed | extend Reason = "missed heartbeat"), + (removed | extend Reason = "request lines removed") + | project Cluster = cluster, Interval, Reason + | order by Interval asc, Reason asc +} diff --git a/scripts/tests/test_ai_gateway_entrypoint.py b/scripts/tests/test_ai_gateway_entrypoint.py index 6cc656e6..6d29ce72 100644 --- a/scripts/tests/test_ai_gateway_entrypoint.py +++ b/scripts/tests/test_ai_gateway_entrypoint.py @@ -147,6 +147,7 @@ def main(self, args, prog_name): package.__path__ = [] request_log = types.ModuleType("cetirun_ai_gateway.request_log") request_log.handler = self.handler + request_log.heartbeat = types.SimpleNamespace(interval=300, start=lambda: self.events.append(("heartbeat",))) guard = types.ModuleType("cetirun_ai_gateway.guard") guard.handler = self.guard content = types.ModuleType("cetirun_ai_gateway.content") @@ -185,13 +186,14 @@ def test_the_spend_log_stays_on_without_the_request_log(self): def test_the_request_log_is_registered_before_the_proxy_starts(self): self.start({"CETIRUN_REQUEST_LOG": "true"}) + # The heartbeat starts last, right before the proxy. self.assertEqual(self.events, [ - ("callback", self.guard), ("callback", self.handler), ("run", self.ARGS, "litellm", False)]) + ("callback", self.guard), ("callback", self.handler), ("heartbeat",), ("run", self.ARGS, "litellm", False)]) def test_the_spend_log_is_turned_off_together_with_the_request_log(self): self.start({"CETIRUN_REQUEST_LOG": "true", "CETIRUN_SPEND_LOGS": "false"}) self.assertEqual(self.events, [ - ("callback", self.guard), ("callback", self.handler), ("run", self.ARGS, "litellm", True)]) + ("callback", self.guard), ("callback", self.handler), ("heartbeat",), ("run", self.ARGS, "litellm", True)]) def test_workers_that_would_load_litellm_again_are_refused(self): cases = [ @@ -210,18 +212,19 @@ def test_workers_that_would_load_litellm_again_are_refused(self): def test_one_worker_is_accepted(self): self.start({"CETIRUN_REQUEST_LOG": "true", "NUM_WORKERS": "1"}, ["--port", "4000", "--num_workers", "1"]) - self.assertEqual(self.events[:2], [("callback", self.guard), ("callback", self.handler)]) + self.assertEqual(self.events[:3], [("callback", self.guard), ("callback", self.handler), ("heartbeat",)]) def test_content_is_registered_when_the_chart_names_a_database(self): self.start({"CETIRUN_REQUEST_LOG": "true", "CETIRUN_CONTENT_ENDPOINT": "https://example.kusto.windows.net", "CETIRUN_CONTENT_DATABASE": "CetiRunContent", "CETIRUN_CONTENT_CLUSTER": "example"}) self.assertEqual(self.events, [ ("callback", self.guard), ("callback", self.handler), ("callback", self.content), - ("run", self.ARGS, "litellm", False)]) + ("heartbeat",), ("run", self.ARGS, "litellm", False)]) def test_content_does_not_need_the_request_log(self): self.start({"CETIRUN_CONTENT_ENDPOINT": "https://example.kusto.windows.net", "CETIRUN_CONTENT_DATABASE": "CetiRunContent", "CETIRUN_CONTENT_CLUSTER": "example"}) + # No request log, no heartbeat: nothing to tell apart. self.assertEqual(self.events, [("callback", self.guard), ("callback", self.content), ("run", self.ARGS, "litellm", False)]) def test_a_litellm_without_the_spend_log_setting_does_not_start(self): diff --git a/scripts/tests/test_ai_gateway_request_log.py b/scripts/tests/test_ai_gateway_request_log.py index bc76b046..4d89d276 100644 --- a/scripts/tests/test_ai_gateway_request_log.py +++ b/scripts/tests/test_ai_gateway_request_log.py @@ -14,6 +14,7 @@ import pathlib import random import sys +import time import types import unittest @@ -470,5 +471,95 @@ def test_module_exposes_the_configured_instance(self): self.assertIsInstance(self.module.handler, self.module.RequestLog) +class RecordingStream(io.StringIO): + """A stream that keeps each write, to see what one write carries.""" + + def __init__(self, failures=0): + super().__init__() + self.writes = [] + self.failures = failures + + def write(self, text): + if self.failures: + self.failures -= 1 + raise OSError("stdout is gone") + self.writes.append(text) + return super().write(text) + + +def wait_for(condition, seconds=5): + deadline = time.monotonic() + seconds + while not condition(): + if time.monotonic() > deadline: + raise AssertionError("timed out") + time.sleep(0.01) + + +class HeartbeatTest(unittest.TestCase): + """The heartbeat lines that let the logs tell a time without calls from a + time whose lines did not arrive.""" + + def setUp(self): + self.module = load_request_log() + + def heartbeat(self, stream, interval): + heartbeat = self.module.Heartbeat(stream=stream, interval=interval, clock=lambda: 1795651200.25) + self.addCleanup(heartbeat.stop, 5) + return heartbeat + + def test_a_heartbeat_line_names_its_type_time_and_interval(self): + self.assertEqual(json.loads(self.module.heartbeat_line(1795651200.25)), { + "log_type": "cetirun.ai_gateway.heartbeat", "schema_version": 1, + "time": "2026-11-26T00:00:00.250Z", "interval_seconds": 300}) + self.assertEqual(json.loads(self.module.heartbeat_line(1795651200.25, 60))["interval_seconds"], 60) + + def test_the_first_line_comes_at_once_and_stop_ends_the_wait(self): + stream = RecordingStream() + heartbeat = self.heartbeat(stream, 60).start() + wait_for(lambda: stream.writes) + heartbeat.stop(5) + self.assertFalse(heartbeat.thread.is_alive()) + self.assertEqual(len(stream.writes), 1) + self.assertTrue(heartbeat.thread.daemon, "A heartbeat never keeps the process alive") + + def test_lines_follow_the_interval_from_one_thread(self): + stream = RecordingStream() + heartbeat = self.heartbeat(stream, 0.02) + heartbeat.start() + thread = heartbeat.thread + heartbeat.start() + self.assertIs(heartbeat.thread, thread) + wait_for(lambda: len(stream.writes) >= 4) + heartbeat.stop(5) + for text in stream.writes: + self.assertEqual(json.loads(text)["log_type"], "cetirun.ai_gateway.heartbeat") + + def test_every_line_is_one_write_while_calls_are_logged(self): + stream = RecordingStream() + heartbeat = self.heartbeat(stream, 0.001) + handler = self.module.RequestLog(stream=stream) + heartbeat.start() + for _ in range(200): + handler.write({"standard_logging_object": success_payload()}) + heartbeat.stop(5) + types_seen = set() + for text in stream.writes: + self.assertTrue(text.endswith("\n") and text.count("\n") == 1, text[:80]) + types_seen.add(json.loads(text)["log_type"]) + self.assertEqual(types_seen, {"cetirun.ai_gateway.request", "cetirun.ai_gateway.heartbeat"}) + + def test_a_failed_write_does_not_end_the_heartbeats(self): + stream = RecordingStream(failures=2) + self.heartbeat(stream, 0.01).start() + wait_for(lambda: len(stream.writes) >= 2) + + def test_the_module_heartbeat_writes_to_stdout_every_five_minutes(self): + heartbeat = self.module.heartbeat + self.assertIsInstance(heartbeat, self.module.Heartbeat) + self.assertEqual(heartbeat.interval, 300) + self.assertIsNone(heartbeat.stream) + self.assertIsNone(heartbeat.thread, "The entrypoint starts it, not the import") + + if __name__ == "__main__": unittest.main() diff --git a/scripts/tests/test_cluster_deploy.py b/scripts/tests/test_cluster_deploy.py index cab42d37..34213c76 100644 --- a/scripts/tests/test_cluster_deploy.py +++ b/scripts/tests/test_cluster_deploy.py @@ -586,6 +586,84 @@ def test_copilot_routes_are_told_apart_by_the_operators_prefix(self): self.assertIn(f"CopilotRoute = tostring(Body['deployment_id']) startswith \"{prefix}\"", (ADX_SCRIPTS / name).read_text()) + def test_gateway_coverage_counts_the_heartbeats_and_follows_the_usage_view(self): + create, retention, caching, gaps = kusto_commands("cetirun-gateway-coverage.kql") + self.assertTrue(create.startswith(".create ifnotexists materialized-view with (folder = ")) + # No backfill, for the reason of the usage view. + self.assertNotIn("backfill", create) + self.assertIn(" GatewayCoverage on table Gateway {", create) + self.assertEqual(re.findall(r"^ {4}(\w+)$", create, re.M), ["Gateway"]) + # The heartbeats that the AI Gateway image writes, per 5 minutes, cluster and Pod, and its request lines at + # the completion time of the call, the time key of GatewayRequests(), with the earliest ingestion time. + request_log = (ROOT / "app/cetirun-ai-gateway/cetirun_ai_gateway/request_log.py").read_text() + log_type = re.search(r'^HEARTBEAT_LOG_TYPE = "([^"]+)"$', request_log, re.M)[1] + request_type = re.search(r'^LOG_TYPE = "([^"]+)"$', request_log, re.M)[1] + self.assertIn('"time": iso_time(end),', request_log) + view = create.replace("\r\n", "\n") + self.assertIn('| where Container == "gateway"\n', view) + self.assertIn(f'| where LogType in ("{log_type}", "{request_type}")\n', view) + self.assertIn(f"| extend At = iff(LogType == \"{request_type}\", todatetime(Body['time']), Timestamp)\n", view) + self.assertIn(f'Heartbeats = countif(LogType == "{log_type}"),\n', view) + self.assertIn(f'Requests = countif(LogType == "{request_type}"),\n', view) + self.assertIn("Arrived = min(ingestion_time())\n", view) + self.assertIn("by Interval = bin(At, 5m), Cluster, Pod", view) + logs = (ROOT / "infra/cluster/modules/adx/cetirun-logs.kql").read_text() + self.assertIn("Timestamp = todatetime(Body['time']),", logs) + # A running Pod writes one heartbeat in each interval, so a Pod without one missed it. + interval = int(re.search(r"^HEARTBEAT_INTERVAL_SECONDS = (\d+)$", request_log, re.M)[1]) + self.assertEqual(interval, 300) + self.assertIn("let step = 5m;", gaps) + # Kept as long as the usage view. + self.assertTrue(retention.startswith(".alter materialized-view GatewayCoverage policy retention")) + self.assertIn("__RETENTION_DAYS__.00:00:00", retention) + self.assertTrue(caching.startswith(".alter materialized-view GatewayCoverage policy caching")) + self.assertIn("GatewayCoverageGaps(cluster:string, fromTime:datetime, toTime:datetime)", gaps) + # An interval counts as observed when a Pod's heartbeats surround it, and as a gap when a Pod that ran then + # lacks one around it, apart from its first and last interval. The interval in which the view started, and + # the ones before, can have lines that arrived before the view: they stay unobserved, and the first + # interval after them needs no heartbeat before it. + self.assertIn("let firstCounted = toscalar(GatewayCoverage | summarize Start = bin(min(Arrived), step) + step);", + gaps) + self.assertIn("let observed = pods | where Here and Before and After and Interval >= firstCounted | distinct Interval;", + gaps) + self.assertIn("| where Interval >= firstCounted\n", gaps.replace("\r\n", "\n")) + self.assertIn("where not(Here) or (not(Before) and Interval != First and Interval != firstCounted) " + "or (not(After) and Interval != Last)", gaps) + self.assertIn("project Pod, Interval = Interval + step, Before = true", gaps) + self.assertIn("project Pod, Interval = Interval - step, After = true", gaps) + # A Pod ran from its first heartbeat to its last in the whole view, whatever the period: a Pod without + # heartbeats for days still missed them in a short period in between. A Pod that writes lines without + # heartbeats, from an older image, does not count. + spans = re.search(r"let spans = GatewayCoverage\r?\n((?: {8}\|.*\r?\n)+)", gaps)[1].splitlines() + self.assertEqual(spans[0].strip(), "| where Cluster == cluster and Heartbeats > 0") + self.assertEqual(spans[1].strip(), "| summarize First = min(Interval), Last = max(Interval) by Pod") + self.assertIn("let pods = spans", gaps) + self.assertIn("| where Cluster == cluster and Heartbeats > 0 and Interval >= firstInterval - step", gaps) + # GatewayRequests() reads the request lines of the Gateway table at the completion time of each call: an + # interval of which the table holds fewer of them than the view counted lost some, also when the retention + # was raised later. Both count by that time over the whole intervals of the period, and only after the + # start of the view. + self.assertNotIn("__LOGS_RETENTION_DAYS__", gaps) + self.assertNotIn("now()", gaps) + self.assertIn("let lastEnd = bin(toTime - 1tick, step) + step;", gaps) + present = re.search(r"let present = Gateway\r?\n((?: {8}\|.*\r?\n)+)", gaps)[1] + self.assertIn(f"| where tostring(Body['log_type']) == \"{request_type}\"", present) + self.assertIn("| extend At = todatetime(Body['time'])", present) + self.assertIn("| where At >= firstInterval and At < lastEnd", present) + self.assertIn("| summarize Present = count() by Interval = bin(At, step)", present) + self.assertIn("Interval >= firstCounted and Interval < toTime", gaps) + self.assertIn("| summarize Counted = sum(Requests) by Interval", gaps) + self.assertIn("| where coalesce(Present, 0) < Counted", gaps) + self.assertEqual(set(re.findall(r'Reason = "([^"]+)"', gaps)), + {"collection not observed", "missed heartbeat", "request lines removed"}) + self.assertIn("no calls were recorded and no heartbeat gap was detected", gaps) + module = (ROOT / "infra/cluster/modules/adx.bicep").read_text() + line = next(text for text in module.splitlines() if text.startswith("var logsFunctions")) + # After the usage view, and with the same retention. + self.assertLess(line.index("adx/cetirun-gateway-usage.kql"), line.index("adx/cetirun-gateway-coverage.kql")) + self.assertEqual(line.count("'__RETENTION_DAYS__', string(gatewayUsageRetentionDays)"), 2) + self.assertNotIn("__LOGS_RETENTION_DAYS__", line) + def test_audit_messages_land_whole_and_expand_into_events(self): table, mapping, function = kusto_commands("cetirun-audit.kql") self.assertEqual(table, ".create-merge table KubeAuditLogs (Records:dynamic)") diff --git a/site/content/en/docs/operations/infrastructure.md b/site/content/en/docs/operations/infrastructure.md index 9d22db94..98246f08 100644 --- a/site/content/en/docs/operations/infrastructure.md +++ b/site/content/en/docs/operations/infrastructure.md @@ -545,6 +545,14 @@ Copilot routes answered. It keeps `adxGatewayUsageRetentionDays` days, 400 by default. This is longer than the request log in its source table. Refer to [Query functions](../observability/#query-functions). +The materialized view `GatewayCoverage` counts the heartbeats of the AI Gateway +in intervals of 5 minutes, for the same number of days. It shows the times +when the request log reached the database. The function +`GatewayCoverageGaps()` lists the intervals whose request lines can be +missing. These include the intervals whose lines the logs database no longer +holds, for example after `adxLogsRetentionDays`. Refer to +[Query functions](../observability/#query-functions). + The view counts the calls from its creation. Kusto fills a new view with the earlier rows of its table (backfill) only while these rows are in the hot cache. The rows of a `Gateway` table older than the hot cache period are not, diff --git a/site/content/en/docs/operations/observability.md b/site/content/en/docs/operations/observability.md index f6885026..e987660b 100644 --- a/site/content/en/docs/operations/observability.md +++ b/site/content/en/docs/operations/observability.md @@ -25,6 +25,7 @@ Treat this collection as a preview. | Sandbox admission server | Metrics on port 8080: `cetirun_sandbox_admission_decisions_total`, `cetirun_sandbox_admission_request_duration_seconds`, `cetirun_sandbox_pod_admission_denials_total`, and `cetirun_sandbox_admission_certificate_not_after_seconds` | `CetiRunMetrics` | | AI Gateway | LiteLLM metrics on the port named `metrics` | `CetiRunMetrics` | | AI Gateway | One JSON line for each model call, with the `log_type` `cetirun.ai_gateway.request`. The line has the model, the tokens, the spend, the timing, the Agent, the Team, and the outcome. It has no prompt or response content | The `Gateway` table of `CetiRunLogs`. `GatewayRequests()` reads it | +| AI Gateway | A heartbeat line every 5 minutes, with the `log_type` `cetirun.ai_gateway.heartbeat` | The `Gateway` table of `CetiRunLogs`. `GatewayCoverage` counts the heartbeats | | Other platform components | Logs on standard output | The `Platform` table of `CetiRunLogs` | The metrics ports of the Operator, the admission server, and the AI Gateway use @@ -178,6 +179,8 @@ The cluster template creates these functions: |---|---|---| | `CetiRunLogs` | `GatewayRequests()` | One AI Gateway call with its Agent, owner, Team, model, tokens, spend, routing and outcome. No request or response content. `CallOrigin` is `health_check` for LiteLLM's own probes, the origin of the classifier for the classifier call of a router, and empty for a client's call. `CopilotRoute` is `true` when a GitHub Copilot route of the owner answered the call | | `CetiRunLogs` | `GatewayDailyUsageV2`, a materialized view | The AI Gateway calls, failed calls, tokens and spend of one day per cluster, Agent, AI Gateway user, owner, Team, model, provider and provider model, GitHub Copilot route and call origin, from the creation of the view. It keeps 400 days by default, longer than the request log | +| `CetiRunLogs` | `GatewayCoverage`, a materialized view | The number of AI Gateway heartbeats, and of request lines at the completion time of their calls, in 5 minutes per cluster and Pod, from the creation of the view, with the time when the first line of each row arrived. Each Pod writes one heartbeat in each interval. It keeps its rows as long as `GatewayDailyUsageV2` | +| `CetiRunLogs` | `GatewayCoverageGaps(cluster, fromTime, toTime)` | One 5-minute interval of the period whose AI Gateway request lines can be missing, with the reason | | `CetiRunLogs` | `KubeEvents()` | One Kubernetes event version | | `CetiRunLogs` | `AgentInventoryHistory()`, `AgentInventory()` | Each record of an Agent's namespace, owner, Team and Agent Policy; the current Agents | | `CetiRunLogs` | `InventorySnapshots()` | One complete inventory snapshot of a kind, per cluster | @@ -228,6 +231,45 @@ GatewayDailyUsageV2 Earlier cluster templates created the view `GatewayDailyUsage`, without these columns. Refer to [Azure Data Explorer](../infrastructure/#azure-data-explorer). +A time without rows of `GatewayRequests()` can be a time without calls. It can +also be a time whose request lines did not reach the database, for example +because the collection stopped. With the request log, each AI Gateway Pod +writes a heartbeat line every 5 minutes. The heartbeats take the same way as +the request lines. `GatewayCoverage` counts them in intervals of 5 minutes, so +a Pod has one heartbeat in each interval. It also counts the request lines, at +the completion time of each call like `GatewayRequests()`. It keeps the time +when the first line of each row arrived. + +The heartbeats sample the collection. `GatewayCoverageGaps()` lists the +intervals of a period whose request lines can be missing, with one of these +reasons: + +| Reason | Meaning | +| --- | --- | +| `collection not observed` | No Pod has heartbeats in the interval and in the intervals before and after it. The collection stopped, or it stopped or started again in the interval, or the AI Gateway did not run. The current interval has this reason until the heartbeats of the next interval arrive. The interval in which the view started, and the intervals before it, always have this reason: they can have lines that arrived before the view. | +| `missed heartbeat` | A Pod that ran in the interval lacks its heartbeat in it, in the interval before it, or in the interval after it. A Pod runs from its first heartbeat to its last in the whole view, also through days without its heartbeats. The collection can have lost lines of that Pod. A Pod needs no heartbeat before its first interval or after its last. | +| `request lines removed` | The `Gateway` table holds fewer request lines of the interval than `GatewayCoverage` counted, both at the completion time of the calls. The retention of the logs database removed them, which counts from the ingestion of a line, or a deletion did. A higher retention does not restore them. `GatewayRequests()` lacks calls of the interval. | + +In an interval without a reason, a usage of zero means that no calls were +recorded and no heartbeat gap was detected. For example, the gaps of the last +day: + +```kusto +GatewayCoverageGaps("example-cluster", ago(1d), now()) +``` + +Use the name of the cluster that the `Cluster` column shows. The daily totals +of `GatewayDailyUsageV2` stay after the request lines expire. For them, only +the reasons `collection not observed` and `missed heartbeat` count. The times +before the AI Gateway image that writes heartbeats, and the times up to the +interval in which the view started, have no coverage. + +The heartbeats show the collection at the times when the Pods wrote them. Lines +that are lost between two heartbeats that arrived leave no gap. The same is +true for lines that a Pod writes after its last heartbeat, for example before +its node fails. `CollectionHealth()` reports the lines that the collector +dropped. + `CollectionHealth()` checks the last 15 minutes by default: - Platform or AI Gateway logs still arrive, and the metrics of the collector @@ -376,7 +418,8 @@ Also watch these signals of the platform: Without the role, only the first CetiRun cluster's ingestor starts. - If you prepare the databases yourself, also run the scripts in `infra/cluster/modules/adx/`, each in its database: - - `cetirun-logs.kql`, then `cetirun-gateway-usage.kql`, in the logs database + - `cetirun-logs.kql`, then `cetirun-gateway-usage.kql` and + `cetirun-gateway-coverage.kql`, in the logs database - `cetirun-metrics.kql`, `cetirun-health.kql`, and `adxmon-functions.kql` in the metrics database - `cetirun-agents.kql` in the Agent logs database @@ -385,8 +428,8 @@ Also watch these signals of the platform: Before you run them, replace `__LOGS_DATABASE__` in `cetirun-health.kql` and `cetirun-agents.kql` with the name of the logs database. Replace - `__RETENTION_DAYS__` in `cetirun-gateway-usage.kql` with the days that the - view keeps. Also set the + `__RETENTION_DAYS__` in `cetirun-gateway-usage.kql` and + `cetirun-gateway-coverage.kql` with the days that the views keep. Also set the ingestion batching policy of each database. The template sets 30 seconds. - For the alerter, a user-assigned managed identity with a federated credential for