Agent OpenTelemetry loses execute spans when JDBC callbacks overlap
Bug Report
Which version of ShardingSphere did you use?
Current master, commit bd48f5204c8bbfcb87f7e52fd8d39f8457946520 (5.5.4-SNAPSHOT). The deterministic regression uses OpenTelemetry SDK 1.58.0 and Java 17.0.15.
Which project did you use? ShardingSphere-JDBC or ShardingSphere-Proxy?
The ShardingSphere Agent OpenTelemetry plugin's JDBC executor callback advice. I investigated this while checking physical SQL execution visibility for a ShardingSphere-JDBC routing-contract project. The current-master reproduction is an advice-level unit test with mocked JDBC metadata; it does not require a database or collector.
Expected behavior
Two overlapping per-unit execute invocations on the same JDBC executor callback should produce two distinct completed /ShardingSphere/executeSQL/ spans. Each span should preserve its own SQL attributes and success/error outcome. An exception in one invocation must not change or disappear into the other invocation's span.
Actual behavior
A deterministic two-thread test starts invocation A, starts invocation B, completes A successfully, then completes B with an exception. Only one span is exported: B's span is ended by A's completion hook. A's span is never ended, and B's error is not recorded because its span has already ended.
The test fails on unchanged current-master production code with:
OpenTelemetryJDBCExecutorCallbackAdviceTest.assertConcurrentInvocations
Expected: is <2>
but: was <1>
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
Reason analyze (If you can)
OpenTelemetryJDBCExecutorCallbackAdvice.recordExecuteInfo stores each started span in TargetAdviceObject.setAttachment. That attachment is a single field on the callback object. afterMethod and onThrowing read the same field, so overlapping invocations overwrite each other's span.
The invocation sequence is:
A.before: attachment = spanA
B.before: attachment = spanB
A.after: end(spanB) with OK
B.throw: record error on already-ended spanB
B.after: end already-ended spanB again
InstanceMethodAdviceExecutor also invokes afterMethod in finally after onThrowing; a fix needs to handle this lifecycle without completing an outer nested invocation. The executor passes the same Object[] args reference through all hooks for one invocation, providing an existing invocation identity.
Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc.
- Create one
OpenTelemetryJDBCExecutorCallbackAdviceand one callback fixture implementingTargetAdviceObject. - Use an
InMemorySpanExporterandSimpleSpanProcessorwith OpenTelemetry SDK. - Prepare two argument arrays for
SELECT 1andSELECT 2. - Use two executor threads and three bounded
CountDownLatchinstances to enforce the exact sequence above. Use the same argument array for all hooks belonging to one invocation, matchingInstanceMethodAdviceExecutor. - Assert two completed span IDs, A's
SELECT 1/OK/no-exception attributes, and B'sSELECT 2/ERROR/one-exception attributes.
Example codes for reproduce this issue (such as a github link).
The test-only reproducer commit keeps production code at the base above. Its OpenTelemetryJDBCExecutorCallbackAdviceTest.assertConcurrentInvocations compiles and deterministically fails with expected 2 / actual 1. Run:
./mvnw -B -pl agent/plugins/tracing/type/opentelemetry -am \
-Dtest=OpenTelemetryJDBCExecutorCallbackAdviceTest#assertConcurrentInvocations \
-Dsurefire.failIfNoSpecifiedTests=false test
Separate 5.5.3/MySQL corroboration
I also reran the runtime-absent fixture at da1240b on 2026-09-08 with the SHA-512-verified official Agent 5.5.3 and MySQL 8.4.11. RouteContract API/hook/SPI/artifact are absent from the forked runtime; datasource-proxy is the backing-callback count oracle. Across 20 controls and 20 forced two-way fan-outs, it reports 60 successful backing callbacks but only 40 completed execute spans (20 control, 20 fan-out). This is an exact forced-overlap fixture, not a production loss rate or current-master database test.
Fix direction to discuss
An invocation-keyed local candidate passes concurrency, nesting, failed-before and exception-then-finally tests. Applying only the two corresponding advice classes to an explicitly modified 5.5.3 Agent also gives 60 completed spans for the same 60-callback MySQL fixture, including two distinct-target children for every fan-out root. This is a local experimental build, not an official release.
I would appreciate guidance on the invocation-state owner before proposing a production PR. A per-thread weak-key map avoids strongly retaining abandoned argument arrays, but stale Span values need a later map access after GC. Dynamic agent-plugins-enabled changes can skip completion hooks. The candidate also adds about 40 B and 62 ns per invocation in a local advice/SDK-only loop, excluding database and exporter work. I am not treating that prototype as performance-neutral or ready to merge.
AI assistance: OpenAI Codex assisted with investigation, reproductions, tests and the experimental candidate.
I added a smaller standalone reproducer using the official Agent 5.5.3 advice classes.
After staging the official archive and nine checksum-pinned application dependency JARs, it runs with Python 3.10+ and Java 17, without a Maven reactor, Mockito, Docker or a database. The four text files include the source, runner, dependency coordinates/download URLs/checksums and instructions. The runner verifies the archive and dependencies before compiling; it makes no network requests.
Both controlled two-thread scenarios start two SQL spans but complete only one:
- A succeeds: only B's span completes, with OK; A remains unfinished.
- A fails: A's synthetic exception is recorded on B's ERROR span; A remains unfinished. This scenario calls A's
afterMethodinfinallyafteronThrowing, matching the executor lifecycle.
The command deliberately exits 1 for the failed expected=2 actual=1 assertion. It checks SQL identity, status and the exception event as well as completion count.
This is direct advice invocation with synthetic metadata, not a bytecode-instrumentation or database test. The current-master regression and separate MySQL integration results in the issue remain distinct evidence. Codex assisted with this additional reproducer and its validation.
hey, could i work on this ?
Thanks for offering to investigate, @PrakarshSrivastav! I can help check a proposed fix against the reproductions.
The best starting point for an upstream change is the test-only reproducer pinned in this issue linked in the issue. It uses a deterministic overlap rather than timing or sleeps. The standalone 5.5.3 reproducer is another way to inspect the failure without building the reactor; it is separate release-specific evidence.
For a fix, the useful checks are:
- Both overlapping invocations export distinct completed spans, with each invocation's own SQL attributes, status, and exception event.
- The exception path still works when
afterMethodruns infinallyafteronThrowing; it must not finish an outer nested invocation. - Nested calls and a failure during
beforeMethoddo not leave or consume another invocation's state.
The issue describes an experimental invocation-keyed approach, but its ownership and cleanup trade-offs remain open, including completion hooks skipped by dynamic plugin disabling. Please don't treat that prototype as a required implementation or a merge-ready fix. A smaller design would be welcome; the maintainers can guide the preferred state owner.
No RouteContract installation is needed for these advice-level regressions. If you share a draft, I can compare its behavior with the existing repro cases.
I opened PR #40097 to fix this. The advice stored the started span in the single attachment slot of the shared JDBCExecutorCallback target, so an overlapping invocation overwrote the slot before the first invocation reached its completion hook. The fix tracks active spans in a per-thread stack (push in the advice start, pop in the completion hooks), which pairs correctly for nested invocations on one thread and for overlapping invocations across threads. The new assertConcurrentInvocations test follows the deterministic scenario from this issue.