[opentelemetry-php-instrumentation] Post hook receives the Closure instead of the bound object when internal method is called through a closure

Open
#2,143 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
56/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
php

Research direction

Start by reading the observer begin and end handling in the OpenTelemetry PHP extension, especially how observer_end() obtains the called object; compare it with PHP’s zend_closure_internal_handler behavior described in the issue. Reproduce with the provided standalone repro.php script and verify all four call forms. Done means both hooks receive the PDO object for each form, without breaking direct calls or array callables.

Written by the indexing model from the issue text.

Description

bug

Describe your environment

PHP 8.5.12 NTS (CLI and FPM); also reproduced on 8.2.35, 8.3.36 and 8.4.27
ext-opentelemetry 1.4.2 and 1.5.0 (latest on PECL), both affected
open-telemetry/opentelemetry-auto-pdo 0.6.0
open-telemetry/context 1.5.0
open-telemetry/sdk 1.15.0
Image Debian 13 based; also reproduced on the official php:8.5-cli (glibc) and php:8.5-cli-alpine (musl) images

Steps to reproduce

When an internal method is invoked through a closure, either with the first-class callable syntax ($pdo->exec(...)) or with Closure::fromCallable([$pdo, 'exec']), the extension passes the bound object to the pre hook but passes the Closure to the post hook.

The script below needs only the extension, with no Composer package. Save it as repro.php:

<?php

use function OpenTelemetry\Instrumentation\hook;

printf("PHP %s, ext-opentelemetry %s\n\n", PHP_VERSION, phpversion('opentelemetry') ?: 'NOT LOADED');

$seen = [];

hook(
    PDO::class,
    'exec',
    pre: static function (mixed $object) use (&$seen): void {
        $seen['pre'] = get_debug_type($object);
    },
    post: static function (mixed $object) use (&$seen): void {
        $seen['post'] = get_debug_type($object);
    },
);

$pdo = new PDO('sqlite::memory:');

$cases = [
    'direct call            $pdo->exec($sql)' => static fn () => $pdo->exec('SELECT 1'),
    'array callable         [$pdo, "exec"]' => static fn () => call_user_func([$pdo, 'exec'], 'SELECT 1'),
    'first-class callable   $pdo->exec(...)' => static fn () => ($pdo->exec(...))('SELECT 1'),
    'Closure::fromCallable  [$pdo, "exec"]' => static fn () => Closure::fromCallable([$pdo, 'exec'])('SELECT 1'),
];

$failed = false;
foreach ($cases as $label => $call) {
    $seen = [];
    $call();
    $ok = 'PDO' === $seen['pre'] && 'PDO' === $seen['post'];
    $failed = $failed || !$ok;
    printf("%-42s pre=%-8s post=%-8s %s\n", $label, $seen['pre'], $seen['post'], $ok ? 'OK' : 'BUG');
}

exit($failed ? 1 : 0);

Run it in the official PHP image. The extension is built from PECL, and the script is piped through stdin, so no volume is needed:

docker run --rm -i php:8.5-cli-alpine sh -c '{ apk add --no-cache $PHPIZE_DEPS && pecl install opentelemetry-1.5.0 && docker-php-ext-enable opentelemetry; } </dev/null >/dev/null 2>&1 && php' < repro.php

The command exits with status 1 when the bug is present.

What is the expected behavior?

post receives the same object as pre (PDO) in all four cases.

What is the actual behavior?

The direct call and the array callable are fine. The two closure forms pass the Closure to post:

PHP 8.5.12, ext-opentelemetry 1.5.0

direct call            $pdo->exec($sql)    pre=PDO      post=PDO      OK
array callable         [$pdo, "exec"]      pre=PDO      post=PDO      OK
first-class callable   $pdo->exec(...)     pre=PDO      post=Closure  BUG
Closure::fromCallable  [$pdo, "exec"]      pre=PDO      post=Closure  BUG

Additional context

Root cause. PHP wraps an internal method turned into a closure in zend_closure_internal_handler. After calling the original handler, it deliberately replaces EX(This) with the closure object, so that the closure is released after the observers have run:

closure->orig_internal_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU);
// Assign to EX(this) so that it is released after observer checks etc.
ZEND_ADD_CALL_FLAG(execute_data, ZEND_CALL_RELEASE_THIS);
Z_OBJ(EX(This)) = &closure->std;

observer_end() then reads the object again from the frame, through func_get_this_or_called_scope() → zend_get_this_object(execute_data), and therefore gets the closure. observer_begin() runs before the overwrite, which is why pre is correct. The same result is observed on PHP 8.2, 8.3, 8.4 and 8.5, so this is not a recent engine change. A possible fix is to unwrap the closure in observer_end() (when EX(This) is a Closure whose function is the observed one, pass its bound this instead), or to keep the object captured in observer_begin().

Consequence. This breaks the PDO auto-instrumentation (open-telemetry/opentelemetry-auto-pdo). Its post hooks declare PDO $pdo as their first parameter (PDOInstrumentation.php), so they throw a TypeError as soon as the method is reached through a closure:

PHP Warning:  PDO::exec(): OpenTelemetry: post hook threw exception, class=PDO function=exec message=OpenTelemetry\Contrib\Instrumentation\PDO\PDOInstrumentation::{closure:OpenTelemetry\Contrib\Instrumentation\PDO\PDOInstrumentation::register():221}(): Argument #1 ($pdo) must be of type PDO, Closure given in Unknown on line 0

Because the post hook throws before self::end() runs, the span started in pre is never ended and its scope is never detached. The next scope detached out of order then triggers:

PHP Notice:  Scope: unexpected call to Scope::detach() for scope #207, scope successfully detached but another scope should have been detached first in vendor/open-telemetry/context/DebugScope.php on line 56

This is not an edge case in user code. Symfony itself does it: PdoSessionHandler::configureSchema() passes $this->getConnection()->exec(...) to the doctrine-bridge schema listeners' "same database" checker. As a result, every doctrine:schema:update or doctrine:schema:validate run on an application that stores sessions with PdoSessionHandler hits it. Since the warning is printed on stdout, it also ends up inside the output of doctrine:schema:update --dump-sql.

Workaround: disable the PDO instrumentation for the affected processes with OTEL_PHP_DISABLED_INSTRUMENTATIONS=pdo.

Related, but different: #1181, where a first-class callable was not hooked at all. Here the hook runs, but post gets the wrong object.

Tip: React with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding +1 or me too, to help us triage it. Learn more here.

Dominant language
PHP
Stars
923
Forks
234
Avg merge
1d 20h
Merged PRs (30d)
35

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from open-telemetry/opentelemetry-php

All issues in open-telemetry/opentelemetry-php

Similar issues

More PHP issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.