Tracing and error telemetry
A trace connects technical observations that belong to the same operation. That connection lets you start with an error and find the graph, selected edge and surrounding activity that explain it. Error telemetry adds a normalized record of a failure so your application can send it to a log service, tracing system, webhook destination or event bridge.
ExecKernel supplies correlation fields and adapters for those destinations. Your application supplies any distributed tracing instrumentation and exporter configuration around the engine. Start by deciding which identifiers you need to connect: a session, one runtime operation and one HTTP request are related, but they are not the same identity.
Keep correlation identities distinct
Section titled “Keep correlation identities distinct”| Field | What it identifies | How to use it |
|---|---|---|
session_id |
The application’s runtime session. | Follow several operations involving the same saved progress. |
operation_id |
One engine operation, such as a start or choice. | Join its logs, audit records, trace observations and errors. |
observation_id, observation_sequence |
One observation and its order within that operation. | Distinguish related records without merging them into one event. |
trace_id, span_id in core telemetry |
Valid captured W3C trace and span identifiers. | Connect runtime observations to an active parent supplied by tracing instrumentation. |
API X-Trace-Id |
An HTTP request correlation identifier. | Find the API response and HTTP log entry; its accepted format is broader than a W3C trace ID. |
The runtime captures the active trace context at the beginning of an operation and keeps that identity with its observations. If successful events are deferred until after saving, they retain the captured parent even if another span is active when the batch is published. With no valid parent, core observations still have their operation identity; the engine does not manufacture a distributed trace ID from the session or operation ID.
For core trace identity, trace IDs are nonzero lowercase hexadecimal strings of 32 characters; span IDs use 16. Invalid or orphan span identifiers are removed. A syntactically valid HTTP correlation string such as request-42 therefore does not become an OpenTelemetry parent automatically.
Capture an error you can investigate
Section titled “Capture an error you can investigate”ErrorTelemetryEmitterInterface::emit(array $event) is the error delivery contract. PsrLoggerErrorTelemetryEmitter projects the sanitized error into a LoggerAdapterInterface; use Psr3LoggerAdapter there when your application already has a PSR-3 logger.
The complete example keeps ordinary diagnostics and normalized error records in separate ArrayExecKernelLogger objects so both are visible in its report:
$diagnostics = new ArrayExecKernelLogger(); $errors = new ArrayExecKernelLogger(); $limiter = new RateLimitedErrorTelemetryEmitter( new PsrLoggerErrorTelemetryEmitter($errors), windowSeconds: 5, maxPerSession: 50, ); $engine = (new ExecKernelFactory())->build( logger: $diagnostics, errorTelemetryEmitter: $limiter, );logger receives the ordinary runtime messages. errorTelemetryEmitter receives the error projection, with its own code, normalized severity and correlation fields. Keeping those roles clear helps you avoid counting two views of one incident as two failed operations.
We will reuse the learning-choice graph from Anatomy of a graph. Node 10 offers a guide on edge 101 and practice on edge 102; practice requires practiceEnabled: true. The example starts with practice disabled and submits edge 102 using operation ID practice-rejected.
The choice throws ForbiddenEdgeException with code EK-SEC-NAV-002. These selected fields come from the normalized error record produced during the same operation:
{ "level": "error", "message": "[EK-RULE-003] ExecKernel error", "context": { "error_code": "EK-RULE-003", "severity": "BLOCKER", "session_id": "learning-error-session", "graph_code": "learning-path", "operation_id": "practice-rejected", "event_phase": "diagnostic", "edge_id": 102, "timestamp": 1700000005 }}The rule observation uses EK-RULE-003; the navigation exception describes the rejected choice with EK-SEC-NAV-002. To investigate, use operation_id=practice-rejected to find the diagnostic log “Condition blocked edge”, then inspect edge 102 and its context_value condition. The input state remains at node 10; there is no successful transition to practice to recover from.
This example has no active distributed trace parent, so its records correctly omit trace_id and span_id. Operation correlation is enough to explain this local rejection. When the application supplies an active OpenTelemetry parent, those fields can connect the same records to the surrounding request or job.
Select safe error data and control volume
Section titled “Select safe error data and control volume”ErrorTelemetryEventBuilder and ErrorTelemetrySanitizer retain selected operational fields and normalize the message to ExecKernel error. They do not forward arbitrary exception messages, nested business context, objects or credentials. Known identifiers and selected node, edge, rule and timing fields remain available for diagnosis.
For example, the downloadable program builds an application error containing a private message, a password and a customer’s email. Its resulting safe projection is:
{ "node_id": 10, "edge_id": 102, "session_id": "learning-error-session", "error_code": "EK-SEC-NAV-002", "severity": "RULE_FAILURE", "event_type": "execkernel.error", "message": "ExecKernel error", "timestamp": 1700000005, "context": { "node_id": 10, "edge_id": 102 }}That is an allowlist projection, not general anonymization. A retained session or graph identifier can still be sensitive in your application. Decide access, retention and any additional pseudonymization at the destination, and do not assume that messages your application sends directly to a generic logger pass through this sanitizer.
RateLimitedErrorTelemetryEmitter controls local delivery volume. The factory wraps a supplied emitter automatically, and preserves an explicitly configured limiter like the one above. Its defaults use a five-second delivery-time window, a maximum of fifty emissions per graph/revision/session bucket, and a minimum severity of RULE_FAILURE. Repeated fingerprints of the same error code, severity, node and edge in that bucket are suppressed during the window.
The limiter uses its delivery clock rather than the event’s timestamp, so an old or simulated event time does not create a new quota window. statistics() reports attempted deliveries and suppression or failure counts. Those counters and limits belong to this limiter instance; they are not a deployment-wide quota. debug: true bypasses severity and quota filtering but still sanitizes records, so use it only when that volume is intended. This is separate from selecting a trace detail level.
Connect an OpenTelemetry tracer
Section titled “Connect an OpenTelemetry tracer”OpenTelemetryTraceAdapter exports allowed runtime trace observations through a TracerInterface. OpenTelemetryErrorEmitter creates an execkernel.error span for normalized error telemetry. Your application must supply a recording tracer whose SDK, processor and exporter are already configured; obtaining a tracer object alone does not establish a working export destination.
The companion integration function accepts that tracer rather than choosing an observability platform:
function tracingOpenTelemetryEngine(TracerInterface $tracer, ?callable $onFailure = null): ExecKernel{ $trace = new OpenTelemetryTraceAdapter( $tracer, level: TraceLevel::DETAILED, failureObserver: $onFailure, ); $errors = new RateLimitedErrorTelemetryEmitter( new OpenTelemetryErrorEmitter($tracer, failureObserver: $onFailure), windowSeconds: 5, maxPerSession: 50, failureObserver: $onFailure, ); return (new ExecKernelFactory())->build( traceEmitter: $trace, errorTelemetryEmitter: $errors, );}TraceLevel::DETAILED includes observations such as edge evaluation and condition results in addition to the basic operational events. BASIC is the default; DEBUG allows the same event set as DETAILED in this adapter. Neither level bypasses the operational-field projection.
Activate your application’s request or job span before calling the engine. If a parent arrives over HTTP or a queue, the application instrumentation must extract and activate it. The adapter reconstructs an export parent from the context captured in each record; it does not adopt whichever span happens to be active later, and does not carry baggage or tracestate through that reconstruction.
Read span timing correctly
Section titled “Read span timing correctly”These adapters create a span when they deliver an observation and end that span after adding its attributes and event. Its start and end use the OpenTelemetry SDK clock at export time. The span’s duration therefore describes that short export activity, even when the observation describes an earlier runtime operation.
Use the exported representation according to the source of each value:
| Exported value | What it can tell you |
|---|---|
| Parent trace and span | Which captured application trace context the observation belongs to. |
ek.operation.id, ek.graph.code, ek.event.phase |
Which runtime operation, graph and observation phase produced it. |
ek.timestamp, ek.observed_at when present |
The recorded observation time, including explicitly supplied or simulated timestamps. |
ek.transition.latency_ms or ek.payload.duration_ms when present |
A duration measured and supplied by the corresponding runtime operation. |
| Export span start/end | When the adapter created and ended that span in the SDK. It cannot reconstruct the earlier operation’s duration. |
For an end-to-end request duration, measure a real application span around the request. For aggregate runtime timings, use the measurements described in Metrics and operational monitoring. A row in a trace viewer is useful correlation evidence, but its visual width is not automatically a measurement of historical runtime work.
Choose the destination and observe delivery failures
Section titled “Choose the destination and observe delivery failures”| Emitter | Destination your application supplies | Delivery behavior to account for |
|---|---|---|
PsrLoggerErrorTelemetryEmitter |
Logger adapter, optionally wrapping a PSR-3 logger. | Sanitized errors become structured log records with severity-derived levels. |
OpenTelemetryErrorEmitter |
Configured TracerInterface. |
Creates the export span described above; SDK export policy remains with your application. |
WebhookErrorEmitter |
HTTP(S) endpoint, headers and optional transport. | Sends sanitized JSON; its default transport has a configurable timeout, defaults to two seconds and does not follow redirects. |
SDKEventBridgeEmitter |
EventBridgeInterface. |
Publishes an ENGINE_ERROR event to that bridge. |
Built-in emitters catch delivery failures so they cannot replace the original runtime result. Their optional failureObserver reports a minimal channel, stage and exception class rather than the exception’s private message. A limiter’s own failure report has its own minimal channel and exception fields. Keep these reports out of a recursive path that tries to send the same failing telemetry again.
Failure isolation does not guarantee delivery or make a synchronous transport cost-free. Configure time bounds and an application delivery mechanism when telemetry must survive exporter outages. Do not retry a confirmed engine choice merely because its telemetry could not be sent.
Connect an API incident to its request
Section titled “Connect an API incident to its request”The HTTP correlation field from Client errors and transport diagnostics identifies one API request. TraceIdMiddleware reuses a single valid incoming X-Trace-Id, or obtains/generates an identifier when needed. It returns that value in the response header and, for JSON object responses, at top-level trace_id on success or error.details.trace_id on an error.
The API accepts 1–128 characters from letters, digits, underscore, dot, colon and hyphen for this header. That is an HTTP correlation contract, not W3C context propagation. Use it to find the compact HTTP log record; supply application tracing instrumentation if you also need a distributed parent around the engine operation.
Complete examples
Section titled “Complete examples”tracing-error-telemetry.php contains the complete local rejection, related records and sanitizer projection, using the learning-path graph. Its optional execution is:
php tracing-error-telemetry.php learning-path.jsontracing-opentelemetry.php contains tracingOpenTelemetryEngine() for use with your application’s configured tracer. It is an integration function, not an exporter installation script.