Comprehensive Technical Documentation

Ariadne Technical Reference Manual

An in-depth guide to Ariadne's internal mechanics, micro-allocation primitives, runtime bytecode instrumentation, reactive stream hooks, and distributed observability bridges.

1. Introduction & Motivation

In modern JVM systems, asynchronous programming models—including thread pools, CompletableFuture, Project Reactor, RxJava, and Java 21 Virtual Threads—introduce severe observability challenges. When an execution fails on a worker thread, standard JVM stack traces are severed at the async boundary. Developers are left with blind, truncated exceptions that show where the code crashed, but not who scheduled it or why it was called.

Ariadne solves this problem. It maintains a continuous causal record across threads with sub-microsecond overhead, reconstructing the full asynchronous ancestry only when an error actually occurs.

2. The Asynchronous Blind Spot Problem

When a method executes synchronously on a single JVM thread, the thread's call stack directly records the entire hierarchy of callers. If an exception is thrown, Throwable.fillInStackTrace() captures this call stack directly from the JVM frame pointers.

However, when execution crosses an asynchronous boundary (for example, submitting a Runnable to an ExecutorService or chaining a Mono.publishOn() in Reactor), the caller thread simply places a task descriptor onto a queue and returns immediately.

The Fundamental Dilemma

Traditional debuggers attempt to solve this by creating a new Throwable() on every single operator creation or scheduling call. Because 99.9% of tasks succeed, this generates massive object allocation, triggers heavy Garbage Collection pauses, and incurs a 10x to 100x throughput penalty. Consequently, tools like Reactor's Hooks.onOperatorDebug() are strictly prohibited in production.

3. Core Mechanical Architecture

Ariadne resolves this dilemma by decoupling causal tracking from stack trace synthesis:

  1. Scheduling Time (Happy Path): When a task is queued, Ariadne allocates a single immutable 40-byte pointer node (Link) in thread-local TLAB memory. Call sites are statically cached in a lock-free registry (SiteRegistry) with zero runtime object allocation during lookup (0 B).
  2. Execution Time: The worker thread attaches the Link to its active context for the duration of the task, ensuring nested asynchronous spawns inherit their parent.
  3. Failure Time (Exception Path): If an exception occurs, Ariadne walks the lightweight linked list backwards, queries the interned call-site registry, synthesizes an AsyncCausalityException, and attaches it via Throwable.addSuppressed().

5. Lazy Backward Synthesis

When an exception escapes an instrumented task, AriadneReconstructor.enrich(Throwable) activates:

  • Traverses the Link hierarchy up to a configurable maximum depth (default: 32 hops).
  • Resolves each siteId to its class name, method name, file name, and line number from the SiteRegistry.
  • Constructs an AsyncCausalityException containing synthesized StackTraceElement frames mapping directly to originating call sites.
  • Appends contextual payloads (such as MDC diagnostic maps) to the exception message.
  • Attaches the synthesized cause to the original throwable using Throwable.addSuppressed(), preserving the original exception class and stack.

6. Modular Ecosystem Overview

Module Artifact Primary Responsibility
Core ariadne-core Micro-allocation engine, Link, ContextCarrier, W3CTraceContext, and reconstructor. Zero external dependencies. Micro-allocation engine, Link, ContextCarrier, and reconstructor. Zero external dependencies.
Agent ariadne-agent ByteBuddy Java Agent for zero-code instrumentation of thread pools and virtual threads.
Reactor ariadne-adapter-reactor Scheduler decorator and operator error hooks for Project Reactor.
RxJava ariadne-adapter-rxjava Schedule handlers for RxJava 3 schedulers (computation, io, single).
MDC ariadne-adapter-mdc Transparent propagation of SLF4J Mapped Diagnostic Context across threads.
Benchmarks ariadne-benchmarks Comprehensive JMH microbenchmark harness.

7. Zero-Code Java Agent

The ariadne-agent module is packaged as a standard Java Agent using ByteBuddy:

java -javaagent:ariadne-agent-0.1.0-beta.1.jar -jar application.jar

Upon JVM startup, the agent dynamically attaches byte-code advice to:

  • java.util.concurrent.Executor.execute(Runnable)
  • java.util.concurrent.ExecutorService.submit(Callable) and submit(Runnable)
  • java.util.concurrent.ScheduledExecutorService.schedule(...), scheduleAtFixedRate, and scheduleWithFixedDelay
  • java.util.concurrent.ForkJoinPool (via ExecutorService.execute(Runnable) / submit())
  • java.util.concurrent.CompletableFuture asynchronous supplier, action stages, and delayedExecutor.
  • Java 21 Thread.ofVirtual().start(Runnable) and Thread.startVirtualThread(Runnable).

The agent automatically checks for the presence of Project Reactor, RxJava, and SLF4J on the application classpath and installs the corresponding adapters without requiring configuration.

8. Reactive Framework Adapters

Project Reactor (ariadne-adapter-reactor)

Attaches to Reactor via Schedulers.onScheduleHook() and Hooks.onOperatorError(). When a task is scheduled on Schedulers.boundedElastic() or Schedulers.parallel(), the active Link is automatically captured and restored during subscription and emission.

RxJava 3 (ariadne-adapter-rxjava)

Utilizes RxJavaPlugins.setScheduleHandler() to wrap Runnable instances before they are dispatched to Schedulers.io() or Schedulers.computation().

9. SLF4J MDC Log Propagation

In distributed microservices, correlation identifiers such as traceId, spanId, and userId are placed in the SLF4J MDC (Mapped Diagnostic Context). Because MDC relies on ThreadLocal, switching threads causes all contextual logging data to vanish.

With ariadne-adapter-mdc:

  1. When AriadneContext.spawn() occurs, the adapter captures a snapshot via MDC.getCopyOfContextMap().
  2. When the worker thread executes the task, it binds the snapshot to the worker thread's MDC.
  3. When the task completes, it cleans up and restores the previous thread context, preventing thread-pool cross-contamination.

10. W3C Tracing & OpenTelemetry

Ariadne natively integrates with the W3C Trace Context standard via TraceContext and TraceContexts:

  • Parses and formats traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01 and optional tracestate.
  • Zero dependencies: strict validation and fast-path hex formatting with sub-nanosecond parsing.
  • Carries ambient trace identity seamlessly alongside the causal Link chain across thread pools, CompletableFuture, and Reactive streams.

Additionally, AriadneOtelBridge (in ariadne-adapter-otel) provides a pure reflection bridge to OpenTelemetry's Span.current():

// Enable via JVM argument or code:
-Dariadne.otel.bridge.enabled=true

// Or programmatically:
AriadneOtelBridge.install();

When an asynchronous failure occurs, Ariadne attaches the correlated W3C trace directly to the synthetic causality exception: [Trace: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01], uniting JVM exceptions with APM trace visualization.

11. Java 21 Scoped Values & Loom

In Java 21, millions of lightweight Virtual Threads can be created concurrently. Traditional ThreadLocal variables can create memory retention leaks if not meticulously cleaned up.

Ariadne's ScopedValueContextCarrier utilizes JDK 21 java.lang.ScopedValue:

  • Values are immutable and bound strictly to lexical execution scopes.
  • Inherited automatically by child threads forked inside Structured Concurrency blocks (StructuredTaskScope).
  • Provides runWhere(Link, Runnable) and callWhere(Link, Callable).
  • Implemented dynamically via MethodHandle reflection so code compiles on standard Java 21 LTS without requiring compile-time preview flags.
ScopedValueContextCarrier carrier = ScopedValueContextCarrier.install();
carrier.runWhere(link, () -> {
    // Immutable lexical binding active for current and child structured threads
    processTask();
});

12. Kotlin Coroutines Bridge

When using Kotlin Coroutines, tasks suspend and resume across different threads and dispatchers. Ariadne's AriadneCoroutineBridge (in ariadne-adapter-kotlin) hooks directly into coroutine scheduling:

// In Kotlin coroutine code:
launch(Dispatchers.Default + AriadneCoroutineBridge.asElement()) {
    delay(100) // Suspends and resumes on a different worker thread
    // Causality is strictly maintained across suspend/resume points!
    fetchOrder()
}

// Exception handler integration:
val handler = CoroutineExceptionHandler { ctx, exception ->
    AriadneCoroutineBridge.enrich(ctx, exception)
    logger.error("Coroutine failed", exception)
}

13. Dynamic Configuration, Fail-Safe & Production Controls

System Property Environment Variable Default Description
ariadne.enabled ARIADNE_ENABLED true Master Kill Switch: Completely disables agent interception and causal tracking.
ariadne.excludes ARIADNE_EXCLUDES (none) Comma-separated class/package exclusion patterns (e.g. com.sensitive.*,org.apache.tomcat.*).
ariadne.exception.context.enabled ARIADNE_EXCEPTION_CONTEXT_ENABLED false Data Leakage Prevention: Controls whether MDC/context is attached to exception messages. Disabled by default to prevent tokens or PII leaking to logs.
ariadne.mdc.allowlist ARIADNE_MDC_ALLOWLIST traceId,spanId,correlationId,traceparent,requestId,tenant Allowlist of permitted MDC keys rendered in exception messages when context is enabled.
ariadne.max.depth ARIADNE_MAX_DEPTH 32 Maximum async causality hops reconstructed (1 to 1024). Enforces memory bounding and sliding window.
ariadne.canary.probes.enabled ARIADNE_CANARY_PROBES_ENABLED true Enables automated self-tests on adapter startup.
ariadne.fail.fast ARIADNE_FAIL_FAST false Throws exceptions immediately if framework hooks conflict.
ariadne.mdc.enabled ARIADNE_MDC_ENABLED true Controls automatic SLF4J MDC context propagation across async boundaries.
ariadne.jmx.enabled ARIADNE_JMX_ENABLED true Registers MBean io.ariadne:type=AriadneManager for live reconfiguration.
ariadne.trace.context.enabled ARIADNE_TRACE_CONTEXT_ENABLED false Enables automatic W3C traceparent capture and propagation alongside causal link chains.
ariadne.otel.bridge.enabled ARIADNE_OTEL_BRIDGE_ENABLED false Enables pure reflection bridge to OpenTelemetry Span.current() for log correlation.

Production Robustness & Safety Guarantees

1. Total Fail-Safe Guarantee

Every ByteBuddy advice method (CompletableFutureAdvice, ExecutorAdvice, ThreadAdvice), runtime wrapper (AriadneRunnable, AriadneCallable), and reconstructor method (AriadneReconstructor.enrich) is encapsulated in top-level try-catch (Throwable) blocks. Under no circumstances—including out-of-memory, classloading conflicts, or malicious tasks throwing during inspection—will Ariadne disrupt or crash the host application. If an exception occurs, the original user exception is preserved and re-thrown unaltered.

2. Data Leakage Prevention (MDC Allowlist)

Exceptions often end up in monitoring platforms (Sentry, Datadog, CloudWatch). Attaching raw MDC contexts risks leaking sensitive credentials (JWTs, session tokens, passwords, SSNs). Ariadne enforces:

  • Disabled by Default: Context attachments in exception messages are turned off by default (ariadne.exception.context.enabled=false).
  • Strict Allowlist: When enabled, only keys explicitly specified in ariadne.mdc.allowlist are rendered.
  • Bounded Footprint: Enforces a hard cap of 50 entries and truncates values exceeding 512 characters with ...[truncated] to prevent log flooding or OOM.

3. Chain Origin Preservation (Root Tradeoff in Sliding Window)

Standard FIFO sliding windows drop the oldest elements first when depth limits are reached. In web applications, the oldest hop is the HTTP Controller / ingress request handler—the single most important anchor for debugging. Ariadne implements root origin preservation:

  • The root origin hop (parent == null) is permanently pinned at the base of the chain.
  • The sliding window retains the most recent (maxDepth / 2 - 1) hops leading directly up to the error.
  • Tradeoff: Intermediate hops between the root origin and the sliding window are pruned, bounding memory to O(maxDepth) to prevent memory retention leaks in unbounded reactive streams while guaranteeing that both the root cause ingress and the immediate failure context are retained.

4. Spring Boot Startup Impact & Type Matcher Optimization

ByteBuddy's hasSuperType(Executor) inspects class hierarchies during loading. To prevent startup degradation in large frameworks (Spring Boot, Tomcat, Netty), Ariadne applies fast-path ignore matchers:

  • Skips framework internal bytecode: org.springframework.cglib.*, org.objectweb.asm.*.
  • Skips logging frameworks: ch.qos.logback.*, org.slf4j.*.
  • Evaluates dynamic class exclusion filter: AriadneConfig.isClassExcluded().
  • Empirical Startup Impact: On a standard Spring Boot application context (with @EnableAsync, ThreadPoolTaskExecutor, Reactor, and MDC), startup time was measured at ~10 to 13 ms, with negligible delta (< 5 ms overhead), proving zero startup friction in enterprise microservices.

14. Microbenchmarks & Performance

Conducted using JMH 1.37 on Linux (Java 21 LTS, 3+ isolated JVM forks, 5 warmup + 5 measurement iterations, compiler blackholes, -prof gc):

Benchmark Operation Observed Latency / Overhead Memory Impact & Analysis
Context Lookup (current()) 1.43 ns 0.0 B — Direct ThreadLocal carrier access at CPU L1 cache speed (1.427 ns/op).
Direct Link Allocation 1.55 ns 40.0 B — Exact object footprint on 64-bit JVM with Compressed OOPs (1.547 ns/op).
Context Hop (spawn) 7.05 ns 40.0 B — Atomic TLAB allocation + depth bound check (7.047 ns/op).
Scoped Attach & Close (contextAttachAndScope) 10.28 ns 0.0 B — ThreadLocal pooling of ReusableScope (zero allocation in try-with-resources).
Cached Site Lookup (cachedSiteRegistryLookup) 1.25 ns 0.0 B — Lock-free BY_DESCRIPTION cache with direct lookup (1.245 ns/op).
Call Site Resolution (CLASS mode) 5.29 ns 0.0 B — ClassValue<Integer> zero-allocation lambda/caller resolution.
Call Site Resolution (SAMPLED:100 mode) 21.11 ns 10.1 B — 1:100 StackWalker sampling with ClassValue cache fallback.
Call Site Resolution (FULL mode) 1320.26 ns (~1.32 µs) 1000.0 B — Uncached StackWalker traversal per asynchronous dispatch.
Single-Hop CompletableFuture (Wrapped) 18.84 µs vs 18.99 µs baseline 216.0 B vs 160.1 B baseline — Overhead within statistical error margin.
Multi-Hop CompletableFuture (Wrapped) 18.69 µs vs 18.42 µs baseline 536.3 B vs 368.0 B baseline — Minimal overhead (+0.27 µs, +168.3 B).
Agent CompletableFuture Pipeline 19.60 µs (Single) / 19.03 µs (Multi) 328.9 B / 856.7 B — Full ByteBuddy agent auto-instrumentation.
Virtual Thread Dispatch 18.07 µs vs 17.55 µs baseline 624.1 B vs 368.1 B baseline — Java 21 Virtual Threads (Thread.ofVirtual).
Project Reactor (Mono Hop) 19.13 µs vs 18.85 µs baseline (+1.5%) 488.0 B — ~5.8x less allocation than Hooks.onOperatorDebug() (2848.1 B).
Project Reactor (Flux Hop) 20.87 µs vs 20.62 µs baseline (+1.2%) 3864.1 B — ~1.8x less allocation than Hooks.onOperatorDebug() (7064.4 B).
Spring Boot Under Load (16 Workers, 25k Reqs) 145,389 req/s vs 138,506 req/s baseline p50: 86.9 µs (+1.9% delta), p99: 427.9 µs tail; 30,002 causal hops actively tracked.

Ariadne vs. OpenTelemetry: Benchmark & Architecture Analysis

While OpenTelemetry is designed for distributed tracing across network boundaries, Ariadne is purpose-built for zero-overhead in-process causal reconstruction within the JVM.

Operation / Dimension Baseline Ariadne OpenTelemetry Java SDK Analysis
Trace Node Creation (Link vs. Span) — 8.16 ns / 40.0 B 115.62 ns / 368.0 B Ariadne is 14.2x faster, 9.2x less memory.
Direct Link Allocation — 4.41 ns / 40.0 B 115.62 ns / 368.0 B 26x faster (TLAB immutable node).
Scope Activation (try-with-resources) — 11.24 ns / 0.0 B 4.63 ns / 32.0 B Ariadne allocates 0 B; OTel allocates 32 B per scope.
Context Read (current) — 1.60 ns / 0.0 B 0.90 ns / 0.0 B Pure ThreadLocal carrier reads.
Java 21 Virtual Threads 3.25 µs / 399.9 B 3.02 µs / 656.0 B 3.14 µs / 560.0 B Both match Loom scheduler performance.
Platform Thread Pool Submit 5.03 µs / 112.2 B 5.83 µs / 168.2 B 5.08 µs / 136.2 B Sub-microsecond execution overhead.
CompletableFuture Single-Hop 5.11 µs / 160.2 B 5.71 µs / 213.4 B 5.08 µs / 194.8 B Minimal propagation overhead (<60 B).
Symbiosis With AriadneOtelBridge, Ariadne captures the active OTel Span identity at zero runtime overhead and attaches it to JVM exception logs ([Trace: 00-...-01]), uniting in-process call stacks with distributed traces.

Run this head-to-head benchmark on your own machine:

java -jar ariadne-benchmarks/target/benchmarks.jar OpenTelemetryComparisonBenchmark -f 1 -wi 2 -i 3 -prof gc

15. Global Static State: Architecture & Operational Limitations

To instrument code transparently without polluting enterprise domain APIs, Ariadne relies on well-scoped global static components. Understanding the concurrency model and operational limitations inherent to this design is essential:

1. Global Call Site Registry (SiteRegistry) and ClassLoader Safety

The SiteRegistry stores call site metadata in static concurrent maps (ConcurrentHashMap). To guarantee immunity against memory leaks (ClassLoader leaks) in application containers (Tomcat, Jetty, WebLogic):

  • ClassLoader Decoupling: The CallSiteMetadata record strictly holds primitive types and String instances. It maintains no strong or weak references to Class<?> or ClassLoader instances. Unloading a WAR/EAR application is never prevented by the registry.
  • Automatic Cleanup via ClassValue: The ClassValue<Integer> cache associates the site ID directly with the target class's internal metadata. When a dynamically generated class or lambda is collected by the JVM Garbage Collector, its corresponding entry is automatically purged without manual intervention.
  • Heap Overflow Protection (Bounded Capacity): The registry is bounded by -Dariadne.registry.max_sites (default: 65,536). If dynamically generated code creates infinite scripts in a loop, the registry gracefully degrades to a generic fallback ID instead of permitting unbounded heap growth.
  • Explicit Lifecycle Management: Exposes SiteRegistry.clear() and SiteRegistry.size() for invocation in ServletContextListener.contextDestroyed() or automated integration test suites.

2. Thread Isolation and Context Leak Prevention (ThreadLocalContextCarrier)

Causal linkage across threads is propagated via ThreadLocal. In reusable thread pools (such as ForkJoinPool or ThreadPoolExecutor), failing to clear a reference would cause cross-task context pollution. Ariadne structurally guarantees cycle integrity: all execution wrappers (AriadneRunnable, AriadneCallable) and Java Agent advices implement mandatory try-finally blocks with attach() and close(), strictly restoring the thread's original context state.

3. Bootstrap ClassLoader Injection & Multi-Tenant Environments

For core JDK classes (java.base, such as CompletableFuture and ThreadPoolExecutor) to invoke the causality engine without module boundary linkage errors, the Java Agent appends the core JAR to the Bootstrap ClassLoader search path via Instrumentation.appendToBootstrapClassLoaderSearch.

Implication for Enterprise Containers (EAR / WAR / OSGi): Because bootstrap-injected classes reside at the root of the JVM classloader hierarchy, their static state is shared across all applications running in the same JVM process. In multi-tenant environments where multiple WARs share a single JVM instance, asynchronous causality chains remain isolated per thread/link, but the metadata registry is shared globally.

4. Call Site Resolution Modes and Empirical Costs (CallSiteMode)

Ariadne provides three call site capture strategies configurable via -Dariadne.callsite.mode=class | sampled:N | full (or the ARIADNE_CALLSITE_MODE environment variable) and dynamically modifiable at runtime via JMX (io.ariadne:type=Ariadne):

  • CLASS (Default, Recommended for Production): Uses ClassValue<Integer> to cache the caller class name derived from the lambda/runnable class (e.g., PaymentService.lambda(PaymentService.java)). Measured latency: 5.29 ns/op with 0.0 B/op allocation (completely avoids StackWalker on hot paths).
  • SAMPLED:N: Samples 1 in every N dispatches with full StackWalker traversal to capture exact method name and line number, serving the remainder via ClassValue. For N=100: 21.11 ns/op and 10.1 B/op.
  • FULL: Executes StackWalker on every asynchronous dispatch to capture caller method and exact source line (e.g., PaymentService.processPayment(PaymentService.java:16)). Latency: 1320.26 ns/op (~1.32 µs/op) and 1000.0 B/op. Recommended for staging environments, canary testing, and targeted local debugging.

16. Getting Started & Installation

Option A: Zero-Code Java Agent (Recommended)

Download ariadne-agent-0.1.0-beta.1.jar from the GitHub Releases page and add the flag to your JVM startup script:

java -javaagent:/path/to/ariadne-agent-0.1.0-beta.1.jar -jar your-app.jar

Option B: Programmatic Maven Dependency

<dependency>
    <groupId>io.github.afonsopaiva</groupId>
    <artifactId>ariadne-core</artifactId>
    <version>0.1.0-beta.1</version>
</dependency>