Skip to content
Open
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
3 changes: 3 additions & 0 deletions PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
84 changes: 81 additions & 3 deletions app/cetirun-ai-gateway/cetirun_ai_gateway/request_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"))
Expand Down Expand Up @@ -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()
12 changes: 12 additions & 0 deletions app/cetirun-ai-gateway/chart/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
9 changes: 9 additions & 0 deletions app/cetirun-ai-gateway/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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")


Expand Down
2 changes: 1 addition & 1 deletion infra/cluster/main.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -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.')
Expand Down
8 changes: 4 additions & 4 deletions infra/cluster/modules/adx.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -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.')
Expand All @@ -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.
Expand Down
114 changes: 114 additions & 0 deletions infra/cluster/modules/adx/cetirun-gateway-coverage.kql
Original file line number Diff line number Diff line change
@@ -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;
Comment thread
AaronLiChen marked this conversation as resolved.
Resolved
// 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
Comment thread
feiskyer marked this conversation as resolved.
Resolved
| 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
}
Loading