Search by

ctxflow / otel

OscarRoLlo

ctxflow for PHP: OpenTelemetry distribution that puts the conversation and the user on every span and exports them to ctxflow.

v0.2.5 2026-12-02 21:34 UTC

This package is auto-updated.

Last update: 2026-12-02 21:35:13 UTC


README

Read-only mirror of packages/otel-php in ctxflow-sh/ctxflow-edge. Open issues and pull requests there.

ctxflow/otel

ctxflow for PHP: a thin OpenTelemetry distribution. It reads the CTXFLOW_* variables, declares itself in the resource (telemetry.distro.name=ctxflow/otel), puts the conversation and the user on every span, and exports the spans to ctxflow by OTLP/HTTP (protobuf). It does not hash, score or hide data. The behaviour is the SDK specification, docs/sdk-spec.md of the ctxflow-edge repository.

Needs PHP 8.2+ and ext-mbstring. It needs open-telemetry/sdk and exporter-otlp 1.3 or later (older versions miss APIs it uses or drop user.id); make test-php-lowest checks the floors. HTTP goes through Guzzle 7.15.2+ or 8.0.1+ (any PSR-18 client that php-http/discovery finds works). ext-protobuf is optional and makes the encoding faster.

Install

composer require ctxflow/otel

In the monorepo, ctxflow/semconv (the generated Ctxflow\Semconv\Semconv constants, packages/semconv/generated/php/Semconv.php) comes from a Composer path repository (../semconv, see composer.json). On Packagist each package comes from its read-only mirror (tools/php_split.py, job packagist of release.yml), without the repositories entry.

Use

Point the exporter at the collector or the core with the standard variables (OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS, OTEL_SERVICE_NAME), then choose one:

Zero code. Set OTEL_PHP_AUTOLOAD_ENABLED=true in the environment of the PHP process (with php-fpm, env[...] in the pool, or clear_env = no). The SDK installs itself when Composer's autoloader loads.

One line.

use Ctxflow\Otel\Ctxflow;
use function Ctxflow\Otel\conversation;

Ctxflow::init();
$tracer = \OpenTelemetry\API\Globals::tracerProvider()->getTracer('my-app');

conversation(function () use ($tracer) {
    $span = $tracer->spanBuilder('chat')->startSpan();
    // ... call the model ...
    $span->end();
}, 'conv-1', userId: 'u1', turn: 0);

conversation($block, $conversationId, $userId, $sessionId, $turn, $title) runs the block with the identity in the baggage, so every span started inside carries it, and restores the context on exit. Conversation::start(...) returns the scope to detach() yourself. Values must be non-empty, trimmed, at most 256 characters; $turn is an int (or a string of digits) from 0 to 2^63 - 1. A bad value throws InvalidArgumentException.

Optional title: conversation($block, 'conv-42', title: 'Alta de empleado') also sets ctxflow.conversation.title on every span inside (1 to 256 characters, trimmed; a bad value throws InvalidArgumentException). The title is not baggage: it stays in the process and is not sent to other services. A nested block with the same id inherits it, one with another id starts without it, and an inner $title wins.

One request is one process: the spans are batched and sent when the process ends (shutdown function), also in php-fpm. Export errors are logged by the SDK and never thrown.

Record reads

A tool that returns records declares which ones, by id and version and never by content:

use function Ctxflow\Otel\declareDataRead;

// inside the tool span
declareDataRead('sql', 'client.customers', [$row['id']], [$row['updated_at']->format(DATE_ATOM)]);

DataRead::attributes($kind, $source, $ids, $versions, $status, $rowCount, $truncated, $title) (also dataRead(...)) is the pure function that returns the ctxflow.data.* attributes; DataRead::declare(...) (also declareDataRead(...)) writes them on the current span, which must be the tool's own span and not a child client span such as a database call. Called with no active span, or when the current span is not recording (it ended or was sampled out), it writes nothing and logs one warning in the OpenTelemetry SDK log (once per process): call it inside the tool's execution, before the span ends. $kind is 'sql' or 'api'; $source is a table or an endpoint template (GET /customers/{id}); $versions has the same order as $ids. An aggregate has no primary key: pass []. Invalid values are left out, never thrown (SDK specification, section 4.5).

Ids leave as you declare them. If a key is personal data (an email, a national id), pass a surrogate id instead.

Record writes

An app or an ETL that writes records declares which ones, by id and new version and never by content. One data.write span carries the whole list:

use function Ctxflow\Otel\dataWriteSpan;

$rows = $db->upsertCustomers($batch);
dataWriteSpan(
    static fn() => null, // the span marks the write; start it after the write, with the new versions
    'client.customers',
    array_column($rows, 'id'),
    array_map(static fn(array $r): string => $r['updated_at']->format(DATE_ATOM), $rows),
);

DataWrite::attributes($source, $ids, $versions) (also dataWrite(...)) is the pure function that returns the ctxflow.data.* attributes; DataWrite::span($block, $source, $ids, $versions) (also dataWriteSpan(...)) runs $block inside a data.write span with them. $versions has the same order as $ids. Invalid values are left out, never thrown (SDK specification, section 4.6).

Ids leave as you declare them. If a key is personal data (an email, a national id), pass a surrogate id instead. Only source, ids and versions leave, never the content of a record.

Declared operation

A tool or a call can state what it does to the client system with one of read, write, update or delete. On a tool, inside the tool:

use function Ctxflow\Otel\declareDataOperation;

declareDataOperation('update'); // the span of the tool

To state the operation of one specific call (for example a POST /graphql that only reads), the attribute must be on that call's own span. If you start the span yourself, set DataOperation::attributes('read') on it:

$span->setAttributes(\Ctxflow\Otel\DataOperation::attributes('read'));

DataOperation::attributes($operation) (also dataOperation(...)) is the pure function that returns ['ctxflow.data.operation' => $operation]; DataOperation::declare($operation) (also declareDataOperation(...)) writes it on the current span. A value that is not one of the four gives no attributes, never an error (SDK specification, section 4.7). The declaration belongs to the span that carries it: a tool states what the tool does and its child spans do not inherit it, and the receiver shows it next to what the calls of the tool do. To state the operation of one specific call, put it on that call's own span.

Hashes

The SDK hashes nothing by itself. These helpers give you the same hashes as the Python SDK and the core, to set on your own spans. Plain sha256 (hex), no key.

use function Ctxflow\Otel\chunkTextHashes;
use function Ctxflow\Otel\sourceHash;
use function Ctxflow\Otel\textHash;

sourceHash($fileBytes); // value of ctxflow.source_hash
chunkTextHashes(array_map(fn ($c) => $c->text, $chunks)); // text hashes for ingest.upsert, same order as the chunk ids
textHash($item->text); // compare with the retrieval item_hashes

Each helper is also a static method of Ctxflow\Otel\Hash.

  • sourceHash($data): sha256 of the bytes of the original document, with no normalization. Use it for ctxflow.source_hash.
  • textHash($text) (also contentHash($text)): sha256 of normalizeText($text), or null if no text is left. normalizeText is Unicode NFC, each run of Unicode white space as one space, trimmed; case is kept. Use it to match the item_hashes of retrieval spans with the hashes you wrote on ingestion.
  • chunkTextHashes($texts): textHash of each chunk text of a write, '' where there is none. Set it as the text hashes of ingest.upsert.
  • asId($value): a chunk id as the store holds it: a string as it is (no trimming), an integer as its decimal digits, anything else ''.

NFC uses ext-intl when it is loaded, else the symfony/polyfill-intl-normalizer that the package requires (slower). White space is Unicode White_Space (not trim() or \s), so the hashes match the other SDKs. Invalid UTF-8 is replaced by U+FFFD before hashing.

Library instrumentation

agentTurn(callable $block, string $agent) (next to conversation()) runs a block as one agent turn: an invoke_agent <agent> span that the LLM spans nest under; an exception is recorded and rethrown unchanged.

Optional, and only active when the library is installed (openai-php/client, theodo-group/llphant and neuron-core/neuron-ai are in suggest and require-dev, never in require).

openai-php/client (0.19.2 or later): Ctxflow\Otel\Instrumentation\OpenAI\OpenAiInstrumentation::factory() returns an OpenAI\Factory that sends through a PSR-18 decorator, which gives each chat completion and Responses API call a GenAI span (model, token usage, input and output text, error status and type). Why the HTTP layer: the library has no event or middleware API, a PSR-18 client is its public extension point (withHttpClient()), and this needs no PHP extension and no patching. The bodies of the HTTP calls are the contract, so it does not depend on the classes of a library version. Streamed calls are not traced and keep working: factory() and instrument($factory) set the stream handler that the library would choose for the inner client (Guzzle, Symfony Psr18Client); if you only pass httpClient() to withHttpClient(), add your own withStreamHandler(). php-http/discovery is a direct dependency (it finds the PSR-18 client); the package conflicts with openai-php/client below 0.19.2. See OpenAI PHP and examples/php/openai/.

LLPhant (theodo-group/llphant 1.10.11 or later, OpenAI chat only): Ctxflow\Otel\Instrumentation\LLPhant\LlphantInstrumentation::openAiConfig() returns an OpenAIConfig whose client (the injection point OpenAIConfig::$client) is an openai-php/client client that sends through the traced HTTP client above, so each LLPhant chat request is a GenAI chat span. LlphantInstrumentation::tool($functionInfo) wraps a tool so that each call the model makes gets an execute_tool <name> span. LLPhant has no agent concept: use agentTurn(). LLPhant requires openai-php/client ^0.19.2, so the dev tree of this package (and the tier 2 scenarios) run on 0.19.x. Development: the dev tree needs ext-gd, ext-dom, ext-zip and ext-xml (LLPhant pulls phpoffice/phpword); make test-php-latest runs the checks on the latest openai-php/client and the latest Guzzle (8), without LLPhant and Prism (their scenarios are skipped). See LLPhant and examples/php/llphant/.

Laravel Prism is in its own package, ctxflow/otel-prism (ctxflow for Laravel/Prism, packages/otel-prism/): it needs illuminate/support for its Laravel service provider, which ctxflow/otel must not require.

neuron-core/neuron-ai (4.x only, MIT): Ctxflow\Otel\Instrumentation\Neuron\NeuronInstrumentation::instrument($agent) subscribes a listener to the agent and makes an invoke_agent span for each run, a chat span for each model call and an execute_tool span for each tool call. Why events: Neuron emits typed observability events (PSR-14, one dispatcher for each agent) and Agent::subscribe() is its public API, so this needs no patching and no PHP extension, and it covers every provider of Neuron (the model call is read from Neuron's own Message and Usage, not from HTTP bodies). The run makes its own invoke_agent span, so agentTurn() is not needed; inside agentTurn() no second one is made. The package conflicts with neuron-core/neuron-ai below 4.0 and from 5.0. See Neuron AI and examples/php/neuron/.

Notes

  • OTEL_TRACES_EXPORTER defaults to otlp_proto_http (an alias of otlp that the SDK registers), OTEL_EXPORTER_OTLP_PROTOCOL to http/protobuf, metrics and logs to none. A value you set wins.
  • No resource detectors (host, process): the resource is the service, OTEL_RESOURCE_ATTRIBUTES, telemetry.sdk.* and telemetry.distro.*. OTEL_PHP_DETECTORS is ignored.
  • A provider you build yourself is not supported yet (PHP providers do not take processors after they are built): use init() or the zero-code start. If the app already installed a real global tracer provider, init() throws RuntimeException and the zero-code start logs one warning and installs nothing (only when the provider exists before the autoloader runs; in the usual order, autoloader first and the app's provider after, ctxflow cannot warn). OTEL_SDK_DISABLED and OTEL_CONFIG_FILE make init() throw.
  • The zero-code start never breaks the app: any failure (for example a provider the app installed) is logged once and ctxflow installs nothing. It also skips what the OpenTelemetry autoloader skips: OTEL_PHP_EXCLUDED_URLS, excluded request headers and Composer scripts. init() throws on such a failure.
  • Call init() outside any active scope (not inside conversation() or a span): the provider is registered in the current OpenTelemetry context and would be lost when that scope ends.
  • Composer plugins: an app that requires ctxflow/otel must allow tbachert/spi and php-http/discovery in config.allow-plugins (the OpenTelemetry SDK needs both).
  • Zero code replaces the initializer of the OpenTelemetry autoloader. The automatic root span (OTEL_PHP_TRANSACTION_SPAN_ENABLED) is started before ctxflow loads and is not part of the ctxflow pipeline.
  • PHP integers are 64-bit, so ctxflow.turn reaches 2^63 - 1 exactly (no JavaScript-style limit).

Development

composer install          # in this directory
php tests/vectors.php     # tier 1: the vectors of packages/semconv/src/ctxflow_semconv/conformance
vendor/bin/phpstan analyse && vendor/bin/php-cs-fixer fix --dry-run --diff

Tier 2 (scenarios, openai-php-chat and llphant-chat with the real libraries, and neuron-php-agent with real Neuron AI, and prism-openai-chat with real Laravel Prism through ctxflow/otel-prism, against a local stub of the OpenAI API): uv run python conformance/harness.py compare php from the repository root. Apache-2.0.