Skip to content

Metrics and operational monitoring

Metrics turn many runtime observations into numbers your application can compare over time. A counter records how many times something happened, a histogram records measured values such as duration, and a gauge represents a current observation such as tracked active sessions. A runtime monitor uses a bounded set of observations to calculate a ratio, a percentile or a diagnostic signal.

ExecKernel supplies metric adapters and passive monitors. Your application chooses their lifetime, collects their output and sends it to the monitoring system you operate. Those choices determine whether a number describes one PHP execution, a long-lived worker or an aggregate assembled outside the engine.

MetricsAdapterInterface has three operations: incrementCounter(), observeHistogram() and setGauge(). PrometheusMetricsAdapter implements them with a Prometheus PHP CollectorRegistry. The registry’s storage is a separate choice from the ExecKernel adapter.

Here the installed Prometheus PHP client supplies an in-memory registry:

$registry = new CollectorRegistry(new InMemory(), false);
$metrics = new PrometheusMetricsAdapter($registry, maxSeriesPerMetric: 128);
$engine = (new ExecKernelFactory())->build(metricsCollector: $metrics);

Pass the adapter once when building the engine. Factory connects the runtime components and their shared metric projection; you do not need to register another counter listener for each component. The null collector used when no adapter is supplied records nothing.

InMemory is deliberate here: the example can inspect the complete set of values from one execution. It does not send anything to a Prometheus server or share data with another PHP worker. RenderTextFormat::render($registry->getMetricFamilySamples()) can produce Prometheus exposition text; your application still owns the endpoint or transport that makes those samples available.

Select measurements by their meaning and unit

Section titled “Select measurements by their meaning and unit”

The built-in runtime projection uses a fixed label schema per metric. graph_code and graph_version identify the observed definition; additional dimensions describe a node, edge, language or error category. Individual session, operation and trace IDs are not metric labels.

Metric Kind and unit What it describes
ek_navigation_attempts_total Counter, attempts Observed navigation attempts for a selected edge.
ek_navigation_success_total / ek_navigation_total Counters, transitions Successfully published navigation results. Both names count the successful transition; do not add them together.
ek_navigation_blocked_total Counter, blocked choices Rule failures during choose or navigate; a rule evaluated while presenting options does not count as a blocked choice.
ek_navigation_latency_ms Histogram, milliseconds Navigation duration supplied by the runtime measurement.
ek_render_latency_ms Histogram, milliseconds Payload-building duration.
ek_session_started_total / ek_session_finished_total Counters, sessions Published starts and terminal completions observed by this projection.
ek_session_active_total Gauge, sessions Distinct sessions the listener has observed as active and still tracks. Despite its name, this is a gauge.
ek_session_duration_seconds Histogram, seconds Difference between the completed state’s creation and update timestamps.
ek_graph_load_seconds Histogram, seconds Loader duration converted from its millisecond measurement.

Read the unit before comparing histograms: navigation and render durations use milliseconds; session and loader metrics above use seconds. An active-session gauge is not a census of your session database. A worker that never observed a session cannot count it, and an expiration observation is not proof that a person abandoned your application.

Successful measurements follow event publication. With deferEvents: true, publishing the returned batch releases those observations; discarding the batch leaves them unpublished. A failed operation still produces its applicable diagnostic measurements. The save boundary is explained in Logs and audit trails.

Add a monitor for a question you can answer

Section titled “Add a monitor for a question you can answer”

A monitor observes the runtime without changing its decision. Its output goes through MonitorTelemetrySinkInterface, which can receive metrics, diagnostic events and logs. That is a different interface from the core metric collector; choosing a Prometheus collector does not automatically export all monitor output into it.

For example, to ask how many choice operations failed, keep a rolling sample window and count only choose outcomes:

$sink = new InMemoryMonitorTelemetrySink(capacity: 100);
$errorRate = new ErrorRateMonitor(
thresholdRate: 0.25, minSamples: 2, countedEvents: ['choose'],
sink: $sink, windowSize: 20,
);
$throughput = new ThroughputMonitor(
intervalSeconds: 60, thresholdCount: 2,
eventNames: ['choose'], sink: $sink,
);
$engine->addMonitor($errorRate);
$engine->addMonitor($throughput);

The error-rate monitor waits for at least two samples, then reports failures divided by observed choices in its last twenty outcomes. The 0.25 threshold is an example setting for generating a diagnostic signal, not a recommended service objective. The throughput monitor counts choices in a configured sixty-second interval. A rejected choice is still an observed choice for both monitors.

InMemoryMonitorTelemetrySink retains bounded lists so the example can display metrics() and events(). For production delivery, implement the sink for your monitoring service or use FlowEventsMonitorTelemetrySink to publish diagnostics under EK:monitor.*. Those diagnostic events do not feed canonical business counters or recursively notify the monitors.

If your application composes a shared dispatcher directly, (new RuntimeMonitorFactory($dispatcher, $config))->registerMonitors($sink) offers configuration-based installation. Its definitions live under monitors, each selected definition needs enabled: true, and registration must happen before runtime operations. The default sink is FlowEventsMonitorTelemetrySink.

We will reuse the learning-choice graph introduced in Anatomy of a graph: node 10 offers guide edge 101 and practice edge 102; practice requires practiceEnabled: true. The example starts one session with practice disabled, submits practice once, then selects the guide successfully and reaches terminal 20.

All rows below belong to graph_code="learning-path" and graph_version=""; this definition declares no revision. The script’s one registry produced:

Measurement Observed value Interpretation
Navigation attempts, edge 102 1 The blocked practice choice was attempted.
Navigation blocked, edge 102 1 That attempted choice failed its condition.
Navigation attempts, edge 101 1 The guide choice was attempted.
Navigation success, edge 101 1 One successful transition reached the guide.
Session started / finished 1 / 1 This listener observed the start and terminal result.
Active-session gauge 0 Its tracked session has reached a terminal node.
Session-duration histogram count / sum 1 / 10 seconds The example’s fixed state timestamps are ten seconds apart.
Error-rate monitor 0.5 One failure among two choices; the start is excluded by configuration.
Throughput monitor 0.033333… choices/second Two choices divided by the configured sixty seconds.

The throughput value uses the configured interval, not the five seconds between the two sample choices. The ten-second session duration comes from the supplied observation timestamps, not a ten-second PHP execution. Neither number is a benchmark. Use Performance and benchmarking when you need measurements of execution cost under a defined workload.

The following monitors answer different questions from the same bounded stream. Their windows are scoped by graph and revision, with additional node, edge or rule dimensions where applicable.

Monitor Question it helps investigate
LatencyMonitor Are navigation or payload-build measurements high or spiking within their sample window?
ConditionCostMonitor Which rule and edge have high evaluation durations or percentiles?
HotNodeMonitor Which nodes have many observed visits inside a time window?
ThroughputMonitor How many configured operations were observed per configured interval?
ErrorRateMonitor What share of the configured operation outcomes failed?
NodeDropMonitor How often did locally tracked node stays resolve through an observed expiration? This does not establish user abandonment.
RuleBlockMonitor What share of the sampled evaluations of a rule on an edge blocked?
ConversionDiveMonitor Has completion fallen among locally observed starts whose completion or expiration was subsequently observed?
CycleStormMonitor How many cycle detections occurred in a time window?
CycleSuspicionMonitor Are consecutive observed histories repeating an A-B-A-B node pattern? This is a suspicion signal, not the cycle breaker’s decision.
PerformanceMonitor Has a duration percentile degraded compared with the previous complete sample window?
RulePressureMonitor How many conditions are declared on attempted edges on average? This is not the number actually evaluated before short-circuiting.

Bounds matter when interpreting those answers. Monitors retain limited buckets, sessions and samples; diagnostics() reports their tracked counts and dropped observations. flush() clears their accumulated state. The lightweight mode suppresses diagnostic alerts and, for monitors that calculate them separately, the extra percentile outputs. Choose window sizes and thresholds for the traffic and question your application actually has.

The runtime metric listener and Prometheus adapter also limit series cardinality. A series is one metric plus one combination of label values. The adapter’s maxSeriesPerMetric controls its budget, and droppedSeries() counts refused attempts to admit new series; repeated attempts for the same refused combination can increase it again. The runtime projection has its own bounds. Keep graph and revision names stable; adding session IDs or raw paths to custom labels can create one series for every request and defeat useful aggregation.

Preserve the collection scope across processes

Section titled “Preserve the collection scope across processes”

An in-memory collector or monitor only knows what the objects in that process observed. Recreating the application resets its local state; another worker starts with a different set of observations. Keep that scope visible in deployment-level monitoring, including the process or instance identity added by your collector.

Two PHP processes keep separate in-memory observations. Your application supplies export or shared storage before an external collector can assemble deployment-level measurements.

For deployment totals, provide a collection strategy that covers each producing process, or use suitable shared storage and export semantics. Counters, histograms and gauges need different treatment: summing independent counters may be meaningful, while summing local active-session gauges can count the same session more than once if different workers observed it. Plan that aggregation outside the engine.

The API’s EndpointMetricsRegistry is another in-memory registry. Its GET /internal/metrics controller returns JSON fields counts, latency_totals, latency_counts and error_counts. HTTP latency totals are in seconds; divide a total by its matching latency count to obtain the observed mean. These are HTTP response observations, separate from the core runtime metrics above.

The route reports the registry attached to the application handling it. In a long-lived embedded app, that can reflect previous requests handled by the same app object. In a conventional PHP-FPM deployment, a fresh bootstrap may create a fresh registry for each request. Requesting /internal/metrics therefore does not aggregate all workers or recover earlier request-local metrics.

The supplied standalone Docker deployment does not expose /internal/metrics: Nginx forwards the public API and health paths, and DeploymentAccessMiddleware returns 404 for /internal/, even with a valid API token. An embedded createApp() registers the route without adding that deployment access layer; if you expose it, your application must supply the access and collection design. Docker deployment describes the supplied deployment boundary.

Health checks answer a separate question: whether a process is alive or configured dependencies are ready now. HealthCheckRegistry supports explicit checks; liveness does not probe dependencies. A healthy response cannot replace a history of operational measurements. See SQLite backup, recovery and health checks for readiness and recovery procedures.

metrics-monitoring.php includes the real Prometheus adapter, both monitors, the two choices, selected samples and generated exposition text. It uses the learning-path definition and assumes the Prometheus PHP client is already available in your application.

Terminal window
php metrics-monitoring.php learning-path.json

The sample counts and ratios above can be read directly from its report. Actual runtime duration measurements can vary between executions; the fixed observation timestamps are only there to make the session-duration and interval examples easy to interpret.