diff --git a/README.md b/README.md index 7c766fb..56b2eb8 100644 --- a/README.md +++ b/README.md @@ -25,11 +25,15 @@ Keploy Enterprise drives dynamic dedup per testcase. Coverage is collected at per-testcase granularity, not process granularity. -A server sends a response before it is done with the request: a filter's code after the chain (a request log, an authentication filter's cleanup) runs after Enterprise has the response and has sent `END`. Since 2.2.0 the agent counts the requests of Tomcat (8.5 to 11), Jetty (9.4 to 12.1) and Undertow, Spring Boot's three servers, from where the server starts running a request to where its response is finished, and each async dispatch of it alike, and `END` first waits until every request that came in since the testcase's `START` is done, for at most `KEPLOY_JAVA_END_WAIT_MS` (200 ms by default, 2 s at most). A request that comes in once `END` has come (a readiness probe, a metrics scrape, or a call the testcase's own code makes after its response) is not waited for. Before, `END` read the probes at once, so under load that code was missed, and the next `START` cleared it as background: the same testcase had different coverage from run to run. A request that is done costs `END` nothing, and a request that came in before the `START` (a stream, a request of the testcase before) is never waited for. When the wait reaches its bound, the log says so at WARNING and the testcase's record ends with `"windowCut":true` (after `classMismatch`; left out otherwise): it holds what was read then, a Keploy that reads the flag does not judge that testcase (an older one judges the hits the record holds), and what the next `START` clears is not sent as background. Limits: what the application runs on threads of its own (an async task on anything but the Spring executors below, an executor's work between two dispatches of an async request, unless the executor is one of those, an Undertow completion listener that runs on the IO thread after an async write) is not counted; Netty, and so WebFlux, is not counted, nor is a server whose classes were loaded before the agent started (it is attached to a running JVM) or whose class loader does not see the agent's classes (a module system such as JBoss Modules); the log says once when a testcase's `END` does not wait, and why. To count them, the agent changes the one method of each server that runs a request (Tomcat's `CoyoteAdapter.service` and `asyncDispatch`, Jetty's `HttpChannel.handle` or, on Jetty 12, its servlet channel's `handle`, Undertow's `Connectors.executeRootHandler`) as the class loads: the server's own code moves to a private method `keploy$request$` beside it, which shows in a stack trace and keeps the method's annotations; the method of the old name, which counts the request and calls it, carries none, so reflection that reads the annotations of `service` itself finds none. The agent makes its change after those of every agent that cannot retransform classes, JaCoCo's among them, whatever the order the agents are attached in: a JaCoCo agent attached before or after keploy-sdk.jar, or in `JAVA_TOOL_OPTIONS`, instruments the server's own class, so `classMismatch` never names it for that. When another agent retransforms or redefines the class later (an APM agent, a profiler, a hot-swap tool), the agent makes its change again, unless the new bytes already carry it (a copy taken from the class as the agent changed it). +A server sends a response before it is done with the request: a filter's code after the chain (a request log, an authentication filter's cleanup) runs after Enterprise has the response and has sent `END`. Since 2.2.0 the agent counts the requests of Tomcat (8.5 to 11), Jetty (9.4 to 12.1) and Undertow, Spring Boot's three servers, from where the server starts running a request to where its response is finished, and each async dispatch of it alike, and `END` first waits until every request that came in since the testcase's `START` is done, for at most `KEPLOY_JAVA_END_WAIT_MS` (200 ms by default, 2 s at most). A request that comes in once `END` has come (a readiness probe, a metrics scrape, or a call the testcase's own code makes after its response) is not waited for. Before, `END` read the probes at once, so under load that code was missed, and the next `START` cleared it as background: the same testcase had different coverage from run to run. A request that is done costs `END` nothing, and a request that came in before the `START` (a stream, a request of the testcase before) is never waited for. When the wait reaches its bound, the log says so at WARNING and the testcase's record ends with `"windowCut":true` (after `classMismatch`; left out otherwise): it holds what was read then, a Keploy that reads the flag does not judge that testcase (an older one judges the hits the record holds), and what the next `START` clears is not sent as background. Limits: work handed to unverified custom executors, untracked async primitives (`ScheduledExecutorService.schedule*`, `ExecutorService.invokeAny`, `Thread.start()`, `ForkJoinTask.fork()`, Reactor `subscribe()`, async method references), or an Undertow completion listener running on the IO thread after an async write is not waited for — instead the active window and following tail window are marked contaminated so dedup fails closed (see below); Netty/WebFlux, gRPC, Vert.x, Micronaut, and JDK `HttpServer` are not counted, nor is a server whose classes were loaded before the agent started (attached to a running JVM) or whose class loader does not see the agent's classes (a module system such as JBoss Modules); the log says once when a testcase's `END` does not wait, and why. To count them, the agent changes the one method of each server that runs a request (Tomcat's `CoyoteAdapter.service` and `asyncDispatch`, Jetty's `HttpChannel.handle` or, on Jetty 12, its servlet channel's `handle`, Undertow's `Connectors.executeRootHandler`) as the class loads: the server's own code moves to a private method `keploy$request$` beside it, which shows in a stack trace and keeps the method's annotations; the method of the old name, which counts the request and calls it, carries none, so reflection that reads the annotations of `service` itself finds none. The agent makes its change after those of every agent that cannot retransform classes, JaCoCo's among them, whatever the order the agents are attached in: a JaCoCo agent attached before or after keploy-sdk.jar, or in `JAVA_TOOL_OPTIONS`, instruments the server's own class, so `classMismatch` never names it for that. When another agent retransforms or redefines the class later (an APM agent, a profiler, a hot-swap tool), the agent makes its change again, unless the new bytes already carry it (a copy taken from the class as the agent changed it). -The work a request hands to a Spring executor (Spring 5.3 to 6.2) counts as the request's too (since 2.2.0): an event listener on an async event multicaster (a `SimpleAsyncTaskExecutor`), a task given to a `ThreadPoolTaskExecutor` (`execute`, `submit`, `submitListenable`, and `submitCompletable`, which Spring runs through `execute`), and an `@Async` method, whatever its executor. `END` waits for that work under the same bound, from the hand-off until the task returns or throws, and a testcase whose work still runs at the bound says `windowCut`. Only work handed off on a thread that runs a counted request, or on one that runs such work, counts: what a scheduler or the application's own threads hand off is not waited for (what a Quartz job or an `@Scheduled` method hands off counts as that job's run instead; see the next paragraph). A task the executor rejects by throwing (a `TaskRejectedException`, a shut-down executor unless its policy is `CallerRunsPolicy`, which then drops the task) is not waited for. A task it drops without throwing (a pool with a `DiscardPolicy` or `DiscardOldestPolicy`), and a task whose `Future` is cancelled or completed before it starts (in a `ThreadPoolTaskExecutor`'s queue, or an `@Async` method's `Future` or `CompletableFuture` that the caller cancels or completes, as `orTimeout` does), hold that testcase's wait to its bound, and it says `windowCut`. Work handed to a plain `java.util.concurrent` executor, a thread or `Timer` the application starts, or a message listener is not counted. A task handed to a `ThreadPoolTaskExecutor` whose pool may order its tasks by their own type goes to it as it is and is not counted: not waited for, and not a job's run. That is a pool whose queue's class is not one of the JDK's queues that keep tasks in the order they came (`LinkedBlockingQueue` or `SynchronousQueue`, the two Spring builds, `ArrayBlockingQueue`, `LinkedBlockingDeque` or `LinkedTransferQueue`), such as a `PriorityBlockingQueue` or a queue with a `Comparator`, or a pool that cannot be read (nothing thrown while reading it or logging it reaches the app's call); the log says so at `INFO`, once for each such executor class (not for a `ThreadPoolTaskExecutor` whose `getThreadPoolExecutor()` is Spring's own and is not initialized yet: its own call then throws, as it does without the agent; nor for a read that runs out of stack or memory: that task goes as it is, and the next one reads the pool again). A task that is `Comparable` goes as it is too, to any executor. Any other task the agent counts reaches the executor in a wrapper of the agent's, a `Future` when the task is one. So an executor whose `TaskDecorator`, `newTaskFor`, `beforeExecute` or `afterExecute` casts the task to its own type fails with a `ClassCastException`, thrown from `execute` or `submit` (from `beforeExecute` or `afterExecute`, on the pool's thread), and one that only checks the task's type sees the wrapper and loses that check's effect. Such an application makes the task itself `Comparable` (it then goes as it is) or sets `KEPLOY_JAVA_DEDUP_DISABLED=true`: `KEPLOY_JAVA_END_WAIT_MS=0` does not help, as the executors are changed with the wait off too. The agent changes `SimpleAsyncTaskExecutor.doExecute`, `ThreadPoolTaskExecutor`'s `execute`, `submit` and `submitListenable`, and `AsyncExecutionAspectSupport.doSubmit` as their classes load, as it changes a server's method (the executor's own code moves to `keploy$async$`), whether or not the wait is on: with the wait off, only a job's hand-offs count, as no request does. +The work a request hands to a Spring executor (Spring 5.3 to 6.2) or to verified standard JDK executors and `CompletableFuture` / `CompletionStage` stages from application code counts as the request's too: an event listener on an async event multicaster (a `SimpleAsyncTaskExecutor`), a task given to a `ThreadPoolTaskExecutor`, `ThreadPoolTaskScheduler`, or `ConcurrentTaskExecutor` (`execute`, `submit`, `submitListenable`, and `submitCompletable`), an `@Async` method, and rewritten application call sites of `Executor`/`ExecutorService`/`ThreadPoolExecutor`/`ScheduledThreadPoolExecutor`/`ForkJoinPool` (`execute`, `submit`, `remove`, `shutdownNow`) and `CompletableFuture` / `CompletionStage` (`runAsync`, `supplyAsync`, `completeAsync`, `*Async` instance methods, and plain dependent stages registered on incomplete futures such as external library `HttpClient.sendAsync().thenAccept(...)`). `END` waits for that work under the same bound, from the hand-off until the task (and any synchronous `CompletableFuture` dependent stage registered before completion) returns or throws, and a testcase whose work still runs at the bound says `windowCut`. Whenever a testcase is cut at `END`, a new `START` arrives without a preceding `END`, or a window records an untracked async hand-off, subsequent windows are marked contaminated (`"tail:"`) until prior lingering work drains (or the untracked tail window elapses). Only work handed off on a thread that runs a counted request, or on one that runs such work, counts: what a scheduler or the application's own threads hand off is not waited for (what a Quartz job, an `@Scheduled` method, or a message listener hands off counts as that job's run instead; see the next paragraph). A task the executor rejects by throwing or whose `Future` is cancelled, removed, or drained via `shutdownNow()` before starting releases its permit promptly. -A scheduled job that runs while a testcase runs puts its lines in that testcase's coverage: JaCoCo's probes do not say which thread hit them. Since 2.2.0 the agent sees each run of a Quartz job (1.x and 2.x, and Spring's Quartz support) and of a Spring `@Scheduled` method, and a testcase whose window a run overlapped, from its `START` to the read of its probes at `END` (a job already running at the `START` counts), names the jobs in `"contaminated":["quartz:." | "scheduled:.", ...]` after `windowCut`: at most 8 names, then `"+N"` for N more; left out when none ran. The probes stay in the record; a Keploy that reads the key does not judge that testcase (an older one ignores the key). A job that ends before a `START` is not named: the `START` clears what it ran. The work a job's run hands to those Spring executors (an event its run publishes to an async multicaster, a task it submits, an `@Async` method it calls) counts as a run of the same job, with the same name, from when the task starts until it returns or throws, whether or not `END` waits: so a testcase whose window the listener runs in is named, even when the job itself returned before that testcase's `START`. What that task hands off counts the same way. `END` does not wait for it. Costs: a lock taken once at each `START` and `END`, and twice per job run, and per job run a reflective read of its name (microseconds), whether or not a testcase runs. Limits: work on threads the application starts itself, a custom executor or a `java.util.Timer`, a message listener, and a testcase's own async work that runs past its `END` on an executor other than the Spring ones above are not seen; a Spring task registered as a plain `Runnable` (a `SchedulingConfigurer`) is not seen either, nor a reactive (`Publisher`-returning) or Kotlin `suspend` `@Scheduled` method, which Spring 6.1+ runs through another class. Code a job's run reaches outside those two methods is not counted: a Quartz job's creation (a `JobFactory`, or Spring's autowiring of the job) and a Spring `ErrorHandler` called after a `@Scheduled` method threw. No job run is seen when the agent was never started as a `-javaagent` in the JVM (attached to a running JVM, or started from the application's code; the log says so at INFO at each such start), nor when either class loaded before the agent started. A job that runs for the whole of a testcase run (a polling loop) names every testcase. To see the runs, the agent changes `org.quartz.core.JobRunShell.run()` and Spring's `ScheduledMethodRunnable.run()` as their classes load, the way it changes a server's request method: the job's own code moves to a private method `keploy$job$run`, and the change is made again when another agent retransforms the class; a class whose loader does not see the agent's classes is left as it is, and the log says so. +Executor wrapping is **fail-closed**: only positively verified safe executors (exact `ThreadPoolExecutor` / `ScheduledThreadPoolExecutor` with exact `AbortPolicy` and an exact in-order JDK queue — `LinkedBlockingQueue`, `SynchronousQueue`, `ArrayBlockingQueue`, `LinkedBlockingDeque`, or `LinkedTransferQueue` — exact `ForkJoinPool`, verified JDK `Delegated*` / `ThreadPerTaskExecutor`, and known Spring executor/adapter types whose subclasses do not override `execute`/`submit`/`doExecute` and whose inner pool is allow-listed) are wrapped. Known same-thread inline executors (`org.springframework.core.task.SyncTaskExecutor` and Guava `com.google.common.util.concurrent.DirectExecutor` / `MoreExecutors.directExecutor()` / `DirectExecutorService`) are allow-listed so they are neither wrapped nor flagged (the task runs inline on the request thread). Plain non-`Executor` synchronous helpers with an `execute(Runnable)` or `submit(...)` method are checked at runtime (`instanceof Executor` / `ExecutorService` / `CompletionService` / Spring `AsyncTaskExecutor`) and are never flagged. Any unknown or custom executor (such as Hazelcast `IExecutorService`, Ignite, Redisson, striped/keyed executors, coalescing executors, custom `ExecutorService` / `ThreadPoolExecutor` / Spring executor subclasses, priority queues, or non-`AbortPolicy` handlers) and any `Comparable` task receives the application's original task untouched so application serialization, ordering, and `instanceof` checks are preserved, while the active testcase window (and subsequent tail window) is marked contaminated (`"untracked-executor:"`). Similarly, untracked async submission sites inside a request or job (`ScheduledExecutorService.schedule*` and Spring `TaskScheduler.schedule*` with weak `ScheduledFuture` liveness tracking until done/cancelled — with verified JDK `ScheduledThreadPoolExecutor` also propagating request/job context across multi-hop retries and downstream fan-outs without blocking `END`, `java.util.Timer.schedule*` / `scheduleAtFixedRate*` with `TimerTask` liveness and cancellation tracking, `ExecutorService.invokeAny`, `Thread.start()` including subclasses via runtime `instanceof Thread` check and JDK 21 `Thread.startVirtualThread` / `Thread.Builder.start` with weak `Thread.isAlive()` liveness tracking, non-JDK/custom executor `execute`/`submit` decided by runtime receiver, `ForkJoinPool.execute`/`submit(ForkJoinTask)` and `ForkJoinTask.fork()`, Guava `ListenableFuture.addListener` / `Futures.addCallback` / `transform*` / `catching*`, Reactor `Mono`/`Flux`/`ParallelFlux` `.subscribe()`, custom `CompletionStage`, and async method references such as `executor::execute`) mark the originating window contaminated (`"untracked-async:"` / `"untracked-executor:"`). When a concrete handle (`ScheduledFuture`, `Thread`, `TimerTask`) is tracked, its liveness alone drives subsequent `tail:` contamination (so a 30 s timeout cancelled before returning, a `Thread.start()` + `join()` finished before the response, or a cancelled `TimerTask` leaves subsequent windows clean). Plain dependent stages on `CompletableFuture` subclasses that inherit dependent methods and `whenComplete` directly (including JDK `HttpClient.sendAsync`'s `MinimalFuture` and JDK `MinimalStage`) are tracked without throwing `UnsupportedOperationException`, and abandoned futures collected by GC release their window permits automatically via `ReferenceQueue` (with a 30 s cap on idle uncompleted permits while actively executing work remains tracked until exit and any late-starting task contaminates the currently open window). Limits: on JDK 16+ without `--add-opens java.base/java.util.concurrent=ALL-UNNAMED`, `Executors.unconfigurableExecutorService(...)`, `Executors.newSingleThreadScheduledExecutor()`, and any `Executors$DelegatedExecutorService` / `DelegatedScheduledExecutorService` wrapper (including `Executors.newSingleThreadExecutor()` when backed by `DelegatedExecutorService` rather than `FinalizableDelegatedExecutorService` / `AutoShutdownDelegatedExecutorService`) cannot be reflectively inspected and fall back to `untracked-executor:java.util.concurrent.Executors$Delegated*`; custom `ScheduledExecutorService` implementations, raw `Thread` / virtual threads, `Timer`, and Spring `TaskScheduler` run tasks unwrapped (app-safe), so nested async hops spawned inside them are not tracked beyond the parent handle's lifetime; RxJava schedulers/observables and Kotlin coroutines are not intercepted. Set `KEPLOY_JAVA_ASYNC_CALLSITES=off` to disable JDK executor and `CompletableFuture` call-site rewriting completely (declaring `asyncExecutors=false`). In external-JaCoCo mode (when `-javaagent:jacocoagent.jar` is attached separately), call-site rewriting matches the derived application package prefix while skipping shaded/relocated packages (`/shaded/`, `/relocated/`, `/repackaged/`) and known library packages; in indexed mode, exact indexed app classes (including `org/springframework/samples/...` such as Spring PetClinic) are rewritten without shaded-package filtering while still keeping core third-party libraries (Netty, OkHttp, gRPC, AWS SDK, etc.) untouched even if misconfigured in `KEPLOY_JAVA_CLASS_DIRS`. + +When Keploy is absent (no collector connected and no control command received), runtime request counting, executor wrapping, and job/listener tracking remain unarmed (zero-allocation static sentinel token, zero task wrapping); every armed window opened while any pre-arming request or job remains in flight (or within the tail window of an unarmed hand-off, plus the first armed window after unarmed traffic ran) is marked contaminated (`"armed-mid-flight"`). If a test records coverage probes while no Tomcat, Jetty, or Undertow request entry ran (for example on Netty/WebFlux, gRPC, Vert.x, Micronaut, JDK `HttpServer`, Armeria, Helidon, Play, or a server loaded before the agent), the record emits `"unverified":["no-server-entry"]` (omitted when empty, and kept separate from `"contaminated"` so older Enterprise collectors keep measuring uncounted servers while v3 collectors fail closed on any non-empty `"unverified"`). + +A scheduled job or message listener that runs while a testcase runs puts its lines in that testcase's coverage: JaCoCo's probes do not say which thread hit them. The agent sees each run of a Quartz job (1.x and 2.x, and Spring's Quartz support), a Spring `@Scheduled` method, and Spring Kafka (`KafkaMessageListenerContainer$ListenerConsumer`), RabbitMQ (`AbstractMessageListenerContainer.doInvokeListener`), and JMS (`AbstractMessageListenerContainer.doInvokeListener`) message listeners. A testcase whose window a run overlapped, from its `START` to the read of its probes at `END` (a job already running at the `START` counts), names the jobs and listeners in `"contaminated":["quartz:." | "scheduled:." | "kafka:@" | "listener:@", ...]` after `windowCut`: at most 8 names, then `"+N"` for N more; left out when none ran. Listener attribution (topic/queue/destination and listener bean class) is inspected once per container instance and cached lock-free. The probes stay in the record; a Keploy that reads the key does not judge that testcase (an older one ignores the key). A job that ends before a `START` is not named: the `START` clears what it ran. The work a job's or listener's run hands to verified executors counts as a run of the same job, with the same name, from when the task starts until it returns or throws, whether or not `END` waits: so a testcase whose window the task runs in is named, even when the job itself returned before that testcase's `START`. Chained re-submissions inherit a 30 s budget from hop 1 so a self-resubmitting loop stops propagating attribution past its budget, while any expired handed-off task that is still executing continues marking overlapping windows `"job-tail:"` until it actually exits. `END` does not wait for it. Limits: work on custom unhooked messaging clients (plain `KafkaConsumer.poll`, `reactor-kafka`, Kafka Streams), a `java.util.Timer`, a Spring `SchedulingConfigurer` plain `Runnable`, or a reactive/Kotlin `suspend` `@Scheduled` method is not seen. No job or listener run is seen when the agent was never started as a `-javaagent` in the JVM, nor when the target class loaded before the agent started. Since 2.2.0 a testcase's record also names, in `"classMismatch":[className, ...]` after its probes, each class whose probes come from bytes other than the ones the agent indexed: a class loader that weaves the bytes it defines (load-time weaving) or an agent listed before JaCoCo's that does not ask to retransform changed the class before JaCoCo saw it, or the JVM loaded a multi-release jar's versioned copy. JaCoCo's id for such a class is not the CRC64 of the indexed bytes, so its probe indices do not belong to the indexed class, and Keploy must not read them against it. The key is left out when there is no such class. Of two copies of one class (loaded twice, from different bytes) that a testcase ran, the record reports the copy the agent indexed, else the one the coverage manifest already names, else the lowest class id compared as an unsigned number; a BACKGROUND record chooses alike, and names such classes in a `classMismatch` of its own. Every class id the agent writes (the coverage manifest's `id`) is 16 lowercase hex digits since 2.2.0; older agents wrote it unpadded, so read it as a hex number. @@ -37,9 +41,9 @@ With the JaCoCo agent in the application's JVM (the usual case), steps 2 and 5 a Before the first testcase's coverage, the agent sends Enterprise one INDEX record on `/tmp/coverage_data.sock`: a JSON object starting with `{"kind":"index",` that says how it found the application's own classes (`source`: `override` when the dirs and jars in `KEPLOY_JAVA_CLASS_DIRS` held them, `derived` from the launch or from `target/classes` or `build/classes/java/main` under the working directory, `whole-jar` or `classpath` when it could not tell them from the libraries, `none`), what it found them from in words (`launch`), the dirs and jars it read them from (`roots`, at most 64, and `rootCount`), the package roots it kept (`packages`), how many classes it indexed, the build id of those classes (`jv1-` and 32 hex; it also names the format of keploy-sdk's build table and the JaCoCo release keploy-sdk analyzes the classes with, so an SDK upgrade that changes either gives the same classes a new build id), which JaCoCo agent measures them (`jacoco`: `embedded`, the one keploy-sdk.jar starts, `attached` by the command, `none`, or `unchecked` when the agent was not started as a `-javaagent`), that embedded agent's `includes=`, and two versions as their jars' manifests name them, or `""` when not known: keploy-sdk.jar's (`sdkVersion`) and that of the JaCoCo agent that measures the classes, embedded or attached (`jacocoVersion`). It carries no class list. It is sent as the agent starts when that path's socket file is there (Enterprise's receiver makes it), and otherwise, or when that send fails, right before the first testcase's coverage; a receiver Enterprise binds anew on that path gets it again before its first record. On the TCP transport used in Kubernetes no INDEX record is sent. -Since 2.2.0 Keploy can also ask for that background, to keep it out of what it compares: it sends the line `BACKGROUND` on `/tmp/coverage_control.sock`. The agent answers `ACK` when it reads JaCoCo's probes in place and a receiver is on `/tmp/coverage_data.sock`, and `IGNORED` otherwise (`KEPLOY_JAVA_SCAN=off`, JaCoCo reached over TCP, the in-place read failed, or no receiver), as an older agent answers a line it does not know. The ask holds for this run of the application and that receiver only: an application started again (native `keploy test` starts it again for each test set) and a receiver Enterprise binds anew on that path (the next docker-compose test set) get no record until Keploy asks again, so Keploy asks after each INDEX record, which comes once per start of the application and once per new receiver. From then on, each `START` that cleared hits made since the previous testcase's `END` sends one BACKGROUND record on `/tmp/coverage_data.sock`, right after that `START` is answered (after the INDEX record, when that receiver does not have it yet): `{"kind":"background","v":1,"build":"","after":"","before":"","executedLinesByFile":{className:[probeIdx]}}`, under the key and in the shape of a testcase's record (with its `classMismatch`, left out when empty), plus `"lost":N` when the records of the N windows before it could not be made or sent. A window with no hits sends nothing. What ran before the first testcase (the application's start, the warmup) is not background, and neither is what ran after an `END` that was not taken or a `START` whose `END` never came (a testcase's own hits): none of it is sent. A test's own work that goes on after its `END` (an async task it started) lands in the next window, and so is reported as background. A Keploy that never asks gets no record, short of a new receiver that replaces the one that asked within the same instant (the agent tells receivers apart by the socket file's inode and modification time). On the TCP transport used in Kubernetes there is no BACKGROUND. +Since 2.2.0 Keploy can also ask for that background, to keep it out of what it compares: it sends the line `BACKGROUND` on `/tmp/coverage_control.sock`. The agent answers `ACK` when it reads JaCoCo's probes in place and a receiver is on `/tmp/coverage_data.sock`, and `IGNORED` otherwise (`KEPLOY_JAVA_SCAN=off`, JaCoCo reached over TCP, the in-place read failed, or no receiver), as an older agent answers a line it does not know. The ask holds for this run of the application and that receiver only: an application started again (native `keploy test` starts it again for each test set) and a receiver Enterprise binds anew on that path (the next docker-compose test set) get no record until Keploy asks again, so Keploy asks after each INDEX record, which comes once per start of the application and once per new receiver. From then on, each `START` that cleared hits made since the previous testcase's `END` sends one BACKGROUND record on `/tmp/coverage_data.sock`, right after that `START` is answered (after the INDEX record, when that receiver does not have it yet): `{"kind":"background","v":1,"build":"","after":"","before":"","executedLinesByFile":{className:[probeIdx]}}`, under the key and in the shape of a testcase's record (with its `classMismatch`, left out when empty), plus `"lost":N` when the records of the N windows before it could not be made or sent. A window with no hits sends nothing. What ran before the first testcase (the application's start, the warmup) is not background, and neither is what ran after an `END` that was not taken or a `START` whose `END` never came (a testcase's own hits): none of it is sent. Likewise, when a gap may hold a test's tail (active lingering work or live untracked handles at `END`, or opening the new window added `tail:`, `job-tail:`, or `armed-mid-flight`), that gap is NOT emitted as `BACKGROUND` and is counted in `"lost"` instead. A Keploy that never asks gets no record, short of a new receiver that replaces the one that asked within the same instant (the agent tells receivers apart by the socket file's inode and modification time). On the Unix control socket, accepted commands reply `ACK proto=3 caps=windowCut=,contaminated=,classMismatch=,background=,ackId=true,asyncExecutors=,listenerContamination=` (and `IGNORED proto=3` when not taken). On the TCP transport used in Kubernetes, the agent sends a dynamic `HELLO` frame on connect (and refreshes it mid-stream if capabilities change) carrying `proto=3`, instance identity (`sdkVersion`, `podUid`, `podName`, `sessionId`, per-JVM `jvmNonce`, deterministic `buildId`), and live capability booleans, and supports opt-in `BACKGROUND` (emitting `BACKGROUND ` after `START`'s `ACK`), opt-in `ACK_ID` (echoing `ACK ` on `START`/`END`/`IGNORED`; bare `ACK` remains the default for older collectors), and `NOP []` resync barriers. -The agent binds `/tmp/coverage_control.sock` before the application's `main` runs, so the socket is listening before the application can answer a health check. It answers `ACK` to each command it took, and `IGNORED` to an `END` that no `START` for that testcase came before: nothing is published for it, and Enterprise keeps that testcase out of the comparison. On the TCP transport used in Kubernetes the same `END` is answered with `IGNORED ` and then `ACK`. +The agent binds `/tmp/coverage_control.sock` before the application's `main` runs, so the socket is listening before the application can answer a health check. It answers `ACK` to each command it took, and `IGNORED` to an `END` that no `START` for that testcase came before: nothing is published for it, and Enterprise keeps that testcase out of the comparison. On the TCP transport used in Kubernetes the same `END` is answered with `IGNORED ` and then `ACK` (or `ACK ` when `ACK_ID` is enabled). ## How to Use @@ -229,7 +233,9 @@ ceiling does not quietly fall behind again. - `KEPLOY_JAVA_DEDUP_DISABLED`: disables the Java dedup agent when set to `true`, `1`, or `yes` - `KEPLOY_JAVA_DEDUP_DIAGNOSTICS`: when `true`, `1`, or `yes`, logs one line per START and END that says how long the command took and how long each step did: `warmup`, then `scan` (the pass that clears the background) for a START; `requests` (the wait for the test's requests, and the Spring async work they handed off, to finish, when one still ran), `scan` (the pass that reads and clears the test's hits), `filter` (the hits made into the test's probes by class), `json` and `send` for an END, plus `classes` on TCP (the check for new app classes, and the class-zip frame when there are some). Where JaCoCo's own reset and dump are used instead, a START has `reset`, and an END has `dump` (JaCoCo's dump), `parse` and `filter` (to the app's classes) in place of `scan` and `filter`; a step that did not run is left out, so an empty dump has only `dump`. A START that cleared background hits also logs how many classes and probes they were. The app's class files are read once: before the app starts, when keploy-sdk.jar starts JaCoCo itself; otherwise on the first START, by the warmup's thread (timed under `warmup`, and, past the 10 seconds that START waits for the warmup, under its `scan`, which waits for the read, or, with JaCoCo's reset and dump, which never wait for it, on the first END whose dump is not empty, under `filter`), or, with the warmup off, under that START's `scan` (or, with JaCoCo's dump, on the first END whose dump is not empty, under `filter`). On the unix socket `took` ends before the answer is written; on TCP it includes the answer. Use it to see where a test's time goes on your app - `KEPLOY_JAVA_SCAN`: `off` (in any case) turns the one-pass read of the application's probes off: each testcase then takes JaCoCo's own reset and dump, as when JaCoCo is reached over TCP, a `START` no longer sees background hits, and `BACKGROUND` is answered `IGNORED`. Use it if the in-place read misbehaves on your JVM; at 50k application classes JaCoCo's reset and dump took about 20 ms per testcase in our profile, against under 2 ms with the in-place read. Default: on -- `KEPLOY_JAVA_END_WAIT_MS`: how long a testcase's `END` waits, at most, for the requests that came in since its `START`, and the Spring async work they hand off, to finish (see "How It Works"). `0` turns the wait off, and leaves the servers' classes unchanged: `END` reads the probes at once, as before 2.2.0. The Spring executors are still changed, so that a job's hand-offs count as its run. At most `2000`: a larger value waits 2000 ms, said once at WARNING, as a longer wait would cost each testcase more than the agent's overhead allows. Default: `200` +- `KEPLOY_JAVA_END_WAIT_MS`: how long a testcase's `END` waits, at most, for the requests that came in since its `START`, and the verified async work they hand off, to finish (see "How It Works"). `0` turns the wait off, and leaves the servers' classes unchanged (`windowCut=false`, `asyncExecutors=false`): `END` reads the probes at once, as before 2.2.0. The Spring executors are still changed, so that a job's hand-offs count as its run. At most `2000`: a larger value waits 2000 ms, said once at WARNING, as a longer wait would cost each testcase more than the agent's overhead allows. Default: `200` +- `KEPLOY_JAVA_ASYNC_CALLSITES`: `off` (in any case) disables JDK executor and `CompletableFuture` call-site rewriting in application classes and declares `asyncExecutors=false` in `HELLO` and Unix `caps=`. Default: on +- `KEPLOY_DEDUP_POD_UID`, `KEPLOY_DEDUP_POD_NAME`, `KEPLOY_DEDUP_SESSION_ID`: optional instance identity fields echoed in the TCP `HELLO` frame so collectors can distinguish replay pods and sessions - `KEPLOY_JAVA_DEDUP_WARMUP_DISABLED`: when `true`, `1`, or `yes`, skips the warmup, which loads and initializes the app's own classes once, on the first START, so that no test is charged with their static initializers. It loads them through the class loader the app runs them with, such as a Spring Boot fat jar's own loader (since 2.2.0; before, a fat jar's classes were not warmed up), so every app class not loaded yet is loaded then, and JaCoCo instruments it: on an app with many classes it never uses, that is more class metadata (metaspace) than the app alone would load. It runs on a thread of its own: the first START waits for it for at most 10 seconds, then goes on, and the warmup stops after the class it is initializing. Its static initializer goes on while the tests run, and each line it runs from then on counts in the test running at the time (between two tests, in none: the next START clears it); classes it did not reach initialize when the app first uses them, as with the warmup off. The log says how long the warmup took, and, when the START stopped waiting, which class it was initializing ## Which classes count as the app's diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/BuildTable.java b/keploy-sdk/src/main/java/io/keploy/dedup/BuildTable.java index ac6dfbe..1443971 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/BuildTable.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/BuildTable.java @@ -187,7 +187,7 @@ static List files(List entries, Function name, Func /** * answer is the control socket's reply to Keploy's TABLE command. When the heap has less free than the - * table needs ({@link #lowHeap}) the analysis is skipped and the reply is {@code IGNORED proto=2 + * table needs ({@link #lowHeap}) the analysis is skipped and the reply is {@code IGNORED proto=3 * reason=low_heap heap_free_mb=F heap_needed_mb=N}, with a WARNING in the app's log; else it is * {@link #request}'s ACK or IGNORED. The heap is read once, here, when Keploy asks: a send that runs after * another one was checked when it was asked. The bound takes loaded, the class count of the index when it diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java index 08d10a7..d5720b1 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -1,81 +1,116 @@ package io.keploy.dedup; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Level; +import java.util.logging.Logger; /** - * JobGate sees the runs of the app's scheduled jobs, so that a test whose - * window a job ran in says so: JaCoCo's probes carry no thread, so the lines - * a Quartz job or a Spring {@code @Scheduled} method runs while a test runs - * land in that test's hits. A test's record names the jobs whose runs + * JobGate sees the runs of the app's scheduled jobs and message listeners, so + * that a test whose window one ran in says so: JaCoCo's probes carry no thread, + * so the lines a Quartz job, a Spring {@code @Scheduled} method, or a Spring + * Kafka/RabbitMQ/JMS message listener runs while a test runs land in that + * test's hits. A test's record names the jobs and listeners whose runs * overlapped its window, from its START to the read of its hits at END, in * {@code contaminated}, and Keploy does not judge such a test. * - *

ServerEntries makes Quartz's {@code JobRunShell.run()} and Spring's - * {@code ScheduledMethodRunnable.run()} call {@link #enter(Object, String)} - * where a job's run starts and {@link #exit(Object)} where it is done, - * however it returns or throws. A run is in a window when it ran when the - * window opened or started before it closed: so a job that started before a - * test and still runs at its START counts in it, and one that ended before - * the START does not (the START clears what it ran). + *

Lock-free hot path: uses concurrent sets/queues without global + * {@code synchronized} monitors (safe for virtual threads on JDK 21-23), caches + * listener container attribution (topic/queue/destination + listener bean) per + * container instance, and is a fast no-op when Keploy is unarmed. * - *

The work a job's run hands to a Spring TaskExecutor (an event listener - * on an async multicaster, a task submitted to a ThreadPoolTaskExecutor, - * an {@code @Async} method) counts as a run of that job, named the same, - * from when the task starts until it returns or throws: RequestGate's - * {@link RequestGate#hand(Object, Runnable)} wraps it as the job's when the - * thread handing it off is in the job's run, so a test whose window the task runs in is marked - * with the job even when the job's own run ended before the test began. - * What that task hands off counts the same way. - * - *

Jobs the app runs on threads of its own, a custom executor or a - * {@code java.util.Timer} are not seen, and neither are message listeners or - * a request's async work that runs past its END. + *

Expired handed-off runs ({@link #handedJobMaxNanos}) stop propagating + * attribution to newly chained hops, but remain tracked while they are still + * executing so every window opened before {@link #exit(Object)} actually runs + * is marked contaminated ({@code job-tail:}). * *

Public only for the classes ServerEntries changes, which call it from * their own packages; not an API. */ public final class JobGate { + private static final Logger LOGGER = Logger.getLogger(KeployDedupAgent.class.getName()); // The most job names a record carries; past them, one more name says // how many more there were ("+3"). static final int NAMES = 8; // The most distinct names a window keeps to count: an app has a few // jobs, and a window past this many counts each further run as one more. static final int KEPT = 1024; + // Maximum duration a handed-off async task (enterAs) keeps attributing + // chained hops before it is marked expired; while still running (until + // exit() actually runs), every window opened is marked "job-tail:". + static volatile long handedJobMaxNanos = TimeUnit.SECONDS.toNanos(30); + private static final Set EXPIRED_LOGGED = ConcurrentHashMap.newKeySet(); - private static final Object LOCK = new Object(); - // The runs going on now, and the window of the test running (null - // between two tests). Both guarded by LOCK: a job's run and a test's - // START or END take it once each, so a run that starts as a window - // opens is either seen running by the opening or sees the window open. - private static final Set RUNNING = new HashSet<>(); - private static Window window; + // Lock-free set of active runs (including expired still-running runs until + // exit() actually runs). Publish-then-scan ordering with volatile `window` + // guarantees no concurrent run is missed when a window opens. + private static final Set RUNNING = ConcurrentHashMap.newKeySet(); + private static volatile Window window; // The run this thread is in: a job's own, or that of a task a job's run // handed off; null on any other thread. private static final ThreadLocal CURRENT = new ThreadLocal<>(); + // Per-instance cached listener attribution names (topic/queue/destination + // + listener bean class) keyed by weak identity so repeated messages incur + // zero reflection and zero String allocation. + private static final ConcurrentHashMap LISTENER_NAME_CACHE = + new ConcurrentHashMap<>(); + private static final ReferenceQueue DEAD_LISTENERS = new ReferenceQueue<>(); + private JobGate() { } + static void arm() { + RequestGate.arm(); + } + + static int activeRunCount() { + return RUNNING.size(); + } + + static boolean hasExpiredRunning() { + if (RUNNING.isEmpty()) { + return false; + } + long now = System.nanoTime(); + for (Run run : RUNNING) { + if (run.isExpired(now)) { + return true; + } + } + return false; + } + /** * Counts a job's run as going on, in the window of the test running now * if one is open. Never throws: the job runs whatever happens here. + * No-op when Keploy is unarmed. * * @param job the object whose {@code run()} runs the job - * @param kind "quartz" or "scheduled" + * @param kind "quartz", "scheduled", "kafka", or "listener" * @return the token to pass to {@link #exit(Object)} when it is done */ public static Object enter(Object job, String kind) { + if (!RequestGate.isArmed()) { + return RequestGate.enterUnarmed(); + } Run run = null; try { - run = new Run(name(job, kind), CURRENT.get()); + run = new Run(name(job, kind), CURRENT.get(), false, 0L); begin(run); } catch (Throwable t) { // The job runs on. A run counted as going on before this (an @@ -87,12 +122,25 @@ public static Object enter(Object job, String kind) { } // enterAs counts a task a job's run handed off as a run of that job, as - // enter does, from when the task starts; exit counts it done. Never - // throws, as enter. - static Object enterAs(String name) { + // enter does, from when the task starts; exit counts it done. A first-hop + // task handed off directly from a scheduled job or listener starts a fresh + // handedJobMaxNanos budget when it begins running (so queue wait time in a + // busy pool does not eat into its budget); chained hops inherit the first + // hop's original deadline. Even if a chained hop starts after its deadline, + // it is still tracked as an expired Run ("job-tail:") until exit() + // runs so overlapping windows are honestly flagged while runningAttribution() + // stops propagating further. + static Object enterAs(Attribution attribution) { + if (attribution == null || !RequestGate.isArmed()) { + return null; + } Run run = null; try { - run = new Run(name, CURRENT.get()); + long now = System.nanoTime(); + long deadline = attribution.hasDeadline + ? attribution.expiresAtNanos + : now + handedJobMaxNanos; + run = new Run(attribution.name, CURRENT.get(), true, deadline); begin(run); } catch (Throwable t) { // As in enter: the task runs on, and a run counted is handed back. @@ -100,23 +148,140 @@ static Object enterAs(String name) { return run; } - // begin counts run as going on, in the window open now if any, and as - // the run this thread is in until its exit. - private static void begin(Run run) { - synchronized (LOCK) { - RUNNING.add(run); - if (window != null) { - window.mark(run.name); + // markUntracked records an untracked async hand-off originated by a job's + // run (e.g., an unknown executor or expired job fan-out) on the currently + // open window (if any) and requests tail contamination on subsequent + // windows. + static void markUntracked(String reason) { + markUntracked(reason, 0L); + } + + static void markUntracked(String reason, long extraTailNanos) { + if (reason == null || reason.isEmpty() || !RequestGate.isArmed()) { + return; + } + Window active = window; + if (active != null) { + active.mark(reason); + } + RequestGate.noteExternalUntrackedTail(reason, extraTailNanos); + } + + // Marks the currently open JobGate window without starting a blind + // time-based tail when the caller is tracking a concrete handle's liveness. + static void markUntrackedWindowOnly(String reason) { + if (reason == null || reason.isEmpty() || !RequestGate.isArmed()) { + return; + } + Window active = window; + if (active != null) { + active.mark(reason); + } + } + + // expiredAttribution returns an already-expired Attribution if this thread + // is currently executing an expired handed-off job Run. Verified executors + // wrap hand-offs with this expired Attribution so multi-hop self-resubmitting + // loops and long fan-out tasks keep marking overlapping windows "job-tail:" + // until they actually exit, while JobGate.running() still returns null. + static Attribution expiredAttribution() { + Run run = CURRENT.get(); + if (run == null) { + return null; + } + long now = System.nanoTime(); + while (run != null) { + if (!run.over && run.isExpired(now)) { + return new Attribution(run.name, true, run.expiresAtNanos); } + run = run.outer; } + return null; + } + + // expiredRunningName returns the job name if this thread is currently + // executing an expired handed-off job Run. + static String expiredRunningName() { + Attribution expired = expiredAttribution(); + return expired == null ? null : expired.name; + } + + // detachThread restores CURRENT without removing the Run from RUNNING, so + // a CompletableFuture's synchronous dependent stages keep JobGate tracking + // active until whenComplete calls exit(token). + static void detachThread(Object token) { + if (token instanceof Run) { + Run run = (Run) token; + if (CURRENT.get() != run) { + return; + } + Run back = run.outer; + while (back != null && back.over) { + back = back.outer; + } + if (back == null) { + CURRENT.remove(); + } else { + CURRENT.set(back); + } + } + } + + // begin counts run as going on, in the window open now if any, and as + // the run this thread is in until its exit. Publish-then-read with open(): + // RUNNING.add(run) happens-before reading volatile `window`; open() writes + // volatile `window` before scanning RUNNING. + private static void begin(Run run) { + RUNNING.add(run); CURRENT.set(run); + Window active = window; + if (active != null) { + active.mark(run.isExpired(System.nanoTime()) ? "job-tail:" + run.name : run.name); + } } // running is the name of the job whose run this thread is in (the job's - // own, or a task it handed off), or null when it is in none. + // own, or a non-expired task it handed off), or null when it is in none. static String running() { + Attribution attr = runningAttribution(); + return attr == null ? null : attr.name; + } + + // runningAttribution returns the active job name and optional carried + // deadline: a direct job run returns hasDeadline=false so the first hop + // starts its handedJobMaxNanos budget when it begins running; a handed-off + // task carries its existing deadline unchanged (hasDeadline=true) so + // chained re-submissions can never extend attribution past hop 1's bound. + static Attribution runningAttribution() { Run run = CURRENT.get(); - return run == null ? null : run.name; + if (run == null) { + return null; + } + long now = System.nanoTime(); + while (run != null && (run.over || run.isExpired(now))) { + run = run.outer; + } + if (run == null) { + return null; + } + return run.handed + ? new Attribution(run.name, true, run.expiresAtNanos) + : new Attribution(run.name, false, 0L); + } + + // Attribution carries a job's name and (for chained hops) its hop-1 + // nanoTime expiry across async hand-offs. + static final class Attribution { + + final String name; + final boolean hasDeadline; + final long expiresAtNanos; + + Attribution(String name, boolean hasDeadline, long expiresAtNanos) { + this.name = name; + this.hasDeadline = hasDeadline; + this.expiresAtNanos = expiresAtNanos; + } } /** @@ -126,11 +291,16 @@ static String running() { * @param token what {@link #enter(Object, String)} returned */ public static void exit(Object token) { + if (token == null) { + return; + } + if (RequestGate.isUnarmedToken(token)) { + RequestGate.exitUnarmed(); + return; + } if (token instanceof Run) { Run run = (Run) token; - synchronized (LOCK) { - RUNNING.remove(run); - } + RUNNING.remove(run); run.over = true; // The thread is back in the run it was in before, if any. A run // exited out of order leaves the thread in the run it is in, and @@ -153,44 +323,284 @@ public static void exit(Object token) { // open starts the window of a test, before its START clears what ran // before it: each run going on now counts in it, as what it runs from - // here on lands in the test. - static void open() { - synchronized (LOCK) { - Window opened = new Window(); - for (Run run : RUNNING) { - opened.mark(run.name); + // here on lands in the test. Handed-off tasks that have run past + // handedJobMaxNanos are NOT forgotten while they are still executing: + // they remain in RUNNING until exit() runs and mark every window opened + // while still alive with "job-tail:". Returns true if any expired + // job-tail run was added to the newly opened window. + static boolean open() { + RequestGate.arm(); + long now = System.nanoTime(); + List expired = null; + boolean hasJobTail = false; + Window opened = new Window(); + window = opened; + for (Run run : RUNNING) { + if (run.isExpired(now)) { + hasJobTail = true; + opened.mark("job-tail:" + run.name); + if (EXPIRED_LOGGED.add(run.name)) { + if (expired == null) { + expired = new ArrayList<>(); + } + expired.add(run.name); + } + continue; + } + opened.mark(run.name); + } + if (expired != null) { + for (String jobName : expired) { + LOGGER.log(Level.INFO, "Keploy dedup: handed-off task from " + jobName + + " is still executing after " + TimeUnit.NANOSECONDS.toMillis(handedJobMaxNanos) + + " ms; marking overlapping windows with job-tail:" + jobName + " until it finishes"); } - window = opened; } + return hasJobTail; } // close ends the window, after its END read the test's hits, and names // the jobs whose runs overlapped it: at most NAMES, then "+N" for the N // more; empty when none ran in it or no window was open. static List close() { - Window closed; - synchronized (LOCK) { - closed = window; - window = null; - } + Window closed = window; + window = null; return closed == null ? Collections.emptyList() : closed.names(); } // name is how a record names a job: "quartz:." for a // Quartz job, "scheduled:." for a Spring @Scheduled - // method, or the kind and the class running it when that cannot be read - // (an unknown version, a class not laid out as expected): the run still - // counts. + // method, cached "kafka:" / "listener:" + // for a message listener, or the kind and the class running it when that + // cannot be read: the run still counts. static String name(Object job, String kind) { + if ("kafka".equals(kind) || "listener".equals(kind)) { + return cachedListenerName(job, kind); + } String name; try { - name = "quartz".equals(kind) ? quartzJob(job) : scheduledMethod(job); + if ("quartz".equals(kind)) { + name = quartzJob(job); + } else if ("scheduled".equals(kind)) { + name = scheduledMethod(job); + } else { + name = job == null ? "?" : job.getClass().getName(); + } } catch (Throwable t) { name = job == null ? "?" : job.getClass().getName(); } return kind + ":" + name; } + private static String cachedListenerName(Object job, String kind) { + if (job == null) { + return kind + ":?"; + } + drainDeadListeners(); + LookupKey probe = new LookupKey(job); + String cached = LISTENER_NAME_CACHE.get(probe); + if (cached != null) { + return cached; + } + String computed = computeListenerName(job, kind); + WeakIdentityKey key = new WeakIdentityKey(job, DEAD_LISTENERS); + String existing = LISTENER_NAME_CACHE.putIfAbsent(key, computed); + return existing != null ? existing : computed; + } + + private static void drainDeadListeners() { + for (Reference ref; (ref = DEAD_LISTENERS.poll()) != null; ) { + LISTENER_NAME_CACHE.remove(ref); + } + } + + private static String computeListenerName(Object container, String kind) { + String destination = null; + String listener = null; + try { + if ("kafka".equals(kind)) { + Object props = invokeNoArg(container, "getContainerProperties"); + if (props == null) { + props = readField(container, "containerProperties"); + } + if (props == null) { + Object outer = readField(container, "this$0"); + if (outer != null) { + props = invokeNoArg(outer, "getContainerProperties"); + } + } + if (props != null) { + destination = extractTopics(props); + listener = extractListenerClass(invokeNoArg(props, "getMessageListener")); + } + if (destination == null) { + destination = formatStrings(readField(container, "topics")); + } + if (listener == null) { + Object l = readField(container, "genericListener"); + if (l == null) { + l = readField(container, "listener"); + } + listener = extractListenerClass(l); + } + } else { + // Spring AMQP: getQueueNames() + getMessageListener() + destination = formatStrings(invokeNoArg(container, "getQueueNames")); + if (destination == null) { + // Spring JMS: getDestinationName() + getMessageListener() + Object destName = invokeNoArg(container, "getDestinationName"); + if (destName instanceof String && !((String) destName).isEmpty()) { + destination = (String) destName; + } + } + listener = extractListenerClass(invokeNoArg(container, "getMessageListener")); + } + } catch (Throwable ignored) { + // Fall through to container class name below. + } + if (destination != null && listener != null) { + return kind + ":" + destination + "@" + listener; + } + if (destination != null) { + return kind + ":" + destination; + } + if (listener != null) { + return kind + ":" + listener; + } + return kind + ":" + container.getClass().getName(); + } + + private static String extractTopics(Object containerProps) { + String topics = formatStrings(invokeNoArg(containerProps, "getTopics")); + if (topics != null) { + return topics; + } + Object pattern = invokeNoArg(containerProps, "getTopicPattern"); + if (pattern != null) { + String s = pattern.toString(); + if (!s.isEmpty()) { + return s; + } + } + Object tpos = invokeNoArg(containerProps, "getTopicPartitions"); + if (tpos != null && tpos.getClass().isArray()) { + int len = Array.getLength(tpos); + if (len > 0) { + StringBuilder sb = new StringBuilder(); + int limit = Math.min(len, 4); + for (int i = 0; i < limit; i++) { + Object elem = Array.get(tpos, i); + Object topic = elem == null ? null : invokeNoArg(elem, "getTopic"); + String part = topic != null ? topic.toString() : String.valueOf(elem); + if (sb.length() > 0) { + sb.append(','); + } + sb.append(part); + } + if (len > limit) { + sb.append(",+").append(len - limit); + } + return sb.toString(); + } + } + return null; + } + + private static String formatStrings(Object value) { + if (value == null) { + return null; + } + if (value instanceof String[]) { + String[] arr = (String[]) value; + if (arr.length == 0) { + return null; + } + StringBuilder sb = new StringBuilder(); + int limit = Math.min(arr.length, 4); + for (int i = 0; i < limit; i++) { + if (arr[i] == null || arr[i].isEmpty()) { + continue; + } + if (sb.length() > 0) { + sb.append(','); + } + sb.append(arr[i]); + } + if (arr.length > limit) { + sb.append(",+").append(arr.length - limit); + } + return sb.length() == 0 ? null : sb.toString(); + } + if (value instanceof Collection) { + Collection col = (Collection) value; + if (col.isEmpty()) { + return null; + } + StringBuilder sb = new StringBuilder(); + int count = 0; + for (Object item : col) { + if (item == null) { + continue; + } + if (count < 4) { + if (sb.length() > 0) { + sb.append(','); + } + sb.append(item.toString()); + } + count++; + } + if (count > 4) { + sb.append(",+").append(count - 4); + } + return sb.length() == 0 ? null : sb.toString(); + } + return null; + } + + private static String extractListenerClass(Object listener) { + if (listener == null) { + return null; + } + // Unwrap Spring messaging adapters (getBean() / getDelegate()). + Object target = invokeNoArg(listener, "getBean"); + if (target == null) { + target = invokeNoArg(listener, "getDelegate"); + } + Object chosen = target != null ? target : listener; + return chosen.getClass().getName(); + } + + private static Object invokeNoArg(Object target, String methodName) { + if (target == null) { + return null; + } + try { + Method m = target.getClass().getMethod(methodName); + m.setAccessible(true); + return m.invoke(target); + } catch (Throwable ignored) { + return null; + } + } + + private static Object readField(Object target, String fieldName) { + if (target == null) { + return null; + } + for (Class c = target.getClass(); c != null && c != Object.class; c = c.getSuperclass()) { + try { + Field f = c.getDeclaredField(fieldName); + f.setAccessible(true); + return f.get(target); + } catch (NoSuchFieldException ignored) { + } catch (Throwable ignored) { + return null; + } + } + return null; + } + // quartzJob is the "." of the job a JobRunShell runs: its // context's JobDetail's key (Quartz 2), or its full name (Quartz 1). private static String quartzJob(Object shell) throws ReflectiveOperationException { @@ -222,46 +632,132 @@ private static String scheduledMethod(Object runnable) throws ReflectiveOperatio return target.getDeclaringClass().getName() + "." + target.getName(); } + private static final class WeakIdentityKey extends WeakReference { + + private final int hash; + + private WeakIdentityKey(Object referent, ReferenceQueue queue) { + super(referent, queue); + this.hash = System.identityHashCode(referent); + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + Object mine = get(); + if (mine == null) { + return false; + } + if (obj instanceof WeakIdentityKey) { + return mine == ((WeakIdentityKey) obj).get(); + } + if (obj instanceof LookupKey) { + return mine == ((LookupKey) obj).target; + } + return false; + } + } + + private static final class LookupKey { + + private final Object target; + private final int hash; + + private LookupKey(Object target) { + this.target = target; + this.hash = System.identityHashCode(target); + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof WeakIdentityKey) { + return target == ((WeakIdentityKey) obj).get(); + } + if (obj instanceof LookupKey) { + return target == ((LookupKey) obj).target; + } + return false; + } + } + private static final class Run { private final String name; // The run the thread was in when this one began, or null. private final Run outer; - // Whether its exit came; only its own thread reads or sets it. - private boolean over; + // True for tasks handed off via enterAs (bounded by expiresAtNanos). + private final boolean handed; + private final long expiresAtNanos; + // Whether its exit came; volatile because deferred CF release can + // finish on another thread via whenComplete. + private volatile boolean over; - private Run(String name, Run outer) { + private Run(String name, Run outer, boolean handed, long expiresAtNanos) { this.name = name; this.outer = outer; + this.handed = handed; + this.expiresAtNanos = expiresAtNanos; + } + + private boolean isExpired(long now) { + return handed && (now - expiresAtNanos) >= 0; } } // Window is the job names that ran in a test's window, in the order - // they first ran in it. + // they first ran in it. Lock-free so JobGate.enter never synchronizes. private static final class Window { - private final Set names = new LinkedHashSet<>(); + // Declared as Set (backed by ConcurrentHashMap.newKeySet) so + // JobGateTest's OOM-injection test can still substitute a custom Set. + private final Set names = ConcurrentHashMap.newKeySet(); + private final ConcurrentLinkedQueue order = new ConcurrentLinkedQueue<>(); + private final AtomicInteger kept = new AtomicInteger(); // Runs of names past KEPT, each counted as one more name. - private int more; + private final AtomicInteger more = new AtomicInteger(); private void mark(String name) { - if (names.size() < KEPT) { - names.add(name); + if (kept.get() < KEPT) { + if (names.add(name)) { + int n = kept.incrementAndGet(); + if (n <= KEPT) { + order.add(name); + } else { + names.remove(name); + kept.decrementAndGet(); + more.incrementAndGet(); + } + } } else if (!names.contains(name)) { - more++; + more.incrementAndGet(); } } private List names() { - List out = new ArrayList<>(Math.min(names.size(), NAMES) + 1); - int left = names.size() + more; - for (String name : names) { - if (out.size() == NAMES) { - break; + List out = new ArrayList<>(NAMES + 1); + int total = 0; + for (String name : order) { + if (out.size() < NAMES) { + out.add(name); } - out.add(name); - left--; + total++; } + int left = (total - out.size()) + more.get(); if (left > 0) { out.add("+" + left); } diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java index 1c48235..51eca2a 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -35,6 +35,8 @@ import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -42,6 +44,7 @@ import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -49,6 +52,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.UUID; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -92,8 +96,14 @@ static String toDedupJson(String id, Map> probesByClass, L static String toDedupJson(String id, Map> probesByClass, List classMismatch, boolean windowCut, List contaminated) { + return toDedupJson(id, probesByClass, classMismatch, windowCut, contaminated, + Collections.emptyList()); + } + + static String toDedupJson(String id, Map> probesByClass, List classMismatch, + boolean windowCut, List contaminated, List unverified) { return GSON.toJson(new DedupPayload(id, - new TestCoverage(probesByClass, classMismatch, windowCut, contaminated))); + new TestCoverage(probesByClass, classMismatch, windowCut, contaminated, unverified))); } // encodeBytecodeFrame builds the bytecode frame the SDK writes to the @@ -133,6 +143,38 @@ static String encodeBytecodeFrame(String buildTag, String manifestJson, byte[] z // -javaagent's premain): once it has, its classes stay changed, and job // runs are seen, across a stop() and a start() with no instrumentation. static volatile boolean transformerAdded; + // Whether ServerEntries was installed with a non-empty app-only class + // allow-list for JDK executor call-site rewriting. + static volatile boolean executorCallSitesEnabled; + // Latched true once any END sees probes recorded with RequestGate + // enteredCount == 0 (and no job contamination), indicating an uncounted + // server (e.g. Armeria, Helidon, Play) not in ServerEntries.UNCOUNTED. + // Permanently drops windowCut (and asyncExecutors) to false in HELLO and + // Unix ACK caps; reset only by tests. + static volatile boolean observedNoServerEntry; + // Latched true once an executor or async method reference targeting a real + // untracked executor/async API is captured outside any active request + // window or tracked job (e.g. stored in a field during startup and invoked + // later inside requests). Permanently drops asyncExecutors to false in + // HELLO and Unix ACK caps; reset only by tests. + static volatile boolean observedPreCapturedUntrackedExecutor; + + private static void noteObservedNoServerEntry(String testId) { + if (!observedNoServerEntry) { + observedNoServerEntry = true; + log(Level.INFO, "Keploy dedup: " + testId + " saw an HTTP server whose requests the SDK cannot count," + + " so window cuts are not trusted for the rest of this run", null); + } + } + + static void noteObservedPreCapturedUntrackedExecutor(String target) { + if (!observedPreCapturedUntrackedExecutor) { + observedPreCapturedUntrackedExecutor = true; + log(Level.INFO, "Keploy dedup: saw an executor method reference (" + target + + ") created outside any tracked request, so background async work cannot be tracked" + + " reliably for the rest of this run", null); + } + } // The answer to a command not taken (a START that could not clear the // counters, an END with no START for that test, as after a restart, an // END whose scan lost hits it had cleared): nothing is published @@ -147,14 +189,259 @@ static String encodeBytecodeFrame(String buildTag, String manifestJson, byte[] z // proto=2 says this SDK answers every command it reads, so Keploy can read // a close with no answer as a command not taken: on macOS a connection // closed with its command unread gives Keploy no error, only the close. - static final String UNIX_REPLY_TAKEN = "ACK proto=2"; - static final String UNIX_REPLY_IGNORED = IGNORED_REPLY + " proto=2"; + // Random UUID generated lazily once per JVM startup (never changes on TCP + // reconnect; distinct across JVM restarts; avoids initializing SecureRandom + // during premain when dedup is disabled) so collectors can detect pod + // identity, restarts, and wrong-JVM routing. + private static final class NonceHolder { + static final String VALUE = UUID.randomUUID().toString(); + } + + static String jvmNonce() { + return NonceHolder.VALUE; + } + + static final String UNIX_REPLY_TAKEN = "ACK proto=3"; + static final String UNIX_REPLY_IGNORED = IGNORED_REPLY + " proto=3"; // The unix control command a Keploy that reads BACKGROUND records sends // to get them: ACK when this SDK will send them to the receiver on the // data socket now, IGNORED when it sees no hits between tests (JaCoCo's // probes not read in place) or no receiver is there. An older SDK // answers IGNORED too, as to any line that is no command. static final String BACKGROUND_COMMAND = "BACKGROUND"; + // Opt-in TCP command enabling correlated "ACK " replies. Without + // it, START/END/IGNORED keep bare "ACK" for older collectors that match + // line == "ACK". Fire-and-forget like BACKGROUND; reset on reconnect. + static final String ACK_ID_COMMAND = "ACK_ID"; + // Resync barrier command over TCP: "NOP " -> "ACK ", bare + // "NOP" -> "ACK". Does not touch activeTestId, lastEndedTestId, or probes. + static final String NOP_COMMAND = "NOP"; + // Optional test-only failure injector for connect-time HELLO guard verification. + static volatile RuntimeException testHelloFailure; + + // Protocol version declared in the dynamic HELLO frame sent immediately on + // TCP connect and on unix ACK proto=3 caps=... replies. + static final int TCP_PROTOCOL_VERSION = 3; + + static String buildUnixCapsReply(boolean windowCut, boolean contaminated, boolean classMismatch, + boolean background, boolean asyncExecutors, boolean listenerContamination) { + return UNIX_REPLY_TAKEN + + " caps=windowCut=" + windowCut + + ",contaminated=" + contaminated + + ",classMismatch=" + classMismatch + + ",background=" + background + + ",ackId=true" + + ",asyncExecutors=" + asyncExecutors + + ",listenerContamination=" + listenerContamination; + } + + static String buildHelloFrame(String sdkVersion, String podUid, String podName, String sessionId, + String jvmNonce, String buildId, + boolean windowCut, boolean contaminated, boolean classMismatch, + boolean background, boolean ackId, boolean nopResync, + boolean asyncExecutors, boolean listenerContamination) { + return "HELLO " + GSON.toJson(new HelloPayload( + sdkVersion == null ? "" : sdkVersion, + podUid == null ? "" : podUid, + podName == null ? "" : podName, + sessionId == null ? "" : sessionId, + jvmNonce == null ? "" : jvmNonce, + buildId == null ? "" : buildId, + windowCut, contaminated, classMismatch, background, ackId, nopResync, + asyncExecutors, listenerContamination)); + } + + private static final class HelloPayload { + @SuppressWarnings("unused") + final int proto = TCP_PROTOCOL_VERSION; + @SuppressWarnings("unused") + final String sdkVersion; + @SuppressWarnings("unused") + final String podUid; + @SuppressWarnings("unused") + final String podName; + @SuppressWarnings("unused") + final String sessionId; + @SuppressWarnings("unused") + final String jvmNonce; + @SuppressWarnings("unused") + final String buildId; + @SuppressWarnings("unused") + final boolean windowCut; + @SuppressWarnings("unused") + final boolean contaminated; + @SuppressWarnings("unused") + final boolean classMismatch; + @SuppressWarnings("unused") + final boolean background; + @SuppressWarnings("unused") + final boolean ackId; + @SuppressWarnings("unused") + final boolean nopResync; + @SuppressWarnings("unused") + final boolean asyncExecutors; + @SuppressWarnings("unused") + final boolean listenerContamination; + + HelloPayload(String sdkVersion, String podUid, String podName, String sessionId, + String jvmNonce, String buildId, + boolean windowCut, boolean contaminated, boolean classMismatch, + boolean background, boolean ackId, boolean nopResync, + boolean asyncExecutors, boolean listenerContamination) { + this.sdkVersion = sdkVersion; + this.podUid = podUid; + this.podName = podName; + this.sessionId = sessionId; + this.jvmNonce = jvmNonce; + this.buildId = buildId; + this.windowCut = windowCut; + this.contaminated = contaminated; + this.classMismatch = classMismatch; + this.background = background; + this.ackId = ackId; + this.nopResync = nopResync; + this.asyncExecutors = asyncExecutors; + this.listenerContamination = listenerContamination; + } + } + + private static final class Capabilities { + final boolean windowCut; + final boolean contaminated; + final boolean classMismatch; + final boolean background; + final boolean asyncExecutors; + final boolean listenerContamination; + + Capabilities(boolean windowCut, boolean contaminated, boolean classMismatch, + boolean background, boolean asyncExecutors, boolean listenerContamination) { + this.windowCut = windowCut; + this.contaminated = contaminated; + this.classMismatch = classMismatch; + this.background = background; + this.asyncExecutors = asyncExecutors; + this.listenerContamination = listenerContamination; + } + + String toUnixAck() { + return buildUnixCapsReply(windowCut, contaminated, classMismatch, background, + asyncExecutors, listenerContamination); + } + + String toHelloFrame(String buildId) { + return buildHelloFrame( + IndexReport.versionOf(IndexReport.class), + envOrProperty("KEPLOY_DEDUP_POD_UID", "keploy.dedup.pod.uid", ""), + envOrProperty("KEPLOY_DEDUP_POD_NAME", "keploy.dedup.pod.name", ""), + envOrProperty("KEPLOY_DEDUP_SESSION_ID", "keploy.dedup.session.id", ""), + jvmNonce(), + buildId, + windowCut, contaminated, classMismatch, background, true, true, + asyncExecutors, listenerContamination); + } + } + + private static Capabilities computeCapabilities(CoverageCollector collector) { + boolean agentAttached = transformerAdded; + boolean endWaitActive = collector.endWaitMillis > 0; + // Base windowCut on ServerEntries being installed (transformerAdded) + // with endWait > 0 and no uncounted server or hook failure rather than + // !countsNone(), so Jetty/Undertow cold-start pods honestly declare + // windowCut=true before their first request loads HttpChannel/Connectors. + // If runtime probes are later recorded with enteredCount==0 (and no job + // contamination), observedNoServerEntry permanently latches false for + // windowCut (and asyncExecutors) for the rest of the JVM, refreshing + // TCP HELLO before that COV and Unix ACK caps on that and later replies. + boolean serverEntriesInstalled = agentAttached && endWaitActive + && !ServerEntries.hasUncountedServer() + && !ServerEntries.hadServerHookFailure() + && !observedNoServerEntry; + boolean windowCut = serverEntriesInstalled; + boolean contaminated = agentAttached; + boolean classMismatch = true; + boolean background = collector.probeScan() != null; + boolean appOnlyActive = collector.coverageIndex.entries == null + || collector.coverageIndex.appOnly; + // Also fail closed via observedPreCapturedUntrackedExecutor if an + // executor or async method reference targeting a real untracked + // executor/async API is captured outside any active request window or + // tracked job (e.g. stored in a field at startup and invoked later on + // the request path), refreshing TCP HELLO and Unix ACK caps. + boolean asyncExecutors = serverEntriesInstalled + && executorCallSitesEnabled + && !isAsyncCallSitesTurnedOff() + && appOnlyActive + && !ServerEntries.wasJpmsGuardTriggered() + && !ServerEntries.hadAppRewriteFailure() + && !observedPreCapturedUntrackedExecutor; + boolean listenerContamination = agentAttached + && !ServerEntries.hadListenerHookFailure() + && !ServerEntries.hasUnhookedConsumer(); + return new Capabilities(windowCut, contaminated, classMismatch, background, + asyncExecutors, listenerContamination); + } + + static boolean isAsyncCallSitesTurnedOff() { + return "off".equalsIgnoreCase(envOrProperty("KEPLOY_JAVA_ASYNC_CALLSITES", + "keploy.java.async.callsites", "")); + } + + // Merges RequestGate contaminations (tail, untracked-executor, + // untracked-async, armed-mid-flight) and JobGate contaminations, + // deduplicated in order and capped at JobGate.NAMES with "+N" overflow. + // Note: "no-server-entry" is NOT merged here — it is carried in the separate + // "unverified" JSON field so older enterprise collectors keep measuring + // uncounted servers while v3 collectors fail closed. + static List mergeContaminations(List requestContams, List jobContams) { + if ((requestContams == null || requestContams.isEmpty()) + && (jobContams == null || jobContams.isEmpty())) { + return Collections.emptyList(); + } + LinkedHashSet merged = new LinkedHashSet<>(); + int overflow = 0; + if (requestContams != null) { + for (String item : requestContams) { + overflow = addContaminationItem(merged, overflow, item); + } + } + if (jobContams != null) { + for (String item : jobContams) { + overflow = addContaminationItem(merged, overflow, item); + } + } + if (merged.size() <= JobGate.NAMES && overflow == 0) { + return new ArrayList<>(merged); + } + List out = new ArrayList<>(JobGate.NAMES + 1); + int kept = 0; + for (String item : merged) { + if (kept < JobGate.NAMES) { + out.add(item); + kept++; + } else { + overflow++; + } + } + if (overflow > 0) { + out.add("+" + overflow); + } + return out; + } + + private static int addContaminationItem(Set merged, int overflow, String item) { + if (item == null || item.isEmpty()) { + return overflow; + } + if (item.startsWith("+")) { + try { + return overflow + Integer.parseInt(item.substring(1)); + } catch (NumberFormatException ignored) { + // Treat as ordinary label. + } + } + merged.add(item); + return overflow; + } private static final AtomicBoolean STARTED = new AtomicBoolean(false); private static final AtomicBoolean SHUTDOWN_HOOK_REGISTERED = new AtomicBoolean(false); @@ -237,6 +524,10 @@ private static boolean start(CoverageIndex index, Instrumentation instrumentatio } startedIndex = index; + // Start unarmed (complete no-op when Keploy is absent); armed as soon + // as a collector connects (TCP connect, live unix data socket, or first + // control command/START). + RequestGate.disarm(); CoverageCollector collector = new CoverageCollector( new JacocoClient(resolveHost(), resolvePort()), index, instrumentation); @@ -303,7 +594,36 @@ private static boolean start(CoverageIndex index, Instrumentation instrumentatio // instruments, and ids, a server's class as the index read it, // and ServerEntries counts in JaCoCo's copy. startJacoco(instrumentation, index); - countRequests(instrumentation, IndexReport.JACOCO_ATTACHED.equals(index.jacoco)); + Set appClasses = Collections.emptySet(); + String appPackagePrefix = null; + List loadedEntries = index.entries; + if (loadedEntries != null) { + if (index.appOnly && !loadedEntries.isEmpty()) { + Set names = new HashSet<>(loadedEntries.size() * 2); + boolean unreadableModuleHit = false; + for (ClassEntry entry : loadedEntries) { + names.add(entry.className); + if (!unreadableModuleHit && ServerEntries.isLocationInUnreadableModule(entry.location)) { + unreadableModuleHit = true; + } + } + if (unreadableModuleHit) { + ServerEntries.markJpmsGuardTriggered(); + } + appClasses = names; + } + } else { + // External JaCoCo attached: avoid eagerly scanning the full + // classpath in premain; use the lightweight package root + // derived from the JVM launch command instead. + AppClasses derived = AppClasses.derive(System.getProperty("java.class.path", ""), + System.getProperty("sun.java.command", ""), System.getProperty("user.dir")); + if (!derived.failed && derived.root != null && !derived.root.isEmpty()) { + appPackagePrefix = derived.root.replace('.', '/') + "/"; + } + } + countRequests(instrumentation, IndexReport.JACOCO_ATTACHED.equals(index.jacoco), + appClasses, appPackagePrefix); } else if (!transformerAdded) { // Attached to a running JVM, or started from the app's code, and // never as a -javaagent: ServerEntries cannot change a class, so @@ -335,7 +655,23 @@ private static boolean start(CoverageIndex index, Instrumentation instrumentatio // the index holds it, and the log says so when the JVM has a JaCoCo // agent of its own (jacocoAttached). static void countRequests(Instrumentation instrumentation, boolean jacocoAttached) { + countRequests(instrumentation, jacocoAttached, Collections.emptySet(), null); + } + + static void countRequests(Instrumentation instrumentation, boolean jacocoAttached, + Set appClasses, String appPackagePrefix) { boolean requests = endWaitMillis() != 0; + boolean asyncCallSitesOff = isAsyncCallSitesTurnedOff(); + Set allowed = asyncCallSitesOff || appClasses == null + ? Collections.emptySet() + : appClasses; + String prefix = asyncCallSitesOff ? null : appPackagePrefix; + boolean hasCallSiteRewrites = !allowed.isEmpty() + || (prefix != null && !prefix.isEmpty()); + if (asyncCallSitesOff) { + log(Level.INFO, "Keploy dedup: KEPLOY_JAVA_ASYNC_CALLSITES is off, so JDK executor and" + + " CompletableFuture call-site rewriting is disabled (asyncExecutors=false)", null); + } try { boolean retransformable = instrumentation.isRetransformClassesSupported(); if (!retransformable && jacocoAttached) { @@ -343,12 +679,15 @@ static void countRequests(Instrumentation instrumentation, boolean jacocoAttache + " true in its manifest, or this JVM cannot retransform, so a JaCoCo agent attached after" + " it instruments the " + (requests ? "server, scheduler and Spring executor" : "scheduler and Spring executor") - + " classes it changes, and each test's classMismatch names them when Keploy measures" + + " classes it changes" + + (hasCallSiteRewrites ? ", as well as any application classes whose executor calls it rewrites" : "") + + ", and each test's classMismatch names them when Keploy measures" + " them. Attach JaCoCo before it, or run keploy-sdk.jar as released", null); } - instrumentation.addTransformer(new ServerEntries(requests), retransformable); + instrumentation.addTransformer(new ServerEntries(requests, allowed, prefix), retransformable); transformerAdded = true; + executorCallSitesEnabled = hasCallSiteRewrites; } catch (RuntimeException e) { log(Level.WARNING, "Keploy dedup does not count the app's requests or see its scheduled jobs' runs:" + " their classes could not be changed to count them", e); @@ -489,6 +828,7 @@ public static void stop() { + " its socket is closed, and it stops once its command ends", null); } } + RequestGate.disarm(); STARTED.set(false); } @@ -732,6 +1072,7 @@ private static final class CommandServer implements CoverageWorker { // receiver may ask between an END and a START). Like activeTestId, // only the worker thread uses it. private String lastEndedTestId; + private boolean lastEndedMayEmitTail; // The between-tests hits the last START cleared, for a receiver that // asked for them: made into a record and sent once that START's // answer is written and its connection closed, off the time Keploy @@ -763,6 +1104,10 @@ void bind() throws IOException { throw t; } serverSocket = socket; + // Arm immediately if Keploy's data receiver is already listening. + if (receiverKey(publisher.socketFile) != null) { + RequestGate.arm(); + } } // run accepts commands until close(). Only this thread closes the @@ -830,6 +1175,7 @@ private void handle(Socket socket) { if (line == null) { return; } + RequestGate.arm(); if (BuildTable.COMMAND.equals(line.trim())) { // the build table: ACK, then sent on its own thread String reply; // or IGNORED, with reason=low_heap when the heap is short @@ -841,6 +1187,9 @@ private void handle(Socket socket) { }, () -> BuildTable.files(index.entries(), e -> e.className, e -> e.bytes), new File(dataSocketPath)); + if (UNIX_REPLY_TAKEN.equals(reply)) { + reply = unixReplyTaken(); + } } catch (Throwable t) { // thrown past here, it would end the accept loop: IGNORED instead log(Level.WARNING, "Keploy coverage: the build table was not started", t); reply = UNIX_REPLY_IGNORED; @@ -857,7 +1206,7 @@ private void handle(Socket socket) { log(Level.SEVERE, "Failed to run Java dedup coverage command: " + line.trim(), e); taken = false; } - writeReply(commandSocket.getOutputStream(), taken ? UNIX_REPLY_TAKEN : UNIX_REPLY_IGNORED); + writeReply(commandSocket.getOutputStream(), taken ? unixReplyTaken() : UNIX_REPLY_IGNORED); } catch (IOException e) { log(Level.SEVERE, "Failed to handle Java dedup coverage command", e); } @@ -889,30 +1238,49 @@ private boolean run(String line) { } } + private String unixReplyTaken() { + try { + return computeCapabilities(collector).toUnixAck(); + } catch (RuntimeException e) { + log(Level.FINE, "Failed to compute live Unix capabilities; falling back to bare ACK proto=3", e); + return UNIX_REPLY_TAKEN; + } + } + // run runs one parsed command under testCaseLock, and marks its steps. private boolean run(CoverageCommand command, Phases phases) { if (command.action == CommandAction.START) { // Set only once the counters are cleared: counters not // cleared hold the lines of the tests before this one, so // this START is not taken and its END is ignored too. + String prevActive = activeTestId; activeTestId = ""; String after = lastEndedTestId; + boolean prevMayEmitTail = lastEndedMayEmitTail; lastEndedTestId = null; + lastEndedMayEmitTail = false; // Warm up app classes once before the first measured window so // one-time lines aren't charged to the first test. collector.warmup(); phases.mark("warmup"); List cleared = new ArrayList<>(); - if (!collector.begin(phases, cleared)) { + boolean[] suppressBackground = {false}; + if (!collector.begin(command.testId, prevActive, phases, cleared, suppressBackground)) { return false; } activeTestId = command.testId; // Only what ran since a test's coverage was read: before the // first test it is the app's start and the warmup, and after // a START with no END, or an END not taken, that test's own - // hits. + // hits. Also suppress gaps that may hold a previous test's + // async/cut/job tail so those probes are not emitted as + // background. if (after != null && !cleared.isEmpty() && publisher.backgroundAsked()) { - pendingBackground = new BackgroundWindow(after, command.testId, cleared); + if (prevMayEmitTail || suppressBackground[0]) { + publisher.noteBackgroundLost(); + } else { + pendingBackground = new BackgroundWindow(after, command.testId, cleared); + } } return true; } @@ -921,6 +1289,7 @@ private boolean run(CoverageCommand command, Phases phases) { // taken (another test's id, its hits lost, its send failed), what // the next START clears may be a test's own hits. lastEndedTestId = null; + lastEndedMayEmitTail = false; if (!command.testId.equals(activeTestId)) { log(Level.SEVERE, "Ignoring mismatched END command. expected=" + activeTestId + ", actual=" @@ -932,10 +1301,22 @@ private boolean run(CoverageCommand command, Phases phases) { } try { - boolean cut = !collector.awaitRequests(command.testId, phases); + RequestGate.WindowOutcome outcome = collector.awaitRequests(command.testId, phases); + boolean cut = !outcome.drained; // The job window closes once the hits are read: a job that // started while they were read may be in them. - TestCoverage coverage = collector.capture(phases).ended(cut, JobGate.close()); + TestCoverage raw = collector.capture(phases); + List jobContams = JobGate.close(); + boolean noServerEntry = transformerAdded && collector.endWaitMillis > 0 + && !raw.probesByClass.isEmpty() && outcome.enteredCount == 0 && jobContams.isEmpty(); + if (noServerEntry) { + noteObservedNoServerEntry(command.testId); + } + List unverified = noServerEntry + ? Collections.singletonList("no-server-entry") + : Collections.emptyList(); + TestCoverage coverage = raw.ended(cut, + mergeContaminations(outcome.contaminations, jobContams), unverified); if (coverage.probesByClass.isEmpty()) { log(Level.FINE, "No Java coverage collected for " + command.testId, null); } @@ -944,6 +1325,7 @@ private boolean run(CoverageCommand command, Phases phases) { // test's own late hits: not a window, as after an END not // taken. lastEndedTestId = cut ? null : command.testId; + lastEndedMayEmitTail = !cut && (outcome.tailActiveAtEnd || noServerEntry || JobGate.hasExpiredRunning()); return true; } catch (Exception e) { // Not ACK for the same reason: nothing reached Keploy. @@ -1011,14 +1393,24 @@ private static void closeQuietly(Closeable closeable) { * connection open for the whole replay. Mirrors {@link CommandServer}'s dispatch * but inverts the roles — here the SDK is the client. Wire protocol: *
-     *   collector -> SDK : "START <id>" | "END <id>"
-     *   SDK -> collector : "ACK"                        (after a START cleared the counters)
-     *                      "COV <compact-json>" + "ACK" (after an END read the test's hits)
-     *                      "IGNORED <id>" + "ACK"         (after a START that could not
-     *                                                     clear them, an END with no START,
-     *                                                     or an END whose hits could not
-     *                                                     be read)
+     *   SDK -> collector (on connect and whenever live capabilities change):
+     *                      "HELLO {<dynamic capabilities json>}"
+     *   collector -> SDK : "ACK_ID" | "BACKGROUND" | "NOP [<token>]" | "START <id>" | "END <id>"
+     *   SDK -> collector : ["HELLO {<updated capabilities json>}"] + "ACK [id]" [+ "BACKGROUND <compact-json>"]
+     *                                                      (after a START cleared the counters;
+     *                                                      BACKGROUND follows ACK so START is
+     *                                                      never delayed by index reporting)
+     *                      ["HELLO {<updated capabilities json>}"] + "COV <compact-json>" + "ACK [id]"
+     *                                                      (after an END read the test's hits)
+     *                      "IGNORED <id>" + "ACK [id]"    (after a START that could not
+     *                                                      clear them, an END with no START,
+     *                                                      or an END whose hits could not
+     *                                                      be read)
      * 
+ * By default {@code ACK} is bare for older collectors that match + * {@code line == "ACK"}. Once the collector sends {@code ACK_ID}, every + * subsequent {@code START}/{@code END}/{@code IGNORED} echoes {@code ACK <id>} + * so the collector can correlate each barrier with the exact test it issued. * The collector starts listening only when replay begins, so the connect loop * retries until it is reachable. */ @@ -1038,6 +1430,23 @@ private static final class CoverageTcpClient implements CoverageWorker { private final Object testCaseLock = new Object(); private volatile Socket socket; private String activeTestId = ""; + // Mirrors CommandServer: set once an END sent a non-cut COV, cleared by + // every START and every END until its record is sent, so what the next + // START clears ran strictly between two tests. + private String lastEndedTestId; + private boolean lastEndedMayEmitTail; + // Opt-in per TCP connection via "BACKGROUND" command so older collectors + // never receive unexpected BACKGROUND frames. + private boolean backgroundRequested; + // Opt-in per TCP connection via "ACK_ID" command so older collectors + // matching bare "ACK" keep working unchanged. + private boolean ackWithId; + // Last HELLO frame sent on this connection: whenever live capabilities + // change (e.g. a server class loads or external JaCoCo finishes + // premain after an early connect), a fresh HELLO is emitted before the + // next START/END reply so the collector never acts on stale flags. + private String lastHelloSent; + private int backgroundLost; // Connect retries spin ~1/s until the collector is reachable; log the first // failure at INFO and the rest at FINE so we don't spam k8s app logs. private boolean connectFailureLogged = false; @@ -1048,12 +1457,28 @@ private static final class CoverageTcpClient implements CoverageWorker { this.port = port; } + private String helloFrame() { + RuntimeException injected = testHelloFailure; + if (injected != null) { + throw injected; + } + return computeCapabilities(collector).toHelloFrame(collector.helloBuildId()); + } + + private void maybeSendUpdatedHello(OutputStream out) throws IOException { + String current = helloFrame(); + if (!current.equals(lastHelloSent)) { + writeLine(out, current); + lastHelloSent = current; + } + } + @Override public void run() { while (running.get()) { try { connectAndServe(); - } catch (IOException e) { + } catch (IOException | RuntimeException | LinkageError e) { if (running.get()) { Level level = connectFailureLogged ? Level.FINE : Level.INFO; connectFailureLogged = true; @@ -1090,10 +1515,21 @@ private void connectAndServe() throws IOException { } socket = open; connectFailureLogged = false; + // Collector connected: arm runtime request/executor/job tracking. + RequestGate.arm(); // Fresh connection (possibly a new proxy replica after a drop): re-arm // the one-time zip send so the collector on the other end gets the // class bytecode. MinIO first-write-wins makes the re-store idempotent. collector.resetBytecodeSentForNewConnection(); + synchronized (testCaseLock) { + activeTestId = ""; + lastEndedTestId = null; + lastEndedMayEmitTail = false; + backgroundRequested = false; + ackWithId = false; + lastHelloSent = null; + backgroundLost = 0; + } log(Level.INFO, "Keploy dedup: connected to collector at " + host + ":" + port, null); try (Socket active = open; BufferedReader reader = new BufferedReader( @@ -1101,12 +1537,63 @@ private void connectAndServe() throws IOException { // dispatch writes a reply's lines here and ack sends them in one // write once the reply is whole. OutputStream out = new BufferedOutputStream(active.getOutputStream(), REPLY_BUFFER_BYTES); + // Declare live protocol + honesty capabilities immediately on connect. + // Older collectors ignore unrecognized lines; newer collectors gate + // removal eligibility on this declaration and refresh it if a later + // HELLO arrives after server/JaCoCo initialization completes. + synchronized (testCaseLock) { + try { + maybeSendUpdatedHello(out); + } catch (RuntimeException | LinkageError e) { + log(Level.FINE, "Failed to compute connect-time HELLO; falling back to minimal HELLO", e); + String fallback = buildHelloFrame("", "", "", "", "", "", + false, false, false, false, true, true, false, false); + writeLine(out, fallback); + lastHelloSent = fallback; + } + out.flush(); + } String line; while (running.get() && (line = reader.readLine()) != null) { String trimmed = line.trim(); if (trimmed.isEmpty()) { continue; } + if (ACK_ID_COMMAND.equals(trimmed)) { + synchronized (testCaseLock) { + ackWithId = true; + } + continue; + } + if (BACKGROUND_COMMAND.equals(trimmed)) { + synchronized (testCaseLock) { + // Always honor BACKGROUND opt-in: frames are only + // emitted when cleared is non-empty (which requires + // a live ProbeScan), so an early BACKGROUND sent + // before external JaCoCo starts still takes effect + // once JaCoCo is ready. Precompute coverageIndex.report() + // off the TCP command thread so the first BACKGROUND + // frame never blocks an incoming END. + backgroundRequested = true; + collector.coverageIndex.precomputeReportAsync(); + if (collector.probeScan() == null && !collector.isJacocoPendingStart()) { + log(Level.INFO, "Keploy dedup: BACKGROUND is not taken on TCP: JaCoCo's probes are" + + " not read in place (KEPLOY_JAVA_SCAN off, JaCoCo over TCP, or the scan" + + " failed), so the hits between two tests are not seen", null); + } + } + continue; + } + if (NOP_COMMAND.equals(trimmed) || trimmed.startsWith(NOP_COMMAND + " ")) { + String token = trimmed.length() > NOP_COMMAND.length() + ? trimmed.substring(NOP_COMMAND.length() + 1).trim() + : ""; + synchronized (testCaseLock) { + writeLine(out, token.isEmpty() ? "ACK" : "ACK " + token); + out.flush(); + } + continue; + } CoverageCommand command = CoverageCommand.parse(trimmed); if (command == null) { continue; @@ -1130,14 +1617,21 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // counters are cleared: counters not cleared hold the lines // of the tests before this one, so this START is not taken // and its END is ignored too. + String prevActive = activeTestId; activeTestId = ""; + String after = lastEndedTestId; + boolean prevMayEmitTail = lastEndedMayEmitTail; + lastEndedTestId = null; + lastEndedMayEmitTail = false; boolean reset; + List cleared = new ArrayList<>(); + boolean[] suppressBackground = {false}; try { // Warm up app classes once before the first measured window so // one-time lines aren't charged to the first test. collector.warmup(); phases.mark("warmup"); - reset = collector.begin(phases, new ArrayList()); + reset = collector.begin(command.testId, prevActive, phases, cleared, suppressBackground); } catch (RuntimeException e) { // Not taken, and the connection goes on: thrown past // here, it ended this thread, and no later command @@ -1152,11 +1646,32 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // collector has no other sign this test went unmeasured. writeLine(out, IGNORED_REPLY + " " + command.testId); } - ack(out); + try { + maybeSendUpdatedHello(out); + } catch (RuntimeException | LinkageError e) { + log(Level.FINE, "Failed to refresh HELLO before START ACK for " + command.testId, e); + } + ack(out, command.testId); + // Emit BACKGROUND after START's ACK (matching the unix path) + // so building coverageIndex.report() / JSON never delays the + // test's START barrier. Suppress gaps that may hold a + // previous test's async/cut/job tail and count them in lost. + if (reset && after != null && !cleared.isEmpty() && backgroundRequested) { + if (prevMayEmitTail || suppressBackground[0]) { + backgroundLost++; + } else { + writeBackgroundFrame(out, after, command.testId, cleared); + } + } return; } if (command.action == CommandAction.END) { + // Set again only once this END's non-cut COV is written: + // after an END not taken or cut, what the next START clears + // may hold this test's own hits. + lastEndedTestId = null; + lastEndedMayEmitTail = false; if (!command.testId.equals(activeTestId)) { log(Level.SEVERE, "Ignoring mismatched END command. expected=" + activeTestId + ", actual=" @@ -1167,7 +1682,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // follows, as it ends the collector's wait, and a collector // that does not know this frame skips it. writeLine(out, IGNORED_REPLY + " " + command.testId); - ack(out); + ack(out, command.testId); return; } @@ -1176,21 +1691,50 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // so exactly one COV must precede every ACK — a missing COV on an // exception would shift the collector onto the next test's frames. TestCoverage coverage; + boolean cut; + boolean tailActiveAtEnd; try { - boolean cut = !collector.awaitRequests(command.testId, phases); - coverage = collector.capture(phases).ended(cut, JobGate.close()); + RequestGate.WindowOutcome outcome = collector.awaitRequests(command.testId, phases); + cut = !outcome.drained; + tailActiveAtEnd = outcome.tailActiveAtEnd; + TestCoverage raw = collector.capture(phases); + List jobContams = JobGate.close(); + if (!tailActiveAtEnd && JobGate.hasExpiredRunning()) { + tailActiveAtEnd = true; + } + boolean noServerEntry = transformerAdded && collector.endWaitMillis > 0 + && !raw.probesByClass.isEmpty() && outcome.enteredCount == 0 + && jobContams.isEmpty(); + if (noServerEntry) { + noteObservedNoServerEntry(command.testId); + tailActiveAtEnd = true; + } + List unverified = noServerEntry + ? Collections.singletonList("no-server-entry") + : Collections.emptyList(); + coverage = raw.ended(cut, + mergeContaminations(outcome.contaminations, jobContams), unverified); } catch (Exception e) { // Not taken, as on the unix socket: an empty COV is // the frame of a test that ran no line of the app. log(Level.SEVERE, "Failed to collect Java coverage for " + command.testId, e); activeTestId = ""; writeLine(out, IGNORED_REPLY + " " + command.testId); - ack(out); + ack(out, command.testId); return; } if (coverage.probesByClass.isEmpty()) { log(Level.FINE, "No Java coverage collected for " + command.testId, null); } + // Emit updated HELLO if capabilities changed during the test + // (e.g. Jetty/Undertow loaded its request entry on first request, + // or probeScan was dropped). Isolated from the COV try block so a + // runtime error computing HELLO can never suppress COV before ACK. + try { + maybeSendUpdatedHello(out); + } catch (RuntimeException | LinkageError e) { + log(Level.FINE, "Failed to refresh HELLO before COV for " + command.testId, e); + } try { // Always emit exactly one COV before ACK — even when empty — // so the line-oriented collector stays in lockstep (the unix @@ -1203,6 +1747,8 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // reply that fits the buffer still leaves in one write, // at the ACK. writeLine(out, cov); + lastEndedTestId = cut ? null : command.testId; + lastEndedMayEmitTail = !cut && tailActiveAtEnd; // Ride the bytecode+manifest over this same raw-TCP channel // (the only app->proxy path the replay agent doesn't mock- // intercept), when the manifest has grown. A failure building @@ -1216,21 +1762,57 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) log(Level.FINE, "Failed to send the COV or CLASSES frame for " + command.testId, e); } finally { activeTestId = ""; - ack(out); + ack(out, command.testId); phases.mark("send"); } } } } + private void writeBackgroundFrame(OutputStream out, String after, String before, + List cleared) throws IOException { + String frame; + int classes; + try { + // Never block the TCP command thread synchronously loading/hashing + // a large app index: if report() is not ready yet for a large + // index, precompute off-thread and count this window in lost. + IndexReport report = collector.coverageIndex.reportForBackground(); + if (report == null) { + backgroundLost++; + return; + } + BackgroundRecord record = new BackgroundRecord( + report.build, after, before, + collector.backgroundProbes(cleared)); + if (backgroundLost > 0) { + record.lost = backgroundLost; + } + classes = record.executedLinesByFile.size(); + frame = BACKGROUND_COMMAND + " " + GSON.toJson(record); + } catch (Throwable t) { + backgroundLost++; + log(backgroundLost == 1 ? Level.WARNING : Level.FINE, + "Keploy dedup: could not build BACKGROUND frame before " + before, t); + return; + } + writeLine(out, frame); + out.flush(); + backgroundLost = 0; + if (diagnosticsEnabled()) { + diagnostic("BACKGROUND frame sent over TCP: after=" + after + ", before=" + before + + ", classes=" + classes); + } + } + // writeLine adds a line to the reply; ack ends the reply and sends it. private static void writeLine(OutputStream out, String message) throws IOException { out.write(message.getBytes(StandardCharsets.UTF_8)); out.write('\n'); } - private static void ack(OutputStream out) throws IOException { - writeLine(out, "ACK"); + private void ack(OutputStream out, String testId) throws IOException { + writeLine(out, ackWithId && testId != null && !testId.isEmpty() ? "ACK " + testId : "ACK"); out.flush(); } @@ -1357,15 +1939,28 @@ private CoverageCollector(JacocoClient jacocoClient, CoverageIndex coverageIndex private ProbeScan probeScan; private boolean probeScanLookedUp; + private synchronized boolean isJacocoPendingStart() { + return !probeScanLookedUp && !isScanTurnedOff() && jacocoClient.lookupInProcessAgent().notStartedYet; + } + private synchronized ProbeScan probeScan() { if (!probeScanLookedUp) { - probeScanLookedUp = true; if (isScanTurnedOff()) { + probeScanLookedUp = true; log(Level.INFO, "Keploy dedup: KEPLOY_JAVA_SCAN is off, so each test takes JaCoCo's dump" + " and reset, and no BACKGROUND record is sent", null); return null; } - Object agent = jacocoClient.runtimeAgent(); + JacocoClient.AgentLookup lookup = jacocoClient.lookupInProcessAgent(); + if (lookup.notStartedYet) { + // External JaCoCo is on the classpath (e.g. attached after + // keploy-sdk) but its premain has not run yet: do not latch + // probeScanLookedUp so a later START/END picks it up once + // started. + return null; + } + probeScanLookedUp = true; + Object agent = lookup.inProcess == null ? null : lookup.inProcess.agent; if (agent != null) { try { probeScan = ProbeScan.locate(agent); @@ -1389,21 +1984,93 @@ private synchronized void dropProbeScan(Throwable cause) { cause); } + private volatile String cachedHelloBuildId; + + // Stable, non-empty, deterministic build/class-index identity for TCP + // HELLO frames. Uses the cached IndexReport buildId if already computed + // (or fast in-memory when <= 4096 entries are already loaded), else + // hashes build tag + class dirs + launch command + classpath metadata + + // sdkVersion without blocking connect on full-jar scanning. Cached once + // so HELLO.buildId never flips mid-connection. + private String helloBuildId() { + String id = cachedHelloBuildId; + if (id != null) { + return id; + } + IndexReport ready = coverageIndex.cachedReport(); + if (ready != null && ready.build != null && !ready.build.isEmpty()) { + id = ready.build; + } else { + List loaded = coverageIndex.entries; + if (loaded != null && !loaded.isEmpty() && loaded.size() <= 4096) { + String b = coverageIndex.report().build; + if (b != null && !b.isEmpty()) { + id = b; + } + } + } + if (id == null || id.isEmpty()) { + id = computeFastDeterministicBuildId(); + } + cachedHelloBuildId = id; + return id; + } + + private String computeFastDeterministicBuildId() { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + updateDigest(md, "keploy-hello-build-v1\n"); + updateDigest(md, envOrProperty("KEPLOY_BUILD_TAG", "keploy.build.tag", "")); + updateDigest(md, "\n"); + updateDigest(md, envOrProperty("KEPLOY_JAVA_CLASS_DIRS", "keploy.java.class.dirs", "")); + updateDigest(md, "\n"); + updateDigest(md, System.getProperty("sun.java.command", "")); + updateDigest(md, "\n"); + updateDigest(md, IndexReport.versionOf(IndexReport.class)); + updateDigest(md, "\n"); + String cp = System.getProperty("java.class.path", ""); + if (!cp.isEmpty()) { + String[] parts = cp.split(Pattern.quote(File.pathSeparator)); + int limit = Math.min(parts.length, 64); + for (int i = 0; i < limit; i++) { + String part = parts[i]; + updateDigest(md, part); + File f = new File(part); + if (f.isFile()) { + updateDigest(md, ":" + f.length() + ":" + f.lastModified()); + } + updateDigest(md, "\n"); + } + } + return "jvh-" + IndexReport.hex(md.digest()).substring(0, 32); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static void updateDigest(MessageDigest md, String s) { + if (s != null && !s.isEmpty()) { + md.update(s.getBytes(StandardCharsets.UTF_8)); + } + } + // begin clears what the app's classes ran since the last test ended, // so that none of it is charged to the next test, and says whether - // it did. With the scan, that is one pass over the app's classes, and - // what it clears is background (a scheduled job, a health check): - // added to cleared, counted in the diagnostics, never in a test's - // hits. Without it, or when the pass fails (in any way: a START only - // has to clear), JaCoCo resets every class, and cleared stays empty. - private boolean begin(Phases phases, List cleared) { + // it did. Sets suppressBackground[0] = true when opening the new window + // added any tail:, job-tail:, or armed-mid-flight contamination. + private boolean begin(String testId, String prevActiveTestId, Phases phases, List cleared, + boolean[] suppressBackground) { // A job running now, or that starts before END reads the hits, // runs in this test's window: opened before the clear, as what // a job ran before is cleared only once it has ended. - JobGate.open(); + boolean jobTail = JobGate.open(); // This test's requests come in from now on; END waits for them - // alone. - RequestGate.open(); + // alone. Any cut/lingering prior window marks this window + // contaminated ("tail:") until drained. + boolean reqTail = RequestGate.open(testId, prevActiveTestId); + if (suppressBackground != null && suppressBackground.length > 0) { + suppressBackground[0] = jobTail || reqTail; + } ProbeScan scan = probeScan(); if (scan != null) { try { @@ -1423,27 +2090,24 @@ private boolean begin(Phases phases, List cleared) { return reset; } - // awaitRequests waits, for at most endWaitMillis, until the requests - // that came in since this test's START are done, and says whether - // they are: a server writes a response before the request is done - // (a filter's code after the chain, a request log), so Keploy can - // send END while the test's own code still runs. False, the END is - // cut: what still runs lands after it. - private boolean awaitRequests(String testId, Phases phases) { + // awaitRequests closes the current RequestGate window, waits for at + // most endWaitMillis when endWaitMillis > 0, and returns the window's + // drain status, request entry count, and collected contaminations. + private RequestGate.WindowOutcome awaitRequests(String testId, Phases phases) { if (ServerEntries.countsNone() && NOT_COUNTED_LOGGED.compareAndSet(false, true)) { log(Level.INFO, notCounted(endWaitMillis, ServerEntries.uncounted()), null); } - if (endWaitMillis == 0 || RequestGate.running() <= 0) { - return true; + RequestGate.WindowOutcome outcome = RequestGate.awaitWindow( + TimeUnit.MILLISECONDS.toNanos(endWaitMillis), endWaitMillis > 0); + if (outcome.waited) { + phases.mark("requests"); } - boolean done = RequestGate.await(TimeUnit.MILLISECONDS.toNanos(endWaitMillis)); - phases.mark("requests"); - if (!done) { + if (!outcome.drained) { log(Level.WARNING, "Keploy dedup: " + testId + "'s requests still ran " + endWaitMillis + " ms after its END, so its record says windowCut and a Keploy that reads it does not" + " judge the test: what they ran after that is not in it (KEPLOY_JAVA_END_WAIT_MS sets the wait)", null); } - return done; + return outcome; } // describe says how many classes and probes hits holds, and names a few classes. @@ -1906,41 +2570,58 @@ private byte[] dump(boolean dump, boolean reset) throws IOException { return dumpOverTcp(dump, reset); } - // runtimeAgent is JaCoCo's agent object in this JVM, or null when - // JaCoCo is reached over TCP. - private Object runtimeAgent() { - InProcessAgent agent = inProcessAgent(); - return agent == null ? null : agent.agent; + private static final class AgentLookup { + static final AgentLookup UNAVAILABLE = new AgentLookup(null, false); + static final AgentLookup NOT_STARTED = new AgentLookup(null, true); + + final InProcessAgent inProcess; + final boolean notStartedYet; + + AgentLookup(InProcessAgent inProcess, boolean notStartedYet) { + this.inProcess = inProcess; + this.notStartedYet = notStartedYet; + } } - private InProcessAgent inProcessAgent() { + // Single shared lookup for JaCoCo's in-process agent: returns + // NOT_STARTED without latching inProcessUnavailable when RT is on the + // classpath but its premain has not started the agent yet. + private AgentLookup lookupInProcessAgent() { if (inProcessUnavailable) { - return null; + return AgentLookup.UNAVAILABLE; } InProcessAgent cached = inProcessAgent; if (cached != null) { - return cached; + return new AgentLookup(cached, false); } synchronized (this) { if (inProcessUnavailable) { - return null; + return AgentLookup.UNAVAILABLE; } if (inProcessAgent != null) { - return inProcessAgent; + return new AgentLookup(inProcessAgent, false); } try { inProcessAgent = InProcessAgent.locate(); + return new AgentLookup(inProcessAgent, false); + } catch (AgentNotStartedException e) { + log(Level.FINE, "JaCoCo in-process agent is not started yet; will retry", e); + return AgentLookup.NOT_STARTED; } catch (Throwable t) { inProcessUnavailable = true; log(Level.FINE, "JaCoCo in-process agent unavailable, will use TCP fallback at " + host + ":" + port, t); + return AgentLookup.UNAVAILABLE; } - return inProcessAgent; } } + private InProcessAgent inProcessAgent() { + return lookupInProcessAgent().inProcess; + } + private byte[] dumpOverTcp(boolean dump, boolean reset) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(32 * 1024); ExecutionDataWriter writer = new ExecutionDataWriter(output); @@ -1977,6 +2658,18 @@ private byte[] dumpOverTcp(boolean dump, boolean reset) throws IOException { } } + // Thrown when org.jacoco.agent.rt.RT is present on the classpath (e.g. + // external -javaagent:jacocoagent.jar attached after keploy-sdk.jar) but + // its premain has not started the agent yet (RT.getAgent() throws + // IllegalStateException). Must not permanently latch in-process lookup off. + private static final class AgentNotStartedException extends ReflectiveOperationException { + private static final long serialVersionUID = 1L; + + AgentNotStartedException(Throwable cause) { + super(cause); + } + } + private static final class InProcessAgent { private final Object agent; @@ -1991,11 +2684,14 @@ private InProcessAgent(Object agent, Method getExecutionData, Method reset) { static InProcessAgent locate() throws ReflectiveOperationException { ReflectiveOperationException firstFailure = null; + AgentNotStartedException notStarted = null; try { InProcessAgent bootstrapAgent = locateWithLoader(null); if (bootstrapAgent != null) { return bootstrapAgent; } + } catch (AgentNotStartedException e) { + notStarted = e; } catch (ReflectiveOperationException e) { firstFailure = e; } @@ -2006,6 +2702,10 @@ static InProcessAgent locate() throws ReflectiveOperationException { if (agent != null) { return agent; } + } catch (AgentNotStartedException e) { + if (notStarted == null) { + notStarted = e; + } } catch (ReflectiveOperationException e) { if (firstFailure == null) { firstFailure = e; @@ -2013,6 +2713,9 @@ static InProcessAgent locate() throws ReflectiveOperationException { } } + if (notStarted != null) { + throw notStarted; + } if (firstFailure != null) { throw firstFailure; } @@ -2029,7 +2732,15 @@ private static InProcessAgent locateWithLoader(ClassLoader loader) throws Reflec String loaderName = loader == null ? "bootstrap" : loader.toString(); diagnostic("resolved JaCoCo RT with loader=" + loaderName + ", source=" + source); } - Object resolved = rtClass.getMethod("getAgent").invoke(null); + Object resolved; + try { + resolved = rtClass.getMethod("getAgent").invoke(null); + } catch (InvocationTargetException e) { + if (e.getCause() instanceof IllegalStateException) { + throw new AgentNotStartedException(e.getCause()); + } + throw e; + } if (resolved == null) { return null; } @@ -2125,29 +2836,76 @@ private List entries() { private volatile String includes = ""; private volatile String jacocoVersion = ""; private volatile IndexReport report; + private final AtomicBoolean reportPrecomputeStarted = new AtomicBoolean(false); + + private IndexReport cachedReport() { + return report; + } + + private void precomputeReportAsync() { + if (report != null || !reportPrecomputeStarted.compareAndSet(false, true)) { + return; + } + try { + Thread t = new Thread(new Runnable() { + @Override + public void run() { + try { + report(); + } catch (Throwable ignored) { + // Never let background precomputation fail the JVM. + } + } + }, "keploy-index-report"); + t.setDaemon(true); + t.start(); + } catch (Throwable ignored) { + reportPrecomputeStarted.set(false); + } + } + + // reportForBackground returns the cached IndexReport immediately when + // ready, computes inline for small already-loaded indexes (<= 256 + // classes), or triggers background precomputation and returns null so + // the TCP command thread never stalls on a large app's index hashing. + private IndexReport reportForBackground() { + IndexReport cached = report; + if (cached != null) { + return cached; + } + List loaded = entries; + if (loaded != null && loaded.size() <= 256) { + return report(); + } + precomputeReportAsync(); + return null; + } // report is the INDEX report of this index: computed once, on the // first call, from entries() (so it reads the index if nothing has). + // Hashing runs outside `lock` so background precomputation never + // blocks an END command waiting on entries(). private IndexReport report() { IndexReport cached = report; if (cached != null) { return cached; } + List all = entries(); + long[] ids = new long[all.size()]; + Set roots = new LinkedHashSet<>(); + for (int i = 0; i < ids.length; i++) { + ClassEntry entry = all.get(i); + ids[i] = IndexReport.classId(entry.bytes); + String root = IndexReport.rootOf(entry.location, entry.className); + if (root != null) { + roots.add(root); + } + } + IndexReport built = new IndexReport(IndexReport.buildId(ids), sourceKind, launch, roots, packages, + all.size(), includes, jacoco, IndexReport.versionOf(IndexReport.class), jacocoVersion); synchronized (lock) { if (report == null) { - List all = entries(); - long[] ids = new long[all.size()]; - Set roots = new LinkedHashSet<>(); - for (int i = 0; i < ids.length; i++) { - ClassEntry entry = all.get(i); - ids[i] = IndexReport.classId(entry.bytes); - String root = IndexReport.rootOf(entry.location, entry.className); - if (root != null) { - roots.add(root); - } - } - report = new IndexReport(IndexReport.buildId(ids), sourceKind, launch, roots, packages, - all.size(), includes, jacoco, IndexReport.versionOf(IndexReport.class), jacocoVersion); + report = built; } return report; } @@ -2544,6 +3302,16 @@ synchronized boolean backgroundAsked() { return backgroundAskedBy != null; } + synchronized void noteBackgroundLost() { + Object key = receiverKey(socketFile); + if (key == null || !key.equals(backgroundAskedBy)) { + backgroundAskedBy = null; + backgroundLost = 0; + return; + } + backgroundLost++; + } + // sendBackground sends a between-tests window's hits (classes makes // them, only when they go out) to the receiver that asked for them, // after the INDEX report when that receiver does not have it yet. @@ -2633,6 +3401,7 @@ private static final class DedupPayload { private final List classMismatch; private final Boolean windowCut; private final List contaminated; + private final List unverified; private DedupPayload(String id, TestCoverage coverage) { this.id = id; @@ -2640,13 +3409,15 @@ private DedupPayload(String id, TestCoverage coverage) { this.classMismatch = coverage.classMismatch.isEmpty() ? null : coverage.classMismatch; this.windowCut = coverage.windowCut ? Boolean.TRUE : null; this.contaminated = coverage.contaminated.isEmpty() ? null : coverage.contaminated; + this.unverified = coverage.unverified.isEmpty() ? null : coverage.unverified; } } // TestCoverage is a test's coverage as its END read it: the probes hit // by class, the classes among them that are not the class the index // read, whether the END was cut (its requests still ran at the end of - // its wait), and the scheduled jobs that ran in its window. + // its wait), the jobs/tails that contaminated its window, and any v3-only + // unverified signals (such as "no-server-entry"). private static final class TestCoverage { static final TestCoverage NONE = new TestCoverage(Collections.>emptyMap(), @@ -2656,24 +3427,27 @@ private static final class TestCoverage { final List classMismatch; final boolean windowCut; final List contaminated; + final List unverified; TestCoverage(Map> probesByClass, List classMismatch) { - this(probesByClass, classMismatch, false, Collections.emptyList()); + this(probesByClass, classMismatch, false, Collections.emptyList(), + Collections.emptyList()); } TestCoverage(Map> probesByClass, List classMismatch, boolean windowCut, - List contaminated) { + List contaminated, List unverified) { this.probesByClass = probesByClass; this.classMismatch = classMismatch; this.windowCut = windowCut; this.contaminated = contaminated; + this.unverified = unverified; } // ended is this coverage as its END sends it: cut when it was read - // at the end of a wait its requests outran, and with the jobs that - // ran in its window. - TestCoverage ended(boolean cut, List jobs) { - return new TestCoverage(probesByClass, classMismatch, cut, jobs); + // at the end of a wait its requests outran, with contaminations and + // any unverified signals. + TestCoverage ended(boolean cut, List jobs, List unverified) { + return new TestCoverage(probesByClass, classMismatch, cut, jobs, unverified); } } diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java index 814a77c..12b9032 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -1,5 +1,6 @@ package io.keploy.dedup; +import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; @@ -7,38 +8,61 @@ import java.util.HashSet; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ForkJoinPool; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.RunnableScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.logging.Level; import java.util.logging.Logger; /** - * OrderedPools says whether an executor's pool may order the tasks it is - * handed by their type, so that a task handed to it must reach it as it is: - * a pool whose queue is a PriorityBlockingQueue, or any queue with a - * Comparator of the app's, casts each task it compares to the app's own - * type, and throws on a task in RequestGate's wrapper. + * OrderedPools enforces a fail-closed allow-list of executors whose task + * handling is positively verified not to cast, serialize, deduplicate, + * reorder-by-type, or silently discard tasks handed to them. * - *

An executor's pool is what its public {@code getThreadPoolExecutor()} - * returns, as Spring's ThreadPoolTaskExecutor has. Its tasks go as they - * are unless its queue is one of the JDK's queues that keep their tasks in - * the order they came and never look at one (Spring builds a - * LinkedBlockingQueue or a SynchronousQueue); a queue of another class, or - * one that cannot be read, may order them. An executor with no such method - * (a SimpleAsyncTaskExecutor, which starts a thread per task, or the - * executor {@code @Async} calls with a Callable, which it never queues as - * it is) has no queue that sees the task. Nothing thrown while reading a - * pool or saying so in the log, by the app's own code too (an exception's - * {@code toString()}, a log Handler), reaches the app's call: that task - * goes as it is. + *

Only positively verified safe executors are wrapped: + *

    + *
  • Exact {@link ThreadPoolExecutor} with exact + * {@link ThreadPoolExecutor.AbortPolicy} and an exact {@code IN_ORDER} + * JDK queue ({@link LinkedBlockingQueue}, {@link SynchronousQueue}, + * {@link ArrayBlockingQueue}, {@link LinkedBlockingDeque}, + * {@link LinkedTransferQueue}).
  • + *
  • Exact {@link ScheduledThreadPoolExecutor} with exact + * {@link ThreadPoolExecutor.AbortPolicy}.
  • + *
  • Exact {@link ForkJoinPool}.
  • + *
  • Exact JDK {@code FinalizableDelegatedExecutorService} / + * {@code AutoShutdownDelegatedExecutorService} (constructed only by + * {@code Executors.newSingleThreadExecutor}), and JDK + * {@code DelegatedExecutorService} / {@code DelegatedScheduledExecutorService} + * only when their underlying delegate can be reflectively read and + * verified through to an allow-listed pool.
  • + *
  • Exact JDK 21+ {@code java.util.concurrent.ThreadPerTaskExecutor}.
  • + *
  • Known Spring executor types ({@code SimpleAsyncTaskExecutor}, + * {@code ThreadPoolTaskExecutor}, {@code ThreadPoolTaskScheduler}, + * {@code ConcurrentTaskExecutor}, and Spring's own anonymous inner + * {@code ThreadPoolTaskExecutor$} / {@code ThreadPoolTaskScheduler$} + * subclasses) verified through to an allow-listed inner pool.
  • + *
+ * + *

Any unknown or unclassified executor (e.g., Hazelcast + * {@code IExecutorService}, Ignite, Redisson, striped/keyed executors, custom + * {@code ExecutorService} or {@code ThreadPoolExecutor} subclasses, priority + * queues, non-{@code AbortPolicy} handlers, coalescing executors) fails CLOSED: + * {@link #orders(Object)} returns {@code true}, the app's task reaches the + * executor untouched, and {@link RequestGate} marks the current test window + * contaminated ({@code untracked-executor:}). */ final class OrderedPools { private static final Logger LOGGER = Logger.getLogger(KeployDedupAgent.class.getName()); + private static final int MAX_DELEGATE_DEPTH = 8; // The queues that never look at a task, by their exact class: a // subclass may override how it takes one. @@ -46,12 +70,90 @@ final class OrderedPools { LinkedBlockingQueue.class, SynchronousQueue.class, ArrayBlockingQueue.class, LinkedBlockingDeque.class, LinkedTransferQueue.class))); - // What POOL holds for a class with no public getThreadPoolExecutor(). + // What lookup caches hold for a class with no matching public method. private static final Object NONE = new Object(); - // The class whose getThreadPoolExecutor() throws IllegalStateException - // while its pool is not initialized, as its execute and submit do. + // Known same-thread inline executors whose execute/submit runs synchronously + // on the calling thread: neither wrapped nor flagged as untracked-executor. + private static final Set INLINE_EXECUTORS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "org.springframework.core.task.SyncTaskExecutor", + "com.google.common.util.concurrent.DirectExecutor", + "com.google.common.util.concurrent.MoreExecutors$DirectExecutor", + "com.google.common.util.concurrent.DirectExecutorService", + "com.google.common.util.concurrent.MoreExecutors$DirectExecutorService"))); + + private static final String SPRING_ASYNC_TASK_EXECUTOR = + "org.springframework.core.task.AsyncTaskExecutor"; + + // Whether a class implements Spring's AsyncTaskExecutor (which extends + // java.util.concurrent.Executor, not ExecutorService, and defines submit/ + // submitListenable/submitCompletable). + private static final ClassValue IS_SPRING_ASYNC_TASK_EXECUTOR = new ClassValue() { + @Override + protected Boolean computeValue(Class type) { + return implementsInterfaceByName(type, SPRING_ASYNC_TASK_EXECUTOR); + } + }; + + private static boolean implementsInterfaceByName(Class type, String interfaceName) { + for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) { + if (interfaceName.equals(c.getName())) { + return true; + } + for (Class iface : c.getInterfaces()) { + if (implementsInterfaceByName(iface, interfaceName)) { + return true; + } + } + } + return false; + } + + static boolean isInlineExecutor(Object executor) { + return executor != null && INLINE_EXECUTORS.contains(executor.getClass().getName()); + } + + static boolean isInlineExecutorClass(Class cls) { + return cls != null && INLINE_EXECUTORS.contains(cls.getName()); + } + + static boolean isSpringAsyncTaskExecutor(Object receiver) { + return receiver instanceof java.util.concurrent.Executor + && Boolean.TRUE.equals(IS_SPRING_ASYNC_TASK_EXECUTOR.get(receiver.getClass())); + } + + static boolean isSpringAsyncTaskExecutorClass(Class cls) { + return cls != null + && java.util.concurrent.Executor.class.isAssignableFrom(cls) + && Boolean.TRUE.equals(IS_SPRING_ASYNC_TASK_EXECUTOR.get(cls)); + } + + // Spring classes whose pool accessor throws IllegalStateException while + // not initialized, as their execute and submit do. private static final String SPRING_POOL = "org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"; + private static final String SPRING_SCHEDULER = "org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler"; + private static final String SPRING_CONCURRENT = "org.springframework.scheduling.concurrent.ConcurrentTaskExecutor"; + private static final String SPRING_SIMPLE_ASYNC = "org.springframework.core.task.SimpleAsyncTaskExecutor"; + private static final String SPRING_TASK_EXECUTOR_ADAPTER = + "org.springframework.core.task.support.TaskExecutorAdapter"; + private static final String SPRING_ASYNC_ASPECT = + "org.springframework.aop.interceptor.AsyncExecutionAspectSupport"; + private static final String JDK_FINALIZABLE_DELEGATED = + "java.util.concurrent.Executors$FinalizableDelegatedExecutorService"; + private static final String JDK_AUTO_SHUTDOWN_DELEGATED = + "java.util.concurrent.Executors$AutoShutdownDelegatedExecutorService"; + private static final String JDK_DELEGATED_SCHEDULED = + "java.util.concurrent.Executors$DelegatedScheduledExecutorService"; + private static final String JDK_DELEGATED = + "java.util.concurrent.Executors$DelegatedExecutorService"; + private static final String JDK_THREAD_PER_TASK = + "java.util.concurrent.ThreadPerTaskExecutor"; + + // Cached reflective handle to Executors$DelegatedExecutorService.e when + // accessible (Java 8, or Java 9+ with --add-opens). Null when inaccessible, + // in which case DelegatedExecutorService / DelegatedScheduledExecutorService + // fail closed. + private static final Field DELEGATED_INNER_FIELD = findDelegatedInnerField(); // A class's public getThreadPoolExecutor(), NONE when it has none, or // the String of what looking it up threw. getMethod resolves each type @@ -61,16 +163,142 @@ final class OrderedPools { // the class's for good: anything else (out of stack or memory for now) // leaves computeValue, so nothing is kept, that task goes as it is, and // the next one looks the class up again. - private static final ClassValue POOL = new ClassValue() { + private static final ClassValue POOL = methodLookup("getThreadPoolExecutor"); + private static final ClassValue SCHEDULED_POOL = methodLookup("getScheduledThreadPoolExecutor"); + private static final ClassValue CONCURRENT_EXECUTOR = methodLookup("getConcurrentExecutor"); + // Spring's TaskExecutorAdapter (used by @Async's AsyncExecutionInterceptor + // to wrap plain JDK ExecutorServices) stores its delegate in a private + // concurrentExecutor field with no public getter. + private static final ClassValue ADAPTER_FIELD = new ClassValue() { @Override protected Object computeValue(Class type) { - try { - return type.getMethod("getThreadPoolExecutor"); - } catch (NoSuchMethodException e) { - return NONE; - } catch (LinkageError | RuntimeException e) { - return e.toString(); + for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) { + if (SPRING_TASK_EXECUTOR_ADAPTER.equals(c.getName())) { + try { + Field f = c.getDeclaredField("concurrentExecutor"); + f.setAccessible(true); + return f; + } catch (Throwable e) { + return e.toString(); + } + } + } + return NONE; + } + }; + + // Whether a Spring executor subclass overrides execute/submit/doExecute + // (outside Spring's own executor base classes), which may cast or inspect + // the task before delegating to the inner pool. + private static final ClassValue OVERRIDES_SPRING_SUBMIT = new ClassValue() { + @Override + protected Boolean computeValue(Class type) { + for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) { + String name = c.getName(); + if (isKnownSpringBaseClass(name)) { + break; + } + if (declares(c, "execute", Runnable.class) + || declares(c, "execute", Runnable.class, long.class) + || declares(c, "submit", Runnable.class) + || declares(c, "submit", Callable.class) + || declares(c, "submitListenable", Runnable.class) + || declares(c, "submitListenable", Callable.class) + || declares(c, "submitCompletable", Runnable.class) + || declares(c, "submitCompletable", Callable.class) + || declares(c, "doExecute", Runnable.class)) { + return Boolean.TRUE; + } } + return Boolean.FALSE; + } + }; + + private static boolean isKnownSpringBaseClass(String name) { + return SPRING_POOL.equals(name) + || SPRING_SCHEDULER.equals(name) + || SPRING_CONCURRENT.equals(name) + || SPRING_SIMPLE_ASYNC.equals(name) + || SPRING_TASK_EXECUTOR_ADAPTER.equals(name) + || SPRING_ASYNC_ASPECT.equals(name); + } + + private static boolean isSpringExecutorHierarchy(Class cls) { + for (Class c = cls; c != null && c != Object.class; c = c.getSuperclass()) { + if (isKnownSpringBaseClass(c.getName())) { + return true; + } + } + return false; + } + + // Returns true iff executor extends one of the Spring executor classes that + // ServerEntries.addAsync actually instrumented, does not override execute/ + // submit/doExecute, and passes OrderedPools' fail-closed verification. + static boolean isHookedAndVerifiedSpringExecutor(Object executor) { + if (executor == null) { + return false; + } + Class cls = executor.getClass(); + String hookedBase = null; + for (Class c = cls; c != null && c != Object.class; c = c.getSuperclass()) { + String name = c.getName(); + if (SPRING_POOL.equals(name) + || SPRING_SCHEDULER.equals(name) + || SPRING_CONCURRENT.equals(name) + || SPRING_SIMPLE_ASYNC.equals(name)) { + hookedBase = name; + break; + } + } + if (hookedBase == null || !ServerEntries.isSpringExecutorHooked(hookedBase)) { + return false; + } + try { + if (Boolean.TRUE.equals(OVERRIDES_SPRING_SUBMIT.get(cls))) { + return false; + } + return !orders(executor); + } catch (Throwable ignored) { + return false; + } + } + + // Whether a ThreadPoolExecutor subclass overrides beforeExecute, + // afterExecute, newTaskFor, execute, submit, or (for + // ScheduledThreadPoolExecutor) decorateTask, which may cast the queued + // Runnable/Callable to an app-specific subtype. Spring's internal + // ThreadPoolTaskExecutor$ and ThreadPoolTaskScheduler$ anonymous subclasses + // only track Spring lifecycle hooks and never cast the task, so they are + // allowed. + private static final ClassValue OVERRIDES_TASK_HOOKS = new ClassValue() { + @Override + protected Boolean computeValue(Class type) { + if (type == ThreadPoolExecutor.class || type == ScheduledThreadPoolExecutor.class) { + return Boolean.FALSE; + } + for (Class c = type; c != null && c != ThreadPoolExecutor.class; c = c.getSuperclass()) { + if (c == ScheduledThreadPoolExecutor.class) { + break; + } + String name = c.getName(); + if (name.startsWith(SPRING_POOL + "$") || name.startsWith(SPRING_SCHEDULER + "$")) { + continue; + } + if (declares(c, "beforeExecute", Thread.class, Runnable.class) + || declares(c, "afterExecute", Runnable.class, Throwable.class) + || declares(c, "newTaskFor", Runnable.class, Object.class) + || declares(c, "newTaskFor", Callable.class) + || declares(c, "execute", Runnable.class) + || declares(c, "submit", Runnable.class) + || declares(c, "submit", Runnable.class, Object.class) + || declares(c, "submit", Callable.class) + || declares(c, "decorateTask", Runnable.class, RunnableScheduledFuture.class) + || declares(c, "decorateTask", Callable.class, RunnableScheduledFuture.class)) { + return Boolean.TRUE; + } + } + return Boolean.FALSE; } }; @@ -80,57 +308,263 @@ protected Object computeValue(Class type) { private OrderedPools() { } - // orders says whether executor's pool may order its tasks by their - // type; the first time it does for an executor's class, it says in the - // log that the tasks handed to that class are not counted. Whatever is - // thrown on the way, by the app's own code too (the toString() of its - // exception, a log Handler of its), stays here: the task goes as it is, - // which is always safe. + private static Field findDelegatedInnerField() { + try { + Class cls = Class.forName(JDK_DELEGATED); + Field f = cls.getDeclaredField("e"); + f.setAccessible(true); + return f; + } catch (Throwable t) { + return null; + } + } + + private static ClassValue methodLookup(final String methodName) { + return new ClassValue() { + @Override + protected Object computeValue(Class type) { + try { + return type.getMethod(methodName); + } catch (NoSuchMethodException e) { + return NONE; + } catch (LinkageError | RuntimeException e) { + return e.toString(); + } + } + }; + } + + private static boolean declares(Class type, String name, Class... params) { + try { + type.getDeclaredMethod(name, params); + return true; + } catch (NoSuchMethodException e) { + return false; + } catch (LinkageError | RuntimeException e) { + // Conservative: if we cannot inspect the subclass, treat it as overriding. + return true; + } + } + + // orders returns true (do NOT wrap) unless executor is positively verified + // on the safe allow-list. The first time an executor class is rejected, it + // logs once at INFO. Whatever is thrown on the way (including an + // exception's toString() or a throwing log Handler) stays here: the task + // goes untouched, which is always app-safe. static boolean orders(Object executor) { try { - return read(executor); + return read(executor, 0, true); } catch (Throwable e) { return true; } } - private static boolean read(Object executor) { + private static boolean read(Object executor, int depth, boolean requireVerified) { if (executor == null) { + // Top-level null is passed only for default commonPool (1-arg + // CompletableFuture.runAsync/supplyAsync) and static Spring + // helpers; a null delegate at depth > 0 always fails closed. + return depth > 0; + } + if (depth > MAX_DELEGATE_DEPTH) { + return uncounted(executor, "its delegate executor chain is too deep to inspect"); + } + Class cls = executor.getClass(); + if (executor instanceof ThreadPoolExecutor) { + return checkThreadPool((ThreadPoolExecutor) executor, executor); + } + if (cls == ForkJoinPool.class) { return false; } - Object pool = POOL.get(executor.getClass()); - if (pool == NONE) { + String className = cls.getName(); + if (JDK_FINALIZABLE_DELEGATED.equals(className) + || JDK_AUTO_SHUTDOWN_DELEGATED.equals(className) + || JDK_THREAD_PER_TASK.equals(className)) { return false; } - if (pool instanceof String) { - return uncounted(executor, "its pool's queue cannot be read (" + pool + ")"); + if (depth > 0 && INLINE_EXECUTORS.contains(className)) { + return false; } - Class queue; + if (JDK_DELEGATED.equals(className) || JDK_DELEGATED_SCHEDULED.equals(className)) { + return readDelegated(executor, depth); + } + if (isSpringExecutorHierarchy(cls)) { + Object pool = POOL.get(cls); + if (pool instanceof String) { + return readViaPoolMethod(executor, pool, SPRING_POOL); + } + if (Boolean.TRUE.equals(OVERRIDES_SPRING_SUBMIT.get(cls))) { + return uncounted(executor, "it is a Spring executor subclass (" + className + + ") that overrides execute/submit/doExecute"); + } + if (pool != NONE) { + return readViaPoolMethod(executor, pool, SPRING_POOL); + } + if (SPRING_SIMPLE_ASYNC.equals(className)) { + return false; + } + Object scheduled = SCHEDULED_POOL.get(cls); + if (scheduled != NONE) { + return readViaPoolMethod(executor, scheduled, SPRING_SCHEDULER); + } + Object concurrent = CONCURRENT_EXECUTOR.get(cls); + if (concurrent != NONE) { + return readViaConcurrentExecutor(executor, concurrent, depth); + } + Object adapterField = ADAPTER_FIELD.get(cls); + if (adapterField != NONE) { + return readViaAdapterField(executor, adapterField, depth); + } + } + if (requireVerified) { + return uncounted(executor, "its executor class is not on the verified safe allow-list"); + } + return false; + } + + private static boolean readViaAdapterField(Object executor, Object fieldOrError, int depth) { + if (fieldOrError instanceof String) { + return uncounted(executor, "its delegate executor cannot be read (" + fieldOrError + ")"); + } + Object delegate; + try { + delegate = ((Field) fieldOrError).get(executor); + } catch (Throwable e) { + if (e instanceof VirtualMachineError) { + return true; + } + return uncounted(executor, "its delegate executor cannot be read (" + e + ")"); + } + if (delegate == null || delegate == executor) { + return uncounted(executor, "its delegate executor cannot be inspected"); + } + return read(delegate, depth + 1, true); + } + + private static boolean readDelegated(Object executor, int depth) { + Field f = DELEGATED_INNER_FIELD; + if (f == null) { + return uncounted(executor, "its wrapped ExecutorService cannot be inspected for queue ordering"); + } + Object inner; try { - queue = ((ThreadPoolExecutor) ((Method) pool).invoke(executor)).getQueue().getClass(); + inner = f.get(executor); + } catch (Throwable t) { + if (t instanceof VirtualMachineError) { + return true; + } + return uncounted(executor, "its wrapped ExecutorService cannot be read (" + t + ")"); + } + if (inner == null || inner == executor) { + return uncounted(executor, "its wrapped ExecutorService cannot be inspected"); + } + return read(inner, depth + 1, true); + } + + private static boolean readViaPoolMethod(Object executor, Object methodOrError, String springClass) { + if (methodOrError instanceof String) { + return uncounted(executor, "its pool's queue cannot be read (" + methodOrError + ")"); + } + ThreadPoolExecutor tpe; + try { + tpe = (ThreadPoolExecutor) ((Method) methodOrError).invoke(executor); } catch (Throwable e) { - // Not a ThreadPoolExecutor, no queue, or not ours to call: the - // task goes as it is, and whatever was thrown stays here. Throwable why = e instanceof InvocationTargetException ? e.getCause() : e; if (why instanceof VirtualMachineError) { - // Out of stack or memory for now: that says nothing of the - // class, so the log says nothing, and the next task's pool - // is read again. return true; } if (e instanceof InvocationTargetException && why instanceof IllegalStateException - && SPRING_POOL.equals(((Method) pool).getDeclaringClass().getName())) { + && springClass.equals(((Method) methodOrError).getDeclaringClass().getName())) { // Spring's pool, not initialized: the executor's own call - // throws the same and takes no task, so the log says - // nothing of its class. + // throws the same and takes no task, so the log says nothing. return true; } return uncounted(executor, "its pool's queue cannot be read (" + why + ")"); } + if (tpe == null) { + return uncounted(executor, "its pool's queue cannot be read (java.lang.NullPointerException)"); + } + return checkThreadPool(tpe, executor); + } + + private static boolean readViaConcurrentExecutor(Object executor, Object methodOrError, int depth) { + if (methodOrError instanceof String) { + return uncounted(executor, "its delegate executor cannot be read (" + methodOrError + ")"); + } + Object delegate; + try { + delegate = ((Method) methodOrError).invoke(executor); + } catch (Throwable e) { + Throwable why = e instanceof InvocationTargetException ? e.getCause() : e; + if (why instanceof VirtualMachineError) { + return true; + } + return uncounted(executor, "its delegate executor cannot be read (" + why + ")"); + } + if (delegate == null || delegate == executor) { + return uncounted(executor, "its delegate executor cannot be inspected"); + } + return read(delegate, depth + 1, true); + } + + private static boolean isAllowedThreadPoolClass(Class cls) { + if (cls == ThreadPoolExecutor.class || cls == ScheduledThreadPoolExecutor.class) { + return true; + } + String name = cls.getName(); + return name.startsWith(SPRING_POOL + "$") || name.startsWith(SPRING_SCHEDULER + "$"); + } + + private static boolean checkThreadPool(ThreadPoolExecutor pool, Object reportedOwner) { + Class poolClass = pool.getClass(); + if (Boolean.TRUE.equals(OVERRIDES_TASK_HOOKS.get(poolClass))) { + return uncounted(reportedOwner, "its pool (" + poolClass.getName() + + ") overrides task hooks that may inspect or cast the task"); + } + try { + RejectedExecutionHandler handler = pool.getRejectedExecutionHandler(); + if (handler == null || handler.getClass() != ThreadPoolExecutor.AbortPolicy.class) { + String handlerName = handler == null ? "null" : handler.getClass().getName(); + return uncounted(reportedOwner, "its rejected execution handler, a " + + handlerName + ", may silently discard or inspect tasks"); + } + } catch (Throwable e) { + if (e instanceof VirtualMachineError) { + return true; + } + return uncounted(reportedOwner, "its pool's rejected execution handler cannot be read (" + e + ")"); + } + if (poolClass == ScheduledThreadPoolExecutor.class + || (pool instanceof ScheduledThreadPoolExecutor + && poolClass.getName().startsWith(SPRING_SCHEDULER + "$"))) { + // Exact ScheduledThreadPoolExecutor (and Spring's own + // ThreadPoolTaskScheduler internal subclass) always wraps + // execute/submit tasks in its own ScheduledFutureTask before + // enqueueing into DelayedWorkQueue, so the queue never casts the + // caller's task. + return false; + } + Class queue; + try { + queue = pool.getQueue().getClass(); + } catch (Throwable e) { + if (e instanceof VirtualMachineError) { + return true; + } + return uncounted(reportedOwner, "its pool's queue cannot be read (" + e + ")"); + } + if (!isAllowedThreadPoolClass(poolClass)) { + if (pool instanceof ScheduledThreadPoolExecutor) { + return uncounted(reportedOwner, "it is a ScheduledThreadPoolExecutor subclass (" + + poolClass.getName() + ") whose task handling cannot be assumed safe"); + } + return uncounted(reportedOwner, "it is a ThreadPoolExecutor subclass (" + + poolClass.getName() + ") whose task handling cannot be assumed safe"); + } if (IN_ORDER.contains(queue)) { return false; } - return uncounted(executor, "its pool's queue, a " + queue.getName() + return uncounted(reportedOwner, "its pool's queue, a " + queue.getName() + ", may order its tasks by their own type"); } diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java index 98f0dc9..f6cb458 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -1,68 +1,377 @@ package io.keploy.dedup; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionService; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.RunnableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.LockSupport; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; /** * RequestGate counts the requests the app's server is running, so that a * test's END can wait until the requests of that test are done before it * reads the test's hits. * - *

A server writes a request's response before the request is done: a - * filter's code after the chain, a request log, runs after Keploy has the - * response and has sent the test's END. Read at once, the END missed those - * hits, and the next START cleared them as hits between two tests. - * ServerEntries makes each request of Tomcat, Jetty and Undertow call - * {@link #enter()} where the server starts running it and {@link #exit(Object)} - * where it is done with it, the response finished. + *

Key guarantees: + *

    + *
  • No-op when Keploy is absent: runtime tracking is + * gated behind {@link #armed}, which becomes {@code true} only when a + * collector connects or the first {@code START} arrives. When unarmed, + * requests, executor submits, and job hooks perform zero wrapping, zero + * allocation, and zero tracking-map writes. If any request or job ran + * while unarmed, the first armed window is marked + * {@code contaminated: ["armed-mid-flight"]}.
  • + *
  • Fail-closed executor wrapping: only executors + * positively verified by {@link OrderedPools} are wrapped. Unknown or + * custom executors receive the original task untouched and the current + * window is marked {@code untracked-executor:}.
  • + *
  • CompletableFuture dependent stages: for + * {@code supplyAsync}/{@code runAsync} and rewritten {@code *Async} + * instance stages, the window permit is released via a + * {@code whenComplete} registered on the returned future before returning + * to the caller (LIFO stack order ensures synchronous dependents execute + * before permit release), while still holding the permit if the future + * is completed early while the supplier/action is in flight.
  • + *
  • Cut-tail contamination: lingering prior windows (from + * a cut END or an unclosed previous test) mark every subsequent window + * {@code tail:} until they finish draining + * ({@code running == 0}).
  • + *
  • Lock-free hot path: zero global {@code synchronized} + * monitors (safe for virtual threads on JDK 21-23), weak-value + * {@code PENDING_BY_FUTURE} removed eagerly on task start and release + * (no self-referencing {@code job.future = exec.submit(job)} leak), and + * {@link ReferenceQueue} permit recovery for abandoned tasks.
  • + *
* - *

The work a request hands to a Spring TaskExecutor (an event listener - * on an async multicaster, an {@code @Async} method, a task submitted to - * a ThreadPoolTaskExecutor) counts as that request's until it is done: - * ServerEntries makes those executors pass each task they are handed, and - * the executor it is for, to {@link #hand(Object, Runnable)} or - * {@link #hand(Object, Callable)}, which, on a thread that runs a request - * or such a task, counts the task in the window that thread counts in, - * from the hand-off until the task returns or throws. On a thread in a - * scheduled job's run (JobGate), or in a task such a run handed off, the - * task counts as a run of that job while it runs, so a test whose window - * it runs in is marked with the job; END does not wait for it. A task - * handed from any other thread (a plain scheduler's, the app's own), or to - * an executor whose pool may order its tasks by their type - * (OrderedPools), is not counted. - * - *

Public only for the server and Spring classes ServerEntries changes, - * which call it from their own packages; not an API. + *

Public only for the server, Spring, and rewritten application classes + * ServerEntries changes, which call it from their own packages; not an API. */ public final class RequestGate { + // Runtime arming gate: false until a collector connects or START arrives. + private static volatile boolean armed = false; + // Set once if any request/job executed while unarmed. + private static volatile boolean unarmedEntered = false; + private static volatile boolean pendingArmedMidFlight = false; + private static final AtomicBoolean ARMED_MID_FLIGHT_CONSUMED = new AtomicBoolean(false); + // Zero-allocation sentinel returned by RequestGate.enter() and + // JobGate.enter() while unarmed so long-running work started before arming + // keeps marking every subsequent window "armed-mid-flight" until exit(). + private static final Object UNARMED_TOKEN = new Object(); + private static final LongAdder UNARMED_IN_FLIGHT = new LongAdder(); + // Timestamp of the last unarmed async hand-off (zero-allocation, zero + // wrapping) so windows opened shortly after arming still carry + // armed-mid-flight even if the initiating unarmed request already exited. + private static volatile long lastUnarmedHandOffNanos; + + // Duration after an untracked async hand-off during which subsequent + // windows are conservatively marked contaminated ("tail:"). + static volatile long untrackedTailWindowNanos = + TimeUnit.MILLISECONDS.toNanos(KeployDedupAgent.MAX_END_WAIT_MILLIS); + // Maximum duration a stuck lingering window (e.g., an abandoned server- + // lifetime future that never completes) keeps contaminating later windows. + static volatile long maxLingeringNanos = TimeUnit.SECONDS.toNanos(30); + // Untracked async tail recorded outside a request window (e.g., from a + // scheduled job or message listener handing work to an unknown executor). + private static volatile boolean externalUntrackedTailPending; + private static volatile long externalUntrackedTailExpiresAtNanos; + private static volatile String externalUntrackedTailReason; + // Weak handles to live untracked Threads/ScheduledFutures started from + // non-request (job) threads so external tails remain active while alive. + private static final ConcurrentLinkedQueue EXTERNAL_UNTRACKED_HANDLES = + new ConcurrentLinkedQueue<>(); + private static final int MAX_UNTRACKED_HANDLES = 64; + private static final long UNARMED_HANDOFF_THROTTLE_NANOS = TimeUnit.MILLISECONDS.toNanos(1); + // Short grace for a Thread subclass registered right before start() while + // still in Thread.State.NEW, and safety margin for Timer.cancel() wall-clock + // vs nanoTime() rounding (covering Linux ~1ms and Windows ~15.6ms clock ticks) + // so an already-firing one-shot task is never misclassified as cancelled-before-fire. + private static final long HANDLE_START_GRACE_NANOS = TimeUnit.MILLISECONDS.toNanos(50); + private static final long TIMER_CANCEL_MARGIN_NANOS = TimeUnit.MILLISECONDS.toNanos(20); + // Weakly-keyed maps of cancelled TimerTasks and Timers populated by rewritten + // TimerTask.cancel() / Timer.cancel() call sites (zero JDK-internal reflection, + // so no JDK 9-15 illegal-access warning when Keploy is absent). + private static final ConcurrentHashMap CANCELLED_TIMER_TASKS = + new ConcurrentHashMap<>(); + private static final ReferenceQueue DEAD_TIMER_TASK_KEYS = new ReferenceQueue<>(); + private static final ConcurrentHashMap CANCELLED_TIMERS = + new ConcurrentHashMap<>(); + private static final ReferenceQueue DEAD_TIMER_KEYS = new ReferenceQueue<>(); + + private static final class TimerCancelInfo { + final boolean cancelledBeforeRun; + final long cancelledAtNanos; + + TimerCancelInfo(boolean cancelledBeforeRun, long cancelledAtNanos) { + this.cancelledBeforeRun = cancelledBeforeRun; + this.cancelledAtNanos = cancelledAtNanos; + } + } + // The window of the test running, made anew at each START and when END // waits: END waits only for the requests that came in since the START, - // never for one that runs from before (a request of the test before, cut - // at its bound, or a stream that never ends) or one that comes in after - // END. - private static volatile Window current = new Window(); + // never for one that runs from before or one that comes in after END. + private static volatile Window current = new Window(null); + + // Prior windows that were cut at END or still have running > 0: every new + // window opened while any lingering window remains active (or just after a + // cut END) is marked contaminated ("tail:") until drained. + private static final Set LINGERING = ConcurrentHashMap.newKeySet(); + private static final int MAX_LINGERING = 64; + + // Weak HandRef set for CompletableFuture stage permits not bound to an + // explicit executor (plain dependents and 1-arg async stages), so abandoned + // futures collected by GC promptly release their window permits via + // DEAD_HANDS instead of pinning LINGERING forever. + private static final Set PENDING_STAGES = ConcurrentHashMap.newKeySet(); + + // Whether a CompletableFuture subclass inherits all 14 plain dependent + // methods and whenComplete directly from CompletableFuture (true for exact + // CompletableFuture, JDK HttpClient's MinimalFuture, and JDK MinimalStage; + // false for custom subclasses overriding those methods). + private static final ClassValue CF_SUBCLASS_SAFE_SYNC = new ClassValue() { + @Override + protected Boolean computeValue(Class type) { + if (type == CompletableFuture.class) { + return Boolean.TRUE; + } + for (Class c = type; c != null && c != CompletableFuture.class; c = c.getSuperclass()) { + if (declaresCfMethod(c, "thenApply", Function.class) + || declaresCfMethod(c, "thenAccept", Consumer.class) + || declaresCfMethod(c, "thenRun", Runnable.class) + || declaresCfMethod(c, "thenCompose", Function.class) + || declaresCfMethod(c, "thenCombine", CompletionStage.class, BiFunction.class) + || declaresCfMethod(c, "thenAcceptBoth", CompletionStage.class, BiConsumer.class) + || declaresCfMethod(c, "runAfterBoth", CompletionStage.class, Runnable.class) + || declaresCfMethod(c, "applyToEither", CompletionStage.class, Function.class) + || declaresCfMethod(c, "acceptEither", CompletionStage.class, Consumer.class) + || declaresCfMethod(c, "runAfterEither", CompletionStage.class, Runnable.class) + || declaresCfMethod(c, "handle", BiFunction.class) + || declaresCfMethod(c, "whenComplete", BiConsumer.class) + || declaresCfMethod(c, "exceptionally", Function.class) + || declaresCfMethod(c, "exceptionallyCompose", Function.class)) { + return Boolean.FALSE; + } + } + return Boolean.TRUE; + } + }; + + private static boolean declaresCfMethod(Class type, String name, Class... params) { + try { + Method m = type.getDeclaredMethod(name, params); + // Ignore javac-generated bridge/synthetic methods (e.g. on + // package-private JDK subclasses like CompletableFuture$MinimalStage). + return !m.isBridge() && !m.isSynthetic(); + } catch (NoSuchMethodException e) { + return false; + } catch (Throwable t) { + // Conservative fail-closed if inspection fails. + return true; + } + } // The window the thread's request, or the task a request handed off it // runs, counts in; null on any other thread. private static final ThreadLocal INSIDE = new ThreadLocal<>(); + // Lock-free weak identity map from submitted Future -> WeakReference, + // explicitly removed on BOTH Hand.enter() and Hand.finishRelease(), so + // self-referencing patterns (job.future = exec.submit(job)) can never leak + // and virtual-thread carriers are never pinned. + private static final ConcurrentHashMap> PENDING_BY_FUTURE = + new ConcurrentHashMap<>(); + private static final ReferenceQueue DEAD_FUTURE_KEYS = new ReferenceQueue<>(); + + // Lock-free weak identity map from Executor -> Set for O(1) + // self-removal on release, shutdownNow() draining, and ReferenceQueue + // permit recovery if a task is abandoned via purge()/getQueue().clear(). + private static final ConcurrentHashMap> PENDING_BY_EXECUTOR = + new ConcurrentHashMap<>(); + private static final ReferenceQueue DEAD_EXECUTOR_KEYS = new ReferenceQueue<>(); + private static final ReferenceQueue DEAD_HANDS = new ReferenceQueue<>(); + + // Bounded poll slice in await() only when the window has tracked submit() + // futures that could be cancelled externally without running. + private static final long FUTURE_SWEEP_INTERVAL_NANOS = TimeUnit.MILLISECONDS.toNanos(10); + // Sweep cancelled/done futures in Window.track() every N inserts so + // windows that never receive an END cannot grow unboundedly on cancelled + // futures. + private static final int FUTURE_SWEEP_STRIDE = 64; + + // Reflective handles for Java 9+ / 12+ CompletableFuture & CompletionStage + // methods so keploy-sdk compiles against --release 8 (Java8ApiTest) while + // rewriting JDK 9+ / 12+ apps. + private static final Method CF_COMPLETE_ASYNC_1 = + findMethod(CompletableFuture.class, "completeAsync", Supplier.class); + private static final Method CF_COMPLETE_ASYNC_2 = + findMethod(CompletableFuture.class, "completeAsync", Supplier.class, Executor.class); + private static final Method CF_EXCEPTIONALLY_COMPOSE = + findMethod(CompletableFuture.class, "exceptionallyCompose", Function.class); + private static final Method CF_EXCEPTIONALLY_ASYNC_1 = + findMethod(CompletableFuture.class, "exceptionallyAsync", Function.class); + private static final Method CF_EXCEPTIONALLY_ASYNC_2 = + findMethod(CompletableFuture.class, "exceptionallyAsync", Function.class, Executor.class); + private static final Method CF_EXCEPTIONALLY_COMPOSE_ASYNC_1 = + findMethod(CompletableFuture.class, "exceptionallyComposeAsync", Function.class); + private static final Method CF_EXCEPTIONALLY_COMPOSE_ASYNC_2 = + findMethod(CompletableFuture.class, "exceptionallyComposeAsync", Function.class, Executor.class); + private static final Method CS_EXCEPTIONALLY_COMPOSE = + findMethod(CompletionStage.class, "exceptionallyCompose", Function.class); + private static final Method CS_EXCEPTIONALLY_ASYNC_1 = + findMethod(CompletionStage.class, "exceptionallyAsync", Function.class); + private static final Method CS_EXCEPTIONALLY_ASYNC_2 = + findMethod(CompletionStage.class, "exceptionallyAsync", Function.class, Executor.class); + private static final Method CS_EXCEPTIONALLY_COMPOSE_ASYNC_1 = + findMethod(CompletionStage.class, "exceptionallyComposeAsync", Function.class); + private static final Method CS_EXCEPTIONALLY_COMPOSE_ASYNC_2 = + findMethod(CompletionStage.class, "exceptionallyComposeAsync", Function.class, Executor.class); + private RequestGate() { } + private static Method findMethod(Class owner, String name, Class... params) { + try { + return owner.getMethod(name, params); + } catch (Throwable ignored) { + return null; + } + } + + static boolean isArmed() { + return armed; + } + + static void noteUnarmedActivity() { + if (!unarmedEntered) { + unarmedEntered = true; + } + } + + static Object enterUnarmed() { + noteUnarmedActivity(); + UNARMED_IN_FLIGHT.increment(); + return UNARMED_TOKEN; + } + + static boolean isUnarmedToken(Object token) { + return token == UNARMED_TOKEN; + } + + static void exitUnarmed() { + UNARMED_IN_FLIGHT.decrement(); + } + + static long unarmedInFlight() { + return UNARMED_IN_FLIGHT.sum(); + } + + static void noteExternalUntrackedTail(String reason) { + noteExternalUntrackedTail(reason, 0L); + } + + static void noteExternalUntrackedTail(String reason, long extraTailNanos) { + if (!armed) { + return; + } + long now = System.nanoTime(); + long boundedExtra = Math.max(0L, Math.min(extraTailNanos, maxLingeringNanos)); + long expires = now + untrackedTailWindowNanos + boundedExtra; + externalUntrackedTailReason = reason == null || reason.isEmpty() ? "job" : reason; + long prev = externalUntrackedTailExpiresAtNanos; + if (prev == 0L || (expires - prev) > 0L) { + externalUntrackedTailExpiresAtNanos = expires; + } + externalUntrackedTailPending = true; + } + + static void arm() { + if (!armed) { + if (unarmedEntered || UNARMED_IN_FLIGHT.sum() > 0 || lastUnarmedHandOffNanos != 0L) { + pendingArmedMidFlight = true; + } + armed = true; + } + } + + static void disarm() { + armed = false; + unarmedEntered = false; + pendingArmedMidFlight = false; + lastUnarmedHandOffNanos = 0L; + ARMED_MID_FLIGHT_CONSUMED.set(false); + externalUntrackedTailPending = false; + externalUntrackedTailExpiresAtNanos = 0L; + externalUntrackedTailReason = null; + EXTERNAL_UNTRACKED_HANDLES.clear(); + CANCELLED_TIMER_TASKS.clear(); + CANCELLED_TIMERS.clear(); + LINGERING.clear(); + current = new Window(null); + } + + static int pendingByFutureSize() { + drainDeadFutureKeys(); + return PENDING_BY_FUTURE.size(); + } + + static int pendingByExecutorSize(Executor executor) { + drainDeadHands(); + drainDeadExecutorKeys(); + if (executor == null) { + return PENDING_BY_EXECUTOR.size(); + } + Set set = PENDING_BY_EXECUTOR.get(new LookupKey(executor)); + return set == null ? 0 : set.size(); + } + /** * Counts a request as running, in the window of the test running now. + * When Keploy is unarmed, returns a zero-allocation sentinel token that + * tracks unarmed in-flight concurrency without allocating or mutating any + * window structures. * * @return the token to pass to {@link #exit(Object)} when it is done */ public static Object enter() { + if (!armed) { + return enterUnarmed(); + } Window window = current; Window outer = INSIDE.get(); // A request in a request (a server's dispatch on the same thread) @@ -71,7 +380,16 @@ public static Object enter() { INSIDE.set(window); // Counted last: whatever failed before it (out of memory) leaves // nothing to undo. + window.enteredCount.incrementAndGet(); + window.executing.incrementAndGet(); window.running.incrementAndGet(); + if (window != current) { + retainLingering(window, System.nanoTime()); + Window cur = current; + if (cur != null && cur != window) { + cur.contaminate("tail:" + window.label()); + } + } return token; } @@ -82,12 +400,22 @@ public static Object enter() { * @param token what {@link #enter()} returned */ public static void exit(Object token) { + if (token == null) { + return; + } + if (token == UNARMED_TOKEN) { + exitUnarmed(); + return; + } if (token instanceof Window) { INSIDE.remove(); - done((Window) token); + Window w = (Window) token; + w.executing.decrementAndGet(); + done(w); } else if (token instanceof Nested) { Nested nested = (Nested) token; INSIDE.set(nested.outer); + nested.window.executing.decrementAndGet(); done(nested.window); } } @@ -96,34 +424,86 @@ public static void exit(Object token) { * Counts a task an executor is handed on a thread that runs a request, * or a task a request handed off, in that thread's window until the * task is done, and returns what the executor runs instead of it. On a - * thread in a scheduled job's run, it returns a task that counts as a - * run of that job while it runs. On any other thread, for a task - * already counted, for a task that is {@link Comparable}, or for an - * executor whose pool may order its tasks by their type, it returns the - * task. - * - *

Neither of the last two is counted: a pool whose queue orders its - * tasks (a PriorityBlockingQueue, or a queue with a Comparator) casts - * each to the app's own type, and throws on a task of another type. END - * does not wait for such a task, and it is no job's run. + * thread in a scheduled job's or message listener's run, returns a task + * that counts as a run of that job while it runs. Fails CLOSED: any + * executor not verified safe by {@link OrderedPools} receives the original + * task untouched and marks the current request window contaminated + * ({@code untracked-executor:}). * * @param executor the executor the task is for, or null * @param task the task the executor is handed * @return what the executor runs instead */ public static Runnable hand(Object executor, Runnable task) { - if (task == null || task instanceof Handed || task instanceof Comparable) { + return handInternal(executor, task, false); + } + + private static JobGate.Attribution currentOrExpiredJob(Window window) { + if (window != null) { + return null; + } + JobGate.Attribution job = JobGate.runningAttribution(); + return job != null ? job : JobGate.expiredAttribution(); + } + + private static void markUntrackedExecutor(Window window, JobGate.Attribution job, Object executor, String fallback) { + String reason = "untracked-executor:" + (executor != null ? executor.getClass().getName() : fallback); + if (window != null) { + window.contaminate(reason); + } else if (job != null) { + boolean expired = job.hasDeadline && (System.nanoTime() - job.expiresAtNanos) >= 0L; + JobGate.markUntracked(expired ? "job-tail:" + job.name : reason); + } + } + + private static Runnable handInternal(Object executor, Runnable task, boolean deferRelease) { + if (!armed) { + if (task != null) { + noteUnarmedHandOffIfInFlight(); + } + return task; + } + if (task == null) { + return null; + } + if (task instanceof Handed) { + if (OrderedPools.isInlineExecutor(executor)) { + return task; + } + if (OrderedPools.orders(executor)) { + Handed existing = (Handed) task; + existing.releaseIfPending(); + if (executor != null) { + markUntrackedExecutor(existing.window, existing.job, executor, "unknown"); + } + return existing.task; + } return task; } Window window = INSIDE.get(); - String job = window == null ? JobGate.running() : null; - if ((window == null && job == null) || OrderedPools.orders(executor)) { + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + return task; + } + if (OrderedPools.isInlineExecutor(executor)) { + return task; + } + if (task instanceof Comparable) { + markUntrackedExecutor(window, job, executor, "comparable"); + return task; + } + if (OrderedPools.orders(executor)) { + if (executor != null) { + markUntrackedExecutor(window, job, executor, "unknown"); + } return task; } // A task that is a Future stays one, for the executor's cancel at // shutdown and its purge of cancelled tasks. - Handed handed = task instanceof Future ? new HandedFuture(window, job, task) - : new Handed(window, job, task); + boolean defer = deferRelease && (window != null || job != null); + Handed handed = task instanceof Future + ? new HandedFuture(window, job, task, defer) + : new Handed(window, job, task, defer); // Counted last, as enter() counts: a failed allocation (out of // memory) leaves nothing counted that no task would release. if (window != null) { @@ -142,12 +522,46 @@ public static Runnable hand(Object executor, Runnable task) { * @return what the executor runs instead */ public static Callable hand(Object executor, Callable task) { - if (task == null || task instanceof HandedCall || task instanceof Comparable) { + if (!armed) { + if (task != null) { + noteUnarmedHandOffIfInFlight(); + } + return task; + } + if (task == null) { + return null; + } + if (task instanceof HandedCall) { + if (OrderedPools.isInlineExecutor(executor)) { + return task; + } + if (OrderedPools.orders(executor)) { + @SuppressWarnings("unchecked") + HandedCall existing = (HandedCall) task; + existing.releaseIfPending(); + if (executor != null) { + markUntrackedExecutor(existing.window, existing.job, executor, "unknown"); + } + return existing.task; + } return task; } Window window = INSIDE.get(); - String job = window == null ? JobGate.running() : null; - if ((window == null && job == null) || OrderedPools.orders(executor)) { + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + return task; + } + if (OrderedPools.isInlineExecutor(executor)) { + return task; + } + if (task instanceof Comparable) { + markUntrackedExecutor(window, job, executor, "comparable"); + return task; + } + if (OrderedPools.orders(executor)) { + if (executor != null) { + markUntrackedExecutor(window, job, executor, "unknown"); + } return task; } HandedCall handed = new HandedCall<>(window, job, task); @@ -158,50 +572,3703 @@ public static Callable hand(Object executor, Callable task) { } /** - * Counts a task {@link #hand(Object, Runnable)} counted as done when the - * executor threw instead of taking it (it rejected it, or was shut - * down), so that END does not wait for a task that never runs. + * Counts a {@link Supplier} handed to {@link CompletableFuture#supplyAsync} + * on a request or job thread until it (and its synchronous dependents) + * complete. * - * @param handed what hand returned - * @param task what hand was passed + * @param executor the executor the supplier is for, or null + * @param supplier the supplier handed off + * @param what the supplier returns + * @return what runs instead */ - public static void dropped(Object handed, Object task) { - if (handed != task && handed instanceof Hand) { - ((Hand) handed).release(); + public static Supplier handSupplier(Object executor, Supplier supplier) { + return handSupplierInternal(executor, supplier, true); + } + + private static Supplier handSupplierInternal(Object executor, Supplier supplier, boolean deferRelease) { + if (!armed) { + if (supplier != null) { + noteUnarmedHandOffIfInFlight(); + } + return supplier; + } + if (supplier == null) { + return null; } + if (supplier instanceof HandedSupplier) { + if (OrderedPools.isInlineExecutor(executor)) { + return supplier; + } + if (OrderedPools.orders(executor)) { + @SuppressWarnings("unchecked") + HandedSupplier existing = (HandedSupplier) supplier; + existing.releaseIfPending(); + if (executor != null) { + markUntrackedExecutor(existing.window, existing.job, executor, "unknown"); + } + return existing.task; + } + return supplier; + } + Window window = INSIDE.get(); + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + return supplier; + } + if (OrderedPools.isInlineExecutor(executor)) { + return supplier; + } + if (supplier instanceof Comparable) { + markUntrackedExecutor(window, job, executor, "comparable"); + return supplier; + } + if (OrderedPools.orders(executor)) { + if (executor != null) { + markUntrackedExecutor(window, job, executor, "unknown"); + } + return supplier; + } + boolean defer = deferRelease && (window != null || job != null); + HandedSupplier handed = new HandedSupplier<>(window, job, supplier, defer); + if (window != null) { + window.running.incrementAndGet(); + } + return handed; } - private static void done(Window window) { - if (window.running.decrementAndGet() == 0) { - Thread waiter = window.waiter; - if (waiter != null) { - LockSupport.unpark(waiter); + private static void noteUnarmedHandOffIfInFlight() { + if (UNARMED_IN_FLIGHT.sum() > 0) { + long now = System.nanoTime(); + long prev = lastUnarmedHandOffNanos; + if (prev == 0L || (now - prev) >= UNARMED_HANDOFF_THROTTLE_NANOS) { + lastUnarmedHandOffNanos = now; } } } - // open starts the window of a test: from now on, END waits for the - // requests that come in, and for no request that came in before. - static void open() { - current = new Window(); + /** + * Call-site wrapper for {@link Executor#execute(Runnable)}: propagates the + * current request window (or job run) across verified JDK executors. + * + * @param executor target executor + * @param task runnable to execute + */ + public static void execute(Executor executor, Runnable task) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + executor.execute(task); + return; + } + Runnable handed = hand(executor, task); + registerForExecutor(executor, handed, task); + try { + executor.execute(handed); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } } - // running is how many requests of the current window are running. - static int running() { - return current.running.get(); + /** + * Call-site wrapper for {@link ExecutorService#submit(Runnable)}. + * + * @param executor target executor service + * @param task runnable to submit + * @return the executor's own future + */ + public static Future submit(ExecutorService executor, Runnable task) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.submit(task); + } + Runnable handed = hand(executor, task); + registerForExecutor(executor, handed, task); + Future future; + try { + future = executor.submit(handed); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + trackSubmitted(future, handed, task); + return future; } - // await closes the current window and waits until none of its requests - // runs, for at most timeoutNanos, and says whether none runs. A request - // that comes in from now on (a readiness probe, a metrics scrape, the - // next client) counts in a window of its own, so it does not draw the - // wait out. One thread waits at a time (the worker, under its test lock). - static boolean await(long timeoutNanos) { - Window window = current; - current = new Window(); - if (window.running.get() <= 0) { - return true; + /** + * Call-site wrapper for {@link ExecutorService#submit(Runnable, Object)}. + * + * @param result type + * @param executor target executor service + * @param task runnable to submit + * @param result result returned on completion + * @return the executor's own future + */ + public static Future submit(ExecutorService executor, Runnable task, T result) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.submit(task, result); + } + Runnable handed = hand(executor, task); + registerForExecutor(executor, handed, task); + Future future; + try { + future = executor.submit(handed, result); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + trackSubmitted(future, handed, task); + return future; + } + + /** + * Call-site wrapper for {@link ExecutorService#submit(Callable)}. + * + * @param result type + * @param executor target executor service + * @param task callable to submit + * @return the executor's own future + */ + public static Future submit(ExecutorService executor, Callable task) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.submit(task); + } + Callable handed = hand(executor, task); + registerForExecutor(executor, handed, task); + Future future; + try { + future = executor.submit(handed); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + trackSubmitted(future, handed, task); + return future; + } + + /** + * Call-site wrapper for {@link CompletableFuture#runAsync(Runnable)}. + * Holds the window permit until synchronous dependent stages registered on + * the returned future finish executing (LIFO {@code postComplete()} order). + * + * @param task runnable to execute asynchronously + * @return the created CompletableFuture + */ + public static CompletableFuture runAsync(Runnable task) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return CompletableFuture.runAsync(task); + } + Runnable handed = handInternal(null, task, true); + CompletableFuture cf; + try { + cf = CompletableFuture.runAsync(handed); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + attachCompletionRelease(cf, handed, task); + return cf; + } + + /** + * Call-site wrapper for {@link CompletableFuture#runAsync(Runnable, Executor)}. + * + * @param task runnable to execute asynchronously + * @param executor target executor + * @return the created CompletableFuture + */ + public static CompletableFuture runAsync(Runnable task, Executor executor) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return CompletableFuture.runAsync(task, executor); + } + Runnable handed = handInternal(executor, task, true); + registerForExecutor(executor, handed, task); + CompletableFuture cf; + try { + cf = CompletableFuture.runAsync(handed, executor); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + attachCompletionRelease(cf, handed, task); + return cf; + } + + /** + * Call-site wrapper for {@link CompletableFuture#supplyAsync(Supplier)}. + * + * @param result type + * @param supplier supplier to execute asynchronously + * @return the created CompletableFuture + */ + public static CompletableFuture supplyAsync(Supplier supplier) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return CompletableFuture.supplyAsync(supplier); + } + Supplier handed = handSupplierInternal(null, supplier, true); + CompletableFuture cf; + try { + cf = CompletableFuture.supplyAsync(handed); + } catch (Throwable t) { + dropped(handed, supplier); + throw t; + } + attachCompletionRelease(cf, handed, supplier); + return cf; + } + + /** + * Call-site wrapper for {@link CompletableFuture#supplyAsync(Supplier, Executor)}. + * + * @param result type + * @param supplier supplier to execute asynchronously + * @param executor target executor + * @return the created CompletableFuture + */ + public static CompletableFuture supplyAsync(Supplier supplier, Executor executor) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return CompletableFuture.supplyAsync(supplier, executor); + } + Supplier handed = handSupplierInternal(executor, supplier, true); + registerForExecutor(executor, handed, supplier); + CompletableFuture cf; + try { + cf = CompletableFuture.supplyAsync(handed, executor); + } catch (Throwable t) { + dropped(handed, supplier); + throw t; + } + attachCompletionRelease(cf, handed, supplier); + return cf; + } + + // --- CompletableFuture & CompletionStage instance method call-site wrappers --- + + private static Hand prepareCfStageHand(CompletableFuture receiver, Executor explicitExecutor, boolean hasExecutor) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return null; + } + Window window = INSIDE.get(); + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + return null; + } + if (hasExecutor) { + if (explicitExecutor == null) { + return null; + } + if (!OrderedPools.isInlineExecutor(explicitExecutor) && OrderedPools.orders(explicitExecutor)) { + markUntrackedExecutor(window, job, explicitExecutor, "unknown"); + return null; + } + } else { + // Default executor: safe only for exact CompletableFuture.class + // (a custom subclass could override defaultExecutor()). + if (receiver != null && receiver.getClass() != CompletableFuture.class) { + markUntrackedExecutor(window, job, receiver, "unknown"); + return null; + } + } + StageHand hand = new StageHand(window, job, true); + if (window != null) { + window.running.incrementAndGet(); + } + if (hasExecutor && explicitExecutor != null) { + registerForExecutor(explicitExecutor, hand, null); + } else { + registerStageHand(hand); + } + return hand; + } + + // Checks isDone() safely without ever throwing UnsupportedOperationException + // on JDK 9+ MinimalStage (CompletableFuture.completedStage/failedStage/ + // minimalCompletionStage). + private static boolean safeIsDone(Object stage) { + if (stage == null) { + return false; + } + if (stage.getClass() == CompletableFuture.class) { + return ((CompletableFuture) stage).isDone(); + } + if (stage instanceof CompletableFuture) { + try { + return ((CompletableFuture) stage).isDone(); + } catch (Throwable ignored) { + return false; + } + } + return false; + } + + private static Hand prepareCfSyncHand(CompletableFuture receiver, CompletionStage other, boolean either) { + if (!armed) { + if (receiver != null) { + noteUnarmedHandOffIfInFlight(); + } + return null; + } + if (receiver == null) { + return null; + } + Window window = INSIDE.get(); + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + return null; + } + if (other == null) { + if (safeIsDone(receiver)) { + return null; + } + } else { + boolean receiverDone = safeIsDone(receiver); + boolean otherDone = safeIsDone(other); + if (either ? (receiverDone || otherDone) : (receiverDone && otherDone)) { + return null; + } + } + // Plain synchronous dependents never invoke defaultExecutor(), so + // CompletableFuture subclasses that inherit the dependent methods and + // whenComplete directly (including JDK HttpClient's MinimalFuture and + // MinimalStage) are safely tracked; only subclasses overriding those + // methods fail closed. + if (!Boolean.TRUE.equals(CF_SUBCLASS_SAFE_SYNC.get(receiver.getClass()))) { + markUntrackedExecutor(window, job, receiver, "unknown"); + return null; + } + StageHand hand = new StageHand(window, job, true); + if (window != null) { + window.running.incrementAndGet(); + registerStageHand(hand); + } + return hand; + } + + private static void registerStageHand(Object handed) { + drainDeadHands(); + if (!(handed instanceof Hand)) { + return; + } + Hand hand = (Hand) handed; + if (hand.window == null || hand.isReleased() || hand.executorRef != null) { + return; + } + try { + HandRef ref = new HandRef(hand, DEAD_HANDS, PENDING_STAGES, hand.window); + PENDING_STAGES.add(ref); + hand.executorRef = ref; + if (hand.isReleased()) { + ref.released = true; + hand.executorRef = null; + PENDING_STAGES.remove(ref); + } + } catch (Throwable ignored) { + // Never affect app execution. + } + } + + private static CompletableFuture finishCfStage(CompletableFuture out, Hand hand) { + if (hand != null) { + attachCompletionRelease(out, hand, null); + } + return out; + } + + private static Supplier wrapSupplier(final Hand hand, final Supplier supplier) { + if (hand == null || supplier == null) { + return null; + } + return new Supplier() { + @Override + public T get() { + Object outer = hand.enter(); + try { + return supplier.get(); + } finally { + hand.exit(outer); + } + } + }; + } + + private static Function wrapFunction(final Hand hand, final Function fn) { + if (hand == null || fn == null) { + return null; + } + return new Function() { + @Override + public U apply(T t) { + Object outer = hand.enter(); + try { + return fn.apply(t); + } finally { + hand.exit(outer); + } + } + }; + } + + private static Consumer wrapConsumer(final Hand hand, final Consumer action) { + if (hand == null || action == null) { + return null; + } + return new Consumer() { + @Override + public void accept(T t) { + Object outer = hand.enter(); + try { + action.accept(t); + } finally { + hand.exit(outer); + } + } + }; + } + + private static Runnable wrapStageRunnable(final Hand hand, final Runnable action) { + if (hand == null || action == null) { + return null; + } + return new Runnable() { + @Override + public void run() { + Object outer = hand.enter(); + try { + action.run(); + } finally { + hand.exit(outer); + } + } + }; + } + + private static BiFunction wrapBiFunction(final Hand hand, + final BiFunction fn) { + if (hand == null || fn == null) { + return null; + } + return new BiFunction() { + @Override + public V apply(T t, U u) { + Object outer = hand.enter(); + try { + return fn.apply(t, u); + } finally { + hand.exit(outer); + } + } + }; + } + + private static BiConsumer wrapBiConsumer(final Hand hand, + final BiConsumer action) { + if (hand == null || action == null) { + return null; + } + return new BiConsumer() { + @Override + public void accept(T t, U u) { + Object outer = hand.enter(); + try { + action.accept(t, u); + } finally { + hand.exit(outer); + } + } + }; + } + + /** + * Call-site wrapper for {@code CompletableFuture.completeAsync(Supplier)}. + * + * @param future result type + * @param cf target future + * @param supplier async supplier + * @return the target future + */ + @SuppressWarnings("unchecked") + public static CompletableFuture completeAsync(CompletableFuture cf, + Supplier supplier) { + Hand hand = supplier == null ? null : prepareCfStageHand(cf, null, false); + Supplier target = hand == null ? supplier : wrapSupplier(hand, supplier); + CompletableFuture out; + try { + out = (CompletableFuture) invokeCfReflect(CF_COMPLETE_ASYNC_1, cf, target); + } catch (Throwable t) { + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@code CompletableFuture.completeAsync(Supplier, Executor)}. + * + * @param future result type + * @param cf target future + * @param supplier async supplier + * @param executor target executor + * @return the target future + */ + @SuppressWarnings("unchecked") + public static CompletableFuture completeAsync(CompletableFuture cf, + Supplier supplier, Executor executor) { + Hand hand = supplier == null ? null : prepareCfStageHand(cf, executor, true); + Supplier target = hand == null ? supplier : wrapSupplier(hand, supplier); + CompletableFuture out; + try { + out = (CompletableFuture) invokeCfReflect(CF_COMPLETE_ASYNC_2, cf, target, executor); + } catch (Throwable t) { + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenApplyAsync(Function)}. + * + * @param input type + * @param output type + * @param cf target future + * @param fn stage function + * @return dependent future + */ + public static CompletableFuture thenApplyAsync(CompletableFuture cf, + Function fn) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.thenApplyAsync(fn); + } + CompletableFuture out; + try { + out = cf.thenApplyAsync(wrapFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenApplyAsync(Function, Executor)}. + * + * @param input type + * @param output type + * @param cf target future + * @param fn stage function + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture thenApplyAsync(CompletableFuture cf, + Function fn, Executor executor) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.thenApplyAsync(fn, executor); + } + CompletableFuture out; + try { + out = cf.thenApplyAsync(wrapFunction(hand, fn), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenAcceptAsync(Consumer)}. + * + * @param input type + * @param cf target future + * @param action stage consumer + * @return dependent future + */ + public static CompletableFuture thenAcceptAsync(CompletableFuture cf, + Consumer action) { + Hand hand = action == null ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.thenAcceptAsync(action); + } + CompletableFuture out; + try { + out = cf.thenAcceptAsync(wrapConsumer(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenAcceptAsync(Consumer, Executor)}. + * + * @param input type + * @param cf target future + * @param action stage consumer + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture thenAcceptAsync(CompletableFuture cf, + Consumer action, Executor executor) { + Hand hand = action == null ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.thenAcceptAsync(action, executor); + } + CompletableFuture out; + try { + out = cf.thenAcceptAsync(wrapConsumer(hand, action), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenRunAsync(Runnable)}. + * + * @param input type + * @param cf target future + * @param action stage runnable + * @return dependent future + */ + public static CompletableFuture thenRunAsync(CompletableFuture cf, Runnable action) { + Hand hand = action == null ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.thenRunAsync(action); + } + CompletableFuture out; + try { + out = cf.thenRunAsync(wrapStageRunnable(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenRunAsync(Runnable, Executor)}. + * + * @param input type + * @param cf target future + * @param action stage runnable + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture thenRunAsync(CompletableFuture cf, Runnable action, + Executor executor) { + Hand hand = action == null ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.thenRunAsync(action, executor); + } + CompletableFuture out; + try { + out = cf.thenRunAsync(wrapStageRunnable(hand, action), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenComposeAsync(Function)}. + * + * @param input type + * @param output type + * @param cf target future + * @param fn composition function + * @return dependent future + */ + public static CompletableFuture thenComposeAsync(CompletableFuture cf, + Function> fn) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.thenComposeAsync(fn); + } + CompletableFuture out; + try { + out = cf.thenComposeAsync(wrapFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenComposeAsync(Function, Executor)}. + * + * @param input type + * @param output type + * @param cf target future + * @param fn composition function + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture thenComposeAsync(CompletableFuture cf, + Function> fn, Executor executor) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.thenComposeAsync(fn, executor); + } + CompletableFuture out; + try { + out = cf.thenComposeAsync(wrapFunction(hand, fn), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenCombineAsync(CompletionStage, BiFunction)}. + * + * @param first input type + * @param second input type + * @param output type + * @param cf target future + * @param other other stage + * @param fn combiner function + * @return dependent future + */ + public static CompletableFuture thenCombineAsync(CompletableFuture cf, + CompletionStage other, BiFunction fn) { + Hand hand = (other == null || fn == null) ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.thenCombineAsync(other, fn); + } + CompletableFuture out; + try { + out = cf.thenCombineAsync(other, wrapBiFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenCombineAsync(CompletionStage, BiFunction, Executor)}. + * + * @param first input type + * @param second input type + * @param output type + * @param cf target future + * @param other other stage + * @param fn combiner function + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture thenCombineAsync(CompletableFuture cf, + CompletionStage other, BiFunction fn, + Executor executor) { + Hand hand = (other == null || fn == null) ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.thenCombineAsync(other, fn, executor); + } + CompletableFuture out; + try { + out = cf.thenCombineAsync(other, wrapBiFunction(hand, fn), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenAcceptBothAsync(CompletionStage, BiConsumer)}. + * + * @param first input type + * @param second input type + * @param cf target future + * @param other other stage + * @param action combiner consumer + * @return dependent future + */ + public static CompletableFuture thenAcceptBothAsync(CompletableFuture cf, + CompletionStage other, BiConsumer action) { + Hand hand = (other == null || action == null) ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.thenAcceptBothAsync(other, action); + } + CompletableFuture out; + try { + out = cf.thenAcceptBothAsync(other, wrapBiConsumer(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenAcceptBothAsync(CompletionStage, BiConsumer, Executor)}. + * + * @param first input type + * @param second input type + * @param cf target future + * @param other other stage + * @param action combiner consumer + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture thenAcceptBothAsync(CompletableFuture cf, + CompletionStage other, BiConsumer action, Executor executor) { + Hand hand = (other == null || action == null) ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.thenAcceptBothAsync(other, action, executor); + } + CompletableFuture out; + try { + out = cf.thenAcceptBothAsync(other, wrapBiConsumer(hand, action), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#runAfterBothAsync(CompletionStage, Runnable)}. + * + * @param first input type + * @param cf target future + * @param other other stage + * @param action stage runnable + * @return dependent future + */ + public static CompletableFuture runAfterBothAsync(CompletableFuture cf, + CompletionStage other, Runnable action) { + Hand hand = (other == null || action == null) ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.runAfterBothAsync(other, action); + } + CompletableFuture out; + try { + out = cf.runAfterBothAsync(other, wrapStageRunnable(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#runAfterBothAsync(CompletionStage, Runnable, Executor)}. + * + * @param first input type + * @param cf target future + * @param other other stage + * @param action stage runnable + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture runAfterBothAsync(CompletableFuture cf, + CompletionStage other, Runnable action, Executor executor) { + Hand hand = (other == null || action == null) ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.runAfterBothAsync(other, action, executor); + } + CompletableFuture out; + try { + out = cf.runAfterBothAsync(other, wrapStageRunnable(hand, action), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#applyToEitherAsync(CompletionStage, Function)}. + * + * @param input type + * @param output type + * @param cf target future + * @param other other stage + * @param fn stage function + * @return dependent future + */ + public static CompletableFuture applyToEitherAsync(CompletableFuture cf, + CompletionStage other, Function fn) { + Hand hand = (other == null || fn == null) ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.applyToEitherAsync(other, fn); + } + CompletableFuture out; + try { + out = cf.applyToEitherAsync(other, wrapFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#applyToEitherAsync(CompletionStage, Function, Executor)}. + * + * @param input type + * @param output type + * @param cf target future + * @param other other stage + * @param fn stage function + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture applyToEitherAsync(CompletableFuture cf, + CompletionStage other, Function fn, Executor executor) { + Hand hand = (other == null || fn == null) ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.applyToEitherAsync(other, fn, executor); + } + CompletableFuture out; + try { + out = cf.applyToEitherAsync(other, wrapFunction(hand, fn), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#acceptEitherAsync(CompletionStage, Consumer)}. + * + * @param input type + * @param cf target future + * @param other other stage + * @param action stage consumer + * @return dependent future + */ + public static CompletableFuture acceptEitherAsync(CompletableFuture cf, + CompletionStage other, Consumer action) { + Hand hand = (other == null || action == null) ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.acceptEitherAsync(other, action); + } + CompletableFuture out; + try { + out = cf.acceptEitherAsync(other, wrapConsumer(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#acceptEitherAsync(CompletionStage, Consumer, Executor)}. + * + * @param input type + * @param cf target future + * @param other other stage + * @param action stage consumer + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture acceptEitherAsync(CompletableFuture cf, + CompletionStage other, Consumer action, Executor executor) { + Hand hand = (other == null || action == null) ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.acceptEitherAsync(other, action, executor); + } + CompletableFuture out; + try { + out = cf.acceptEitherAsync(other, wrapConsumer(hand, action), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#runAfterEitherAsync(CompletionStage, Runnable)}. + * + * @param input type + * @param cf target future + * @param other other stage + * @param action stage runnable + * @return dependent future + */ + public static CompletableFuture runAfterEitherAsync(CompletableFuture cf, + CompletionStage other, Runnable action) { + Hand hand = (other == null || action == null) ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.runAfterEitherAsync(other, action); + } + CompletableFuture out; + try { + out = cf.runAfterEitherAsync(other, wrapStageRunnable(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#runAfterEitherAsync(CompletionStage, Runnable, Executor)}. + * + * @param input type + * @param cf target future + * @param other other stage + * @param action stage runnable + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture runAfterEitherAsync(CompletableFuture cf, + CompletionStage other, Runnable action, Executor executor) { + Hand hand = (other == null || action == null) ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.runAfterEitherAsync(other, action, executor); + } + CompletableFuture out; + try { + out = cf.runAfterEitherAsync(other, wrapStageRunnable(hand, action), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#handleAsync(BiFunction)}. + * + * @param input type + * @param output type + * @param cf target future + * @param fn handler function + * @return dependent future + */ + public static CompletableFuture handleAsync(CompletableFuture cf, + BiFunction fn) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.handleAsync(fn); + } + CompletableFuture out; + try { + out = cf.handleAsync(wrapBiFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#handleAsync(BiFunction, Executor)}. + * + * @param input type + * @param output type + * @param cf target future + * @param fn handler function + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture handleAsync(CompletableFuture cf, + BiFunction fn, Executor executor) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.handleAsync(fn, executor); + } + CompletableFuture out; + try { + out = cf.handleAsync(wrapBiFunction(hand, fn), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#whenCompleteAsync(BiConsumer)}. + * + * @param result type + * @param cf target future + * @param action completion consumer + * @return dependent future + */ + public static CompletableFuture whenCompleteAsync(CompletableFuture cf, + BiConsumer action) { + Hand hand = action == null ? null : prepareCfStageHand(cf, null, false); + if (hand == null) { + return cf.whenCompleteAsync(action); + } + CompletableFuture out; + try { + out = cf.whenCompleteAsync(wrapBiConsumer(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#whenCompleteAsync(BiConsumer, Executor)}. + * + * @param result type + * @param cf target future + * @param action completion consumer + * @param executor target executor + * @return dependent future + */ + public static CompletableFuture whenCompleteAsync(CompletableFuture cf, + BiConsumer action, Executor executor) { + Hand hand = action == null ? null : prepareCfStageHand(cf, executor, true); + if (hand == null) { + return cf.whenCompleteAsync(action, executor); + } + CompletableFuture out; + try { + out = cf.whenCompleteAsync(wrapBiConsumer(hand, action), executor); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@code CompletableFuture.exceptionallyAsync(Function)}. + * + * @param result type + * @param cf target future + * @param fn recovery function + * @return dependent future + */ + @SuppressWarnings("unchecked") + public static CompletableFuture exceptionallyAsync(CompletableFuture cf, + Function fn) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, null, false); + Function target = hand == null ? fn : wrapFunction(hand, fn); + CompletableFuture out; + try { + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_ASYNC_1, cf, target); + } catch (Throwable t) { + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@code CompletableFuture.exceptionallyAsync(Function, Executor)}. + * + * @param result type + * @param cf target future + * @param fn recovery function + * @param executor target executor + * @return dependent future + */ + @SuppressWarnings("unchecked") + public static CompletableFuture exceptionallyAsync(CompletableFuture cf, + Function fn, Executor executor) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, executor, true); + Function target = hand == null ? fn : wrapFunction(hand, fn); + CompletableFuture out; + try { + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_ASYNC_2, cf, target, executor); + } catch (Throwable t) { + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@code CompletableFuture.exceptionallyComposeAsync(Function)}. + * + * @param result type + * @param cf target future + * @param fn recovery composition function + * @return dependent future + */ + @SuppressWarnings("unchecked") + public static CompletableFuture exceptionallyComposeAsync(CompletableFuture cf, + Function> fn) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, null, false); + Function> target = hand == null ? fn : wrapFunction(hand, fn); + CompletableFuture out; + try { + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE_ASYNC_1, cf, target); + } catch (Throwable t) { + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@code CompletableFuture.exceptionallyComposeAsync(Function, Executor)}. + * + * @param result type + * @param cf target future + * @param fn recovery composition function + * @param executor target executor + * @return dependent future + */ + @SuppressWarnings("unchecked") + public static CompletableFuture exceptionallyComposeAsync(CompletableFuture cf, + Function> fn, Executor executor) { + Hand hand = fn == null ? null : prepareCfStageHand(cf, executor, true); + Function> target = hand == null ? fn : wrapFunction(hand, fn); + CompletableFuture out; + try { + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE_ASYNC_2, cf, target, executor); + } catch (Throwable t) { + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); + } + return finishCfStage(out, hand); + } + + // --- CompletableFuture plain dependent stage wrappers (tracks external library futures) --- + + /** + * Call-site wrapper for {@link CompletableFuture#thenApply(Function)}. + * + * @param input type + * @param output type + * @param cf target future + * @param fn stage function + * @return dependent future + */ + public static CompletableFuture thenApply(CompletableFuture cf, + Function fn) { + Hand hand = fn == null ? null : prepareCfSyncHand(cf, null, false); + if (hand == null) { + return cf.thenApply(fn); + } + CompletableFuture out; + try { + out = cf.thenApply(wrapFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenAccept(Consumer)}. + * + * @param input type + * @param cf target future + * @param action stage consumer + * @return dependent future + */ + public static CompletableFuture thenAccept(CompletableFuture cf, + Consumer action) { + Hand hand = action == null ? null : prepareCfSyncHand(cf, null, false); + if (hand == null) { + return cf.thenAccept(action); + } + CompletableFuture out; + try { + out = cf.thenAccept(wrapConsumer(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenRun(Runnable)}. + * + * @param input type + * @param cf target future + * @param action stage runnable + * @return dependent future + */ + public static CompletableFuture thenRun(CompletableFuture cf, Runnable action) { + Hand hand = action == null ? null : prepareCfSyncHand(cf, null, false); + if (hand == null) { + return cf.thenRun(action); + } + CompletableFuture out; + try { + out = cf.thenRun(wrapStageRunnable(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenCompose(Function)}. + * + * @param input type + * @param output type + * @param cf target future + * @param fn composition function + * @return dependent future + */ + public static CompletableFuture thenCompose(CompletableFuture cf, + Function> fn) { + Hand hand = fn == null ? null : prepareCfSyncHand(cf, null, false); + if (hand == null) { + return cf.thenCompose(fn); + } + CompletableFuture out; + try { + out = cf.thenCompose(wrapFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenCombine(CompletionStage, BiFunction)}. + * + * @param first input type + * @param second input type + * @param output type + * @param cf target future + * @param other other stage + * @param fn combiner function + * @return dependent future + */ + public static CompletableFuture thenCombine(CompletableFuture cf, + CompletionStage other, BiFunction fn) { + Hand hand = (other == null || fn == null) ? null : prepareCfSyncHand(cf, other, false); + if (hand == null) { + return cf.thenCombine(other, fn); + } + CompletableFuture out; + try { + out = cf.thenCombine(other, wrapBiFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#thenAcceptBoth(CompletionStage, BiConsumer)}. + * + * @param first input type + * @param second input type + * @param cf target future + * @param other other stage + * @param action combiner consumer + * @return dependent future + */ + public static CompletableFuture thenAcceptBoth(CompletableFuture cf, + CompletionStage other, BiConsumer action) { + Hand hand = (other == null || action == null) ? null : prepareCfSyncHand(cf, other, false); + if (hand == null) { + return cf.thenAcceptBoth(other, action); + } + CompletableFuture out; + try { + out = cf.thenAcceptBoth(other, wrapBiConsumer(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#runAfterBoth(CompletionStage, Runnable)}. + * + * @param first input type + * @param cf target future + * @param other other stage + * @param action stage runnable + * @return dependent future + */ + public static CompletableFuture runAfterBoth(CompletableFuture cf, + CompletionStage other, Runnable action) { + Hand hand = (other == null || action == null) ? null : prepareCfSyncHand(cf, other, false); + if (hand == null) { + return cf.runAfterBoth(other, action); + } + CompletableFuture out; + try { + out = cf.runAfterBoth(other, wrapStageRunnable(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#applyToEither(CompletionStage, Function)}. + * + * @param input type + * @param output type + * @param cf target future + * @param other other stage + * @param fn stage function + * @return dependent future + */ + public static CompletableFuture applyToEither(CompletableFuture cf, + CompletionStage other, Function fn) { + Hand hand = (other == null || fn == null) ? null : prepareCfSyncHand(cf, other, true); + if (hand == null) { + return cf.applyToEither(other, fn); + } + CompletableFuture out; + try { + out = cf.applyToEither(other, wrapFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#acceptEither(CompletionStage, Consumer)}. + * + * @param input type + * @param cf target future + * @param other other stage + * @param action stage consumer + * @return dependent future + */ + public static CompletableFuture acceptEither(CompletableFuture cf, + CompletionStage other, Consumer action) { + Hand hand = (other == null || action == null) ? null : prepareCfSyncHand(cf, other, true); + if (hand == null) { + return cf.acceptEither(other, action); + } + CompletableFuture out; + try { + out = cf.acceptEither(other, wrapConsumer(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#runAfterEither(CompletionStage, Runnable)}. + * + * @param input type + * @param cf target future + * @param other other stage + * @param action stage runnable + * @return dependent future + */ + public static CompletableFuture runAfterEither(CompletableFuture cf, + CompletionStage other, Runnable action) { + Hand hand = (other == null || action == null) ? null : prepareCfSyncHand(cf, other, true); + if (hand == null) { + return cf.runAfterEither(other, action); + } + CompletableFuture out; + try { + out = cf.runAfterEither(other, wrapStageRunnable(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#handle(BiFunction)}. + * + * @param input type + * @param output type + * @param cf target future + * @param fn handler function + * @return dependent future + */ + public static CompletableFuture handle(CompletableFuture cf, + BiFunction fn) { + Hand hand = fn == null ? null : prepareCfSyncHand(cf, null, false); + if (hand == null) { + return cf.handle(fn); + } + CompletableFuture out; + try { + out = cf.handle(wrapBiFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#whenComplete(BiConsumer)}. + * + * @param result type + * @param cf target future + * @param action completion consumer + * @return dependent future + */ + public static CompletableFuture whenComplete(CompletableFuture cf, + BiConsumer action) { + Hand hand = action == null ? null : prepareCfSyncHand(cf, null, false); + if (hand == null) { + return cf.whenComplete(action); + } + CompletableFuture out; + try { + out = cf.whenComplete(wrapBiConsumer(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@link CompletableFuture#exceptionally(Function)}. + * + * @param result type + * @param cf target future + * @param fn recovery function + * @return dependent future + */ + public static CompletableFuture exceptionally(CompletableFuture cf, + Function fn) { + Hand hand = fn == null ? null : prepareCfSyncHand(cf, null, false); + if (hand == null) { + return cf.exceptionally(fn); + } + CompletableFuture out; + try { + out = cf.exceptionally(wrapFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; + } + return finishCfStage(out, hand); + } + + /** + * Call-site wrapper for {@code CompletableFuture.exceptionallyCompose(Function)}. + * + * @param result type + * @param cf target future + * @param fn recovery composition function + * @return dependent future + */ + @SuppressWarnings("unchecked") + public static CompletableFuture exceptionallyCompose(CompletableFuture cf, + Function> fn) { + Hand hand = fn == null ? null : prepareCfSyncHand(cf, null, false); + Function> target = hand == null ? fn : wrapFunction(hand, fn); + CompletableFuture out; + try { + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE, cf, target); + } catch (Throwable t) { + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); + } + return finishCfStage(out, hand); + } + + // --- CompletionStage *Async and plain dependent call-site wrappers --- + + /** + * Call-site wrapper for {@link CompletionStage#thenApplyAsync(Function)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param fn stage function + * @return dependent stage + */ + public static CompletionStage stageThenApplyAsync(CompletionStage stage, + Function fn) { + if (stage instanceof CompletableFuture) { + return thenApplyAsync((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenApplyAsync(fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenApplyAsync(Function, Executor)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param fn stage function + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageThenApplyAsync(CompletionStage stage, + Function fn, Executor executor) { + if (stage instanceof CompletableFuture) { + return thenApplyAsync((CompletableFuture) stage, fn, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenApplyAsync(fn, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenAcceptAsync(Consumer)}. + * + * @param input type + * @param stage target stage + * @param action stage consumer + * @return dependent stage + */ + public static CompletionStage stageThenAcceptAsync(CompletionStage stage, + Consumer action) { + if (stage instanceof CompletableFuture) { + return thenAcceptAsync((CompletableFuture) stage, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenAcceptAsync(action); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenAcceptAsync(Consumer, Executor)}. + * + * @param input type + * @param stage target stage + * @param action stage consumer + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageThenAcceptAsync(CompletionStage stage, + Consumer action, Executor executor) { + if (stage instanceof CompletableFuture) { + return thenAcceptAsync((CompletableFuture) stage, action, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenAcceptAsync(action, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenRunAsync(Runnable)}. + * + * @param input type + * @param stage target stage + * @param action stage runnable + * @return dependent stage + */ + public static CompletionStage stageThenRunAsync(CompletionStage stage, Runnable action) { + if (stage instanceof CompletableFuture) { + return thenRunAsync((CompletableFuture) stage, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenRunAsync(action); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenRunAsync(Runnable, Executor)}. + * + * @param input type + * @param stage target stage + * @param action stage runnable + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageThenRunAsync(CompletionStage stage, Runnable action, + Executor executor) { + if (stage instanceof CompletableFuture) { + return thenRunAsync((CompletableFuture) stage, action, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenRunAsync(action, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenComposeAsync(Function)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param fn composition function + * @return dependent stage + */ + public static CompletionStage stageThenComposeAsync(CompletionStage stage, + Function> fn) { + if (stage instanceof CompletableFuture) { + return thenComposeAsync((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenComposeAsync(fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenComposeAsync(Function, Executor)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param fn composition function + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageThenComposeAsync(CompletionStage stage, + Function> fn, Executor executor) { + if (stage instanceof CompletableFuture) { + return thenComposeAsync((CompletableFuture) stage, fn, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenComposeAsync(fn, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenCombineAsync(CompletionStage, BiFunction)}. + * + * @param first input type + * @param second input type + * @param output type + * @param stage target stage + * @param other other stage + * @param fn combiner function + * @return dependent stage + */ + public static CompletionStage stageThenCombineAsync(CompletionStage stage, + CompletionStage other, BiFunction fn) { + if (stage instanceof CompletableFuture) { + return thenCombineAsync((CompletableFuture) stage, other, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenCombineAsync(other, fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenCombineAsync(CompletionStage, BiFunction, Executor)}. + * + * @param first input type + * @param second input type + * @param output type + * @param stage target stage + * @param other other stage + * @param fn combiner function + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageThenCombineAsync(CompletionStage stage, + CompletionStage other, BiFunction fn, + Executor executor) { + if (stage instanceof CompletableFuture) { + return thenCombineAsync((CompletableFuture) stage, other, fn, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenCombineAsync(other, fn, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenAcceptBothAsync(CompletionStage, BiConsumer)}. + * + * @param first input type + * @param second input type + * @param stage target stage + * @param other other stage + * @param action combiner consumer + * @return dependent stage + */ + public static CompletionStage stageThenAcceptBothAsync(CompletionStage stage, + CompletionStage other, BiConsumer action) { + if (stage instanceof CompletableFuture) { + return thenAcceptBothAsync((CompletableFuture) stage, other, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenAcceptBothAsync(other, action); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenAcceptBothAsync(CompletionStage, BiConsumer, Executor)}. + * + * @param first input type + * @param second input type + * @param stage target stage + * @param other other stage + * @param action combiner consumer + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageThenAcceptBothAsync(CompletionStage stage, + CompletionStage other, BiConsumer action, Executor executor) { + if (stage instanceof CompletableFuture) { + return thenAcceptBothAsync((CompletableFuture) stage, other, action, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenAcceptBothAsync(other, action, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#runAfterBothAsync(CompletionStage, Runnable)}. + * + * @param first input type + * @param stage target stage + * @param other other stage + * @param action stage runnable + * @return dependent stage + */ + public static CompletionStage stageRunAfterBothAsync(CompletionStage stage, + CompletionStage other, Runnable action) { + if (stage instanceof CompletableFuture) { + return runAfterBothAsync((CompletableFuture) stage, other, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.runAfterBothAsync(other, action); + } + + /** + * Call-site wrapper for {@link CompletionStage#runAfterBothAsync(CompletionStage, Runnable, Executor)}. + * + * @param first input type + * @param stage target stage + * @param other other stage + * @param action stage runnable + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageRunAfterBothAsync(CompletionStage stage, + CompletionStage other, Runnable action, Executor executor) { + if (stage instanceof CompletableFuture) { + return runAfterBothAsync((CompletableFuture) stage, other, action, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.runAfterBothAsync(other, action, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#applyToEitherAsync(CompletionStage, Function)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param other other stage + * @param fn stage function + * @return dependent stage + */ + public static CompletionStage stageApplyToEitherAsync(CompletionStage stage, + CompletionStage other, Function fn) { + if (stage instanceof CompletableFuture) { + return applyToEitherAsync((CompletableFuture) stage, other, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.applyToEitherAsync(other, fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#applyToEitherAsync(CompletionStage, Function, Executor)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param other other stage + * @param fn stage function + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageApplyToEitherAsync(CompletionStage stage, + CompletionStage other, Function fn, Executor executor) { + if (stage instanceof CompletableFuture) { + return applyToEitherAsync((CompletableFuture) stage, other, fn, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.applyToEitherAsync(other, fn, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#acceptEitherAsync(CompletionStage, Consumer)}. + * + * @param input type + * @param stage target stage + * @param other other stage + * @param action stage consumer + * @return dependent stage + */ + public static CompletionStage stageAcceptEitherAsync(CompletionStage stage, + CompletionStage other, Consumer action) { + if (stage instanceof CompletableFuture) { + return acceptEitherAsync((CompletableFuture) stage, other, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.acceptEitherAsync(other, action); + } + + /** + * Call-site wrapper for {@link CompletionStage#acceptEitherAsync(CompletionStage, Consumer, Executor)}. + * + * @param input type + * @param stage target stage + * @param other other stage + * @param action stage consumer + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageAcceptEitherAsync(CompletionStage stage, + CompletionStage other, Consumer action, Executor executor) { + if (stage instanceof CompletableFuture) { + return acceptEitherAsync((CompletableFuture) stage, other, action, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.acceptEitherAsync(other, action, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#runAfterEitherAsync(CompletionStage, Runnable)}. + * + * @param input type + * @param stage target stage + * @param other other stage + * @param action stage runnable + * @return dependent stage + */ + public static CompletionStage stageRunAfterEitherAsync(CompletionStage stage, + CompletionStage other, Runnable action) { + if (stage instanceof CompletableFuture) { + return runAfterEitherAsync((CompletableFuture) stage, other, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.runAfterEitherAsync(other, action); + } + + /** + * Call-site wrapper for {@link CompletionStage#runAfterEitherAsync(CompletionStage, Runnable, Executor)}. + * + * @param input type + * @param stage target stage + * @param other other stage + * @param action stage runnable + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageRunAfterEitherAsync(CompletionStage stage, + CompletionStage other, Runnable action, Executor executor) { + if (stage instanceof CompletableFuture) { + return runAfterEitherAsync((CompletableFuture) stage, other, action, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.runAfterEitherAsync(other, action, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#handleAsync(BiFunction)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param fn handler function + * @return dependent stage + */ + public static CompletionStage stageHandleAsync(CompletionStage stage, + BiFunction fn) { + if (stage instanceof CompletableFuture) { + return handleAsync((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.handleAsync(fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#handleAsync(BiFunction, Executor)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param fn handler function + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageHandleAsync(CompletionStage stage, + BiFunction fn, Executor executor) { + if (stage instanceof CompletableFuture) { + return handleAsync((CompletableFuture) stage, fn, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.handleAsync(fn, executor); + } + + /** + * Call-site wrapper for {@link CompletionStage#whenCompleteAsync(BiConsumer)}. + * + * @param result type + * @param stage target stage + * @param action completion consumer + * @return dependent stage + */ + public static CompletionStage stageWhenCompleteAsync(CompletionStage stage, + BiConsumer action) { + if (stage instanceof CompletableFuture) { + return whenCompleteAsync((CompletableFuture) stage, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.whenCompleteAsync(action); + } + + /** + * Call-site wrapper for {@link CompletionStage#whenCompleteAsync(BiConsumer, Executor)}. + * + * @param result type + * @param stage target stage + * @param action completion consumer + * @param executor target executor + * @return dependent stage + */ + public static CompletionStage stageWhenCompleteAsync(CompletionStage stage, + BiConsumer action, Executor executor) { + if (stage instanceof CompletableFuture) { + return whenCompleteAsync((CompletableFuture) stage, action, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.whenCompleteAsync(action, executor); + } + + /** + * Call-site wrapper for {@code CompletionStage.exceptionallyAsync(Function)}. + * + * @param result type + * @param stage target stage + * @param fn recovery function + * @return dependent stage + */ + @SuppressWarnings("unchecked") + public static CompletionStage stageExceptionallyAsync(CompletionStage stage, + Function fn) { + if (stage instanceof CompletableFuture) { + return exceptionallyAsync((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + try { + return (CompletionStage) invokeCfReflect(CS_EXCEPTIONALLY_ASYNC_1, stage, fn); + } catch (Throwable t) { + throw sneakyThrow(t); + } + } + + /** + * Call-site wrapper for {@code CompletionStage.exceptionallyAsync(Function, Executor)}. + * + * @param result type + * @param stage target stage + * @param fn recovery function + * @param executor target executor + * @return dependent stage + */ + @SuppressWarnings("unchecked") + public static CompletionStage stageExceptionallyAsync(CompletionStage stage, + Function fn, Executor executor) { + if (stage instanceof CompletableFuture) { + return exceptionallyAsync((CompletableFuture) stage, fn, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + try { + return (CompletionStage) invokeCfReflect(CS_EXCEPTIONALLY_ASYNC_2, stage, fn, executor); + } catch (Throwable t) { + throw sneakyThrow(t); + } + } + + /** + * Call-site wrapper for {@code CompletionStage.exceptionallyComposeAsync(Function)}. + * + * @param result type + * @param stage target stage + * @param fn recovery composition function + * @return dependent stage + */ + @SuppressWarnings("unchecked") + public static CompletionStage stageExceptionallyComposeAsync(CompletionStage stage, + Function> fn) { + if (stage instanceof CompletableFuture) { + return exceptionallyComposeAsync((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + try { + return (CompletionStage) invokeCfReflect(CS_EXCEPTIONALLY_COMPOSE_ASYNC_1, stage, fn); + } catch (Throwable t) { + throw sneakyThrow(t); + } + } + + /** + * Call-site wrapper for {@code CompletionStage.exceptionallyComposeAsync(Function, Executor)}. + * + * @param result type + * @param stage target stage + * @param fn recovery composition function + * @param executor target executor + * @return dependent stage + */ + @SuppressWarnings("unchecked") + public static CompletionStage stageExceptionallyComposeAsync(CompletionStage stage, + Function> fn, Executor executor) { + if (stage instanceof CompletableFuture) { + return exceptionallyComposeAsync((CompletableFuture) stage, fn, executor); + } + noteUntrackedAsync("untracked-async:completion-stage"); + try { + return (CompletionStage) invokeCfReflect(CS_EXCEPTIONALLY_COMPOSE_ASYNC_2, stage, fn, executor); + } catch (Throwable t) { + throw sneakyThrow(t); + } + } + + /** + * Call-site wrapper for {@link CompletionStage#thenApply(Function)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param fn stage function + * @return dependent stage + */ + public static CompletionStage stageThenApply(CompletionStage stage, + Function fn) { + if (stage instanceof CompletableFuture) { + return thenApply((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenApply(fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenAccept(Consumer)}. + * + * @param input type + * @param stage target stage + * @param action stage consumer + * @return dependent stage + */ + public static CompletionStage stageThenAccept(CompletionStage stage, + Consumer action) { + if (stage instanceof CompletableFuture) { + return thenAccept((CompletableFuture) stage, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenAccept(action); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenRun(Runnable)}. + * + * @param input type + * @param stage target stage + * @param action stage runnable + * @return dependent stage + */ + public static CompletionStage stageThenRun(CompletionStage stage, Runnable action) { + if (stage instanceof CompletableFuture) { + return thenRun((CompletableFuture) stage, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenRun(action); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenCompose(Function)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param fn composition function + * @return dependent stage + */ + public static CompletionStage stageThenCompose(CompletionStage stage, + Function> fn) { + if (stage instanceof CompletableFuture) { + return thenCompose((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenCompose(fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenCombine(CompletionStage, BiFunction)}. + * + * @param first input type + * @param second input type + * @param output type + * @param stage target stage + * @param other other stage + * @param fn combiner function + * @return dependent stage + */ + public static CompletionStage stageThenCombine(CompletionStage stage, + CompletionStage other, BiFunction fn) { + if (stage instanceof CompletableFuture) { + return thenCombine((CompletableFuture) stage, other, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenCombine(other, fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#thenAcceptBoth(CompletionStage, BiConsumer)}. + * + * @param first input type + * @param second input type + * @param stage target stage + * @param other other stage + * @param action combiner consumer + * @return dependent stage + */ + public static CompletionStage stageThenAcceptBoth(CompletionStage stage, + CompletionStage other, BiConsumer action) { + if (stage instanceof CompletableFuture) { + return thenAcceptBoth((CompletableFuture) stage, other, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.thenAcceptBoth(other, action); + } + + /** + * Call-site wrapper for {@link CompletionStage#runAfterBoth(CompletionStage, Runnable)}. + * + * @param first input type + * @param stage target stage + * @param other other stage + * @param action stage runnable + * @return dependent stage + */ + public static CompletionStage stageRunAfterBoth(CompletionStage stage, + CompletionStage other, Runnable action) { + if (stage instanceof CompletableFuture) { + return runAfterBoth((CompletableFuture) stage, other, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.runAfterBoth(other, action); + } + + /** + * Call-site wrapper for {@link CompletionStage#applyToEither(CompletionStage, Function)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param other other stage + * @param fn stage function + * @return dependent stage + */ + public static CompletionStage stageApplyToEither(CompletionStage stage, + CompletionStage other, Function fn) { + if (stage instanceof CompletableFuture) { + return applyToEither((CompletableFuture) stage, other, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.applyToEither(other, fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#acceptEither(CompletionStage, Consumer)}. + * + * @param input type + * @param stage target stage + * @param other other stage + * @param action stage consumer + * @return dependent stage + */ + public static CompletionStage stageAcceptEither(CompletionStage stage, + CompletionStage other, Consumer action) { + if (stage instanceof CompletableFuture) { + return acceptEither((CompletableFuture) stage, other, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.acceptEither(other, action); + } + + /** + * Call-site wrapper for {@link CompletionStage#runAfterEither(CompletionStage, Runnable)}. + * + * @param input type + * @param stage target stage + * @param other other stage + * @param action stage runnable + * @return dependent stage + */ + public static CompletionStage stageRunAfterEither(CompletionStage stage, + CompletionStage other, Runnable action) { + if (stage instanceof CompletableFuture) { + return runAfterEither((CompletableFuture) stage, other, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.runAfterEither(other, action); + } + + /** + * Call-site wrapper for {@link CompletionStage#handle(BiFunction)}. + * + * @param input type + * @param output type + * @param stage target stage + * @param fn handler function + * @return dependent stage + */ + public static CompletionStage stageHandle(CompletionStage stage, + BiFunction fn) { + if (stage instanceof CompletableFuture) { + return handle((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.handle(fn); + } + + /** + * Call-site wrapper for {@link CompletionStage#whenComplete(BiConsumer)}. + * + * @param result type + * @param stage target stage + * @param action completion consumer + * @return dependent stage + */ + public static CompletionStage stageWhenComplete(CompletionStage stage, + BiConsumer action) { + if (stage instanceof CompletableFuture) { + return whenComplete((CompletableFuture) stage, action); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.whenComplete(action); + } + + /** + * Call-site wrapper for {@link CompletionStage#exceptionally(Function)}. + * + * @param result type + * @param stage target stage + * @param fn recovery function + * @return dependent stage + */ + public static CompletionStage stageExceptionally(CompletionStage stage, + Function fn) { + if (stage instanceof CompletableFuture) { + return exceptionally((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + return stage.exceptionally(fn); + } + + /** + * Call-site wrapper for {@code CompletionStage.exceptionallyCompose(Function)}. + * + * @param result type + * @param stage target stage + * @param fn recovery composition function + * @return dependent stage + */ + @SuppressWarnings("unchecked") + public static CompletionStage stageExceptionallyCompose(CompletionStage stage, + Function> fn) { + if (stage instanceof CompletableFuture) { + return exceptionallyCompose((CompletableFuture) stage, fn); + } + noteUntrackedAsync("untracked-async:completion-stage"); + try { + return (CompletionStage) invokeCfReflect(CS_EXCEPTIONALLY_COMPOSE, stage, fn); + } catch (Throwable t) { + throw sneakyThrow(t); + } + } + + private static Object invokeCfReflect(Method method, Object target, Object... args) throws Throwable { + if (method == null) { + throw new NoSuchMethodError("CompletableFuture/CompletionStage method unavailable on this JDK"); + } + try { + return method.invoke(target, args); + } catch (InvocationTargetException e) { + throw e.getCause() != null ? e.getCause() : e; + } + } + + @SuppressWarnings("unchecked") + private static RuntimeException sneakyThrow(Throwable t) throws E { + throw (E) t; + } + + // --- Untracked async call-site pass-through contamination helpers --- + + /** + * Records an untracked async hand-off occurring inside an active request + * window or scheduled/listener job run without wrapping the task. + * + * @param reason contamination reason label + */ + public static void noteUntrackedAsync(String reason) { + noteUntrackedAsync(reason, 0L); + } + + private static void noteUntrackedAsync(String reason, long extraTailNanos) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return; + } + if (reason == null || reason.isEmpty()) { + return; + } + Window window = INSIDE.get(); + if (window != null) { + window.contaminate(reason, extraTailNanos); + if (window != current) { + retainLingering(window, System.nanoTime()); + } + return; + } + if (JobGate.runningAttribution() != null) { + JobGate.markUntracked(reason, extraTailNanos); + return; + } + String expiredJob = JobGate.expiredRunningName(); + if (expiredJob != null) { + JobGate.markUntracked("job-tail:" + expiredJob, extraTailNanos); + } + } + + /** + * Checks at runtime whether a receiver of {@code execute(Runnable)} is an + * untracked {@link Executor}, ignoring non-{@link Executor} helpers, + * allow-listed same-thread inline executors, and hooked/verified Spring + * executors. + * + * @param receiver target receiver of {@code execute(Runnable)} + */ + public static void noteIfUntrackedExecutor(Object receiver) { + if (!(receiver instanceof Executor)) { + return; + } + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + return; + } + if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + return; + } + noteUntrackedAsync("untracked-executor:" + receiver.getClass().getName(), 0L); + } + + /** + * Checks at runtime whether a receiver of {@code submit*} is an untracked + * {@link ExecutorService}, {@link CompletionService}, or Spring + * {@code AsyncTaskExecutor}, ignoring non-executor helpers, allow-listed + * same-thread inline executors, and hooked/verified Spring executors. + * + * @param receiver target receiver of {@code submit*} + */ + public static void noteIfUntrackedSubmit(Object receiver) { + if (!(receiver instanceof ExecutorService) + && !(receiver instanceof CompletionService) + && !OrderedPools.isSpringAsyncTaskExecutor(receiver)) { + return; + } + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + return; + } + if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + return; + } + noteUntrackedAsync("untracked-executor:" + receiver.getClass().getName(), 0L); + } + + /** + * Checks at runtime whether a bound {@code execute(Runnable)} method + * reference receiver is an untracked {@link Executor}, ignoring + * non-{@link Executor} helpers, allow-listed same-thread inline executors, + * and hooked/verified Spring executors. When captured outside any active + * request window or tracked job (including before arming), permanently + * latches {@code asyncExecutors=false} because later invocations through + * the captured lambda bypass rewritten call sites. + * + * @param receiver captured receiver of {@code execute(Runnable)} method reference + */ + public static void noteIfUntrackedExecutorMethodRef(Object receiver) { + if (!(receiver instanceof Executor)) { + return; + } + if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + return; + } + String name = receiver.getClass().getName(); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(name); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(name); + return; + } + noteUntrackedAsync("untracked-executor:" + name, 0L); + } + + /** + * Checks at runtime whether a bound {@code submit*} method reference + * receiver is an untracked {@link ExecutorService}, + * {@link CompletionService}, or Spring {@code AsyncTaskExecutor}, ignoring + * non-executor helpers, allow-listed same-thread inline executors, and + * hooked/verified Spring executors. When captured outside any active + * request window or tracked job (including before arming), permanently + * latches {@code asyncExecutors=false}. + * + * @param receiver captured receiver of {@code submit*} method reference + */ + public static void noteIfUntrackedSubmitMethodRef(Object receiver) { + if (!(receiver instanceof ExecutorService) + && !(receiver instanceof CompletionService) + && !OrderedPools.isSpringAsyncTaskExecutor(receiver)) { + return; + } + if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + return; + } + String name = receiver.getClass().getName(); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(name); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(name); + return; + } + noteUntrackedAsync("untracked-executor:" + name, 0L); + } + + /** + * Checks at runtime whether the owner class of an unbound + * {@code execute(Runnable)} method reference is an untracked + * {@link Executor}, ignoring non-{@link Executor} types and allow-listed + * same-thread inline executors. When captured outside any active request + * window or tracked job (including before arming), permanently latches + * {@code asyncExecutors=false}. + * + * @param owner declaring owner class of the method reference + */ + public static void noteIfUntrackedExecutorClass(Class owner) { + if (owner == null || !Executor.class.isAssignableFrom(owner)) { + return; + } + if (OrderedPools.isInlineExecutorClass(owner)) { + return; + } + String name = owner.getName(); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(name); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(name); + return; + } + noteUntrackedAsync("untracked-executor:" + name, 0L); + } + + /** + * Checks at runtime whether the owner class of an unbound {@code submit*} + * method reference is an untracked {@link ExecutorService}, + * {@link CompletionService}, or Spring {@code AsyncTaskExecutor}, ignoring + * non-executor types and allow-listed same-thread inline executors. When + * captured outside any active request window or tracked job (including + * before arming), permanently latches {@code asyncExecutors=false}. + * + * @param owner declaring owner class of the method reference + */ + public static void noteIfUntrackedSubmitClass(Class owner) { + if (owner == null + || (!ExecutorService.class.isAssignableFrom(owner) + && !CompletionService.class.isAssignableFrom(owner) + && !OrderedPools.isSpringAsyncTaskExecutorClass(owner))) { + return; + } + if (OrderedPools.isInlineExecutorClass(owner)) { + return; + } + String name = owner.getName(); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(name); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(name); + return; + } + noteUntrackedAsync("untracked-executor:" + name, 0L); + } + + /** + * Records an untracked async method reference capture. Inside an active + * request window or tracked job it contaminates that window; outside any + * window or job (including before arming) it permanently latches + * {@code asyncExecutors=false}. + * + * @param reason contamination reason label describing the method reference + */ + public static void noteUntrackedAsyncMethodRef(String reason) { + if (reason == null || reason.isEmpty()) { + return; + } + if (!armed) { + noteUnarmedHandOffIfInFlight(); + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(reason); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(reason); + return; + } + noteUntrackedAsync(reason, 0L); + } + + /** + * Records cancellation of a {@link Timer} with timestamp so tasks that had + * not started stop driving tail contamination immediately, while any + * already-running body stays covered for {@code untrackedTailWindowNanos}. + * + * @param timer cancelled timer + */ + public static void noteTimerCancelled(Timer timer) { + if (timer == null || !armed) { + return; + } + drainDeadTimerKeys(); + CANCELLED_TIMERS.putIfAbsent(new WeakIdentityKey(timer, DEAD_TIMER_KEYS), Long.valueOf(System.nanoTime())); + } + + /** + * Records the result of {@link TimerTask#cancel()} when {@code target} is a + * {@link TimerTask}: {@code cancelled == true} means the task was still + * scheduled (not yet fired for a one-shot task), whereas {@code false} + * means it had already fired (and its {@code run()} body may still be + * executing, so tail protection is kept for {@code untrackedTailWindowNanos}). + * + * @param target receiver of {@code cancel()} + * @param cancelled return value of {@code cancel()} + */ + public static void noteTimerTaskCancelResult(Object target, boolean cancelled) { + if (!(target instanceof TimerTask) || !armed) { + return; + } + drainDeadTimerTaskKeys(); + CANCELLED_TIMER_TASKS.putIfAbsent(new WeakIdentityKey(target, DEAD_TIMER_TASK_KEYS), + new TimerCancelInfo(cancelled, System.nanoTime())); + } + + private static void drainDeadTimerTaskKeys() { + for (Reference ref; (ref = DEAD_TIMER_TASK_KEYS.poll()) != null; ) { + CANCELLED_TIMER_TASKS.remove(ref); + } + } + + private static void drainDeadTimerKeys() { + for (Reference ref; (ref = DEAD_TIMER_KEYS.poll()) != null; ) { + CANCELLED_TIMERS.remove(ref); + } + } + + private static TimerCancelInfo timerTaskCancelInfo(TimerTask task) { + if (task == null || CANCELLED_TIMER_TASKS.isEmpty()) { + return null; + } + drainDeadTimerTaskKeys(); + return CANCELLED_TIMER_TASKS.get(new LookupKey(task)); + } + + private static Long timerCancelledAtNanos(Timer timer) { + if (timer == null || CANCELLED_TIMERS.isEmpty()) { + return null; + } + drainDeadTimerKeys(); + return CANCELLED_TIMERS.get(new LookupKey(timer)); + } + + private static long safeScheduledExecutionTime(TimerTask task) { + if (task == null) { + return 0L; + } + try { + return task.scheduledExecutionTime(); + } catch (Throwable ignored) { + return 0L; + } + } + + /** + * Checks whether {@code target} is a {@link Thread} instance before a + * non-{@code java.lang.Thread} {@code start()} call, flags an untracked + * thread start if so, and weakly tracks the thread's liveness so tail + * contamination persists only while the thread remains alive. + * + * @param target receiver of {@code start()} + */ + public static void noteIfThread(Object target) { + if (!(target instanceof Thread)) { + return; + } + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return; + } + noteTrackedUntrackedAsync("untracked-async:thread-start", target, false); + } + + /** + * Weakly tracks a newly started {@link Thread} (e.g., returned by JDK 21 + * {@code Thread.startVirtualThread} or {@code Thread.Builder.start}) so + * subsequent windows remain marked with tail contamination while the thread + * is still alive. + * + * @param thread returned thread instance + */ + public static void trackUntrackedThread(Object thread) { + trackUntrackedThread(thread, null); + } + + /** + * Flags and weakly tracks a newly started {@link Thread} so subsequent + * windows remain marked with tail contamination only while the thread stays + * alive (no blind 2 s tail once dead). + * + * @param thread returned thread instance + * @param reason contamination label for the originating window + */ + public static void trackUntrackedThread(Object thread, String reason) { + if (!armed) { + if (thread instanceof Thread) { + noteUnarmedHandOffIfInFlight(); + } + return; + } + if (thread instanceof Thread) { + noteTrackedUntrackedAsync(reason, thread, true); + } else if (reason != null && !reason.isEmpty()) { + noteUntrackedAsync(reason, 0L); + } + } + + /** + * Weakly tracks a {@link Future} (e.g., returned by Spring + * {@code TaskScheduler.schedule*}) so subsequent windows remain marked with + * tail contamination until the scheduled future completes or is cancelled. + * + * @param future returned future instance + */ + public static void trackUntrackedFuture(Object future) { + trackUntrackedFuture(future, null); + } + + /** + * Flags and weakly tracks a returned {@link Future} so subsequent windows + * remain marked with tail contamination only while the future is not done + * or cancelled (no blind 2 s or delay-based tail once done/cancelled). + * + * @param future returned future instance + * @param reason contamination label for the originating window + */ + public static void trackUntrackedFuture(Object future, String reason) { + if (!armed) { + if (future instanceof Future) { + noteUnarmedHandOffIfInFlight(); + } + return; + } + if (future instanceof Future) { + noteTrackedUntrackedAsync(reason, future, true); + } else if (reason != null && !reason.isEmpty()) { + noteUntrackedAsync(reason, 0L); + } + } + + private static void noteTrackedUntrackedAsync(String reason, Object target, boolean alreadyStarted) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return; + } + if (target == null) { + if (reason != null && !reason.isEmpty()) { + noteUntrackedAsync(reason, 0L); + } + return; + } + long now = System.nanoTime(); + noteTrackedHandle(reason, new UntrackedHandle(target, alreadyStarted, now), now); + } + + private static void noteTrackedTimerTask(Timer timer, TimerTask task, long delayMillis, long periodMillis, + boolean periodic) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return; + } + if (task == null) { + noteUntrackedAsync("untracked-async:timer", 0L); + return; + } + long now = System.nanoTime(); + UntrackedHandle handle = UntrackedHandle.forTimerTask(timer, task, delayMillis, periodMillis, periodic, now); + noteTrackedHandle("untracked-async:timer", handle, now); + } + + private static void noteTrackedHandle(String reason, UntrackedHandle handle, long now) { + Window window = INSIDE.get(); + if (window != null) { + if (reason != null && !reason.isEmpty()) { + window.contaminateTracked(reason); + } + window.addUntrackedHandle(handle, now); + if (window != current) { + retainLingering(window, now); + } + return; + } + String effectiveReason = reason; + if (JobGate.runningAttribution() != null) { + if (effectiveReason != null && !effectiveReason.isEmpty()) { + JobGate.markUntrackedWindowOnly(effectiveReason); + } + externalUntrackedTailReason = effectiveReason == null || effectiveReason.isEmpty() ? "job" : effectiveReason; + if (!addHandleToQueue(EXTERNAL_UNTRACKED_HANDLES, handle, now)) { + noteExternalUntrackedTail(effectiveReason, maxLingeringNanos); + } + return; + } + String expiredJob = JobGate.expiredRunningName(); + if (expiredJob != null) { + String jobReason = "job-tail:" + expiredJob; + JobGate.markUntrackedWindowOnly(jobReason); + externalUntrackedTailReason = jobReason; + if (!addHandleToQueue(EXTERNAL_UNTRACKED_HANDLES, handle, now)) { + noteExternalUntrackedTail(jobReason, maxLingeringNanos); + } + } + } + + private static boolean addHandleToQueue(ConcurrentLinkedQueue queue, UntrackedHandle handle, + long now) { + if (queue.size() >= MAX_UNTRACKED_HANDLES) { + sweepUntrackedHandles(queue, now); + if (queue.size() >= MAX_UNTRACKED_HANDLES) { + return false; + } + } + queue.add(handle); + return true; + } + + private static boolean sweepUntrackedHandles(ConcurrentLinkedQueue queue, long now) { + if (queue == null || queue.isEmpty()) { + return false; + } + boolean anyAlive = false; + for (UntrackedHandle h : queue) { + if (h.isActive(now)) { + anyAlive = true; + } else { + queue.remove(h); + } + } + return anyAlive; + } + + private static Runnable wrapScheduledContext(ScheduledExecutorService executor, Runnable command) { + if (!armed || command == null || command instanceof Comparable || command instanceof ScheduledContextRunnable) { + return command; + } + Window window = INSIDE.get(); + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + return command; + } + if (OrderedPools.orders(executor)) { + return command; + } + return new ScheduledContextRunnable(window, job, command); + } + + private static Callable wrapScheduledContext(ScheduledExecutorService executor, Callable callable) { + if (!armed || callable == null || callable instanceof Comparable + || callable instanceof ScheduledContextCallable) { + return callable; + } + Window window = INSIDE.get(); + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + return callable; + } + if (OrderedPools.orders(executor)) { + return callable; + } + return new ScheduledContextCallable<>(window, job, callable); + } + + /** + * Pass-through call-site wrapper for {@link ScheduledExecutorService#schedule(Runnable, long, TimeUnit)}. + * + * @param executor target scheduled executor + * @param command task to schedule + * @param delay execution delay + * @param unit time unit of delay + * @return scheduled future + */ + public static ScheduledFuture schedule(ScheduledExecutorService executor, Runnable command, + long delay, TimeUnit unit) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.schedule(command, delay, unit); + } + ScheduledFuture sf = executor.schedule(wrapScheduledContext(executor, command), delay, unit); + noteTrackedUntrackedAsync("untracked-async:schedule", sf, true); + return sf; + } + + /** + * Pass-through call-site wrapper for {@link ScheduledExecutorService#schedule(Callable, long, TimeUnit)}. + * + * @param result type + * @param executor target scheduled executor + * @param callable task to schedule + * @param delay execution delay + * @param unit time unit of delay + * @return scheduled future + */ + public static ScheduledFuture schedule(ScheduledExecutorService executor, Callable callable, + long delay, TimeUnit unit) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.schedule(callable, delay, unit); + } + ScheduledFuture sf = executor.schedule(wrapScheduledContext(executor, callable), delay, unit); + noteTrackedUntrackedAsync("untracked-async:schedule", sf, true); + return sf; + } + + /** + * Pass-through call-site wrapper for + * {@link ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)}. + * + * @param executor target scheduled executor + * @param command task to schedule + * @param initialDelay initial delay + * @param period execution period + * @param unit time unit + * @return scheduled future + */ + public static ScheduledFuture scheduleAtFixedRate(ScheduledExecutorService executor, Runnable command, + long initialDelay, long period, TimeUnit unit) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.scheduleAtFixedRate(command, initialDelay, period, unit); + } + ScheduledFuture sf = executor.scheduleAtFixedRate( + wrapScheduledContext(executor, command), initialDelay, period, unit); + noteTrackedUntrackedAsync("untracked-async:schedule", sf, true); + return sf; + } + + /** + * Pass-through call-site wrapper for + * {@link ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)}. + * + * @param executor target scheduled executor + * @param command task to schedule + * @param initialDelay initial delay + * @param delay delay between runs + * @param unit time unit + * @return scheduled future + */ + public static ScheduledFuture scheduleWithFixedDelay(ScheduledExecutorService executor, Runnable command, + long initialDelay, long delay, TimeUnit unit) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); + } + ScheduledFuture sf = executor.scheduleWithFixedDelay( + wrapScheduledContext(executor, command), initialDelay, delay, unit); + noteTrackedUntrackedAsync("untracked-async:schedule", sf, true); + return sf; + } + + private static long dateDelayMillis(Date time) { + if (time == null) { + return 0L; + } + long diff = time.getTime() - System.currentTimeMillis(); + return diff > 0L ? diff : 0L; + } + + /** + * Pass-through call-site wrapper for {@link Timer#schedule(TimerTask, long)}. + * + * @param timer target timer + * @param task timer task + * @param delay execution delay in milliseconds + */ + public static void timerSchedule(Timer timer, TimerTask task, long delay) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.schedule(task, delay); + return; + } + timer.schedule(task, delay); + noteTrackedTimerTask(timer, task, delay, 0L, false); + } + + /** + * Pass-through call-site wrapper for {@link Timer#schedule(TimerTask, Date)}. + * + * @param timer target timer + * @param task timer task + * @param time execution time + */ + public static void timerSchedule(Timer timer, TimerTask task, Date time) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.schedule(task, time); + return; + } + long delay = dateDelayMillis(time); + timer.schedule(task, time); + noteTrackedTimerTask(timer, task, delay, 0L, false); + } + + /** + * Pass-through call-site wrapper for {@link Timer#schedule(TimerTask, long, long)}. + * + * @param timer target timer + * @param task timer task + * @param delay initial delay in milliseconds + * @param period period in milliseconds + */ + public static void timerSchedule(Timer timer, TimerTask task, long delay, long period) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.schedule(task, delay, period); + return; + } + timer.schedule(task, delay, period); + noteTrackedTimerTask(timer, task, delay, period, true); + } + + /** + * Pass-through call-site wrapper for {@link Timer#schedule(TimerTask, Date, long)}. + * + * @param timer target timer + * @param task timer task + * @param firstTime first execution time + * @param period period in milliseconds + */ + public static void timerSchedule(Timer timer, TimerTask task, Date firstTime, long period) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.schedule(task, firstTime, period); + return; + } + long delay = dateDelayMillis(firstTime); + timer.schedule(task, firstTime, period); + noteTrackedTimerTask(timer, task, delay, period, true); + } + + /** + * Pass-through call-site wrapper for {@link Timer#scheduleAtFixedRate(TimerTask, long, long)}. + * + * @param timer target timer + * @param task timer task + * @param delay initial delay in milliseconds + * @param period period in milliseconds + */ + public static void timerScheduleAtFixedRate(Timer timer, TimerTask task, long delay, long period) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.scheduleAtFixedRate(task, delay, period); + return; + } + timer.scheduleAtFixedRate(task, delay, period); + noteTrackedTimerTask(timer, task, delay, period, true); + } + + /** + * Pass-through call-site wrapper for {@link Timer#scheduleAtFixedRate(TimerTask, Date, long)}. + * + * @param timer target timer + * @param task timer task + * @param firstTime first execution time + * @param period period in milliseconds + */ + public static void timerScheduleAtFixedRate(Timer timer, TimerTask task, Date firstTime, long period) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.scheduleAtFixedRate(task, firstTime, period); + return; + } + long delay = dateDelayMillis(firstTime); + timer.scheduleAtFixedRate(task, firstTime, period); + noteTrackedTimerTask(timer, task, delay, period, true); + } + + /** + * Pass-through call-site wrapper for {@link ExecutorService#invokeAny(Collection)}. + * + * @param result type + * @param executor target executor service + * @param tasks tasks to invoke + * @return result of one completed task + * @throws InterruptedException if interrupted while waiting + * @throws ExecutionException if no task completes successfully + */ + public static T invokeAny(ExecutorService executor, Collection> tasks) + throws InterruptedException, ExecutionException { + noteUntrackedAsync("untracked-async:invokeAny"); + return executor.invokeAny(tasks); + } + + /** + * Pass-through call-site wrapper for + * {@link ExecutorService#invokeAny(Collection, long, TimeUnit)}. + * + * @param result type + * @param executor target executor service + * @param tasks tasks to invoke + * @param timeout maximum wait time + * @param unit time unit of timeout + * @return result of one completed task + * @throws InterruptedException if interrupted while waiting + * @throws ExecutionException if no task completes successfully + * @throws TimeoutException if timeout elapses before any task completes + */ + public static T invokeAny(ExecutorService executor, Collection> tasks, + long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + noteUntrackedAsync("untracked-async:invokeAny"); + return executor.invokeAny(tasks, timeout, unit); + } + + /** + * Pass-through call-site wrapper for {@link Thread#start()}. + * + * @param thread thread to start + */ + public static void startThread(Thread thread) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + thread.start(); + return; + } + thread.start(); + noteTrackedUntrackedAsync("untracked-async:thread-start", thread, true); + } + + /** + * Call-site wrapper for {@link ThreadPoolExecutor#remove(Runnable)}: finds + * and removes either the original task (releasing any tracked submitted + * Future permit, e.g. {@code tpe.remove((Runnable) future)}) or the + * wrapped {@link Handed} entry if {@code task} was wrapped, releasing its + * pending window permit so END does not wait for it. Skips the second + * queue scan when this executor has no tracked pending tasks. + * + * @param executor target thread pool + * @param task runnable to remove + * @return {@code true} if the task was removed + */ + public static boolean remove(ThreadPoolExecutor executor, Runnable task) { + if (executor.remove(task)) { + Hand associated = takeFutureHand(task); + if (associated != null) { + associated.releaseIfPending(); + } + return true; + } + if (task == null || !hasPendingForExecutor(executor)) { + return false; + } + for (Runnable queued : executor.getQueue()) { + if (queued instanceof Handed) { + Handed handed = (Handed) queued; + if (handed.task == task && executor.remove(handed)) { + handed.releaseIfPending(); + return true; + } + } + } + return false; + } + + /** + * Call-site wrapper for {@link ExecutorService#shutdownNow()}: releases + * pending window permits for all queued tasks of {@code executor} and + * unwraps any {@link Handed} items in the returned list so callers casting + * them never see {@link Handed}. + * + * @param executor target executor service + * @return list of tasks that never commenced execution + */ + public static List shutdownNow(ExecutorService executor) { + List pending = executor.shutdownNow(); + releaseAllPendingForExecutor(executor); + if (pending == null || pending.isEmpty()) { + return pending; + } + List unwrapped = null; + for (int i = 0; i < pending.size(); i++) { + Runnable item = pending.get(i); + if (item instanceof Handed) { + Handed handed = (Handed) item; + handed.releaseIfPending(); + if (unwrapped == null) { + unwrapped = new ArrayList<>(pending); + } + unwrapped.set(i, handed.task); + } else { + Hand associated = takeFutureHand(item); + if (associated != null) { + associated.releaseIfPending(); + } + } + } + return unwrapped != null ? unwrapped : pending; + } + + private static void drainDeadHands() { + for (Reference ref; (ref = DEAD_HANDS.poll()) != null; ) { + HandRef hr = (HandRef) ref; + if (hr.set.remove(hr) && !hr.released) { + hr.released = true; + done(hr.window); + } + } + } + + private static void drainDeadExecutorKeys() { + for (Reference ref; (ref = DEAD_EXECUTOR_KEYS.poll()) != null; ) { + PENDING_BY_EXECUTOR.remove(ref); + } + } + + private static void drainDeadFutureKeys() { + for (Reference ref; (ref = DEAD_FUTURE_KEYS.poll()) != null; ) { + PENDING_BY_FUTURE.remove(ref); + } + } + + private static boolean hasPendingForExecutor(Executor executor) { + if (executor == null || PENDING_BY_EXECUTOR.isEmpty()) { + return false; + } + Set set = PENDING_BY_EXECUTOR.get(new LookupKey(executor)); + return set != null && !set.isEmpty(); + } + + private static void registerForExecutor(Executor executor, Object handed, Object task) { + drainDeadHands(); + drainDeadExecutorKeys(); + if (executor == null || handed == task || !(handed instanceof Hand)) { + return; + } + Hand hand = (Hand) handed; + if (hand.window == null || hand.isReleased()) { + return; + } + try { + LookupKey probe = new LookupKey(executor); + Set set = PENDING_BY_EXECUTOR.get(probe); + if (set == null) { + Set fresh = ConcurrentHashMap.newKeySet(); + Set existing = PENDING_BY_EXECUTOR.putIfAbsent( + new WeakIdentityKey(executor, DEAD_EXECUTOR_KEYS), fresh); + set = existing != null ? existing : fresh; + } + HandRef ref = new HandRef(hand, DEAD_HANDS, set, hand.window); + set.add(ref); + hand.executorRef = ref; + if (hand.isReleased()) { + ref.released = true; + hand.executorRef = null; + set.remove(ref); + } + } catch (Throwable ignored) { + // Never affect app execution. + } + } + + private static void releaseAllPendingForExecutor(Executor executor) { + drainDeadHands(); + drainDeadExecutorKeys(); + if (executor == null) { + return; + } + Set set = PENDING_BY_EXECUTOR.remove(new LookupKey(executor)); + if (set == null) { + return; + } + for (HandRef ref : set) { + Hand hand = ref.get(); + if (hand != null) { + hand.releaseIfPending(); + } else if (set.remove(ref) && !ref.released) { + ref.released = true; + done(ref.window); + } + } + set.clear(); + } + + /** + * Records a Future returned by a Spring executor's submit method so that if + * the caller cancels or completes it before it runs, the request window + * releases its permit without waiting for END to time out. + * + * @param result return value from the executor method + * @param handed what hand returned + * @param task original task passed to hand + */ + public static void submitted(Object result, Object handed, Object task) { + if (result instanceof CompletableFuture) { + attachCompletionRelease((CompletableFuture) result, handed, task); + } else if (result instanceof Future) { + trackSubmitted((Future) result, handed, task); + } + } + + private static boolean isFutureTerminated(Future future) { + if (future == null) { + return true; + } + try { + return future.isCancelled() || future.isDone(); + } catch (Throwable ignored) { + return false; + } + } + + private static void trackSubmitted(Future future, Object handed, Object task) { + drainDeadFutureKeys(); + if (future == null || handed == task || !(handed instanceof Hand)) { + return; + } + Hand hand = (Hand) handed; + if (hand.window == null || hand.isStartedOrReleased()) { + return; + } + if (isFutureTerminated(future)) { + hand.releaseIfPending(); + return; + } + hand.window.track(hand, future); + if (hand.isStartedOrReleased()) { + hand.window.untrack(hand); + return; + } + WeakIdentityKey key = new WeakIdentityKey(future, DEAD_FUTURE_KEYS); + PENDING_BY_FUTURE.put(key, new WeakReference(hand)); + hand.futureKey = key; + if (hand.isStartedOrReleased()) { + hand.clearFutureKey(); + } + } + + private static Hand takeFutureHand(Object key) { + drainDeadFutureKeys(); + if (key == null || PENDING_BY_FUTURE.isEmpty()) { + return null; + } + WeakReference ref = PENDING_BY_FUTURE.remove(new LookupKey(key)); + return ref == null ? null : ref.get(); + } + + private static void attachCompletionRelease(CompletableFuture cf, Object handed, Object task) { + if (cf != null && handed != task && handed instanceof Hand) { + final Hand hand = (Hand) handed; + registerStageHand(hand); + try { + cf.whenComplete((result, error) -> hand.onFutureCompleted()); + } catch (Throwable t) { + hand.onFutureCompleted(); + } + } + } + + /** + * Counts a task {@link #hand(Object, Runnable)} counted as done when the + * executor threw instead of taking it (it rejected it, or was shut + * down), so that END does not wait for a task that never runs. Releases + * only if the task has not already started running on a worker thread. + * + * @param handed what hand returned + * @param task what hand was passed + */ + public static void dropped(Object handed, Object task) { + if (handed != task && handed instanceof Hand) { + ((Hand) handed).releaseIfPending(); + } + } + + private static void done(Window window) { + if (window.running.decrementAndGet() == 0) { + Thread waiter = window.waiter; + if (waiter != null) { + LockSupport.unpark(waiter); + } + } + } + + // open starts the window of a test: from now on, END waits for the + // requests that come in, and for no request that came in before. + static boolean open() { + return open(null, null); + } + + // open(testId, prevActiveTestId) opens a fresh test window, records + // armed-mid-flight while any unarmed request/job remains in flight (or + // once after unarmed traffic occurred prior to arming), and marks the new + // window contaminated ("tail:") if the previous test was cut, + // unclosed, had a blind untracked async hand-off, or any prior window still + // has running > 0 or live tracked handles. Returns true if any tail:, + // job-tail:, or armed-mid-flight reason was added to the newly opened window. + static boolean open(String testId, String prevActiveTestId) { + arm(); + drainDeadHands(); + long now = System.nanoTime(); + Window next = new Window(testId); + if (UNARMED_IN_FLIGHT.sum() > 0) { + pendingArmedMidFlight = false; + ARMED_MID_FLIGHT_CONSUMED.set(true); + next.contaminate("armed-mid-flight"); + } else if (lastUnarmedHandOffNanos != 0L && (now - lastUnarmedHandOffNanos) < untrackedTailWindowNanos) { + pendingArmedMidFlight = false; + ARMED_MID_FLIGHT_CONSUMED.set(true); + next.contaminate("armed-mid-flight"); + } else if ((pendingArmedMidFlight || unarmedEntered) + && ARMED_MID_FLIGHT_CONSUMED.compareAndSet(false, true)) { + pendingArmedMidFlight = false; + next.contaminate("armed-mid-flight"); + } + // Swap current BEFORE inspecting prev so no request can enter prev + // after we check prev.running. + Window prev = current; + current = next; + if (prev != null) { + prev.sweepCancelledFutures(); + boolean prevRunning = prev.running.get() > 0; + boolean prevAliveHandles = prev.hasAliveUntrackedHandles(now); + boolean prevBlindUntracked = prev.hasBlindUntrackedAsync; + if (prevRunning || prevAliveHandles || prevBlindUntracked || prev.untrackedHandlesOverflowed) { + if (prev.testId == null && prevActiveTestId != null && !prevActiveTestId.isEmpty()) { + prev.fallbackId = prevActiveTestId; + } + if (prevBlindUntracked && prev.untrackedTailExpiresAtNanos == 0L) { + prev.extendUntrackedTail(now, 0L); + } + retainLingering(prev, now); + } + } + if (prevActiveTestId != null && !prevActiveTestId.isEmpty()) { + next.contaminate("tail:" + prevActiveTestId); + } + if (externalUntrackedTailPending + || sweepUntrackedHandles(EXTERNAL_UNTRACKED_HANDLES, now) + || (externalUntrackedTailExpiresAtNanos != 0L + && (now - externalUntrackedTailExpiresAtNanos) < 0L)) { + String extReason = externalUntrackedTailReason; + next.contaminate("tail:" + (extReason != null && !extReason.isEmpty() ? extReason : "job")); + externalUntrackedTailPending = false; + if (externalUntrackedTailExpiresAtNanos != 0L && (now - externalUntrackedTailExpiresAtNanos) >= 0L) { + externalUntrackedTailExpiresAtNanos = 0L; + } + } + for (Window lingering : LINGERING) { + lingering.sweepCancelledFutures(); + boolean lingeringExpired = lingering.lingeringSinceNanos != 0L + && (now - lingering.lingeringSinceNanos) >= maxLingeringNanos; + boolean aliveHandles = lingering.hasAliveUntrackedHandles(now); + // Actively executing work (executing > 0) and live untracked + // threads/futures/TimerTasks NEVER expire under maxLingeringNanos; + // only idle uncompleted permits (running > 0 && executing == 0) and + // overflowed handle caps are bounded by maxLingeringNanos. + boolean stillRunning = lingering.executing.get() > 0 + || aliveHandles + || (!lingeringExpired && (lingering.running.get() > 0 || lingering.untrackedHandlesOverflowed)); + boolean reportCut = lingering.wasCut && !lingering.cutReportedOnce; + boolean untrackedActive = lingering.hasBlindUntrackedAsync + && (!lingering.untrackedTailReportedOnce + || (now - lingering.untrackedTailExpiresAtNanos) < 0L); + if (stillRunning || reportCut || untrackedActive) { + next.contaminate("tail:" + lingering.label()); + if (reportCut) { + lingering.cutReportedOnce = true; + } + if (lingering.hasBlindUntrackedAsync) { + lingering.untrackedTailReportedOnce = true; + } + } + boolean cutDone = !lingering.wasCut || lingering.cutReportedOnce; + boolean untrackedDone = !lingering.hasBlindUntrackedAsync + || (lingering.untrackedTailReportedOnce + && (now - lingering.untrackedTailExpiresAtNanos) >= 0L); + if (!stillRunning && cutDone && untrackedDone) { + LINGERING.remove(lingering); + // Dekker re-check after remove closes the TOCTOU window with + // concurrent Hand.enter / addUntrackedHandle / noteUntrackedAsync. + if (lingering.executing.get() > 0 + || lingering.hasAliveUntrackedHandles(now) + || (lingering.hasBlindUntrackedAsync + && (now - lingering.untrackedTailExpiresAtNanos) < 0L)) { + LINGERING.add(lingering); + } + } + } + return next.hasOpeningTail(); + } + + private static void retainLingering(Window window, long now) { + if (window.lingeringSinceNanos == 0L) { + window.lingeringSinceNanos = now; + } + if (LINGERING.contains(window)) { + return; + } + if (LINGERING.size() >= MAX_LINGERING) { + for (Window existing : LINGERING) { + existing.sweepCancelledFutures(); + boolean lingeringExpired = existing.lingeringSinceNanos != 0L + && (now - existing.lingeringSinceNanos) >= maxLingeringNanos; + boolean aliveHandles = existing.hasAliveUntrackedHandles(now); + boolean stillRunning = existing.executing.get() > 0 + || aliveHandles + || (!lingeringExpired && (existing.running.get() > 0 || existing.untrackedHandlesOverflowed)); + boolean cutDone = !existing.wasCut || existing.cutReportedOnce; + boolean untrackedDone = !existing.hasBlindUntrackedAsync + || (existing.untrackedTailReportedOnce + && (now - existing.untrackedTailExpiresAtNanos) >= 0L); + if (!stillRunning && cutDone && untrackedDone) { + LINGERING.remove(existing); + if (existing.executing.get() > 0 + || existing.hasAliveUntrackedHandles(now) + || (existing.hasBlindUntrackedAsync + && (now - existing.untrackedTailExpiresAtNanos) < 0L)) { + LINGERING.add(existing); + } + } + } + // Strictly bound memory if 64+ windows are already stuck lingering; + // those 64 entries already mark every subsequent window "tail:...". + if (LINGERING.size() >= MAX_LINGERING) { + return; + } + } + LINGERING.add(window); + } + + // running is how many requests of the current window are running. + static int running() { + drainDeadHands(); + Window window = current; + window.sweepCancelledFutures(); + return window.running.get(); + } + + // await closes the current window and waits until none of its requests + // runs, for at most timeoutNanos, and says whether none runs. + static boolean await(long timeoutNanos) { + return awaitWindow(timeoutNanos, true).drained; + } + + private static boolean hasActiveLingering(long now) { + if (UNARMED_IN_FLIGHT.sum() > 0) { + return true; + } + if (lastUnarmedHandOffNanos != 0L && (now - lastUnarmedHandOffNanos) < untrackedTailWindowNanos) { + return true; + } + if (externalUntrackedTailPending + || sweepUntrackedHandles(EXTERNAL_UNTRACKED_HANDLES, now) + || (externalUntrackedTailExpiresAtNanos != 0L + && (now - externalUntrackedTailExpiresAtNanos) < 0L)) { + return true; + } + for (Window lingering : LINGERING) { + lingering.sweepCancelledFutures(); + boolean lingeringExpired = lingering.lingeringSinceNanos != 0L + && (now - lingering.lingeringSinceNanos) >= maxLingeringNanos; + boolean aliveHandles = lingering.hasAliveUntrackedHandles(now); + boolean stillRunning = lingering.executing.get() > 0 + || aliveHandles + || (!lingeringExpired && (lingering.running.get() > 0 || lingering.untrackedHandlesOverflowed)); + boolean untrackedActive = lingering.hasBlindUntrackedAsync + && (!lingering.untrackedTailReportedOnce + || (now - lingering.untrackedTailExpiresAtNanos) < 0L); + if (stillRunning || untrackedActive) { + return true; + } + } + return false; + } + + // awaitWindow closes the current window, optionally waits up to + // timeoutNanos for its requests/tasks to finish, retains the window in + // LINGERING if cut, still running, carrying a blind untracked async + // hand-off, or holding alive tracked handles, and returns its outcome. + static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { + drainDeadHands(); + Window window = current; + current = new Window(null); + window.sweepCancelledFutures(); + int initialRunning = window.running.get(); + if (!wait) { + long now = System.nanoTime(); + if (window.hasBlindUntrackedAsync) { + window.extendUntrackedTail(now, 0L); + } + if (initialRunning > 0 || window.hasBlindUntrackedAsync + || window.hasAliveUntrackedHandles(now) || window.untrackedHandlesOverflowed) { + retainLingering(window, now); + } + return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations(), + hasActiveLingering(now)); + } + if (initialRunning <= 0) { + long now = System.nanoTime(); + if (window.hasBlindUntrackedAsync) { + window.extendUntrackedTail(now, 0L); + } + if (window.hasBlindUntrackedAsync || window.hasAliveUntrackedHandles(now) + || window.untrackedHandlesOverflowed) { + retainLingering(window, now); + } + return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations(), + hasActiveLingering(now)); } + boolean drained = false; // Set before the count is read again: an exit that takes the count // to 0 after that read finds the waiter and wakes it, and one that // took it to 0 before is seen by the read. @@ -209,22 +4276,384 @@ static boolean await(long timeoutNanos) { try { long deadline = System.nanoTime() + timeoutNanos; while (window.running.get() > 0) { + drainDeadHands(); + window.sweepCancelledFutures(); + if (window.running.get() <= 0) { + drained = true; + break; + } long left = deadline - System.nanoTime(); if (left <= 0 || Thread.currentThread().isInterrupted()) { - return false; + drained = false; + break; } - LockSupport.parkNanos(RequestGate.class, left); + long waitNanos = window.hasPendingFutures() + ? Math.min(left, FUTURE_SWEEP_INTERVAL_NANOS) + : left; + LockSupport.parkNanos(RequestGate.class, waitNanos); + } + if (window.running.get() <= 0) { + drained = true; } - return true; } finally { window.waiter = null; } + long now = System.nanoTime(); + boolean needsRetain = !drained || window.hasBlindUntrackedAsync + || window.hasAliveUntrackedHandles(now) || window.untrackedHandlesOverflowed; + if (needsRetain) { + if (!drained) { + window.wasCut = true; + } + if (window.hasBlindUntrackedAsync) { + window.extendUntrackedTail(now, 0L); + } + retainLingering(window, now); + } + return new WindowOutcome(drained, true, window.enteredCount.get(), window.contaminations(), + hasActiveLingering(now)); + } + + static final class WindowOutcome { + final boolean drained; + final boolean waited; + final int enteredCount; + final List contaminations; + // True when this window OR any older lingering window still has active + // async work, live untracked handles, or an active blind untracked tail + // at END — meaning probes from a test's tail may land in the gap after + // END and must NOT be emitted as BACKGROUND. + final boolean tailActiveAtEnd; + + WindowOutcome(boolean drained, boolean waited, int enteredCount, List contaminations, + boolean tailActiveAtEnd) { + this.drained = drained; + this.waited = waited; + this.enteredCount = enteredCount; + this.contaminations = contaminations; + this.tailActiveAtEnd = tailActiveAtEnd; + } + } + + private static final class UntrackedHandle { + + private final WeakReference ref; + private final WeakReference timerRef; + private final boolean alreadyStarted; + private final long registeredAtNanos; + private final boolean timerPeriodic; + private final long timerExpectedFireAtNanos; + private final long timerPeriodMillis; + private final long timerInitialScheduledExecMillis; + private volatile boolean observedAlive; + + private UntrackedHandle(Object target, boolean alreadyStarted, long registeredAtNanos) { + this(target, null, alreadyStarted, registeredAtNanos, false, 0L, 0L, 0L); + } + + private UntrackedHandle(Object target, Timer timer, boolean alreadyStarted, long registeredAtNanos, + boolean timerPeriodic, long timerExpectedFireAtNanos, long timerPeriodMillis, + long timerInitialScheduledExecMillis) { + this.ref = new WeakReference(target); + this.timerRef = timer == null ? null : new WeakReference(timer); + this.alreadyStarted = alreadyStarted; + this.registeredAtNanos = registeredAtNanos; + this.timerPeriodic = timerPeriodic; + this.timerExpectedFireAtNanos = timerExpectedFireAtNanos; + this.timerPeriodMillis = timerPeriodMillis; + this.timerInitialScheduledExecMillis = timerInitialScheduledExecMillis; + } + + private static UntrackedHandle forTimerTask(Timer timer, TimerTask task, long delayMillis, + long periodMillis, boolean periodic, long now) { + long safeDelayMs = delayMillis > 0L ? delayMillis : 0L; + long delayNanos = TimeUnit.MILLISECONDS.toNanos(safeDelayMs); + if (delayNanos < 0L) { + delayNanos = maxLingeringNanos; + } + long expectedFire = now + delayNanos; + long safePeriodMs = periodMillis > 0L ? periodMillis : 1L; + long initialExec = safeScheduledExecutionTime(task); + return new UntrackedHandle(task, timer, true, now, periodic, expectedFire, safePeriodMs, initialExec); + } + + private boolean isActive(long now) { + Object target = ref.get(); + if (target == null) { + return false; + } + if (target instanceof Thread) { + Thread t = (Thread) target; + if (t.isAlive()) { + observedAlive = true; + return true; + } + if (alreadyStarted || observedAlive || t.getState() == Thread.State.TERMINATED) { + return false; + } + // Registered immediately before subThread.start() and still NEW: + // keep active briefly in case the OS thread hasn't transitioned yet. + long grace = Math.min(HANDLE_START_GRACE_NANOS, untrackedTailWindowNanos); + return (now - registeredAtNanos) < grace; + } + if (target instanceof Future) { + return !isFutureTerminated((Future) target); + } + if (target instanceof TimerTask) { + TimerTask task = (TimerTask) target; + TimerCancelInfo cancelInfo = timerTaskCancelInfo(task); + if (cancelInfo != null) { + if (cancelInfo.cancelledBeforeRun) { + if (!timerPeriodic) { + // One-shot TimerTask.cancel() returned true => still SCHEDULED, + // never fired and will never run. + return false; + } + // Periodic TimerTask.cancel() returned true: drop immediately ONLY + // if scheduledExecutionTime() never advanced (cancelled before its + // first tick); otherwise a tick's run() body may still be executing. + long curExec = safeScheduledExecutionTime(task); + if (curExec == timerInitialScheduledExecMillis + && (cancelInfo.cancelledAtNanos - timerExpectedFireAtNanos) < 0L) { + return false; + } + } + // Cancelled after firing (or while a body may still be executing): + // keep active for untrackedTailWindowNanos from cancellation, then drop. + return (now - cancelInfo.cancelledAtNanos) < untrackedTailWindowNanos; + } + Timer t = timerRef == null ? null : timerRef.get(); + Long timerCancelledAt = t == null ? null : timerCancelledAtNanos(t); + if (timerCancelledAt != null) { + boolean cancelledBeforeFirstFire = + (timerCancelledAt.longValue() - timerExpectedFireAtNanos) < -TIMER_CANCEL_MARGIN_NANOS + && (!timerPeriodic || safeScheduledExecutionTime(task) == timerInitialScheduledExecMillis); + if (cancelledBeforeFirstFire) { + return false; + } + return (now - timerCancelledAt.longValue()) < untrackedTailWindowNanos; + } + if (!timerPeriodic) { + // One-shot TimerTask not cancelled before fire: TimerThread sets + // state=EXECUTED before calling run(), so keep active for the full + // untrackedTailWindowNanos measured from expected fire time. + return (now - timerExpectedFireAtNanos) < untrackedTailWindowNanos; + } + if ((now - timerExpectedFireAtNanos) < 0L) { + return true; + } + long execMillis = safeScheduledExecutionTime(task); + if (execMillis <= 0L) { + return (now - registeredAtNanos) < maxLingeringNanos; + } + long tailWindowMs = TimeUnit.NANOSECONDS.toMillis(untrackedTailWindowNanos); + long slackMillis = Math.max(timerPeriodMillis * 2L, tailWindowMs); + return System.currentTimeMillis() <= execMillis + timerPeriodMillis + slackMillis; + } + return false; + } } private static final class Window { + private static final AtomicReferenceFieldUpdater FUTURES_UPDATER = + AtomicReferenceFieldUpdater.newUpdater(Window.class, ConcurrentHashMap.class, "futures"); + private static final AtomicReferenceFieldUpdater HANDLES_UPDATER = + AtomicReferenceFieldUpdater.newUpdater(Window.class, ConcurrentLinkedQueue.class, "untrackedHandles"); + + private final String testId; + private volatile String fallbackId; private final AtomicInteger running = new AtomicInteger(); + // Actively executing requests and worker tasks (distinct from queued/ + // idle permits in `running`) so maxLingeringNanos never drops work that + // is actually executing app code. + private final AtomicInteger executing = new AtomicInteger(); + private final AtomicInteger enteredCount = new AtomicInteger(); private volatile Thread waiter; + private volatile boolean wasCut; + private volatile boolean cutReportedOnce; + // True when any untracked async (blind or handle-tracked) occurred in this window. + private volatile boolean hadUntrackedAsync; + // True ONLY when an untracked async WITHOUT a tracked liveness handle occurred + // (drives the time-based untrackedTailWindowNanos fallback). + private volatile boolean hasBlindUntrackedAsync; + private volatile long untrackedTailExpiresAtNanos; + private volatile boolean untrackedTailReportedOnce; + private volatile long lingeringSinceNanos; + // Pending submitted tasks keyed by Hand (self-removed on release in + // O(1), plus periodically swept on track() for cancelled futures so + // windows without an END cannot grow unboundedly). + @SuppressWarnings("rawtypes") + private volatile ConcurrentHashMap futures; + // Weak handles to live untracked Threads, ScheduledFutures, and + // TimerTasks started in this window so tail contamination persists + // strictly while they stay alive. + @SuppressWarnings("rawtypes") + private volatile ConcurrentLinkedQueue untrackedHandles; + private volatile boolean untrackedHandlesOverflowed; + private final AtomicInteger insertsSinceSweep = new AtomicInteger(); + // Lock-free contamination reasons collected during this window. + private final Set contamSet = ConcurrentHashMap.newKeySet(); + private final ConcurrentLinkedQueue contamOrder = new ConcurrentLinkedQueue<>(); + private final AtomicInteger contamCount = new AtomicInteger(); + + private Window(String testId) { + this.testId = testId; + } + + private String label() { + if (testId != null && !testId.isEmpty()) { + return testId; + } + String fb = fallbackId; + return fb != null && !fb.isEmpty() ? fb : "prev"; + } + + private void extendUntrackedTail(long now, long extraTailNanos) { + long boundedExtra = Math.max(0L, Math.min(extraTailNanos, maxLingeringNanos)); + long target = now + untrackedTailWindowNanos + boundedExtra; + long prev = untrackedTailExpiresAtNanos; + if (prev == 0L || (target - prev) > 0L) { + untrackedTailExpiresAtNanos = target; + } + } + + private void contaminate(String reason) { + contaminate(reason, 0L); + } + + private void contaminate(String reason, long extraTailNanos) { + if (reason == null || reason.isEmpty()) { + return; + } + if (reason.startsWith("untracked-")) { + hadUntrackedAsync = true; + hasBlindUntrackedAsync = true; + extendUntrackedTail(System.nanoTime(), extraTailNanos); + } + addContamReason(reason); + } + + private void contaminateTracked(String reason) { + if (reason == null || reason.isEmpty()) { + return; + } + if (reason.startsWith("untracked-")) { + hadUntrackedAsync = true; + } + addContamReason(reason); + } + + private void addContamReason(String reason) { + if (contamCount.get() < JobGate.KEPT && contamSet.add(reason)) { + if (contamCount.incrementAndGet() <= JobGate.KEPT) { + contamOrder.add(reason); + } else { + contamSet.remove(reason); + contamCount.decrementAndGet(); + } + } + } + + private boolean hasOpeningTail() { + for (String reason : contamOrder) { + if (reason.startsWith("tail:") || reason.startsWith("job-tail:") + || "armed-mid-flight".equals(reason)) { + return true; + } + } + return false; + } + + private List contaminations() { + if (contamOrder.isEmpty()) { + return Collections.emptyList(); + } + List out = new ArrayList<>(); + for (String reason : contamOrder) { + out.add(reason); + } + return out; + } + + @SuppressWarnings("unchecked") + private ConcurrentHashMap>> futuresMap(boolean create) { + ConcurrentHashMap>> map = + (ConcurrentHashMap>>) futures; + if (map != null || !create) { + return map; + } + ConcurrentHashMap>> fresh = new ConcurrentHashMap<>(); + if (FUTURES_UPDATER.compareAndSet(this, null, fresh)) { + return fresh; + } + return (ConcurrentHashMap>>) futures; + } + + private void track(Hand hand, Future future) { + ConcurrentHashMap>> map = futuresMap(true); + map.put(hand, new WeakReference>(future)); + if (insertsSinceSweep.incrementAndGet() >= FUTURE_SWEEP_STRIDE) { + insertsSinceSweep.set(0); + sweepCancelledFutures(); + } + } + + private void untrack(Hand hand) { + ConcurrentHashMap>> map = futuresMap(false); + if (map != null) { + map.remove(hand); + } + } + + private boolean hasPendingFutures() { + ConcurrentHashMap>> map = futuresMap(false); + return map != null && !map.isEmpty(); + } + + private void sweepCancelledFutures() { + ConcurrentHashMap>> map = futuresMap(false); + if (map == null || map.isEmpty()) { + return; + } + for (Map.Entry>> entry : map.entrySet()) { + Hand hand = entry.getKey(); + if (hand.isReleased()) { + map.remove(hand, entry.getValue()); + continue; + } + Future f = entry.getValue().get(); + if (isFutureTerminated(f)) { + hand.releaseIfPending(); + map.remove(hand, entry.getValue()); + } + } + } + + @SuppressWarnings("unchecked") + private ConcurrentLinkedQueue untrackedHandlesQueue(boolean create) { + ConcurrentLinkedQueue q = + (ConcurrentLinkedQueue) untrackedHandles; + if (q != null || !create) { + return q; + } + ConcurrentLinkedQueue fresh = new ConcurrentLinkedQueue<>(); + if (HANDLES_UPDATER.compareAndSet(this, null, fresh)) { + return fresh; + } + return (ConcurrentLinkedQueue) untrackedHandles; + } + + private void addUntrackedHandle(UntrackedHandle handle, long now) { + hadUntrackedAsync = true; + if (!addHandleToQueue(untrackedHandlesQueue(true), handle, now)) { + untrackedHandlesOverflowed = true; + } + } + + private boolean hasAliveUntrackedHandles(long now) { + return sweepUntrackedHandles(untrackedHandlesQueue(false), now); + } } // Nested is the token of a request entered on a thread that already @@ -240,41 +4669,270 @@ private Nested(Window window, Window outer) { } } - // Hand is a task counted in a request's window: done once, when it - // returns or throws, or when the executor did not take it. Or, with no - // window, a task a job's run handed off: a run of that job while it - // runs, and nothing to count done when the executor did not take it. + private static final class WeakIdentityKey extends WeakReference { + + private final int hash; + + private WeakIdentityKey(Object referent, ReferenceQueue queue) { + super(referent, queue); + this.hash = System.identityHashCode(referent); + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + Object mine = get(); + if (mine == null) { + return false; + } + if (obj instanceof WeakIdentityKey) { + return mine == ((WeakIdentityKey) obj).get(); + } + if (obj instanceof LookupKey) { + return mine == ((LookupKey) obj).target; + } + return false; + } + } + + private static final class LookupKey { + + private final Object target; + private final int hash; + + private LookupKey(Object target) { + this.target = target; + this.hash = System.identityHashCode(target); + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof WeakIdentityKey) { + return target == ((WeakIdentityKey) obj).get(); + } + if (obj instanceof LookupKey) { + return target == ((LookupKey) obj).target; + } + return false; + } + } + + private static final class HandRef extends WeakReference { + + private final Set set; + private final Window window; + private volatile boolean released; + + private HandRef(Hand referent, ReferenceQueue queue, Set set, Window window) { + super(referent, queue); + this.set = set; + this.window = window; + } + } + + // Hand is a task counted in a request's window (or a job's run). + // Bitmask state supports both immediate release on exit (execute/submit) + // and deferred release on CompletableFuture postComplete (supplyAsync/ + // runAsync/*Async) so synchronous dependent stages execute before permit + // release while early cf.complete() during execution still waits for exit(). private abstract static class Hand { - private static final AtomicIntegerFieldUpdater RELEASED = - AtomicIntegerFieldUpdater.newUpdater(Hand.class, "released"); + private static final int FLAG_STARTED = 1; + private static final int FLAG_EXITED = 2; + private static final int FLAG_CF_DONE = 4; + private static final int FLAG_RELEASED = 8; + + private static final AtomicIntegerFieldUpdater STATE = + AtomicIntegerFieldUpdater.newUpdater(Hand.class, "state"); // The window it counts in, or null for a job's task. final Window window; - // The job whose run handed it off, when window is null. - final String job; - private volatile int released; + // The job attribution whose run handed it off, when window is null. + final JobGate.Attribution job; + // True for CompletableFuture stages whose permit is released via + // whenComplete after LIFO synchronous dependents run. + final boolean deferRelease; + // Weak token in per-executor tracking set for O(1) self-removal. + volatile HandRef executorRef; + // Weak key in PENDING_BY_FUTURE for O(1) eager removal on start/release. + volatile WeakIdentityKey futureKey; + // JobGate token kept alive across CompletableFuture postComplete() when + // window == null && job != null && deferRelease. + volatile Object deferredJobToken; + private volatile int state; - Hand(Window window, String job) { + Hand(Window window, JobGate.Attribution job, boolean deferRelease) { this.window = window; this.job = job; + this.deferRelease = deferRelease; } - final void release() { - if (window != null && RELEASED.compareAndSet(this, 0, 1)) { + final boolean isReleased() { + return (state & FLAG_RELEASED) != 0; + } + + final boolean isStartedOrReleased() { + return (state & (FLAG_STARTED | FLAG_RELEASED)) != 0; + } + + final void clearFutureKey() { + WeakIdentityKey fk = futureKey; + if (fk != null) { + futureKey = null; + PENDING_BY_FUTURE.remove(fk); + } + } + + private void finishRelease() { + if (window != null) { + clearFutureKey(); + window.untrack(this); + HandRef ref = executorRef; + if (ref != null) { + ref.released = true; + executorRef = null; + ref.set.remove(ref); + } done(window); + } else { + Object jt = deferredJobToken; + if (jt != null) { + deferredJobToken = null; + JobGate.exit(jt); + } + } + } + + // release marks this task done unconditionally (non-deferred exit). + final void release() { + if (window == null && job == null) { + return; + } + for (;;) { + int s = state; + if ((s & FLAG_RELEASED) != 0) { + return; + } + if (STATE.compareAndSet(this, s, s | FLAG_EXITED | FLAG_RELEASED)) { + finishRelease(); + return; + } + } + } + + // onFutureCompleted is invoked by the CompletableFuture's whenComplete + // callback (registered immediately before returning the CF, so LIFO + // postComplete pops caller-registered synchronous dependents first). + final void onFutureCompleted() { + if (window == null && job == null) { + return; + } + if (!deferRelease) { + releaseIfPending(); + return; + } + for (;;) { + int s = state; + if ((s & FLAG_RELEASED) != 0) { + return; + } + int next = s | FLAG_CF_DONE; + boolean doRelease = (s & FLAG_STARTED) == 0 || (s & FLAG_EXITED) != 0; + if (doRelease) { + next |= FLAG_RELEASED; + } + if (STATE.compareAndSet(this, s, next)) { + if (doRelease) { + finishRelease(); + } + return; + } + } + } + + // releaseIfPending marks this task done only if it has not started + // running yet: cancellation/timeout/drop/shutdownNow of an + // already-running task waits for its finally block's exit() so the + // window stays open while app code is still executing. + final void releaseIfPending() { + if (window == null && job == null) { + return; + } + for (;;) { + int s = state; + if ((s & (FLAG_STARTED | FLAG_RELEASED)) != 0) { + return; + } + if (STATE.compareAndSet(this, s, s | FLAG_RELEASED)) { + finishRelease(); + return; + } } } - // enter makes the running thread count in the task's window, so - // that what the task hands off counts too, and returns the window - // the thread counted in before; for a job's task, it starts a run - // of the job (so what the task hands off is the job's too), and - // returns its token. final Object enter() { if (window == null) { - return JobGate.enterAs(job); + for (;;) { + int s = state; + if ((s & FLAG_STARTED) != 0) { + break; + } + int next = (s & ~FLAG_RELEASED) | FLAG_STARTED; + if (STATE.compareAndSet(this, s, next)) { + break; + } + } + Object jt = JobGate.enterAs(job); + if (deferRelease) { + deferredJobToken = jt; + } + return jt; + } + for (;;) { + int s = state; + if ((s & FLAG_STARTED) != 0) { + break; + } + if ((s & FLAG_RELEASED) != 0) { + // Late start after an earlier pending release (e.g. + // shutdownNow race or early cf.complete()): re-acquire the + // window permit so exit() releases it cleanly when done. + if (STATE.compareAndSet(this, s, (s & ~FLAG_RELEASED) | FLAG_STARTED)) { + window.running.incrementAndGet(); + break; + } + } else if (STATE.compareAndSet(this, s, s | FLAG_STARTED)) { + break; + } } + window.executing.incrementAndGet(); + if (window != current) { + // Re-retain closed windows BEFORE reading `current` so either a + // concurrent open() sees executing > 0 in LINGERING or our + // volatile read of `current` sees the newly opened window and + // contaminates it immediately before any task probe runs. + retainLingering(window, System.nanoTime()); + Window cur = current; + if (cur != null && cur != window) { + cur.contaminate("tail:" + window.label()); + } + } + clearFutureKey(); Window outer = INSIDE.get(); INSIDE.set(window); return outer; @@ -282,15 +4940,167 @@ final Object enter() { final void exit(Object outer) { if (window == null) { - JobGate.exit(outer); - return; + if (!deferRelease) { + JobGate.exit(outer); + return; + } + JobGate.detachThread(outer); + for (;;) { + int s = state; + if ((s & FLAG_RELEASED) != 0) { + return; + } + int next = s | FLAG_EXITED; + boolean doRelease = (next & FLAG_CF_DONE) != 0; + if (doRelease) { + next |= FLAG_RELEASED; + } + if (STATE.compareAndSet(this, s, next)) { + if (doRelease) { + finishRelease(); + } + return; + } + } } + window.executing.decrementAndGet(); if (outer == null) { INSIDE.remove(); } else { INSIDE.set((Window) outer); } - release(); + if (!deferRelease) { + release(); + return; + } + for (;;) { + int s = state; + if ((s & FLAG_RELEASED) != 0) { + return; + } + int next = s | FLAG_EXITED; + boolean doRelease = (next & FLAG_CF_DONE) != 0; + if (doRelease) { + next |= FLAG_RELEASED; + } + if (STATE.compareAndSet(this, s, next)) { + if (doRelease) { + finishRelease(); + } + return; + } + } + } + } + + // Context-only re-runnable wrappers for verified JDK ScheduledThreadPoolExecutor + // tasks: hold no window.running permit (END never waits on delayed/periodic + // tasks), while propagating INSIDE/JobGate attribution and window.executing + // across multi-hop retries and downstream async fan-outs. + private static final class ScheduledContextRunnable implements Runnable { + + private final Window window; + private final JobGate.Attribution job; + private final Runnable task; + + private ScheduledContextRunnable(Window window, JobGate.Attribution job, Runnable task) { + this.window = window; + this.job = job; + this.task = task; + } + + @Override + public void run() { + if (window != null) { + window.executing.incrementAndGet(); + if (window != current) { + retainLingering(window, System.nanoTime()); + Window cur = current; + if (cur != null && cur != window) { + cur.contaminate("tail:" + window.label()); + } + } + Window outer = INSIDE.get(); + INSIDE.set(window); + try { + task.run(); + } finally { + window.executing.decrementAndGet(); + if (outer == null) { + INSIDE.remove(); + } else { + INSIDE.set(outer); + } + } + return; + } + Object jt = JobGate.enterAs(job); + try { + task.run(); + } finally { + JobGate.exit(jt); + } + } + + @Override + public String toString() { + return task.toString(); + } + } + + private static final class ScheduledContextCallable implements Callable { + + private final Window window; + private final JobGate.Attribution job; + private final Callable task; + + private ScheduledContextCallable(Window window, JobGate.Attribution job, Callable task) { + this.window = window; + this.job = job; + this.task = task; + } + + @Override + public V call() throws Exception { + if (window != null) { + window.executing.incrementAndGet(); + if (window != current) { + retainLingering(window, System.nanoTime()); + Window cur = current; + if (cur != null && cur != window) { + cur.contaminate("tail:" + window.label()); + } + } + Window outer = INSIDE.get(); + INSIDE.set(window); + try { + return task.call(); + } finally { + window.executing.decrementAndGet(); + if (outer == null) { + INSIDE.remove(); + } else { + INSIDE.set(outer); + } + } + } + Object jt = JobGate.enterAs(job); + try { + return task.call(); + } finally { + JobGate.exit(jt); + } + } + + @Override + public String toString() { + return task.toString(); + } + } + + private static final class StageHand extends Hand { + StageHand(Window window, JobGate.Attribution job, boolean deferRelease) { + super(window, job, deferRelease); } } @@ -298,8 +5108,8 @@ private static class Handed extends Hand implements Runnable { final Runnable task; - Handed(Window window, String job, Runnable task) { - super(window, job); + Handed(Window window, JobGate.Attribution job, Runnable task, boolean deferRelease) { + super(window, job, deferRelease); this.task = task; } @@ -321,8 +5131,8 @@ public String toString() { private static final class HandedFuture extends Handed implements RunnableFuture { - HandedFuture(Window window, String job, Runnable task) { - super(window, job, task); + HandedFuture(Window window, JobGate.Attribution job, Runnable task, boolean deferRelease) { + super(window, job, task, deferRelease); } @SuppressWarnings("unchecked") @@ -359,10 +5169,10 @@ public Object get(long timeout, TimeUnit unit) private static final class HandedCall extends Hand implements Callable { - private final Callable task; + final Callable task; - HandedCall(Window window, String job, Callable task) { - super(window, job); + HandedCall(Window window, JobGate.Attribution job, Callable task) { + super(window, job, false); this.task = task; } @@ -381,4 +5191,29 @@ public String toString() { return String.valueOf(task); } } + + private static final class HandedSupplier extends Hand implements Supplier { + + final Supplier task; + + HandedSupplier(Window window, JobGate.Attribution job, Supplier task, boolean deferRelease) { + super(window, job, deferRelease); + this.task = task; + } + + @Override + public T get() { + Object outer = enter(); + try { + return task.get(); + } finally { + exit(outer); + } + } + + @Override + public String toString() { + return String.valueOf(task); + } + } } diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java index 688c64a..901fe59 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -1,6 +1,10 @@ package io.keploy.dedup; +import java.io.File; import java.lang.instrument.ClassFileTransformer; +import java.net.URI; +import java.net.URL; +import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; @@ -18,57 +22,25 @@ import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** - * ServerEntries makes each request of Tomcat, Jetty and Undertow count in - * {@link RequestGate} while the server runs it: the method each server runs - * a request in (and each async dispatch of it) becomes a method of the same - * name and access that calls {@link RequestGate#enter()}, then the server's - * own code, renamed {@code keploy$request$} and private, then - * {@link RequestGate#exit(Object)}, however it returns or throws. Nothing - * else in the server's code changes. - * - *

It is added as a transformer that can retransform, so the JVM runs it - * after every transformer that cannot, as JaCoCo's, whatever the order the - * agents were attached in: JaCoCo instruments, and ids, the server's own - * class, and this wraps JaCoCo's copy. When another agent retransforms or - * redefines a class this changed as it loaded, the JVM passes the class as - * it was before this changed it (a retransform) or the redefiner's bytes (a - * redefine), and this changes them again, as the JVM refuses a class that - * has lost a method, unless they already carry the change, which the JVM - * then takes as they are. - * - *

Only classes loaded from now on change (the JVM refuses a method added - * to a loaded class), so a server started before the SDK is not counted, and - * neither is one whose class loader does not see keploy-sdk.jar's classes, - * as in a module system (both said in the log). A server in a named module - * (Tomcat's jar on the module path) is counted: the JVM makes a module whose - * class an agent changed read the class path's classes. Netty, and so - * WebFlux, is not counted: END then reads a test's hits as soon as it comes. - * - *

It makes each run of a scheduled job count in {@link JobGate} the same - * way: Quartz's {@code JobRunShell.run()} and Spring's - * {@code ScheduledMethodRunnable.run()} (each {@code @Scheduled} method) - * become methods that call {@link JobGate#enter(Object, String)}, then their - * own code, renamed {@code keploy$job$run}, then {@link JobGate#exit(Object)}, - * so that a test whose window a job ran in says so. Those count whether or - * not END waits for requests. - * - *

It makes the work a request hands to a Spring TaskExecutor count as - * the request's (see {@link RequestGate#hand(Object, Runnable)}): the - * methods of SimpleAsyncTaskExecutor (an async event multicaster's), - * ThreadPoolTaskExecutor and {@code @Async}'s interceptor that take a task - * become methods that hand the task, and the executor it is for (the - * interceptor's executor argument, else the executor itself), to - * RequestGate, then call their own code, renamed - * {@code keploy$async$}, with what RequestGate gave back, and when that - * throws, tell RequestGate the task was dropped. A task a job's run hands - * off counts as that run whether or not END waits for requests; a - * request's counts only when it does (servers are changed only then). + * ServerEntries instruments: + *

    + *
  • Tomcat, Jetty, and Undertow request entries into {@link RequestGate}.
  • + *
  • Quartz, Spring {@code @Scheduled}, and Spring Kafka/AMQP/JMS message + * listeners into {@link JobGate}.
  • + *
  • Spring async executors into {@link RequestGate}.
  • + *
  • Application-only JDK executor, {@code CompletableFuture} + * ({@code runAsync}, {@code supplyAsync}, and {@code *Async} instance + * methods), {@code ScheduledExecutorService.schedule*}, + * {@code ExecutorService.invokeAny}, and {@code Thread.start} call sites + * into {@link RequestGate} static helpers.
  • + *
*/ final class ServerEntries implements ClassFileTransformer { @@ -111,44 +83,228 @@ final class ServerEntries implements ClassFileTransformer { // ScheduledMethodRunnable, on the scheduler's threads. addJob("Quartz", "org/quartz/core/JobRunShell", "quartz", "run"); addJob("Spring", "org/springframework/scheduling/support/ScheduledMethodRunnable", "scheduled", "run"); - // Spring's executors a request hands work to: SimpleAsyncTaskExecutor - // (an async event multicaster's, and Spring's default for @Async) - // starts each task in doExecute, whatever method it was handed in; - // ThreadPoolTaskExecutor (Spring Boot's) passes each to its pool in - // the method it was handed in (its submitCompletable, from Spring 6, - // is AsyncTaskExecutor's default, which hands the task to execute); - // @Async's interceptor hands each call to its executor, whatever - // that is, in doSubmit. - addAsync("org/springframework/core/task/SimpleAsyncTaskExecutor", "doExecute"); + // Message listeners: an inbound message + // delivered on a consumer thread during a test's window mixes the + // listener's probes into the test's record, so mark the test contaminated. + addJob("Kafka", "org/springframework/kafka/listener/KafkaMessageListenerContainer$ListenerConsumer", + "kafka", "invokeRecordListener", "invokeBatchListener", "invokeOnMessage"); + addJob("RabbitMQ", "org/springframework/amqp/rabbit/listener/AbstractMessageListenerContainer", + "listener", "doInvokeListener"); + addJob("JMS", "org/springframework/jms/listener/AbstractMessageListenerContainer", + "listener", "doInvokeListener"); + // Spring's executors a request hands work to. + addAsync("org/springframework/core/task/SimpleAsyncTaskExecutor", "doExecute", "submitCompletable"); addAsync("org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor", "execute", "submit", - "submitListenable"); + "submitListenable", "submitCompletable"); + addAsync("org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler", "execute", "submit", + "submitListenable", "submitCompletable"); + addAsync("org/springframework/scheduling/concurrent/ConcurrentTaskExecutor", "execute", "submit", + "submitListenable", "submitCompletable"); addAsync("org/springframework/aop/interceptor/AsyncExecutionAspectSupport", "doSubmit"); } - // Classes of servers that are not counted, so that the log can name them. + // Classes of servers that are not counted, so that the log can name them + // and HELLO/caps can report windowCut=false. private static final Map UNCOUNTED = new HashMap<>(); static { UNCOUNTED.put("io/netty/handler/codec/http/HttpServerCodec", "Netty"); UNCOUNTED.put("reactor/netty/http/server/HttpServer", "Reactor Netty"); + UNCOUNTED.put("io/grpc/netty/NettyServer", "gRPC"); + UNCOUNTED.put("io/grpc/netty/shaded/io/grpc/netty/NettyServer", "gRPC"); + UNCOUNTED.put("io/grpc/internal/ServerImpl", "gRPC"); + UNCOUNTED.put("io/vertx/core/http/impl/HttpServerImpl", "Vert.x"); + UNCOUNTED.put("io/micronaut/http/server/netty/NettyHttpServer", "Micronaut"); + UNCOUNTED.put("sun/net/httpserver/ServerImpl", "JDK HttpServer"); } + // Classes of messaging consumers that ServerEntries does not hook into + // JobGate, so HELLO/caps can honestly report listenerContamination=false. + private static final Map UNHOOKED_CONSUMERS = new HashMap<>(); + + static { + UNHOOKED_CONSUMERS.put("org/apache/kafka/streams/KafkaStreams", "Kafka Streams"); + UNHOOKED_CONSUMERS.put("reactor/kafka/receiver/KafkaReceiver", "Reactor Kafka"); + UNHOOKED_CONSUMERS.put("reactor/kafka/receiver/internals/DefaultKafkaReceiver", "Reactor Kafka"); + UNHOOKED_CONSUMERS.put("io/awspring/cloud/sqs/listener/SqsMessageListenerContainer", "Spring Cloud SQS"); + UNHOOKED_CONSUMERS.put("com/amazonaws/services/sqs/AmazonSQSClient", "AWS SQS"); + UNHOOKED_CONSUMERS.put("software/amazon/awssdk/services/sqs/DefaultSqsClient", "AWS SQS"); + UNHOOKED_CONSUMERS.put("software/amazon/awssdk/services/sqs/DefaultSqsAsyncClient", "AWS SQS Async"); + UNHOOKED_CONSUMERS.put("org/springframework/data/redis/listener/RedisMessageListenerContainer", + "Spring Data Redis"); + UNHOOKED_CONSUMERS.put("org/apache/pulsar/client/impl/ConsumerImpl", "Apache Pulsar"); + UNHOOKED_CONSUMERS.put("org/apache/pulsar/client/impl/MultiTopicsConsumerImpl", "Apache Pulsar"); + UNHOOKED_CONSUMERS.put("com/google/cloud/pubsub/v1/Subscriber", "GCP Pub/Sub"); + } + + private static final Set RAW_CONSUMER_OWNERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "org/apache/kafka/clients/consumer/KafkaConsumer", + "org/apache/kafka/clients/consumer/Consumer", + "com/rabbitmq/client/Channel", + "javax/jms/MessageConsumer", + "jakarta/jms/MessageConsumer"))); + private static final Set COUNTED = new CopyOnWriteArraySet<>(); private static final Set SEEN_UNCOUNTED = new CopyOnWriteArraySet<>(); + private static final Set SEEN_UNHOOKED_CONSUMERS = new CopyOnWriteArraySet<>(); + private static final Set HOOKED_SPRING_CLASSES = new CopyOnWriteArraySet<>(); + private static volatile boolean serverHookFailed; + private static volatile boolean listenerHookFailed; + private static volatile boolean jpmsGuardTriggered; + private static volatile boolean appRewriteFailed; + + // Per-loader cache for seesGate(loader) to avoid repeated Class.forName + // calls and ClassNotFoundExceptions during startup class loading. + private static final Map SEES_GATE = new WeakHashMap<>(); + // On Java 9+, normalized code-source locations of boot-layer named modules + // that do not read RequestGate's unnamed module: rewriting classes inside + // those named modules would throw IllegalAccessError at call sites. Empty + // on Java 8 or when no unreadable named modules exist. + private static final Set UNREADABLE_MODULE_LOCATIONS = findUnreadableModuleLocations(); + + // Constant-pool class owners targeted by wrapExecutorCalls. + private static final Set TARGET_EXECUTOR_OWNERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "java/util/concurrent/Executor", + "java/util/concurrent/ExecutorService", + "java/util/concurrent/ScheduledExecutorService", + "java/util/concurrent/AbstractExecutorService", + "java/util/concurrent/ThreadPoolExecutor", + "java/util/concurrent/ScheduledThreadPoolExecutor", + "java/util/concurrent/ForkJoinPool", + "java/util/concurrent/ForkJoinTask", + "java/util/concurrent/ExecutorCompletionService", + "java/util/concurrent/CompletableFuture", + "java/util/concurrent/CompletionStage", + "java/lang/Thread", + "java/lang/Thread$Builder", + "java/lang/Thread$Builder$OfVirtual", + "java/lang/Thread$Builder$OfPlatform", + "java/util/Timer", + "java/util/TimerTask", + "org/springframework/scheduling/TaskScheduler", + "com/google/common/util/concurrent/Futures", + "com/google/common/util/concurrent/ListenableFuture", + "reactor/core/publisher/Mono", + "reactor/core/publisher/Flux", + "reactor/core/publisher/ParallelFlux"))); + + // Constant-pool method names (CONSTANT_NameAndType, tag 12) targeted by + // wrapExecutorCalls for non-JDK owners (custom executor subtypes, Thread + // subclasses, Spring TaskScheduler, Guava, Reactor subscribe, method + // references, and raw consumer polling). Methods whose owners are always + // in TARGET_EXECUTOR_OWNERS (CompletableFuture/CompletionStage/remove/ + // shutdownNow) are matched by tag 7 above to avoid unnecessary ASM passes. + private static final Set TARGET_ASYNC_METHOD_NAMES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "execute", "submit", "submitListenable", "submitCompletable", + "schedule", "scheduleAtFixedRate", "scheduleWithFixedDelay", + "invokeAny", "fork", "subscribe", "start", "startVirtualThread", "cancel", + "addListener", "addCallback", "transform", "transformAsync", "catching", "catchingAsync", + "poll", "basicConsume", "receive", "setMessageListener"))); + + // CompletableFuture *Async instance methods rewritten to RequestGate. + private static final Map> CF_ASYNC_INSTANCE_METHODS = + buildStageAsyncMethods("Ljava/util/concurrent/CompletableFuture;"); + // CompletableFuture plain dependent instance methods rewritten to RequestGate. + private static final Map> CF_SYNC_INSTANCE_METHODS = + buildStageSyncMethods("Ljava/util/concurrent/CompletableFuture;"); + // CompletionStage *Async interface methods rewritten to RequestGate. + private static final Map> CS_ASYNC_INSTANCE_METHODS = + buildStageAsyncMethods("Ljava/util/concurrent/CompletionStage;"); + // CompletionStage plain dependent interface methods rewritten to RequestGate. + private static final Map> CS_SYNC_INSTANCE_METHODS = + buildStageSyncMethods("Ljava/util/concurrent/CompletionStage;"); + + private static Map> buildStageAsyncMethods(String ret) { + Map> m = new HashMap<>(); + String cs = "Ljava/util/concurrent/CompletionStage;"; + String ex = "Ljava/util/concurrent/Executor;"; + String fn = "Ljava/util/function/Function;"; + String cons = "Ljava/util/function/Consumer;"; + String run = "Ljava/lang/Runnable;"; + String bifn = "Ljava/util/function/BiFunction;"; + String bicons = "Ljava/util/function/BiConsumer;"; + m.put("thenApplyAsync", setOf("(" + fn + ")" + ret, "(" + fn + ex + ")" + ret)); + m.put("thenAcceptAsync", setOf("(" + cons + ")" + ret, "(" + cons + ex + ")" + ret)); + m.put("thenRunAsync", setOf("(" + run + ")" + ret, "(" + run + ex + ")" + ret)); + m.put("thenComposeAsync", setOf("(" + fn + ")" + ret, "(" + fn + ex + ")" + ret)); + m.put("thenCombineAsync", setOf("(" + cs + bifn + ")" + ret, "(" + cs + bifn + ex + ")" + ret)); + m.put("thenAcceptBothAsync", setOf("(" + cs + bicons + ")" + ret, "(" + cs + bicons + ex + ")" + ret)); + m.put("runAfterBothAsync", setOf("(" + cs + run + ")" + ret, "(" + cs + run + ex + ")" + ret)); + m.put("applyToEitherAsync", setOf("(" + cs + fn + ")" + ret, "(" + cs + fn + ex + ")" + ret)); + m.put("acceptEitherAsync", setOf("(" + cs + cons + ")" + ret, "(" + cs + cons + ex + ")" + ret)); + m.put("runAfterEitherAsync", setOf("(" + cs + run + ")" + ret, "(" + cs + run + ex + ")" + ret)); + m.put("handleAsync", setOf("(" + bifn + ")" + ret, "(" + bifn + ex + ")" + ret)); + m.put("whenCompleteAsync", setOf("(" + bicons + ")" + ret, "(" + bicons + ex + ")" + ret)); + m.put("exceptionallyAsync", setOf("(" + fn + ")" + ret, "(" + fn + ex + ")" + ret)); + m.put("exceptionallyComposeAsync", setOf("(" + fn + ")" + ret, "(" + fn + ex + ")" + ret)); + return Collections.unmodifiableMap(m); + } + + private static Map> buildStageSyncMethods(String ret) { + Map> m = new HashMap<>(); + String cs = "Ljava/util/concurrent/CompletionStage;"; + String fn = "Ljava/util/function/Function;"; + String cons = "Ljava/util/function/Consumer;"; + String run = "Ljava/lang/Runnable;"; + String bifn = "Ljava/util/function/BiFunction;"; + String bicons = "Ljava/util/function/BiConsumer;"; + m.put("thenApply", setOf("(" + fn + ")" + ret)); + m.put("thenAccept", setOf("(" + cons + ")" + ret)); + m.put("thenRun", setOf("(" + run + ")" + ret)); + m.put("thenCompose", setOf("(" + fn + ")" + ret)); + m.put("thenCombine", setOf("(" + cs + bifn + ")" + ret)); + m.put("thenAcceptBoth", setOf("(" + cs + bicons + ")" + ret)); + m.put("runAfterBoth", setOf("(" + cs + run + ")" + ret)); + m.put("applyToEither", setOf("(" + cs + fn + ")" + ret)); + m.put("acceptEither", setOf("(" + cs + cons + ")" + ret)); + m.put("runAfterEither", setOf("(" + cs + run + ")" + ret)); + m.put("handle", setOf("(" + bifn + ")" + ret)); + m.put("whenComplete", setOf("(" + bicons + ")" + ret)); + m.put("exceptionally", setOf("(" + fn + ")" + ret)); + m.put("exceptionallyCompose", setOf("(" + fn + ")" + ret)); + return Collections.unmodifiableMap(m); + } + + private static Set setOf(String... values) { + return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(values))); + } // The classes this changed as they loaded, by their loader: the ones it // changes again when another agent retransforms them. private final Map> changed = new WeakHashMap<>(); + // Application classes whose executor call sites were rewritten on load, + // by their loader: re-applied if another agent retransforms them. + private final Map> rewritten = new WeakHashMap<>(); // Whether servers' requests count (END waits for them); jobs' runs // count either way. private final boolean requests; + // Allow-list of indexed application VM class names eligible for JDK + // executor call-site rewriting; empty when app-only indexing was not run + // eagerly (e.g. external JaCoCo attached) or failed. + private final Set appClasses; + // Lightweight package prefix ("com/acme/") derived from AppClasses when + // appClasses is empty because an external JaCoCo agent skipped premain + // index loading; null when unavailable. + private final String appPackagePrefix; ServerEntries() { - this(true); + this(true, Collections.emptySet(), null); } ServerEntries(boolean requests) { + this(requests, Collections.emptySet(), null); + } + + ServerEntries(boolean requests, Set appClasses) { + this(requests, appClasses, null); + } + + ServerEntries(boolean requests, Set appClasses, String appPackagePrefix) { this.requests = requests; + this.appClasses = appClasses == null || appClasses.isEmpty() + ? Collections.emptySet() + : Collections.unmodifiableSet(new HashSet<>(appClasses)); + this.appPackagePrefix = appPackagePrefix == null || appPackagePrefix.isEmpty() ? null : appPackagePrefix; } private static void add(String server, String className, String... methods) { @@ -174,6 +330,93 @@ static boolean countsNone() { return COUNTED.isEmpty(); } + static boolean hasUncountedServer() { + return !SEEN_UNCOUNTED.isEmpty(); + } + + static boolean hasUnhookedConsumer() { + return !SEEN_UNHOOKED_CONSUMERS.isEmpty(); + } + + static boolean isSpringExecutorHooked(String binaryClassName) { + return HOOKED_SPRING_CLASSES.contains(binaryClassName); + } + + static void markSpringExecutorHookedForTests(String binaryClassName) { + HOOKED_SPRING_CLASSES.add(binaryClassName); + } + + static void unmarkSpringExecutorHookedForTests(String binaryClassName) { + HOOKED_SPRING_CLASSES.remove(binaryClassName); + } + + static boolean hadServerHookFailure() { + return serverHookFailed; + } + + static boolean hadListenerHookFailure() { + return listenerHookFailed; + } + + static boolean wasJpmsGuardTriggered() { + return jpmsGuardTriggered; + } + + static boolean hadAppRewriteFailure() { + return appRewriteFailed; + } + + static void markJpmsGuardTriggered() { + jpmsGuardTriggered = true; + } + + // Snapshot/restore helpers for unit tests exercising dynamic HELLO/caps flags. + static Set snapshotCounted() { + return new HashSet<>(COUNTED); + } + + static void restoreCounted(Set snapshot) { + COUNTED.clear(); + if (snapshot != null) { + COUNTED.addAll(snapshot); + } + } + + static Set snapshotUncounted() { + return new HashSet<>(SEEN_UNCOUNTED); + } + + static void restoreUncounted(Set snapshot) { + SEEN_UNCOUNTED.clear(); + if (snapshot != null) { + SEEN_UNCOUNTED.addAll(snapshot); + } + } + + static Set snapshotUnhookedConsumers() { + return new HashSet<>(SEEN_UNHOOKED_CONSUMERS); + } + + static void restoreUnhookedConsumers(Set snapshot) { + SEEN_UNHOOKED_CONSUMERS.clear(); + if (snapshot != null) { + SEEN_UNHOOKED_CONSUMERS.addAll(snapshot); + } + } + + static void setHookStatusForTests(boolean serverFailed, boolean listenerFailed, boolean jpmsSkipped) { + setHookStatusForTests(serverFailed, listenerFailed, jpmsSkipped, false); + } + + static void setHookStatusForTests(boolean serverFailed, boolean listenerFailed, boolean jpmsSkipped, + boolean rewriteFailed) { + serverHookFailed = serverFailed; + listenerHookFailed = listenerFailed; + jpmsGuardTriggered = jpmsSkipped; + appRewriteFailed = rewriteFailed; + SEEN_UNHOOKED_CONSUMERS.clear(); + } + // uncounted names the servers whose requests do not count that the app // loaded, as Netty. static List uncounted() { @@ -192,6 +435,39 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (uncounted != null) { SEEN_UNCOUNTED.add(uncounted); } + String unhookedConsumer = UNHOOKED_CONSUMERS.get(className); + if (unhookedConsumer != null) { + SEEN_UNHOOKED_CONSUMERS.add(unhookedConsumer); + } + if (shouldRewriteExecutorCalls(className)) { + if (!canAccessGate(loader, protectionDomain)) { + if (seesGate(loader)) { + jpmsGuardTriggered = true; + } else { + appRewriteFailed = true; + } + scanRawConsumerCalls(classfileBuffer); + return null; + } + try { + byte[] updated = wrapExecutorCalls(classfileBuffer); + if (updated != null) { + recordRewritten(loader, className); + } + return updated; + } catch (Throwable t) { + appRewriteFailed = true; + LOGGER.log(Level.FINE, "Keploy dedup skipped executor call-site wrap for " + className, t); + } + } else if (className != null && isRewriteAllowedPackage(className) + && !isKnownMessagingPoolWrapper(className)) { + // Even when KEPLOY_JAVA_ASYNC_CALLSITES=off or no app allow-list + // is configured, read-only CP scan still detects direct raw + // Kafka/RabbitMQ/JMS consumer calls so listenerContamination + // stays honest without modifying any bytecode (skipping known + // JMS/RabbitMQ pooling/recovery wrappers used by Spring Boot). + scanRawConsumerCalls(classfileBuffer); + } return null; } // With the wait off, servers are left as they are, and so no task @@ -209,6 +485,7 @@ public byte[] transform(ClassLoader loader, String className, Class classBein return null; } if (!seesGate(loader)) { + noteEntryHookFailure(entry); LOGGER.log(Level.WARNING, "Keploy dedup does not count " + entry.what() + ": the class loader of " + name + " does not see keploy-sdk.jar's classes, so " + entry.lost(requests)); return null; @@ -218,12 +495,15 @@ public byte[] transform(ClassLoader loader, String className, Class classBein boolean carries = carriesChange(classfileBuffer); byte[] wrapped = carries ? null : wrap(classfileBuffer, entry); if (!carries && wrapped == null) { + noteEntryHookFailure(entry); LOGGER.log(Level.WARNING, "Keploy dedup does not count " + entry.what() + ": " + name + " has no method " + entry.methods + " to count them in"); return null; } if (entry.job == null && !entry.async) { COUNTED.add(entry.server); + } else if (entry.async) { + HOOKED_SPRING_CLASSES.add(name); } synchronized (changed) { Set names = changed.get(loader); @@ -238,23 +518,52 @@ public byte[] transform(ClassLoader loader, String className, Class classBein return wrapped; } catch (Throwable t) { // Never fail the server's class: it loads unchanged. + noteEntryHookFailure(entry); LOGGER.log(Level.WARNING, "Keploy dedup does not count " + entry.what() + ": " + name + " could not be changed", t); return null; } } - // changedAgain is a class another agent retransforms or redefines, when - // this changed it as it loaded. The JVM passes a retransform the class as - // it was before this changed it, and a redefine the redefiner's bytes, - // and refuses a class that has lost a method this added: so either is - // changed again, unless the bytes already carry the change (a redefiner's - // copy of the class as this changed it), which the JVM then takes as they - // are. Any other class is left as it is: it was loaded unchanged, and the - // JVM refuses a method added to it. + private static void noteEntryHookFailure(Entry entry) { + if (entry.job == null && !entry.async) { + serverHookFailed = true; + } else if ("kafka".equals(entry.job) || "listener".equals(entry.job)) { + listenerHookFailed = true; + } + } + + private void recordRewritten(ClassLoader loader, String className) { + synchronized (rewritten) { + Set names = rewritten.get(loader); + if (names == null) { + names = new HashSet<>(); + rewritten.put(loader, names); + } + names.add(className); + } + } + + private boolean wasRewritten(ClassLoader loader, String className) { + if (!shouldRewriteExecutorCalls(className)) { + return false; + } + synchronized (rewritten) { + Set names = rewritten.get(loader); + return names != null && names.contains(className); + } + } + private byte[] changedAgain(ClassLoader loader, String className, byte[] classfile) { Entry entry = ENTRIES.get(className); if (entry == null) { + if (wasRewritten(loader, className)) { + try { + return wrapExecutorCalls(classfile); + } catch (Throwable t) { + LOGGER.log(Level.FINE, "Keploy dedup skipped executor call-site re-wrap for " + className, t); + } + } // Most classes an agent retransforms: no lock taken for them. return null; } @@ -283,25 +592,34 @@ private byte[] changedAgain(ClassLoader loader, String className, byte[] classfi } } - // seesGate says whether code of a class loader defines calls the - // RequestGate END reads (and so JobGate, of the same jar): one it cannot - // see would fail each request or job, and a copy of its own would count - // where END never looks. private static boolean seesGate(ClassLoader loader) { - // The bootstrap loader (null) does not see it either. + // The bootstrap loader (null) does not see keploy-sdk.jar. + if (loader == null) { + return false; + } + Boolean cached; + synchronized (SEES_GATE) { + cached = SEES_GATE.get(loader); + } + if (cached != null) { + return cached; + } + boolean sees; try { - return Class.forName(RequestGate.class.getName(), false, loader) == RequestGate.class; + sees = Class.forName(RequestGate.class.getName(), false, loader) == RequestGate.class; } catch (Throwable t) { - return false; + sees = false; } + synchronized (SEES_GATE) { + SEES_GATE.put(loader, sees); + } + return sees; } private static boolean isInterface(byte[] classfile) { return (new ClassReader(classfile).getAccess() & Opcodes.ACC_INTERFACE) != 0; } - // carriesChange says whether the class already declares a method this - // renamed: only wrap names a method so. static boolean carriesChange(byte[] classfile) { final boolean[] carries = {false}; new ClassReader(classfile).accept(new ClassVisitor(Opcodes.ASM9) { @@ -317,9 +635,6 @@ public MethodVisitor visitMethod(int access, String name, String descriptor, Str return carries[0]; } - // wrap returns the class with each method of these names counted as a - // server's request, or null when it has none to count (abstract and - // native methods only). transform passes over an interface before it. static byte[] wrap(byte[] classfile, Set methods) { return wrap(classfile, methods, null, false); } @@ -328,10 +643,873 @@ private static byte[] wrap(byte[] classfile, Entry entry) { return wrap(classfile, entry.methods, entry.job, entry.async); } - // wrap with a job kind counts each method's run as a job's run of that - // kind (JobGate) instead; with async, it hands each method's task (its - // first Runnable or Callable argument; a method with none is left as - // it is) to RequestGate instead. + boolean shouldRewriteExecutorCalls(String className) { + if (className == null || !isRewriteAllowedPackage(className)) { + return false; + } + if (!appClasses.isEmpty()) { + // Exact indexed app class allow-list: do NOT apply shaded-package + // filtering; isRewriteAllowedPackage still blocks framework/library + // classes if misconfigured in KEPLOY_JAVA_CLASS_DIRS while allowing + // org/springframework/samples/... (e.g. Spring PetClinic). + return appClasses.contains(className); + } + return appPackagePrefix != null + && className.startsWith(appPackagePrefix) + && !isShadedOrRelocated(className); + } + + private static boolean isKnownMessagingPoolWrapper(String className) { + return className.startsWith("org/messaginghub/pooled/") + || className.startsWith("org/apache/activemq/jms/pool/") + || className.startsWith("com/rabbitmq/client/impl/recovery/"); + } + + private static boolean isInternalOrAgentClass(String className) { + return className.startsWith("java/") + || className.startsWith("javax/") + || className.startsWith("sun/") + || className.startsWith("jdk/") + || className.startsWith("com/sun/") + || className.startsWith("io/keploy/") + || className.startsWith("org/jacoco/") + || className.startsWith("org/newsclub/"); + } + + static boolean canAccessGate(ClassLoader loader, ProtectionDomain protectionDomain) { + if (!seesGate(loader)) { + return false; + } + if (protectionDomain != null && !UNREADABLE_MODULE_LOCATIONS.isEmpty()) { + CodeSource cs = protectionDomain.getCodeSource(); + URL location = cs == null ? null : cs.getLocation(); + if (location != null) { + try { + String normalized = normalizeLocation(location.toURI()); + if (normalized != null && UNREADABLE_MODULE_LOCATIONS.contains(normalized)) { + return false; + } + } catch (Throwable ignored) { + } + } + } + return true; + } + + static Set unreadableModuleLocations() { + return UNREADABLE_MODULE_LOCATIONS; + } + + static boolean isLocationInUnreadableModule(String location) { + if (location == null || location.isEmpty() || UNREADABLE_MODULE_LOCATIONS.isEmpty()) { + return false; + } + int bang = location.indexOf('!'); + String root = bang > 0 ? location.substring(0, bang) : location; + try { + String normalized = normalizeLocation(new File(root).toURI()); + if (normalized != null && UNREADABLE_MODULE_LOCATIONS.contains(normalized)) { + return true; + } + } catch (Throwable ignored) { + } + return UNREADABLE_MODULE_LOCATIONS.contains(root); + } + + private static String normalizeLocation(URI uri) { + if (uri == null) { + return null; + } + if ("file".equalsIgnoreCase(uri.getScheme())) { + try { + return new File(uri).getCanonicalPath(); + } catch (Throwable ignored) { + try { + return new File(uri).getAbsolutePath(); + } catch (Throwable ignored2) { + } + } + } + return uri.normalize().toString(); + } + + private static Set findUnreadableModuleLocations() { + try { + java.lang.reflect.Method getModule = Class.class.getMethod("getModule"); + Object gateModule = getModule.invoke(RequestGate.class); + if (gateModule == null) { + return Collections.emptySet(); + } + Class moduleClass = gateModule.getClass(); + java.lang.reflect.Method isNamed = moduleClass.getMethod("isNamed"); + java.lang.reflect.Method canRead = moduleClass.getMethod("canRead", moduleClass); + java.lang.reflect.Method getName = moduleClass.getMethod("getName"); + Class layerClass = Class.forName("java.lang.ModuleLayer"); + Object bootLayer = layerClass.getMethod("boot").invoke(null); + Set modules = (Set) layerClass.getMethod("modules").invoke(bootLayer); + Object config = layerClass.getMethod("configuration").invoke(bootLayer); + java.lang.reflect.Method findModule = config.getClass().getMethod("findModule", String.class); + Set unreadable = new HashSet<>(); + for (Object mod : modules) { + if (!Boolean.TRUE.equals(isNamed.invoke(mod))) { + continue; + } + if (Boolean.TRUE.equals(canRead.invoke(mod, gateModule))) { + continue; + } + String modName = (String) getName.invoke(mod); + Object optResolved = findModule.invoke(config, modName); + if (optResolved == null) { + continue; + } + if (Boolean.TRUE.equals(optResolved.getClass().getMethod("isPresent").invoke(optResolved))) { + Object resolved = optResolved.getClass().getMethod("get").invoke(optResolved); + Object ref = resolved.getClass().getMethod("reference").invoke(resolved); + Object optLoc = ref.getClass().getMethod("location").invoke(ref); + if (optLoc != null + && Boolean.TRUE.equals(optLoc.getClass().getMethod("isPresent").invoke(optLoc))) { + Object uri = optLoc.getClass().getMethod("get").invoke(optLoc); + if (uri instanceof URI) { + String normalized = normalizeLocation((URI) uri); + if (normalized != null) { + unreadable.add(normalized); + } + } + } + } + } + return unreadable.isEmpty() ? Collections.emptySet() : Collections.unmodifiableSet(unreadable); + } catch (Throwable t) { + // Java 8 (no Module/ModuleLayer) or restricted reflection. + return Collections.emptySet(); + } + } + + static boolean isShadedOrRelocated(String className) { + return className.contains("/shaded/") + || className.contains("/relocated/") + || className.contains("/repackaged/") + || className.startsWith("shaded/") + || className.startsWith("relocated/"); + } + + // Belt-and-suspenders guard in case KEPLOY_JAVA_CLASS_DIRS or + // appPackagePrefix includes framework/library classes; note + // org/apache/ is NOT blanket-excluded so Apache-hosted applications (e.g. + // org/apache/fineract/) remain eligible. Shaded/relocated filtering is + // applied only in prefix mode (not exact appClasses index mode). + static boolean isRewriteAllowedPackage(String className) { + return className != null + && !isInternalOrAgentClass(className) + && !className.startsWith("io/netty/") + && !className.startsWith("reactor/") + && !className.startsWith("okhttp3/") + && !className.startsWith("okio/") + && !className.startsWith("io/lettuce/") + && !className.startsWith("io/grpc/") + && !className.startsWith("software/amazon/") + && !className.startsWith("com/amazonaws/") + && (!className.startsWith("org/springframework/") + || className.startsWith("org/springframework/samples/")) + && !className.startsWith("org/apache/catalina/") + && !className.startsWith("org/apache/coyote/") + && !className.startsWith("org/apache/tomcat/") + && !className.startsWith("org/apache/http/") + && !className.startsWith("org/apache/hc/") + && !className.startsWith("org/apache/kafka/") + && !className.startsWith("org/apache/logging/log4j/") + && !className.startsWith("org/eclipse/jetty/") + && !className.startsWith("io/undertow/") + && !className.startsWith("org/quartz/") + && !className.startsWith("com/zaxxer/") + && !className.startsWith("kotlin/") + && !className.startsWith("kotlinx/") + && !className.startsWith("com/google/common/") + && !className.startsWith("com/github/benmanes/caffeine/") + && !className.startsWith("io/vertx/") + && !className.startsWith("io/micrometer/") + && !className.startsWith("io/opentelemetry/") + && !className.startsWith("ch/qos/logback/") + && !className.startsWith("org/slf4j/") + && !className.startsWith("com/mongodb/") + && !className.startsWith("redis/clients/"); + } + + // Fast constant-pool scan: checks CONSTANT_Class (tag 7) against + // TARGET_EXECUTOR_OWNERS AND CONSTANT_NameAndType (tag 12) method names + // against TARGET_ASYNC_METHOD_NAMES so custom executor subtypes, Thread + // subclasses, CompletionStage, method references, and direct consumer + // polling are never missed while non-async classes skip ClassWriter. + static boolean hasExecutorReference(ClassReader reader) { + int itemCount = reader.getItemCount(); + char[] buf = new char[reader.getMaxStringLength()]; + for (int i = 1; i < itemCount; i++) { + int offset = reader.getItem(i); + if (offset == 0) { + continue; + } + int tag = reader.readByte(offset - 1); + if (tag == 7) { + String owner = reader.readUTF8(offset, buf); + if (TARGET_EXECUTOR_OWNERS.contains(owner)) { + return true; + } + } else if (tag == 12) { + String memberName = reader.readUTF8(offset, buf); + if (TARGET_ASYNC_METHOD_NAMES.contains(memberName)) { + return true; + } + } + } + return false; + } + + private static void scanRawConsumerCalls(byte[] classfile) { + if (classfile == null || classfile.length < 16) { + return; + } + try { + ClassReader reader = new ClassReader(classfile); + int itemCount = reader.getItemCount(); + char[] buf = new char[reader.getMaxStringLength()]; + boolean hasOwner = false; + for (int i = 1; i < itemCount; i++) { + int offset = reader.getItem(i); + if (offset != 0 && reader.readByte(offset - 1) == 7 + && RAW_CONSUMER_OWNERS.contains(reader.readUTF8(offset, buf))) { + hasOwner = true; + break; + } + } + if (!hasOwner) { + return; + } + reader.accept(new ClassVisitor(Opcodes.ASM9) { + @Override + public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, + String[] exceptions) { + return new MethodVisitor(Opcodes.ASM9) { + @Override + public void visitMethodInsn(int opcode, String owner, String mname, String desc, + boolean isInterface) { + if (isDirectRawConsumerCall(owner, mname)) { + SEEN_UNHOOKED_CONSUMERS.add(owner.replace('/', '.') + "." + mname); + } + } + }; + } + }, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); + } catch (Throwable ignored) { + // Read-only heuristic scan must never affect class loading. + } + } + + private static boolean isSingleArgExecutorExecute(String mname, String desc) { + return "execute".equals(mname) && "(Ljava/lang/Runnable;)V".equals(desc); + } + + private static boolean isSingleArgExecutorSubmit(String mname, String desc) { + return ("submit".equals(mname) || "submitListenable".equals(mname) || "submitCompletable".equals(mname)) + && (desc.startsWith("(Ljava/lang/Runnable;)") + || desc.startsWith("(Ljava/util/concurrent/Callable;)")); + } + + private static boolean isTwoArgExecutorSubmit(String mname, String desc) { + return "submit".equals(mname) && desc.startsWith("(Ljava/lang/Runnable;Ljava/lang/Object;)"); + } + + private static boolean isForkJoinTaskSubmission(String owner, String mname, String desc) { + if ("java/util/concurrent/ForkJoinPool".equals(owner) + && ("execute".equals(mname) || "submit".equals(mname)) + && desc.startsWith("(Ljava/util/concurrent/ForkJoinTask;)")) { + return true; + } + return false; + } + + private static boolean isUntrackedScheduleOrInvokeAny(String mname, String desc) { + if ("schedule".equals(mname) + && (desc.startsWith("(Ljava/lang/Runnable;") + || desc.startsWith("(Ljava/util/concurrent/Callable;"))) { + return true; + } + if (("scheduleAtFixedRate".equals(mname) || "scheduleWithFixedDelay".equals(mname)) + && desc.startsWith("(Ljava/lang/Runnable;")) { + return true; + } + if ("invokeAny".equals(mname) + && (desc.startsWith("(Ljava/util/Collection;)") + || desc.startsWith("(Ljava/util/Collection;JLjava/util/concurrent/TimeUnit;)"))) { + return true; + } + return false; + } + + private static boolean isTimerSchedule(String owner, String mname, String desc) { + return "java/util/Timer".equals(owner) + && ("schedule".equals(mname) || "scheduleAtFixedRate".equals(mname)) + && desc.startsWith("(Ljava/util/TimerTask;"); + } + + private static boolean isGuavaAsyncCall(int opcode, String owner, String mname, String desc) { + if ((opcode == Opcodes.INVOKEINTERFACE || opcode == Opcodes.INVOKEVIRTUAL) + && "addListener".equals(mname) + && "(Ljava/lang/Runnable;Ljava/util/concurrent/Executor;)V".equals(desc)) { + return true; + } + if (opcode == Opcodes.INVOKESTATIC + && "com/google/common/util/concurrent/Futures".equals(owner) + && ("addCallback".equals(mname) + || "transform".equals(mname) + || "transformAsync".equals(mname) + || "catching".equals(mname) + || "catchingAsync".equals(mname))) { + return true; + } + return false; + } + + private static boolean isReactorSubscribe(String owner, String mname) { + return "subscribe".equals(mname) + && ("reactor/core/publisher/Mono".equals(owner) + || "reactor/core/publisher/Flux".equals(owner) + || "reactor/core/publisher/ParallelFlux".equals(owner)); + } + + private static boolean isDirectRawConsumerCall(String owner, String mname) { + if ("poll".equals(mname) + && ("org/apache/kafka/clients/consumer/KafkaConsumer".equals(owner) + || "org/apache/kafka/clients/consumer/Consumer".equals(owner))) { + return true; + } + if ("basicConsume".equals(mname) && "com/rabbitmq/client/Channel".equals(owner)) { + return true; + } + if (("receive".equals(mname) || "setMessageListener".equals(mname)) + && ("javax/jms/MessageConsumer".equals(owner) + || "jakarta/jms/MessageConsumer".equals(owner))) { + return true; + } + return false; + } + + private static boolean isHookedSpringMethodRefOwner(String owner) { + return "org/springframework/core/task/SimpleAsyncTaskExecutor".equals(owner) + || "org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor".equals(owner) + || "org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler".equals(owner) + || "org/springframework/scheduling/concurrent/ConcurrentTaskExecutor".equals(owner); + } + + private static boolean isInstanceMethodHandle(Handle h) { + int tag = h.getTag(); + return tag == Opcodes.H_INVOKEVIRTUAL + || tag == Opcodes.H_INVOKEINTERFACE + || tag == Opcodes.H_INVOKESPECIAL; + } + + private static boolean isExecutorExecuteMethodRefTarget(Handle h) { + return isInstanceMethodHandle(h) + && !isHookedSpringMethodRefOwner(h.getOwner()) + && isSingleArgExecutorExecute(h.getName(), h.getDesc()); + } + + private static boolean isExecutorSubmitMethodRefTarget(Handle h) { + return isInstanceMethodHandle(h) + && !isHookedSpringMethodRefOwner(h.getOwner()) + && (isSingleArgExecutorSubmit(h.getName(), h.getDesc()) + || isTwoArgExecutorSubmit(h.getName(), h.getDesc())); + } + + private static boolean isAsyncMethodRefTarget(Handle h) { + String owner = h.getOwner(); + String mname = h.getName(); + String desc = h.getDesc(); + if (isUntrackedScheduleOrInvokeAny(mname, desc) + || isTimerSchedule(owner, mname, desc) + || isForkJoinTaskSubmission(owner, mname, desc)) { + return true; + } + if ("java/util/concurrent/CompletableFuture".equals(owner)) { + if ("runAsync".equals(mname) || "supplyAsync".equals(mname) || "completeAsync".equals(mname)) { + return true; + } + Set asyncDescs = CF_ASYNC_INSTANCE_METHODS.get(mname); + if (asyncDescs != null && asyncDescs.contains(desc)) { + return true; + } + Set syncDescs = CF_SYNC_INSTANCE_METHODS.get(mname); + if (syncDescs != null && syncDescs.contains(desc)) { + return true; + } + } + if ("java/util/concurrent/CompletionStage".equals(owner)) { + Set asyncDescs = CS_ASYNC_INSTANCE_METHODS.get(mname); + if (asyncDescs != null && asyncDescs.contains(desc)) { + return true; + } + Set syncDescs = CS_SYNC_INSTANCE_METHODS.get(mname); + if (syncDescs != null && syncDescs.contains(desc)) { + return true; + } + } + if ("fork".equals(mname) && "()Ljava/util/concurrent/ForkJoinTask;".equals(desc)) { + return true; + } + if ("java/lang/Thread".equals(owner) + && (("start".equals(mname) && "()V".equals(desc)) + || ("startVirtualThread".equals(mname) + && "(Ljava/lang/Runnable;)Ljava/lang/Thread;".equals(desc)))) { + return true; + } + if ("start".equals(mname) && "(Ljava/lang/Runnable;)Ljava/lang/Thread;".equals(desc)) { + return true; + } + return isReactorSubscribe(owner, mname); + } + + private static String stageHelperName(String mname) { + return "stage" + Character.toUpperCase(mname.charAt(0)) + mname.substring(1); + } + + // wrapExecutorCalls redirects standard JDK executor hand-off call sites, + // CompletableFuture (runAsync, supplyAsync, completeAsync, *Async and plain + // dependent stages), CompletionStage (*Async and plain dependent stages), + // remove/shutdownNow, and untracked async sites (schedule*, invokeAny, + // Thread.start, custom executor subtypes, ForkJoinTask.fork, Reactor + // subscribe, async method references) to RequestGate static helpers. + // Returns null when the class contains no matching call sites. + static byte[] wrapExecutorCalls(byte[] classfile) { + ClassReader reader = new ClassReader(classfile); + if ((reader.getAccess() & Opcodes.ACC_INTERFACE) != 0) { + return null; + } + if (!hasExecutorReference(reader)) { + return null; + } + ClassWriter writer = new ClassWriter(reader, 0); + final boolean[] changed = {false}; + reader.accept(new ClassVisitor(Opcodes.ASM9, writer) { + @Override + public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, + String[] exceptions) { + MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions); + if (mv == null) { + return null; + } + return new MethodVisitor(Opcodes.ASM9, mv) { + private int extraStack; + + private void ensureExtraStack(int needed) { + if (extraStack < needed) { + extraStack = needed; + } + } + + private void emitUntrackedFlag(String reason) { + changed[0] = true; + ensureExtraStack(1); + super.visitLdcInsn(reason); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteUntrackedAsync", + "(Ljava/lang/String;)V", false); + } + + @Override + public void visitInvokeDynamicInsn(String indyName, String indyDesc, Handle bsm, + Object... bsmArgs) { + if (bsmArgs != null) { + for (Object arg : bsmArgs) { + if (arg instanceof Handle) { + Handle h = (Handle) arg; + boolean execRef = isExecutorExecuteMethodRefTarget(h); + boolean submitRef = !execRef && isExecutorSubmitMethodRefTarget(h); + if (execRef || submitRef) { + Type[] indyArgs = Type.getArgumentTypes(indyDesc); + boolean isBoundMethodRef = bsm != null + && "java/lang/invoke/LambdaMetafactory".equals(bsm.getOwner()) + && indyArgs.length == 1 + && indyArgs[0].getSort() == Type.OBJECT; + if (isBoundMethodRef) { + // Bound method ref: captured receiver sits on top of stack. + // DUP receiver and verify its runtime Executor/submit type + // so plain non-Executor helpers (e.g. txHelper::execute) + // are ignored with zero contamination, while real untracked + // executors captured outside any window latch asyncExecutors=false. + changed[0] = true; + ensureExtraStack(1); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, + execRef ? "noteIfUntrackedExecutorMethodRef" + : "noteIfUntrackedSubmitMethodRef", + "(Ljava/lang/Object;)V", false); + } else { + // Unbound method ref (e.g. TxHelper::execute as BiConsumer) + // or non-standard capture: LDC the handle's owner Class + // and verify assignability at runtime (note: checks only the + // declaring owner class, not runtime subclasses passed later). + changed[0] = true; + ensureExtraStack(1); + super.visitLdcInsn(Type.getObjectType(h.getOwner())); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, + execRef ? "noteIfUntrackedExecutorClass" + : "noteIfUntrackedSubmitClass", + "(Ljava/lang/Class;)V", false); + } + break; + } + if (isAsyncMethodRefTarget(h)) { + changed[0] = true; + ensureExtraStack(1); + super.visitLdcInsn("untracked-async:method-ref:" + + h.getOwner().replace('/', '.') + "." + h.getName()); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, + "noteUntrackedAsyncMethodRef", + "(Ljava/lang/String;)V", false); + break; + } + } + } + } + super.visitInvokeDynamicInsn(indyName, indyDesc, bsm, bsmArgs); + } + + @Override + public void visitMethodInsn(int opcode, String owner, String mname, String desc, + boolean isInterface) { + if (isDirectRawConsumerCall(owner, mname)) { + SEEN_UNHOOKED_CONSUMERS.add(owner.replace('/', '.') + "." + mname); + } + if (opcode == Opcodes.INVOKEINTERFACE + && ("java/util/concurrent/Executor".equals(owner) + || "java/util/concurrent/ExecutorService".equals(owner) + || "java/util/concurrent/ScheduledExecutorService".equals(owner)) + && "execute".equals(mname) && "(Ljava/lang/Runnable;)V".equals(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "execute", + "(Ljava/util/concurrent/Executor;Ljava/lang/Runnable;)V", false); + return; + } + if (opcode == Opcodes.INVOKEVIRTUAL + && ("java/util/concurrent/AbstractExecutorService".equals(owner) + || "java/util/concurrent/ThreadPoolExecutor".equals(owner) + || "java/util/concurrent/ScheduledThreadPoolExecutor".equals(owner) + || "java/util/concurrent/ForkJoinPool".equals(owner)) + && "execute".equals(mname) && "(Ljava/lang/Runnable;)V".equals(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "execute", + "(Ljava/util/concurrent/Executor;Ljava/lang/Runnable;)V", false); + return; + } + if ((opcode == Opcodes.INVOKEINTERFACE + && ("java/util/concurrent/ExecutorService".equals(owner) + || "java/util/concurrent/ScheduledExecutorService".equals(owner))) + || (opcode == Opcodes.INVOKEVIRTUAL + && ("java/util/concurrent/AbstractExecutorService".equals(owner) + || "java/util/concurrent/ThreadPoolExecutor".equals(owner) + || "java/util/concurrent/ScheduledThreadPoolExecutor".equals(owner) + || "java/util/concurrent/ForkJoinPool".equals(owner)))) { + if ("submit".equals(mname)) { + if ("(Ljava/lang/Runnable;)Ljava/util/concurrent/Future;".equals(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "submit", + "(Ljava/util/concurrent/ExecutorService;Ljava/lang/Runnable;)" + + "Ljava/util/concurrent/Future;", + false); + return; + } + if ("(Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Future;" + .equals(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "submit", + "(Ljava/util/concurrent/ExecutorService;Ljava/lang/Runnable;" + + "Ljava/lang/Object;)Ljava/util/concurrent/Future;", + false); + return; + } + if ("(Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future;".equals(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "submit", + "(Ljava/util/concurrent/ExecutorService;Ljava/util/concurrent/Callable;)" + + "Ljava/util/concurrent/Future;", + false); + return; + } + } + if ("invokeAny".equals(mname) + && ("(Ljava/util/Collection;)Ljava/lang/Object;".equals(desc) + || "(Ljava/util/Collection;JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;" + .equals(desc))) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "invokeAny", + "(Ljava/util/concurrent/ExecutorService;" + desc.substring(1), false); + return; + } + } + if ((opcode == Opcodes.INVOKEINTERFACE + && "java/util/concurrent/ScheduledExecutorService".equals(owner)) + || (opcode == Opcodes.INVOKEVIRTUAL + && "java/util/concurrent/ScheduledThreadPoolExecutor".equals(owner))) { + if ("schedule".equals(mname) + && ("(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)" + + "Ljava/util/concurrent/ScheduledFuture;").equals(desc) + || "schedule".equals(mname) + && ("(Ljava/util/concurrent/Callable;JLjava/util/concurrent/TimeUnit;)" + + "Ljava/util/concurrent/ScheduledFuture;").equals(desc) + || ("scheduleAtFixedRate".equals(mname) || "scheduleWithFixedDelay".equals(mname)) + && ("(Ljava/lang/Runnable;JJLjava/util/concurrent/TimeUnit;)" + + "Ljava/util/concurrent/ScheduledFuture;").equals(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, mname, + "(Ljava/util/concurrent/ScheduledExecutorService;" + desc.substring(1), false); + return; + } + } + if (opcode == Opcodes.INVOKEVIRTUAL + && ("java/util/concurrent/ThreadPoolExecutor".equals(owner) + || "java/util/concurrent/ScheduledThreadPoolExecutor".equals(owner)) + && "remove".equals(mname) && "(Ljava/lang/Runnable;)Z".equals(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "remove", + "(Ljava/util/concurrent/ThreadPoolExecutor;Ljava/lang/Runnable;)Z", false); + return; + } + if (((opcode == Opcodes.INVOKEINTERFACE + && ("java/util/concurrent/ExecutorService".equals(owner) + || "java/util/concurrent/ScheduledExecutorService".equals(owner))) + || (opcode == Opcodes.INVOKEVIRTUAL + && ("java/util/concurrent/AbstractExecutorService".equals(owner) + || "java/util/concurrent/ThreadPoolExecutor".equals(owner) + || "java/util/concurrent/ScheduledThreadPoolExecutor".equals(owner) + || "java/util/concurrent/ForkJoinPool".equals(owner)))) + && "shutdownNow".equals(mname) && "()Ljava/util/List;".equals(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "shutdownNow", + "(Ljava/util/concurrent/ExecutorService;)Ljava/util/List;", false); + return; + } + if (opcode == Opcodes.INVOKESTATIC + && "java/util/concurrent/CompletableFuture".equals(owner)) { + if ("runAsync".equals(mname) + && ("(Ljava/lang/Runnable;)Ljava/util/concurrent/CompletableFuture;".equals(desc) + || ("(Ljava/lang/Runnable;Ljava/util/concurrent/Executor;)" + + "Ljava/util/concurrent/CompletableFuture;").equals(desc))) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "runAsync", desc, false); + return; + } + if ("supplyAsync".equals(mname) + && ("(Ljava/util/function/Supplier;)Ljava/util/concurrent/CompletableFuture;" + .equals(desc) + || ("(Ljava/util/function/Supplier;Ljava/util/concurrent/Executor;)" + + "Ljava/util/concurrent/CompletableFuture;").equals(desc))) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "supplyAsync", desc, false); + return; + } + } + if (opcode == Opcodes.INVOKEVIRTUAL + && "java/util/concurrent/CompletableFuture".equals(owner)) { + if ("completeAsync".equals(mname) + && ("(Ljava/util/function/Supplier;)Ljava/util/concurrent/CompletableFuture;" + .equals(desc) + || ("(Ljava/util/function/Supplier;Ljava/util/concurrent/Executor;)" + + "Ljava/util/concurrent/CompletableFuture;").equals(desc))) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "completeAsync", + "(Ljava/util/concurrent/CompletableFuture;" + desc.substring(1), false); + return; + } + Set descs = CF_ASYNC_INSTANCE_METHODS.get(mname); + if (descs != null && descs.contains(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, mname, + "(Ljava/util/concurrent/CompletableFuture;" + desc.substring(1), false); + return; + } + Set syncDescs = CF_SYNC_INSTANCE_METHODS.get(mname); + if (syncDescs != null && syncDescs.contains(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, mname, + "(Ljava/util/concurrent/CompletableFuture;" + desc.substring(1), false); + return; + } + } + if (opcode == Opcodes.INVOKEINTERFACE + && "java/util/concurrent/CompletionStage".equals(owner)) { + Set descs = CS_ASYNC_INSTANCE_METHODS.get(mname); + if (descs != null && descs.contains(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, stageHelperName(mname), + "(Ljava/util/concurrent/CompletionStage;" + desc.substring(1), false); + return; + } + Set syncDescs = CS_SYNC_INSTANCE_METHODS.get(mname); + if (syncDescs != null && syncDescs.contains(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, stageHelperName(mname), + "(Ljava/util/concurrent/CompletionStage;" + desc.substring(1), false); + return; + } + } + if (opcode == Opcodes.INVOKEVIRTUAL && "java/util/Timer".equals(owner)) { + if ("schedule".equals(mname) + && ("(Ljava/util/TimerTask;J)V".equals(desc) + || "(Ljava/util/TimerTask;Ljava/util/Date;)V".equals(desc) + || "(Ljava/util/TimerTask;JJ)V".equals(desc) + || "(Ljava/util/TimerTask;Ljava/util/Date;J)V".equals(desc))) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "timerSchedule", + "(Ljava/util/Timer;" + desc.substring(1), false); + return; + } + if ("scheduleAtFixedRate".equals(mname) + && ("(Ljava/util/TimerTask;JJ)V".equals(desc) + || "(Ljava/util/TimerTask;Ljava/util/Date;J)V".equals(desc))) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "timerScheduleAtFixedRate", + "(Ljava/util/Timer;" + desc.substring(1), false); + return; + } + if ("cancel".equals(mname) && "()V".equals(desc)) { + // Record Timer.cancel() AFTER cancel() returns so + // cancelledAtNanos never precedes an already-started fire. + changed[0] = true; + ensureExtraStack(1); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteTimerCancelled", + "(Ljava/util/Timer;)V", false); + return; + } + } + if (opcode == Opcodes.INVOKEVIRTUAL + && "java/lang/Thread".equals(owner) + && "start".equals(mname) + && "()V".equals(desc)) { + changed[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "startThread", + "(Ljava/lang/Thread;)V", false); + return; + } + if (opcode == Opcodes.INVOKESTATIC + && "java/lang/Thread".equals(owner) + && "startVirtualThread".equals(mname) + && "(Ljava/lang/Runnable;)Ljava/lang/Thread;".equals(desc)) { + changed[0] = true; + ensureExtraStack(2); + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + super.visitInsn(Opcodes.DUP); + super.visitLdcInsn("untracked-async:virtual-thread"); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "trackUntrackedThread", + "(Ljava/lang/Object;Ljava/lang/String;)V", false); + return; + } + if ((opcode == Opcodes.INVOKEINTERFACE || opcode == Opcodes.INVOKEVIRTUAL) + && "start".equals(mname) + && "(Ljava/lang/Runnable;)Ljava/lang/Thread;".equals(desc)) { + changed[0] = true; + ensureExtraStack(2); + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + super.visitInsn(Opcodes.DUP); + super.visitLdcInsn("untracked-async:thread-builder"); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "trackUntrackedThread", + "(Ljava/lang/Object;Ljava/lang/String;)V", false); + return; + } + // Flag-only async submission sites (task untouched, 100% app-safe). + if (isGuavaAsyncCall(opcode, owner, mname, desc)) { + emitUntrackedFlag("untracked-async:guava-future"); + } else if (opcode == Opcodes.INVOKEVIRTUAL || opcode == Opcodes.INVOKEINTERFACE) { + if (isSingleArgExecutorExecute(mname, desc)) { + // Decide at runtime by actual receiver (must be java.util.concurrent.Executor, + // neither an allow-listed inline executor nor a hooked+verified Spring executor). + changed[0] = true; + ensureExtraStack(2); + super.visitInsn(Opcodes.DUP2); + super.visitInsn(Opcodes.POP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfUntrackedExecutor", + "(Ljava/lang/Object;)V", false); + } else if (isSingleArgExecutorSubmit(mname, desc)) { + // Decide at runtime by actual receiver (must be ExecutorService, + // CompletionService, or Spring AsyncTaskExecutor). + changed[0] = true; + ensureExtraStack(2); + super.visitInsn(Opcodes.DUP2); + super.visitInsn(Opcodes.POP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfUntrackedSubmit", + "(Ljava/lang/Object;)V", false); + } else if (isTwoArgExecutorSubmit(mname, desc)) { + // Stack: [..., recv, runnable, result] (all cat-1 refs). + // Inspect recv at runtime without locals so Guava/Netty + // submit(Runnable, T) returning subtype futures are caught + // while non-executor helpers are ignored. + changed[0] = true; + ensureExtraStack(2); + super.visitInsn(Opcodes.DUP2_X1); + super.visitInsn(Opcodes.POP2); + super.visitInsn(Opcodes.DUP_X2); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfUntrackedSubmit", + "(Ljava/lang/Object;)V", false); + } else if (isForkJoinTaskSubmission(owner, mname, desc)) { + emitUntrackedFlag("untracked-async:forkjoin-task"); + } else if (isTimerSchedule(owner, mname, desc)) { + emitUntrackedFlag("untracked-async:timer"); + } else if (isUntrackedScheduleOrInvokeAny(mname, desc)) { + if (!"invokeAny".equals(mname) + && desc.endsWith(")Ljava/util/concurrent/ScheduledFuture;")) { + changed[0] = true; + ensureExtraStack(2); + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + super.visitInsn(Opcodes.DUP); + super.visitLdcInsn("untracked-async:schedule"); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "trackUntrackedFuture", + "(Ljava/lang/Object;Ljava/lang/String;)V", false); + return; + } + emitUntrackedFlag("untracked-async:" + ("invokeAny".equals(mname) + ? "invokeAny" : "schedule")); + } else if ("fork".equals(mname) + && "()Ljava/util/concurrent/ForkJoinTask;".equals(desc)) { + emitUntrackedFlag("untracked-async:fork"); + } else if (isReactorSubscribe(owner, mname)) { + emitUntrackedFlag("untracked-async:reactor-subscribe"); + } else if (opcode == Opcodes.INVOKEVIRTUAL + && "start".equals(mname) && "()V".equals(desc)) { + // Only flag if runtime receiver is a Thread subclass (zero false + // positives on non-Thread start() methods). + changed[0] = true; + ensureExtraStack(1); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfThread", + "(Ljava/lang/Object;)V", false); + } else if (opcode == Opcodes.INVOKEVIRTUAL + && "cancel".equals(mname) && "()Z".equals(desc)) { + // Track TimerTask.cancel() along with its boolean return value + // (true => cancelled before firing; false => already fired/running): + // [recv] -> DUP -> [recv, recv] -> INVOKEVIRTUAL -> [recv, z] + // -> DUP_X1 -> [z, recv, z] -> INVOKESTATIC -> [z]. + changed[0] = true; + ensureExtraStack(2); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + super.visitInsn(Opcodes.DUP_X1); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteTimerTaskCancelResult", + "(Ljava/lang/Object;Z)V", false); + return; + } + } + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + super.visitMaxs(maxStack + extraStack, maxLocals); + } + }; + } + }, 0); + return changed[0] ? writer.toByteArray() : null; + } + static byte[] wrap(byte[] classfile, Set methods, String job, boolean async) { ClassReader reader = new ClassReader(classfile); ClassWriter writer = new ClassWriter(reader, 0); @@ -342,11 +1520,8 @@ static byte[] wrap(byte[] classfile, Set methods, String job, boolean as private static final class Entry { - // The server or scheduler whose code it is, as the log names it. private final String server; - // The JobGate kind of a job's entry; null for a server's or an executor's. private final String job; - // Whether it is an executor's: the tasks a request hands it count. private final boolean async; private final Set methods; @@ -357,12 +1532,10 @@ private Entry(String server, String job, boolean async, Set methods) { this.methods = Collections.unmodifiableSet(methods); } - // what is what this entry counts, as the log says it. private String what() { return server + (async ? "'s async tasks" : job == null ? "'s requests" : "'s job runs"); } - // effect is what counting them does. private String effect(boolean requests) { String jobs = "a task a scheduled job's run hands off counts as that run, so a test whose window it" + " runs in is marked contaminated in its record"; @@ -373,7 +1546,6 @@ private String effect(boolean requests) { + " not judge it"; } - // lost is what is lost when they cannot be counted. private String lost(boolean requests) { String jobs = "a test is not marked contaminated when work a scheduled job hands off runs in its window"; return async ? (requests ? "a test's END reads its hits without waiting for the tasks its requests" @@ -383,10 +1555,6 @@ private String lost(boolean requests) { } } - // Wrapper renames each method to count and, at the class's end, adds - // the method that counts it under its old name and access: in - // RequestGate, with a job kind in JobGate, or with async the task it - // is handed in RequestGate. private static final class Wrapper extends ClassVisitor { private static final int NOT_COUNTED = Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE | Opcodes.ACC_BRIDGE @@ -436,9 +1604,6 @@ public void visitEnd() { super.visitEnd(); } - // task is the index of a method's first Runnable or Callable - // argument: the task an executor's method is handed; -1 when it - // has none. private static int task(String descriptor) { Type[] args = Type.getArgumentTypes(descriptor); for (int i = 0; i < args.length; i++) { @@ -450,8 +1615,6 @@ private static int task(String descriptor) { return -1; } - // counting adds, under the method's name and access, a method that - // counts the request in RequestGate around a call of the renamed one. private void counting(Method method) { if (async) { handing(method); @@ -485,7 +1648,6 @@ private void counting(Method method) { if (job == null) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "enter", "()Ljava/lang/Object;", false); } else { - // The job's object (null for a static method) and its kind. if (isStatic) { mv.visitInsn(Opcodes.ACONST_NULL); } else { @@ -525,8 +1687,6 @@ private void counting(Method method) { mv.visitEnd(); } - // executor is the index of a method's first AsyncTaskExecutor - // argument: the executor its task is for; -1 when it has none. private static int executor(Type[] args) { for (int i = 0; i < args.length; i++) { if (args[i].getDescriptor().equals(EXECUTOR)) { @@ -536,11 +1696,6 @@ private static int executor(Type[] args) { return -1; } - // handing adds, under an executor's method's name and access, a - // method that hands its task, and the executor it is for (its - // executor argument, else this), to RequestGate and calls the - // renamed one with what RequestGate gave back in its place; when - // that throws, RequestGate hears the task was dropped. private void handing(Method method) { int access = method.access & ~Opcodes.ACC_SYNCHRONIZED; boolean isStatic = (access & Opcodes.ACC_STATIC) != 0; @@ -602,6 +1757,13 @@ private void handing(Method method) { mv.visitMethodInsn(isStatic ? Opcodes.INVOKESTATIC : Opcodes.INVOKESPECIAL, owner, renamedPrefix + method.name, method.descriptor, false); mv.visitLabel(end); + if (returns.getSort() == Type.OBJECT) { + mv.visitInsn(Opcodes.DUP); + mv.visitVarInsn(Opcodes.ALOAD, handed); + mv.visitVarInsn(Opcodes.ALOAD, taskSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "submitted", + "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V", false); + } mv.visitInsn(returns.getOpcode(Opcodes.IRETURN)); mv.visitLabel(thrown); @@ -614,16 +1776,14 @@ private void handing(Method method) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "dropped", "(Ljava/lang/Object;Ljava/lang/Object;)V", false); mv.visitInsn(Opcodes.ATHROW); - mv.visitMaxs(Math.max(Math.max(slot, returns.getSize()), 3), handed + 1); + mv.visitMaxs(Math.max(Math.max(slot, returns.getSize() + 3), 4), handed + 1); mv.visitEnd(); } - // gate is the class whose exit the counting method calls. private String gate() { return job == null ? GATE : JOB_GATE; } - // frameType is how a stack map frame names a local of this type. private static Object frameType(Type type) { switch (type.getSort()) { case Type.BOOLEAN: diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/AppIndexTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/AppIndexTest.java index 3caee80..399e8ff 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/AppIndexTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/AppIndexTest.java @@ -413,13 +413,15 @@ public void aJvmWithNoReceiverNeverReadsItsIndexForTheReport() throws Exception assertTrue(KeployDedupAgent.start()); // Answered after the send at the bind: the worker runs it before its // first accept. - assertEquals("IGNORED proto=2\n", send("END test-set-0/test-0")); + assertEquals("IGNORED proto=3\n", send("END test-set-0/test-0")); assertNotLogged("fingerprint"); } private void startAndSendStart() throws IOException { assertTrue(KeployDedupAgent.start()); - assertEquals("ACK proto=2\n", send("START test-set-0/test-1")); + String reply = send("START test-set-0/test-1"); + assertTrue("expected ACK proto=3 caps=..., got: " + reply, + reply.startsWith("ACK proto=3 caps=") && reply.endsWith("\n")); } // assertIndex checks the INDEX report of the index the agent started on. diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/AsyncHandTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/AsyncHandTest.java index 06fce5f..397e77f 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/AsyncHandTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/AsyncHandTest.java @@ -498,7 +498,6 @@ public void close() { logger.addHandler(handler); try { assertFalse("no executor", OrderedPools.orders(null)); - assertFalse("no pool", OrderedPools.orders(new Object())); for (BlockingQueue queue : Arrays.>asList(new LinkedBlockingQueue<>(), new SynchronousQueue<>(), new ArrayBlockingQueue<>(1), new LinkedBlockingDeque<>(), new LinkedTransferQueue<>())) { @@ -513,6 +512,9 @@ public void close() { } assertEquals(logged.toString(), 0, logged.size()); + assertTrue("unknown object fails closed", OrderedPools.orders(new Object())); + logged.clear(); + assertTrue(OrderedPools.orders(new Priority(pool(new PriorityBlockingQueue<>())))); assertTrue("said once", OrderedPools.orders(new Priority(pool(new PriorityBlockingQueue<>())))); assertEquals(Collections.singletonList("INFO Keploy dedup does not count the tasks handed to " @@ -773,16 +775,18 @@ protected Class findClass(String binary) throws ClassNotFoundException { return executor; } - // An executor whose class has a public getThreadPoolExecutor() and a - // public method that names a type no class loader has. + // An executor whose class (extending Spring's SimpleAsyncTaskExecutor) has + // a public getThreadPoolExecutor() and a public method that names a type no + // class loader has. private static Object missingTypeExecutor() throws Exception { String name = "org/example/pools/MissingType"; + String parent = "org/springframework/core/task/SimpleAsyncTaskExecutor"; ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); - writer.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, name, null, "java/lang/Object", null); + writer.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, name, null, parent, null); MethodVisitor init = writer.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); init.visitCode(); init.visitVarInsn(Opcodes.ALOAD, 0); - init.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, parent, "", "()V", false); init.visitInsn(Opcodes.RETURN); init.visitMaxs(0, 0); init.visitEnd(); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ControlSocketTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ControlSocketTest.java index f6bf530..3f01213 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ControlSocketTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ControlSocketTest.java @@ -51,10 +51,11 @@ * The unix control socket Keploy sends START and END on. Keploy fires its first * test as soon as the app answers its health check, so the socket must listen * by the time start() (premain, before the app's main) returns. Every command - * the SDK reads gets one answer line before the close: "ACK proto=2" if it was - * taken, "IGNORED proto=2" if not. Keploy reads a close with no answer from an - * SDK that says proto=2 as a command not taken, so only a connection closed - * with nothing sent may go unanswered. + * the SDK reads gets one answer line before the close: + * "ACK proto=3 caps=windowCut=...,contaminated=...,classMismatch=...,background=...,ackId=true,asyncExecutors=...,listenerContamination=..." + * if it was taken, "IGNORED proto=3" if not. Keploy reads a close with no + * answer from an SDK that says proto>=2 as a command not taken, so only a + * connection closed with nothing sent may go unanswered. * *

The answers are compared with literals, not the SDK's constants: Keploy * reads the words, so a change to them must fail here. @@ -65,8 +66,10 @@ public class ControlSocketTest { private static final String WARMUP_DISABLED_PROPERTY = "keploy.java.dedup.warmup.disabled"; private static final String CLASS_DIRS_PROPERTY = "keploy.java.class.dirs"; private static final String END_WAIT_PROPERTY = "keploy.java.end.wait.ms"; - private static final String TAKEN = "ACK proto=2\n"; - private static final String IGNORED = "IGNORED proto=2\n"; + private static final String TAKEN = + "ACK proto=3 caps=windowCut=false,contaminated=false,classMismatch=true," + + "background=false,ackId=true,asyncExecutors=false,listenerContamination=false\n"; + private static final String IGNORED = "IGNORED proto=3\n"; private String savedControlPath; private String savedDataPath; @@ -114,6 +117,8 @@ public void setUp() throws IOException { // unless a row sets its own bound. System.setProperty(BuildTable.MIN_HEAP_PROPERTY, "0"); KeployDedupAgent.transformerAdded = false; + KeployDedupAgent.executorCallSitesEnabled = false; + ServerEntries.setHookStatusForTests(false, false, false); } /** A TABLE row needs the heap check's env var unset: it would win over the property setUp sets. */ @@ -139,6 +144,8 @@ public void tearDown() throws Exception { System.clearProperty(BuildTable.MIN_HEAP_PROPERTY); System.clearProperty(END_WAIT_PROPERTY); KeployDedupAgent.transformerAdded = false; + KeployDedupAgent.executorCallSitesEnabled = false; + ServerEntries.setHookStatusForTests(false, false, false); if (jacoco != null) { jacoco.close(); } @@ -208,8 +215,8 @@ public void aTestStartedAndEndedIsAnsweredTakenAndItsCoverageIsSent() throws Exc @Test public void aJobRunningInATestsWindowIsNamedInItsRecordAndOneBetweenTestsIsNot() throws Exception { - startWithJacoco(); data = new DataReceiver(KeployDedupAgent.dataSocketPath); + startWithJacoco(); // Running when the START opens the window, done before its END. Object running = JobGate.enter(new Object(), "quartz"); try { @@ -394,7 +401,7 @@ public void aTableAskedWhenTheHeapIsShortIsDeclinedWithLowHeapAndSendsNothing() int asked = BuildTable.requests(); assertEquals(TAKEN, send("START test-set-0/test-1")); String reply = send("TABLE"); - assertTrue(reply, reply.matches("IGNORED proto=2 reason=low_heap heap_free_mb=\\d+ heap_needed_mb=" + assertTrue(reply, reply.matches("IGNORED proto=3 reason=low_heap heap_free_mb=\\d+ heap_needed_mb=" + needed + "\n")); assertEquals("no send started", asked, BuildTable.requests()); assertNull("no table frame", data.payloads.poll(2, TimeUnit.SECONDS)); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java index 9a0cbb9..0631816 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java @@ -108,6 +108,7 @@ public void endWithNoStartNamesTheTestThenAnswersAck() throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertHello(in.readLine()); // Two, so that a missing ACK shows as the next test's frame in its place. out.write("END test-set-0/test-47\nEND test-set-0/test-48\n".getBytes(StandardCharsets.UTF_8)); @@ -130,6 +131,7 @@ public void aStartWhoseResetFailedNamesTheTestThenAnswersAckAndSoDoesItsEnd() th OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); assertEquals("ACK", in.readLine()); @@ -168,6 +170,7 @@ public void anEndWhoseDumpFailedNamesTheTestThenAnswersAckAndEndsTheTest() throw OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); assertEquals("ACK", in.readLine()); @@ -203,6 +206,7 @@ public void aStartThatThrowsNamesTheTestThenAnswersAckAndTheConnectionGoesOn() t OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1", in.readLine()); @@ -232,6 +236,7 @@ public void theManifestWritesAClassIdAs16HexDigitsAndTheCovNamesAClassJacocoSawO OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); assertEquals("ACK", in.readLine()); @@ -262,6 +267,7 @@ public void aCutEndSaysSoInItsCovAfterClassMismatch() throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); assertEquals("ACK", in.readLine()); @@ -282,6 +288,7 @@ public void aCutEndSaysSoInItsCovAfterClassMismatch() throws Exception { send(out, "END test-set-0/test-2"); String cov = in.readLine(); assertTrue(cov, cov.startsWith("COV ") && !cov.contains("windowCut")); + assertEquals("ACK", in.readLine()); } } @@ -296,15 +303,18 @@ public void anEndIsAnsweredWithoutWaitingForTheCollectorsDelayedAck() throws Exc sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); + assertHelloLine(readLineRaw(in)); long[] micros = new long[ROUND_TRIPS]; for (int i = 0; i < ROUND_TRIPS; i++) { - send(out, "START test-set-0/test-" + i); + String id = "test-set-0/test-" + i; + send(out, "START " + id); assertEquals("ACK\n", readReply(in)); long sent = System.nanoTime(); - send(out, "END test-set-0/test-" + i); + send(out, "END " + id); String reply = readReply(in); micros[i] = (System.nanoTime() - sent) / 1000; - assertTrue(reply, reply.startsWith("COV {\"id\":\"test-set-0/test-" + i + "\"")); + assertTrue(reply, reply.startsWith("COV {\"id\":\"" + id + "\"") + && reply.endsWith("\nACK\n")); } long[] sorted = micros.clone(); Arrays.sort(sorted); @@ -323,17 +333,19 @@ public void eachReplyIsReadInOnePiece() throws Exception { sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); + assertHelloLine(readLineRaw(in)); byte[] buf = new byte[64 * 1024]; for (int i = 0; i < ROUND_TRIPS; i++) { - send(out, "START test-set-0/test-" + i); + String id = "test-set-0/test-" + i; + send(out, "START " + id); assertEquals("ACK\n", readOnce(in, buf)); - send(out, "END test-set-0/test-" + i); + send(out, "END " + id); String reply = readOnce(in, buf); assertTrue("round " + i + " read " + reply, - reply.startsWith("COV {\"id\":\"test-set-0/test-" + i + "\"") && reply.endsWith("}\nACK\n")); + reply.startsWith("COV {\"id\":\"" + id + "\"") && reply.endsWith("}\nACK\n")); // Not taken (an END with no START): the IGNORED line and the ACK. - send(out, "END test-set-0/test-" + i); - assertEquals("IGNORED test-set-0/test-" + i + "\nACK\n", readOnce(in, buf)); + send(out, "END " + id); + assertEquals("IGNORED " + id + "\nACK\n", readOnce(in, buf)); } } } @@ -347,6 +359,7 @@ public void theSocketToKeployHasNagleOff() throws Exception { try (Socket sdk = collector.accept()) { sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); + assertHelloLine(readLineRaw(sdk.getInputStream())); send(out, "END test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1\nACK\n", readReply(sdk.getInputStream())); Field worker = KeployDedupAgent.class.getDeclaredField("coverageWorker"); @@ -379,6 +392,7 @@ public void aFrameLargerThanTheReplyBufferArrivesWholeAndTheRepliesAfterItStayFa sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); + assertHelloLine(readLineRaw(in)); send(out, "START test-set-0/test-0"); assertEquals("ACK\n", readReply(in)); probes[0] = true; @@ -399,13 +413,14 @@ public void aFrameLargerThanTheReplyBufferArrivesWholeAndTheRepliesAfterItStayFa long[] micros = new long[ROUND_TRIPS]; for (int i = 1; i <= ROUND_TRIPS; i++) { - send(out, "START test-set-0/test-" + i); + String id = "test-set-0/test-" + i; + send(out, "START " + id); assertEquals("ACK\n", readReply(in)); long sent = System.nanoTime(); - send(out, "END test-set-0/test-" + i); + send(out, "END " + id); reply = readReply(in); micros[i - 1] = (System.nanoTime() - sent) / 1000; - assertTrue(reply, reply.startsWith("COV {\"id\":\"test-set-0/test-" + i + "\"") + assertTrue(reply, reply.startsWith("COV {\"id\":\"" + id + "\"") && reply.endsWith("}\nACK\n")); } long[] sorted = micros.clone(); @@ -435,6 +450,7 @@ public void aJobThatStartsWhileEndWaitsForTheRequestsOrReadsTheHitsIsNamed() thr sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); + assertHelloLine(readLineRaw(in)); send(out, "START test-set-0/test-1"); assertEquals("ACK\n", readReply(in)); jacoco.onDump = () -> JobGate.exit(JobGate.enter(new Object(), "scheduled")); @@ -491,6 +507,7 @@ public void close() { sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); + assertHelloLine(readLineRaw(in)); for (int last = test + (connection == 1 ? 2 : 1); test < last; test++) { String id = "test-set-0/test-" + test; System.setProperties(jvm); @@ -500,7 +517,8 @@ public void close() { int thrown = unreadable.thrown.get(); send(out, "END " + id); String reply = readReply(in); - assertTrue(reply, reply.startsWith("COV {\"id\":\"" + id + "\"") && reply.endsWith("}\nACK\n")); + assertTrue(reply, reply.startsWith("COV {\"id\":\"" + id + "\"") + && reply.endsWith("}\nACK\n")); assertEquals("COV, ACK and the end of the reply: " + reply, 3, reply.split("\n", -1).length); assertTrue("the build tag's read threw", unreadable.thrown.get() > thrown); assertEquals("connection " + connection + ", " + id + ": " + warnings(logged), @@ -519,6 +537,99 @@ public void close() { } } + @Test(timeout = 60000) + public void betweenTestsBackgroundProbesAreEmittedOnTcpOnlyWhenRequested() throws Exception { + byte[] shopBytes = new byte[] {1, 2, 3}; + File shop = new File(tmp.newFolder("classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + System.setProperty(END_WAIT_PROPERTY, "30"); + boolean[] probes = inProcessJacoco().probes(IndexReport.classId(shopBytes), "com/acme/Shop", 4); + assertTrue(KeployDedupAgent.start()); + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(30000); + OutputStream out = sdk.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertHello(in.readLine()); + // Opt in to correlated ACKs on this connection. + send(out, "ACK_ID"); + + // Before requesting BACKGROUND: hits between tests are cleared, no BACKGROUND frame emitted. + send(out, "START test-set-0/test-0"); + assertEquals("ACK test-set-0/test-0", in.readLine()); + probes[0] = true; + send(out, "END test-set-0/test-0"); + assertEquals("COV {\"id\":\"test-set-0/test-0\",\"executedLinesByFile\":{\"com/acme/Shop\":[0]}}", + in.readLine()); + assertEquals("ACK test-set-0/test-0", in.readLine()); + + probes[3] = true; // background hit before BACKGROUND opt-in + send(out, "START test-set-0/test-1"); + assertEquals("ACK test-set-0/test-1", in.readLine()); + assertFalse("cleared even without BACKGROUND opt-in", probes[3]); + + // Opt in to BACKGROUND (no extra ACK emitted on TCP). + send(out, "BACKGROUND"); + probes[1] = true; + send(out, "END test-set-0/test-1"); + assertEquals("COV {\"id\":\"test-set-0/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}}", + in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); + + // Background job fires between END test-1 and START test-2. + // ACK arrives FIRST so START is never delayed by coverageIndex.report(), + // followed immediately by the BACKGROUND frame. + probes[3] = true; + send(out, "START test-set-0/test-2"); + assertEquals("ACK test-set-0/test-2", in.readLine()); + String bgLine = in.readLine(); + assertTrue("expected BACKGROUND frame after ACK, got: " + bgLine, + bgLine != null && bgLine.startsWith("BACKGROUND ")); + assertTrue(bgLine, bgLine.contains("\"kind\":\"background\"")); + assertTrue(bgLine, bgLine.contains("\"after\":\"test-set-0/test-1\"")); + assertTrue(bgLine, bgLine.contains("\"before\":\"test-set-0/test-2\"")); + assertTrue(bgLine, bgLine.contains("\"com/acme/Shop\":[3]")); + assertFalse("background probe cleared for test-2", probes[3]); + + probes[2] = true; + send(out, "END test-set-0/test-2"); + assertEquals("COV {\"id\":\"test-set-0/test-2\",\"executedLinesByFile\":{\"com/acme/Shop\":[2]}}", + in.readLine()); + assertEquals("ACK test-set-0/test-2", in.readLine()); + + // After a windowCut END, hits cleared by the next START are NOT reported as background. + send(out, "START test-set-0/test-3"); + assertEquals("ACK test-set-0/test-3", in.readLine()); + Object req = RequestGate.enter(); + try { + send(out, "END test-set-0/test-3"); + String cov3 = in.readLine(); + assertTrue(cov3, cov3.contains("\"windowCut\":true")); + assertEquals("ACK test-set-0/test-3", in.readLine()); + } finally { + RequestGate.exit(req); + } + probes[3] = true; + send(out, "START test-set-0/test-4"); + assertEquals("ACK test-set-0/test-4", in.readLine()); + // Confirm no BACKGROUND frame followed START test-4's ACK. + send(out, "NOP after-cut"); + assertEquals("no BACKGROUND frame after cut END", "ACK after-cut", in.readLine()); + } + } + + private static void assertHello(String line) { + assertTrue("expected HELLO frame, got: " + line, + line != null && line.startsWith("HELLO {\"proto\":3,") && line.endsWith("}")); + } + + private static void assertHelloLine(String raw) { + assertTrue("expected HELLO line, got: " + raw, + raw != null && raw.startsWith("HELLO {\"proto\":3,") && raw.endsWith("}\n")); + } + // warnings are the WARNING records that say a CLASSES frame could not be built. private static List warnings(List logged) { List out = new java.util.ArrayList<>(); @@ -607,16 +718,38 @@ private InProcessScanTest.Agent inProcessJacoco() throws ReflectiveOperationExce return agent; } - // readReply reads up to the end of a reply: its ACK line. + // readReply reads up to the end of a reply: its ACK line ("ACK \n" or "ACK\n"). private static String readReply(InputStream in) throws IOException { StringBuilder reply = new StringBuilder(); byte[] buf = new byte[64 * 1024]; - while (reply.length() < 4 || !reply.substring(reply.length() - 4).equals("ACK\n")) { + while (!endsWithAckLine(reply)) { reply.append(readOnce(in, buf)); } return reply.toString(); } + private static boolean endsWithAckLine(StringBuilder reply) { + int len = reply.length(); + if (len < 4 || reply.charAt(len - 1) != '\n') { + return false; + } + int lineStart = reply.lastIndexOf("\n", len - 2) + 1; + String lastLine = reply.substring(lineStart, len - 1); + return lastLine.equals("ACK") || lastLine.startsWith("ACK "); + } + + private static String readLineRaw(InputStream in) throws IOException { + java.io.ByteArrayOutputStream line = new java.io.ByteArrayOutputStream(); + int b; + while ((b = in.read()) != -1) { + line.write(b); + if (b == '\n') { + break; + } + } + return new String(line.toByteArray(), StandardCharsets.UTF_8); + } + // readOnce is one read: what has come of the reply when it wakes. private static String readOnce(InputStream in, byte[] buf) throws IOException { int n; diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/DedupWireFormatTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/DedupWireFormatTest.java index 0cd90e2..0e6ad44 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/DedupWireFormatTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/DedupWireFormatTest.java @@ -88,6 +88,27 @@ public void theJobsThatRanInATestsWindowSitAfterWindowCutAndAreLeftOutWhenNone() Collections.emptyList())); } + @Test + public void unverifiedNoServerEntrySitsOutsideContaminatedForEnterpriseCompat() { + Map> probes = new LinkedHashMap<>(); + probes.put("com/foo/Bar", Arrays.asList(0, 1)); + + // Uncounted-server window (e.g. WebFlux/gRPC/Armeria/Helidon): + // must carry NO "contaminated" key (so released enterprise DedupRecord.notMeasuredBy + // keeps measuring it) and MUST carry "unverified":["no-server-entry"] for v3 collectors. + String json = KeployDedupAgent.toDedupJson("t", probes, Collections.emptyList(), false, + Collections.emptyList(), Collections.singletonList("no-server-entry")); + assertEquals("{\"id\":\"t\",\"executedLinesByFile\":{\"com/foo/Bar\":[0,1]}," + + "\"unverified\":[\"no-server-entry\"]}", json); + assertTrue("must omit contaminated for old enterprise notMeasuredBy compat", + !json.contains("\"contaminated\"")); + + // Omitted when empty. + assertEquals("{\"id\":\"t\",\"executedLinesByFile\":{\"com/foo/Bar\":[0,1]}}", + KeployDedupAgent.toDedupJson("t", probes, Collections.emptyList(), false, + Collections.emptyList(), Collections.emptyList())); + } + @Test public void covPayloadWithNoCoverageSerializesEmptyMap() { String json = KeployDedupAgent.toDedupJson( diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java new file mode 100644 index 0000000..a593631 --- /dev/null +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -0,0 +1,704 @@ +package io.keploy.dedup; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.jar.Attributes; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import org.example.servers.AsyncHonestyApp; +import org.example.servers.AsyncTail; +import org.example.servers.Tail; +import org.jacoco.agent.AgentJar; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +/** + * End-to-end forked {@code -javaagent} JVM tests verifying v3 protocol honesty across both + * embedded-JaCoCo index mode AND external-JaCoCo {@code appPackagePrefix} k8s + * mode, plain JDK executors, {@code CompletableFuture} dependent stages, + * fail-closed unknown executors, {@code KEPLOY_JAVA_ASYNC_CALLSITES=off}, + * whole-jar fallback, Jetty cold-start, uncounted server + * {@code no-server-entry}, and Kafka listener attribution in TCP {@code COV}. + */ +public class ForkedAsyncAndHonestyTest { + + private static final String ASYNC_TAIL = AsyncTail.class.getName().replace('.', '/'); + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + @Test(timeout = 120000) + public void forkedIndexModePlainExecutorTailCausesWindowCutAndTailContaminationUntilDrained() throws Exception { + try (ForkedApp app = startFork("tomcat", "80", false, false, null, null)) { + JsonObject hello = parseHello(app.initialHello); + assertEquals(3, hello.get("proto").getAsInt()); + assertTrue("windowCut true", hello.get("windowCut").getAsBoolean()); + assertTrue("asyncExecutors true in index mode", hello.get("asyncExecutors").getAsBoolean()); + assertEquals("pod-uid-1", hello.get("podUid").getAsString()); + assertEquals("pod-name-1", hello.get("podName").getAsString()); + assertEquals("session-1", hello.get("sessionId").getAsString()); + assertFalse("jvmNonce non-empty", hello.get("jvmNonce").getAsString().isEmpty()); + assertFalse("buildId non-empty", hello.get("buildId").getAsString().isEmpty()); + + // Test 1: submits a 450ms task to plain Executors.newFixedThreadPool with endWait=80ms -> windowCut:true! + String cov1 = app.runHttpTest("ts/t1", "/submit-tail?ms=450"); + assertTrue("Test 1 must be windowCut: " + cov1, cov1.contains("\"windowCut\":true")); + + // Test 2 starts IMMEDIATELY while Test 1's 450ms task is STILL executing -> contaminated: ["tail:ts/t1"]! + String cov2 = app.runHttpTest("ts/t2", "/clean"); + assertTrue("Test 2 must carry tail contamination from cut Test 1: " + cov2, + cov2.contains("\"contaminated\":[\"tail:ts/t1\"]")); + + // Wait for Test 1's 450ms task to drain completely -> Test 3 must be clean! + Thread.sleep(600); + String cov3 = app.runHttpTest("ts/t3", "/clean"); + assertFalse("Test 3 after drain must not be windowCut: " + cov3, cov3.contains("windowCut")); + assertFalse("Test 3 after drain must not be contaminated: " + cov3, cov3.contains("contaminated")); + } + } + + @Test(timeout = 120000) + public void forkedExternalJacocoPrefixModeTracksCompletableFutureDependentsAndChainedAsync() throws Exception { + // Exact k8s mode: -javaagent:jacocoagent.jar FIRST, -javaagent:keploy-sdk.jar SECOND, + // NO KEPLOY_JAVA_CLASS_DIRS -> premain derives appPackagePrefix ("org/example/servers/")! + try (ForkedApp app = startFork("tomcat", "80", true, false, null, null)) { + JsonObject hello = parseHello(app.initialHello); + assertTrue("k8s external-JaCoCo prefix mode must declare windowCut=true", + hello.get("windowCut").getAsBoolean()); + assertTrue("k8s external-JaCoCo prefix mode must declare asyncExecutors=true", + hello.get("asyncExecutors").getAsBoolean()); + + // 1. Fast supplier with slow synchronous dependent: supplyAsync(20ms, pool).thenAccept(350ms audit) + // with endWait=80ms -> MUST report windowCut:true while audit runs! + String cov1 = app.runHttpTest("ts/cf-dep", "/cf-then-accept?ms=350"); + assertTrue("CF dependent thenAccept(audit) must keep window open and trigger windowCut: " + cov1, + cov1.contains("\"windowCut\":true")); + + // Wait for audit to finish, then verify tail contamination was observed and drains. + Thread.sleep(500); + String covDrain = app.runHttpTest("ts/drain-after-cf", "/clean"); + assertTrue("window after cut CF dependent must report tail:ts/cf-dep: " + covDrain, + covDrain.contains("\"contaminated\":[\"tail:ts/cf-dep\"]")); + + // 2. Chained thenApplyAsync(350ms, pool) with endWait=80ms -> MUST report windowCut:true! + String cov2 = app.runHttpTest("ts/cf-chain", "/cf-then-apply-async?ms=350"); + assertTrue("CF thenApplyAsync must keep window open and trigger windowCut: " + cov2, + cov2.contains("\"windowCut\":true")); + Thread.sleep(500); + } + + // Also verify with long endWait (2000ms) that the dependent audit's AsyncTail probe lands INSIDE Test 1's COV! + try (ForkedApp app = startFork("tomcat", "2000", true, false, null, null)) { + String cov = app.runHttpTest("ts/cf-dep-captured", "/cf-then-accept?ms=250"); + assertFalse("sufficient wait must not cut: " + cov, cov.contains("windowCut")); + assertTrue("dependent audit's AsyncTail probe must land in COV: " + cov, + cov.contains("\"" + ASYNC_TAIL + "\"")); + } + } + + @Test(timeout = 120000) + public void forkedUnknownSerializableExecutorIsUnwrappedAndContaminatesCurrentAndNextWindow() throws Exception { + try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { + // 1. Synchronous SerializableOnlyExecutor throws IllegalStateException if task is wrapped. + String cov = app.runHttpTest("ts/unknown-exec", "/unknown-serializable"); + assertFalse("must not fail or cut: " + cov, cov.contains("windowCut")); + assertTrue("unknown executor must contaminate COV with untracked-executor: " + cov, + cov.contains("\"contaminated\":[\"untracked-executor:" + + AsyncHonestyApp.SerializableOnlyExecutor.class.getName() + "\"]")); + + // 2. Async 350ms task on unknown SerializableOnlyExecutor -> Test 1 gets + // untracked-executor:... AND Test 2 immediately gets tail:ts/unknown-async! + String covAsync = app.runHttpTest("ts/unknown-async", "/unknown-serializable-async?ms=350"); + assertTrue("Test 1 must carry untracked-executor: " + covAsync, + covAsync.contains("untracked-executor:" + + AsyncHonestyApp.SerializableOnlyExecutor.class.getName())); + String covNext = app.runHttpTest("ts/after-unknown", "/clean"); + assertTrue("Test 2 immediately after untracked async hand-off must carry tail contamination: " + covNext, + covNext.contains("\"tail:ts/unknown-async\"")); + Thread.sleep(450); + } + } + + @Test(timeout = 120000) + public void forkedExternalCfDependentAndConcreteAsyncFormsAreTrackedOrFlagged() throws Exception { + try (ForkedApp app = startFork("tomcat", "80", false, false, null, null)) { + // External library CompletableFuture.thenAccept(350ms audit) with endWait=80ms -> windowCut:true! + String covExtCut = app.runHttpTest("ts/ext-cf-cut", "/external-cf-dependent?ms=350"); + assertTrue("external CF plain thenAccept must hold window permit and cut at 80ms: " + covExtCut, + covExtCut.contains("\"windowCut\":true")); + Thread.sleep(450); + String covAfterExt = app.runHttpTest("ts/after-ext-cf", "/clean"); + assertTrue("window after cut external CF must carry tail:ts/ext-cf-cut: " + covAfterExt, + covAfterExt.contains("\"tail:ts/ext-cf-cut\"")); + + // CompletionStage-typed thenApplyAsync(350ms) with endWait=80ms -> windowCut:true! + String covStage = app.runHttpTest("ts/stage-async", "/completion-stage-async?ms=350"); + assertTrue("CompletionStage.thenApplyAsync must hold window permit and cut at 80ms: " + covStage, + covStage.contains("\"windowCut\":true")); + Thread.sleep(450); + app.runHttpTest("ts/after-stage", "/clean"); + } + + // With 2000ms endWait: external CF dependent's AsyncTail probe lands cleanly inside COV, + // and concrete custom pool / Thread subclass / ForkJoinTask.fork / CompletionService / method-ref all flag! + try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { + String covExt = app.runHttpTest("ts/ext-cf-ok", "/external-cf-dependent?ms=200"); + assertFalse("external CF with sufficient wait must not cut: " + covExt, covExt.contains("windowCut")); + assertFalse("external CF with sufficient wait must not contaminate: " + covExt, + covExt.contains("contaminated")); + assertTrue("external CF audit probe must land in COV: " + covExt, + covExt.contains("\"" + ASYNC_TAIL + "\"")); + + String covConcrete = app.runHttpTest("ts/concrete-pool", "/concrete-pool"); + assertTrue("concrete ThreadPoolExecutor subclass must contaminate: " + covConcrete, + covConcrete.contains("untracked-executor:" + AsyncHonestyApp.ConcreteCustomPool.class.getName())); + + String covSubThread = app.runHttpTest("ts/sub-thread", "/subclassed-thread"); + assertTrue("subclassed Thread.start() must contaminate: " + covSubThread, + covSubThread.contains("\"untracked-async:thread-start\"")); + + String covFork = app.runHttpTest("ts/fj-fork", "/fork-join-fork"); + assertTrue("ForkJoinTask.fork() must contaminate: " + covFork, + covFork.contains("\"untracked-async:fork\"")); + + String covEcs = app.runHttpTest("ts/ecs-submit", "/completion-service"); + assertTrue("ExecutorCompletionService.submit() must contaminate: " + covEcs, + covEcs.contains("untracked-executor:java.util.concurrent.ExecutorCompletionService")); + + String covMethodRef = app.runHttpTest("ts/method-ref", "/method-ref"); + assertTrue("executor::execute method ref must contaminate: " + covMethodRef, + covMethodRef.contains("untracked-executor:java.util.concurrent.ThreadPoolExecutor")); + } + } + + @Test(timeout = 120000) + public void forkedUntrackedScheduleAndThreadStartContaminateCov() throws Exception { + try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { + String covSched = app.runHttpTest("ts/sched", "/untracked-schedule"); + assertTrue("ScheduledExecutorService.schedule must contaminate COV: " + covSched, + covSched.contains("\"untracked-async:schedule\"")); + + String covThread = app.runHttpTest("ts/thread", "/untracked-thread"); + assertTrue("Thread.start() must contaminate COV: " + covThread, + covThread.contains("\"untracked-async:thread-start\"")); + } + } + + @Test(timeout = 120000) + public void forkedAsyncCallSitesOffSwitchLeavesTasksUnwrappedAndDeclaresAsyncExecutorsFalse() throws Exception { + try (ForkedApp app = startFork("tomcat", "80", false, true, null, null)) { + JsonObject hello = parseHello(app.initialHello); + assertTrue("windowCut still true for Tomcat", hello.get("windowCut").getAsBoolean()); + assertFalse("KEPLOY_JAVA_ASYNC_CALLSITES=off must declare asyncExecutors=false", + hello.get("asyncExecutors").getAsBoolean()); + + // Plain ExecutorService.submit is NOT rewritten when KEPLOY_JAVA_ASYNC_CALLSITES=off. + String cov = app.runHttpTest("ts/off", "/submit-tail?ms=350"); + assertFalse("plain executor must NOT be wrapped when callsites=off: " + cov, + cov.contains("windowCut")); + Thread.sleep(450); + } + } + + @Test(timeout = 120000) + public void forkedWholeJarFallbackDeclaresAsyncExecutorsFalse() throws Exception { + // Build an executable jar that carries foreign META-INF/maven metadata and no + // package root for a known launcher (forces IndexReport.SOURCE_WHOLE_JAR, appOnly=false). + File wholeJar = tmp.newFile("whole-jar-" + System.nanoTime() + ".jar"); + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + mf.getMainAttributes().put(Attributes.Name.MAIN_CLASS, AsyncHonestyApp.class.getName()); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(wholeJar), mf)) { + // No classes under org/example/servers inside this jar -> AppClasses.derive finds 0 + // classes under root, falling back to whole-jar on a dummy class inside the jar. + jos.putNextEntry(new ZipEntry("com/thirdparty/Dummy.class")); + jos.write(new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, 0, 0, 0, 52}); + jos.closeEntry(); + jos.putNextEntry(new ZipEntry("META-INF/maven/com.thirdparty/dummy1/pom.properties")); + jos.write("groupId=com.thirdparty\nartifactId=dummy1\n".getBytes(StandardCharsets.UTF_8)); + jos.closeEntry(); + jos.putNextEntry(new ZipEntry("META-INF/maven/org.other/dummy2/pom.properties")); + jos.write("groupId=org.other\nartifactId=dummy2\n".getBytes(StandardCharsets.UTF_8)); + jos.closeEntry(); + } + try (ForkedApp app = startFork("whole-jar", "200", false, false, wholeJar, null)) { + JsonObject hello = parseHello(app.initialHello); + assertFalse("whole-jar fallback must declare asyncExecutors=false, got: " + app.initialHello, + hello.get("asyncExecutors").getAsBoolean()); + String log = readFile(app.log); + assertTrue("positive control: whole-jar fallback logged: " + log, + log.contains("could not tell the app's own classes from its libraries")); + } + } + + @Test(timeout = 120000) + public void forkedJettyColdStartDeclaresWindowCutTrueAndUncountedServerMarksNoServerEntry() throws Exception { + String jettyNonce; + // 1. Jetty cold-start: BEFORE any HTTP request is made, HELLO already declares windowCut=true! + try (ForkedApp jetty = startFork("jetty", "2000", false, false, null, null)) { + JsonObject hello = parseHello(jetty.initialHello); + jettyNonce = hello.get("jvmNonce").getAsString(); + assertTrue("Jetty cold-start must declare windowCut=true before first request: " + jetty.initialHello, + hello.get("windowCut").getAsBoolean()); + String cov = jetty.runHttpTest("ts/jetty-1", "/clean"); + assertFalse("Jetty request is counted, no no-server-entry: " + cov, cov.contains("no-server-entry")); + } + + // 2. Uncounted HTTP server (JDK HttpServer): sun/net/httpserver/ServerImpl is in UNCOUNTED + // (so HELLO reports windowCut=false once loaded) AND runtime probes with enteredCount == 0 + // still fail closed with no-server-entry! + try (ForkedApp uncounted = startFork("uncounted", "2000", false, false, null, null)) { + JsonObject hello = parseHello(uncounted.initialHello); + assertNotEquals("distinct JVM restart must generate a distinct jvmNonce", + jettyNonce, hello.get("jvmNonce").getAsString()); + String cov = uncounted.runHttpTest("ts/uncounted-1", "/clean"); + assertTrue("uncounted server recording probes must emit unverified no-server-entry: " + cov, + cov.contains("\"unverified\":[\"no-server-entry\"]")); + assertFalse("uncounted server must NOT put no-server-entry in contaminated (enterprise compat): " + cov, + cov.contains("\"contaminated\"")); + assertNotNull("JDK HttpServer must refresh HELLO with windowCut=false", uncounted.lastHello); + JsonObject latest = parseHello(uncounted.lastHello); + assertFalse("JDK HttpServer must declare windowCut=false: " + uncounted.lastHello, + latest.get("windowCut").getAsBoolean()); + assertFalse("JDK HttpServer must declare asyncExecutors=false: " + uncounted.lastHello, + latest.get("asyncExecutors").getAsBoolean()); + } + } + + @Test(timeout = 120000) + public void forkedVirtualThreadStartAndBuilderFlagAndTrackLiveness() throws Exception { + String spec = System.getProperty("java.specification.version"); + org.junit.Assume.assumeTrue("Virtual threads require JDK 21+", + !spec.startsWith("1.") && Integer.parseInt(spec) >= 21); + + // External-JaCoCo prefix mode ("org/example/servers/") automatically rewrites + // the dynamically defined org/example/servers/VirtualThreadHelper on load! + // For each virtual-thread form: + // 1. Start a latch-held virtual thread during window 1 (assert untracked-async:*). + // 2. Immediately run a throwaway /clean window to CONSUME the one-time + // untrackedTailReportedOnce report. + // 3. Sleep 2200ms (strictly past the default 2000ms untrackedTailWindowNanos) + // while the virtual thread remains blocked on the latch. + // 4. Run /clean and assert tail: — this CAN ONLY PASS if the + // post-call DUP + trackUntrackedThread tracked Thread.isAlive(). + // 5. Release the latch via /release-virtual and assert the next /clean is clean. + try (ForkedApp app = startFork("tomcat", "2000", true, false, null, null)) { + String covDirect = app.runHttpTest("ts/vthread-1", "/virtual-thread-latch"); + assertTrue("Thread.startVirtualThread must contaminate COV: " + covDirect, + covDirect.contains("\"untracked-async:virtual-thread\"")); + + // Consume one-time report so the later assertion genuinely depends on Thread.isAlive(). + app.runHttpTest("ts/vthread-consume-once", "/clean"); + Thread.sleep(2200); // Strictly past default 2000ms base tail while virtual thread is held on latch! + String covAfterDirect = app.runHttpTest("ts/vthread-still-alive", "/clean"); + assertTrue("window past 2s base tail & after one-time report while virtual thread is alive " + + "must carry tail: " + covAfterDirect, + covAfterDirect.contains("\"tail:ts/vthread-1\"")); + + app.runHttpTest("ts/vthread-release", "/release-virtual"); + String covDirectDone = app.runHttpTest("ts/vthread-done", "/clean"); + assertFalse("window after virtual thread exits must be clean: " + covDirectDone, + covDirectDone.contains("\"tail:ts/vthread-1\"")); + + String covBuilder = app.runHttpTest("ts/vbuilder-1", "/virtual-builder-latch"); + assertTrue("Thread.ofVirtual().start() must contaminate COV: " + covBuilder, + covBuilder.contains("\"untracked-async:thread-builder\"")); + + // Consume one-time report so the later assertion genuinely depends on Thread.isAlive(). + app.runHttpTest("ts/vbuilder-consume-once", "/clean"); + Thread.sleep(2200); // Strictly past default 2000ms base tail while builder virtual thread is held on latch! + String covAfterBuilder = app.runHttpTest("ts/vbuilder-still-alive", "/clean"); + assertTrue("window past 2s base tail & after one-time report while builder virtual thread is alive " + + "must carry tail: " + covAfterBuilder, + covAfterBuilder.contains("\"tail:ts/vbuilder-1\"")); + + app.runHttpTest("ts/vbuilder-release", "/release-virtual"); + String covBuilderDone = app.runHttpTest("ts/vbuilder-done", "/clean"); + assertFalse("window after builder virtual thread exits must be clean: " + covBuilderDone, + covBuilderDone.contains("\"tail:ts/vbuilder-1\"")); + } + } + + @Test(timeout = 120000) + public void forkedKafkaListenerHookEmitsTopicAndBeanAttributionInTcpCov() throws Exception { + try (ForkedApp kafka = startFork("kafka", "2000", false, false, null, null)) { + JsonObject hello = parseHello(kafka.initialHello); + assertTrue("listenerContamination must be true", hello.get("listenerContamination").getAsBoolean()); + String cov = kafka.runKafkaTest("ts/kafka-1"); + assertTrue("Kafka listener COV must carry topic + bean attribution: " + cov, + cov.contains("\"contaminated\":[\"kafka:orders-topic@" + + AsyncHonestyApp.OrdersListenerBean.class.getName() + "\"]")); + } + } + + private static JsonObject parseHello(String line) { + assertNotNull("HELLO line must not be null", line); + assertTrue("expected HELLO frame, got: " + line, line.startsWith("HELLO {")); + return JsonParser.parseString(line.substring("HELLO ".length())).getAsJsonObject(); + } + + private ForkedApp startFork(String mode, String endWait, boolean externalJacocoPrefixMode, + boolean asyncCallSitesOff, File wholeJarOverride, String extraClassDirs) throws Exception { + File classes = tmp.newFolder(); + for (Class cls : new Class[] { + AsyncHonestyApp.class, AsyncHonestyApp.AsyncServlet.class, + AsyncHonestyApp.SerializableOnlyExecutor.class, AsyncHonestyApp.ConcreteCustomPool.class, + AsyncHonestyApp.MyWorkerThread.class, AsyncHonestyApp.VirtualThreadLauncher.class, + AsyncHonestyApp.OrdersListenerBean.class, AsyncHonestyApp.FakeKafkaProps.class, + AsyncTail.class, Tail.class + }) { + String key = cls.getName().replace('.', '/') + ".class"; + File copy = new File(classes, key); + copy.getParentFile().mkdirs(); + try (InputStream in = cls.getClassLoader().getResourceAsStream(key)) { + Files.copy(in, copy.toPath()); + } + } + + ServerSocket collector = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(60000); + List cmd = new ArrayList<>(); + cmd.add(new File(System.getProperty("java.home"), "bin/java").getPath()); + cmd.add("-Djava.io.tmpdir=" + tmp.newFolder().getPath()); + if (externalJacocoPrefixMode) { + File jacocoJar = tmp.newFile("jacocoagent-" + System.nanoTime() + ".jar"); + AgentJar.extractTo(jacocoJar); + cmd.add("-javaagent:" + jacocoJar.getPath() + "=includes=org.example.*,output=none"); + } + cmd.add("-javaagent:" + sdkJar().getPath()); + + List cp = new ArrayList<>(); + if (wholeJarOverride != null) { + cp.add(wholeJarOverride.getAbsolutePath()); + } + for (String entry : System.getProperty("java.class.path").split(File.pathSeparator)) { + cp.add(new File(entry).getAbsolutePath()); + } + cmd.add("-cp"); + cmd.add(String.join(File.pathSeparator, cp)); + if (wholeJarOverride != null) { + // Launch directly with -jar would omit test classpath; simulate whole-jar by passing + // KEPLOY_JAVA_CLASS_DIRS unset and working dir without target/classes while + // sun.java.command points to wholeJarOverride via a separate class? Instead, pass + // wholeJarOverride as the single classpath jar via -cp would miss AsyncHonestyApp, + // so pass KEPLOY_JAVA_CLASS_DIRS unset AND a custom main? Even cleaner: run with + // -cp : and no KEPLOY_JAVA_CLASS_DIRS, and have wholeJar contain + // the main class! Wait: AsyncHonestyApp needs only JDK classes in "whole-jar" mode! + cmd.set(cmd.size() - 1, wholeJarOverride.getAbsolutePath() + File.pathSeparator + + String.join(File.pathSeparator, cp)); + } + cmd.add(AsyncHonestyApp.class.getName()); + cmd.add(mode); + + File log = tmp.newFile("fork-" + mode + "-" + System.nanoTime() + ".log"); + ProcessBuilder pb = new ProcessBuilder(cmd) + .directory(tmp.newFolder()) + .redirectErrorStream(true) + .redirectOutput(log); + Map env = pb.environment(); + env.keySet().removeIf(k -> k.startsWith("KEPLOY_") || k.equals("JAVA_TOOL_OPTIONS") + || k.equals("JDK_JAVA_OPTIONS") || k.equals("_JAVA_OPTIONS")); + if (!externalJacocoPrefixMode && wholeJarOverride == null) { + env.put("KEPLOY_JAVA_CLASS_DIRS", extraClassDirs != null ? extraClassDirs : classes.getPath()); + } + if (wholeJarOverride != null) { + // Point KEPLOY_JAVA_CLASS_DIRS to a non-existent dir AND run from wholeJar + // so AppClasses.derive fails (main class not in jar's own package) and + // CoverageIndex falls back to whole-jar/classpath (appOnly=false)! + env.put("KEPLOY_JAVA_CLASS_DIRS", new File(tmp.getRoot(), "nonexistent-dir").getPath()); + // Use a launcher class name that AppClasses treats as a known framework launcher + // by running org.springframework.boot.loader? Even simpler: override sun.java.command + // by running a jar whose main is in default/unknown launcher or with -D! + // Actually: for wholeJarOverride, let's put a launcher class in wholeJarOverride and run `-jar`! + cmd.clear(); + cmd.add(new File(System.getProperty("java.home"), "bin/java").getPath()); + cmd.add("-Djava.io.tmpdir=" + tmp.newFolder().getPath()); + cmd.add("-javaagent:" + sdkJar().getPath()); + cmd.add("-cp"); + cmd.add(String.join(File.pathSeparator, cp)); + // Force AppClasses.derive failure using a known launcher class name? No, run -jar wholeJar + // with keploy-sdk on boot/agent classpath! + File shadedJar = buildWholeJarLauncher(wholeJarOverride); + cmd.clear(); + cmd.add(new File(System.getProperty("java.home"), "bin/java").getPath()); + cmd.add("-Djava.io.tmpdir=" + tmp.newFolder().getPath()); + cmd.add("-javaagent:" + sdkJarWithClasses().getPath()); + cmd.add("-jar"); + cmd.add(shadedJar.getPath()); + pb.command(cmd); + env.remove("KEPLOY_JAVA_CLASS_DIRS"); + } + env.put("KEPLOY_COVERAGE_ENDPOINT", "127.0.0.1:" + collector.getLocalPort()); + env.put("KEPLOY_JAVA_DEDUP_WARMUP_DISABLED", "true"); + env.put("KEPLOY_JAVA_END_WAIT_MS", endWait); + env.put("KEPLOY_DEDUP_POD_UID", "pod-uid-1"); + env.put("KEPLOY_DEDUP_POD_NAME", "pod-name-1"); + env.put("KEPLOY_DEDUP_SESSION_ID", "session-1"); + if (asyncCallSitesOff) { + env.put("KEPLOY_JAVA_ASYNC_CALLSITES", "off"); + } + + Process proc = pb.start(); + try { + int port = waitForPort(log, proc); + Socket sdk = collector.accept(); + sdk.setSoTimeout(60000); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + OutputStream out = sdk.getOutputStream(); + String hello = in.readLine(); + return new ForkedApp(proc, log, collector, sdk, in, out, port, hello); + } catch (Throwable t) { + proc.destroyForcibly(); + collector.close(); + throw t; + } + } + + // Builds an executable jar whose Main-Class is in the default package (no + // package root -> AppClasses.derive fails, CoverageIndex falls back to + // whole-jar with appOnly=false). + private File buildWholeJarLauncher(File outJar) throws IOException { + org.objectweb.asm.ClassWriter cw = new org.objectweb.asm.ClassWriter(org.objectweb.asm.ClassWriter.COMPUTE_MAXS); + cw.visit(org.objectweb.asm.Opcodes.V1_8, org.objectweb.asm.Opcodes.ACC_PUBLIC, "RootMain", + null, "java/lang/Object", null); + org.objectweb.asm.MethodVisitor mv = cw.visitMethod( + org.objectweb.asm.Opcodes.ACC_PUBLIC | org.objectweb.asm.Opcodes.ACC_STATIC, + "main", "([Ljava/lang/String;)V", null, new String[] {"java/lang/Exception"}); + mv.visitCode(); + mv.visitFieldInsn(org.objectweb.asm.Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); + mv.visitLdcInsn("PORT 0"); + mv.visitMethodInsn(org.objectweb.asm.Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", + "(Ljava/lang/String;)V", false); + mv.visitFieldInsn(org.objectweb.asm.Opcodes.GETSTATIC, "java/lang/System", "in", "Ljava/io/InputStream;"); + mv.visitMethodInsn(org.objectweb.asm.Opcodes.INVOKEVIRTUAL, "java/io/InputStream", "read", "()I", false); + mv.visitInsn(org.objectweb.asm.Opcodes.POP); + mv.visitInsn(org.objectweb.asm.Opcodes.RETURN); + mv.visitMaxs(2, 1); + mv.visitEnd(); + cw.visitEnd(); + + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + mf.getMainAttributes().put(Attributes.Name.MAIN_CLASS, "RootMain"); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(outJar), mf)) { + jos.putNextEntry(new ZipEntry("RootMain.class")); + jos.write(cw.toByteArray()); + jos.closeEntry(); + jos.putNextEntry(new ZipEntry("META-INF/maven/com.thirdparty/dummy1/pom.properties")); + jos.write("groupId=com.thirdparty\nartifactId=dummy1\n".getBytes(StandardCharsets.UTF_8)); + jos.closeEntry(); + jos.putNextEntry(new ZipEntry("META-INF/maven/org.other/dummy2/pom.properties")); + jos.write("groupId=org.other\nartifactId=dummy2\n".getBytes(StandardCharsets.UTF_8)); + jos.closeEntry(); + } + return outJar; + } + + private File sdkJarWithClasses() throws IOException { + File jar = tmp.newFile("keploy-sdk-cp-" + System.nanoTime() + ".jar"); + Manifest manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + manifest.getMainAttributes().putValue("Premain-Class", KeployDedupAgent.class.getName()); + manifest.getMainAttributes().putValue("Can-Retransform-Classes", "true"); + StringBuilder cp = new StringBuilder(); + for (String entry : System.getProperty("java.class.path").split(File.pathSeparator)) { + if (cp.length() > 0) { + cp.append(' '); + } + cp.append(new File(entry).toURI().toASCIIString()); + } + manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, cp.toString()); + try (JarOutputStream out = new JarOutputStream(new FileOutputStream(jar), manifest)) { + out.putNextEntry(new ZipEntry("META-INF/keploy-test")); + out.closeEntry(); + } + return jar; + } + + private File sdkJar() throws IOException { + File jar = tmp.newFile("keploy-sdk-" + System.nanoTime() + ".jar"); + Manifest manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + manifest.getMainAttributes().putValue("Premain-Class", KeployDedupAgent.class.getName()); + manifest.getMainAttributes().putValue("Can-Retransform-Classes", "true"); + try (JarOutputStream out = new JarOutputStream(new FileOutputStream(jar), manifest)) { + out.putNextEntry(new ZipEntry("META-INF/keploy-test")); + out.closeEntry(); + } + return jar; + } + + private static int waitForPort(File log, Process proc) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); + while (System.nanoTime() < deadline) { + for (String line : Files.readAllLines(log.toPath(), StandardCharsets.UTF_8)) { + if (line.startsWith("PORT ")) { + return Integer.parseInt(line.substring("PORT ".length()).trim()); + } + } + assertTrue("forked JVM exited early:\n" + readFile(log), proc.isAlive()); + Thread.sleep(50); + } + throw new AssertionError("timed out waiting for PORT:\n" + readFile(log)); + } + + private static String readFile(File f) throws IOException { + return new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8); + } + + private static String httpGet(int port, String path) throws IOException { + try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), port)) { + socket.setSoTimeout(30000); + socket.getOutputStream().write(("GET " + path + " HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII)); + InputStream in = socket.getInputStream(); + String status = readHttpLine(in); + assertTrue("expected HTTP 200 for " + path + ", got: " + status, status.contains(" 200 ")); + int length = -1; + String header; + while (!(header = readHttpLine(in)).isEmpty()) { + if (header.toLowerCase(java.util.Locale.ROOT).startsWith("content-length:")) { + length = Integer.parseInt(header.substring("content-length:".length()).trim()); + } + } + if (length >= 0) { + byte[] body = new byte[length]; + int read = 0; + while (read < length) { + int n = in.read(body, read, length - read); + assertTrue(n > 0); + read += n; + } + return new String(body, StandardCharsets.UTF_8); + } + ByteArrayOutputStream rest = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + for (int n; (n = in.read(buf)) > 0; ) { + rest.write(buf, 0, n); + } + return new String(rest.toByteArray(), StandardCharsets.UTF_8); + } + } + + private static String readHttpLine(InputStream in) throws IOException { + ByteArrayOutputStream line = new ByteArrayOutputStream(); + int b; + while ((b = in.read()) >= 0 && b != '\n') { + if (b != '\r') { + line.write(b); + } + } + return new String(line.toByteArray(), StandardCharsets.US_ASCII); + } + + private static final class ForkedApp implements AutoCloseable { + final Process proc; + final File log; + final ServerSocket collector; + final Socket sdk; + final BufferedReader in; + final OutputStream out; + final int port; + final String initialHello; + String lastHello; + + ForkedApp(Process proc, File log, ServerSocket collector, Socket sdk, + BufferedReader in, OutputStream out, int port, String initialHello) { + this.proc = proc; + this.log = log; + this.collector = collector; + this.sdk = sdk; + this.in = in; + this.out = out; + this.port = port; + this.initialHello = initialHello; + this.lastHello = initialHello; + } + + String runHttpTest(String testId, String path) throws IOException { + send("START " + testId); + String ack = nextNonHello(); + assertEquals("ACK", ack); + assertEquals("ok", httpGet(port, path)); + send("END " + testId); + String cov = nextNonHello(); + assertTrue("expected COV, got: " + cov, cov != null && cov.startsWith("COV ")); + String line; + while (!(line = nextNonHello()).equals("ACK")) { + assertTrue(line, line.startsWith("CLASSES ") || line.startsWith("MANIFEST ")); + } + return cov.substring("COV ".length()); + } + + String runKafkaTest(String testId) throws IOException { + send("START " + testId); + assertEquals("ACK", nextNonHello()); + try (Socket cmd = new Socket(InetAddress.getLoopbackAddress(), port)) { + cmd.setSoTimeout(30000); + cmd.getOutputStream().write("fire\n".getBytes(StandardCharsets.UTF_8)); + cmd.getOutputStream().flush(); + BufferedReader cmdIn = new BufferedReader( + new InputStreamReader(cmd.getInputStream(), StandardCharsets.UTF_8)); + assertEquals("DONE", cmdIn.readLine()); + } + send("END " + testId); + String cov = nextNonHello(); + assertTrue("expected COV, got: " + cov, cov != null && cov.startsWith("COV ")); + String line; + while (!(line = nextNonHello()).equals("ACK")) { + assertTrue(line, line.startsWith("CLASSES ") || line.startsWith("MANIFEST ")); + } + return cov.substring("COV ".length()); + } + + private String nextNonHello() throws IOException { + String line = in.readLine(); + while (line != null && line.startsWith("HELLO ")) { + lastHello = line; + line = in.readLine(); + } + return line; + } + + private void send(String cmd) throws IOException { + out.write((cmd + "\n").getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + + @Override + public void close() throws Exception { + try { sdk.close(); } catch (IOException ignored) { } + try { collector.close(); } catch (IOException ignored) { } + try { proc.getOutputStream().close(); } catch (IOException ignored) { } + if (!proc.waitFor(30, TimeUnit.SECONDS)) { + proc.destroyForcibly().waitFor(10, TimeUnit.SECONDS); + } + } + } +} diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java new file mode 100644 index 0000000..3fb61f4 --- /dev/null +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -0,0 +1,5669 @@ +package io.keploy.dedup; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Serializable; +import java.lang.ref.WeakReference; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.CodeSource; +import java.security.ProtectionDomain; +import java.security.cert.Certificate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.RunnableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import java.util.jar.Attributes; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import org.junit.After; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.newsclub.net.unix.AFUNIXSocket; +import org.newsclub.net.unix.AFUNIXSocketAddress; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.ModuleVisitor; +import org.objectweb.asm.Opcodes; +import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; + +/** + * Covers the v3 honest TCP protocol (dynamic HELLO capabilities, backwards-compatible + * bare ACK + opt-in ACK_ID, NOP/bare NOP resync, reconnect state reset, BACKGROUND + * probe-scan-off behavior), strict app-only JDK executor call-site rewriting + * (including branches/stack-map frames, retransform preservation, constant-pool + * fast skip, cancel/timeout/discard/remove/shutdownNow safety, OrderedPools + + * ConcurrentTaskExecutor + pass-through decorator guards, bounded job hand-off + * attribution), and Kafka/RabbitMQ/JMS listener contamination. + */ +public class HonestProtocolAndAsyncTest { + + private static final String ENDPOINT_PROPERTY = "keploy.coverage.endpoint"; + private static final String JACOCO_PORT_PROPERTY = "keploy.jacoco.port"; + private static final String WARMUP_DISABLED_PROPERTY = "keploy.java.dedup.warmup.disabled"; + private static final String END_WAIT_PROPERTY = "keploy.java.end.wait.ms"; + private static final String SCAN_PROPERTY = "keploy.java.scan"; + private static final String CLASS_DIRS_PROPERTY = "keploy.java.class.dirs"; + private static final String ASYNC_CALLSITES_PROPERTY = "keploy.java.async.callsites"; + private static final String POD_UID_PROPERTY = "keploy.dedup.pod.uid"; + private static final String POD_NAME_PROPERTY = "keploy.dedup.pod.name"; + private static final String SESSION_ID_PROPERTY = "keploy.dedup.session.id"; + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private ServerSocket collector; + private FakeJacoco jacoco; + private ClassLoader savedContextLoader; + private boolean savedTransformerAdded; + private boolean savedExecutorCallSitesEnabled; + private boolean savedObservedNoServerEntry; + private boolean savedObservedPreCapturedUntrackedExecutor; + private Set savedCounted; + private Set savedUncounted; + private long savedHandedJobMaxNanos; + private String savedControlSocketPath; + private String savedDataSocketPath; + + @Before + public void setUp() { + savedTransformerAdded = KeployDedupAgent.transformerAdded; + savedExecutorCallSitesEnabled = KeployDedupAgent.executorCallSitesEnabled; + savedObservedNoServerEntry = KeployDedupAgent.observedNoServerEntry; + savedObservedPreCapturedUntrackedExecutor = KeployDedupAgent.observedPreCapturedUntrackedExecutor; + savedCounted = ServerEntries.snapshotCounted(); + savedUncounted = ServerEntries.snapshotUncounted(); + savedHandedJobMaxNanos = JobGate.handedJobMaxNanos; + savedControlSocketPath = KeployDedupAgent.controlSocketPath; + savedDataSocketPath = KeployDedupAgent.dataSocketPath; + KeployDedupAgent.observedNoServerEntry = false; + KeployDedupAgent.observedPreCapturedUntrackedExecutor = false; + ServerEntries.restoreUncounted(Collections.emptySet()); + ServerEntries.setHookStatusForTests(false, false, false); + RequestGate.disarm(); + RequestGate.open(); + JobGate.close(); + } + + @After + public void tearDown() throws IOException { + KeployDedupAgent.stop(); + if (savedContextLoader != null) { + Thread.currentThread().setContextClassLoader(savedContextLoader); + savedContextLoader = null; + } + KeployDedupAgent.transformerAdded = savedTransformerAdded; + KeployDedupAgent.executorCallSitesEnabled = savedExecutorCallSitesEnabled; + KeployDedupAgent.observedNoServerEntry = savedObservedNoServerEntry; + KeployDedupAgent.observedPreCapturedUntrackedExecutor = savedObservedPreCapturedUntrackedExecutor; + ServerEntries.restoreCounted(savedCounted); + ServerEntries.restoreUncounted(savedUncounted); + ServerEntries.setHookStatusForTests(false, false, false); + JobGate.handedJobMaxNanos = savedHandedJobMaxNanos; + KeployDedupAgent.controlSocketPath = savedControlSocketPath; + KeployDedupAgent.dataSocketPath = savedDataSocketPath; + KeployDedupAgent.testHelloFailure = null; + System.clearProperty(ENDPOINT_PROPERTY); + System.clearProperty(JACOCO_PORT_PROPERTY); + System.clearProperty(WARMUP_DISABLED_PROPERTY); + System.clearProperty(END_WAIT_PROPERTY); + System.clearProperty(SCAN_PROPERTY); + System.clearProperty(CLASS_DIRS_PROPERTY); + System.clearProperty(ASYNC_CALLSITES_PROPERTY); + System.clearProperty(POD_UID_PROPERTY); + System.clearProperty(POD_NAME_PROPERTY); + System.clearProperty(SESSION_ID_PROPERTY); + if (collector != null) { + collector.close(); + collector = null; + } + if (jacoco != null) { + jacoco.close(); + jacoco = null; + } + JobGate.close(); + RequestGate.disarm(); + } + + private static JsonObject parseHello(String line) { + assertTrue("expected HELLO frame, got: " + line, line != null && line.startsWith("HELLO {")); + return JsonParser.parseString(line.substring("HELLO ".length())).getAsJsonObject(); + } + + @Test(timeout = 60000) + public void helloReportsLiveCapabilitiesAndIdentityAccuratelyAcrossRuntimeConfigurations() throws Exception { + System.setProperty(POD_UID_PROPERTY, "uid-1234"); + System.setProperty(POD_NAME_PROPERTY, "orders-pod-0"); + System.setProperty(SESSION_ID_PROPERTY, "sess-abc"); + + // Case 1: no -javaagent, no in-process JaCoCo -> windowCut/contaminated/background/asyncExecutors/listener false. + KeployDedupAgent.transformerAdded = false; + KeployDedupAgent.executorCallSitesEnabled = false; + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + ServerEntries.setHookStatusForTests(false, false, false); + JsonObject h1 = parseHello(connectAndReadHello(false)); + assertEquals(3, h1.get("proto").getAsInt()); + assertEquals("uid-1234", h1.get("podUid").getAsString()); + assertEquals("orders-pod-0", h1.get("podName").getAsString()); + assertEquals("sess-abc", h1.get("sessionId").getAsString()); + assertEquals(KeployDedupAgent.jvmNonce(), h1.get("jvmNonce").getAsString()); + assertFalse("buildId must be non-empty", h1.get("buildId").getAsString().isEmpty()); + assertFalse(h1.get("windowCut").getAsBoolean()); + assertFalse(h1.get("contaminated").getAsBoolean()); + assertTrue(h1.get("classMismatch").getAsBoolean()); + assertFalse(h1.get("background").getAsBoolean()); + assertTrue(h1.get("ackId").getAsBoolean()); + assertFalse(h1.get("asyncExecutors").getAsBoolean()); + assertFalse(h1.get("listenerContamination").getAsBoolean()); + + // Case 2: -javaagent attached, Jetty/Undertow cold-start (no server loaded yet!), + // endWait > 0, in-process JaCoCo scan on, app classes indexed -> windowCut & asyncExecutors TRUE! + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + ServerEntries.restoreCounted(Collections.emptySet()); + JsonObject h2 = parseHello(connectAndReadHello(true)); + assertEquals("jvmNonce stays stable across reconnects", h1.get("jvmNonce").getAsString(), + h2.get("jvmNonce").getAsString()); + assertTrue("Jetty/Undertow cold start must declare windowCut=true", h2.get("windowCut").getAsBoolean()); + assertTrue(h2.get("contaminated").getAsBoolean()); + assertTrue(h2.get("background").getAsBoolean()); + assertTrue(h2.get("asyncExecutors").getAsBoolean()); + assertTrue(h2.get("listenerContamination").getAsBoolean()); + + // Case 3: endWait == 0 -> BOTH windowCut AND asyncExecutors must be false. + System.setProperty(END_WAIT_PROPERTY, "0"); + JsonObject h3 = parseHello(connectAndReadHello(true)); + assertFalse(h3.get("windowCut").getAsBoolean()); + assertFalse("asyncExecutors must be false when END_WAIT=0", h3.get("asyncExecutors").getAsBoolean()); + assertTrue(h3.get("contaminated").getAsBoolean()); + assertTrue(h3.get("listenerContamination").getAsBoolean()); + System.clearProperty(END_WAIT_PROPERTY); + + // Case 4: Netty/WebFlux detected (SEEN_UNCOUNTED non-empty) -> BOTH windowCut AND asyncExecutors false! + ServerEntries.restoreUncounted(Collections.singleton("Netty")); + JsonObject h4 = parseHello(connectAndReadHello(true)); + assertFalse("Netty must declare windowCut=false", h4.get("windowCut").getAsBoolean()); + assertFalse("Netty must declare asyncExecutors=false", h4.get("asyncExecutors").getAsBoolean()); + ServerEntries.restoreUncounted(Collections.emptySet()); + + // Case 5: KEPLOY_JAVA_SCAN=off -> background must be false even with in-process JaCoCo. + System.setProperty(SCAN_PROPERTY, "off"); + JsonObject h5 = parseHello(connectAndReadHello(true)); + assertTrue(h5.get("windowCut").getAsBoolean()); + assertFalse(h5.get("background").getAsBoolean()); + assertTrue(h5.get("asyncExecutors").getAsBoolean()); + System.clearProperty(SCAN_PROPERTY); + + // Case 6: KEPLOY_JAVA_ASYNC_CALLSITES=off -> asyncExecutors must be false. + System.setProperty(ASYNC_CALLSITES_PROPERTY, "off"); + JsonObject h6 = parseHello(connectAndReadHello(true)); + assertTrue(h6.get("windowCut").getAsBoolean()); + assertFalse("KEPLOY_JAVA_ASYNC_CALLSITES=off must declare asyncExecutors=false", + h6.get("asyncExecutors").getAsBoolean()); + System.clearProperty(ASYNC_CALLSITES_PROPERTY); + + // Case 7: JPMS guard triggered -> asyncExecutors must be false. + ServerEntries.setHookStatusForTests(false, false, true); + JsonObject h7 = parseHello(connectAndReadHello(true)); + assertFalse("JPMS skipped must declare asyncExecutors=false", h7.get("asyncExecutors").getAsBoolean()); + + // Case 8: Listener hook failure OR unhooked consumer -> listenerContamination must be false. + ServerEntries.setHookStatusForTests(false, true, false); + JsonObject h8 = parseHello(connectAndReadHello(true)); + assertFalse("listener hook failure must declare listenerContamination=false", + h8.get("listenerContamination").getAsBoolean()); + ServerEntries.setHookStatusForTests(false, false, false); + + // Case 8b: Unhooked consumer (e.g. KafkaStreams) -> listenerContamination must be false. + ServerEntries entries = new ServerEntries(true); + entries.transform(getClass().getClassLoader(), "org/apache/kafka/streams/KafkaStreams", null, null, + generatePlainClass("org/apache/kafka/streams/KafkaStreams")); + JsonObject h8b = parseHello(connectAndReadHello(true)); + assertFalse("KafkaStreams must declare listenerContamination=false", + h8b.get("listenerContamination").getAsBoolean()); + ServerEntries.setHookStatusForTests(false, false, false); + + // Case 8c: Uncounted servers (gRPC, Vert.x, Micronaut, JDK HttpServer) -> windowCut & asyncExecutors false. + for (String srv : new String[] { + "io/grpc/netty/NettyServer", + "io/vertx/core/http/impl/HttpServerImpl", + "io/micronaut/http/server/netty/NettyHttpServer", + "sun/net/httpserver/ServerImpl" + }) { + ServerEntries.restoreUncounted(Collections.emptySet()); + entries.transform(getClass().getClassLoader(), srv, null, null, generatePlainClass(srv)); + JsonObject hs = parseHello(connectAndReadHello(true)); + assertFalse(srv + " must declare windowCut=false", hs.get("windowCut").getAsBoolean()); + assertFalse(srv + " must declare asyncExecutors=false", hs.get("asyncExecutors").getAsBoolean()); + } + ServerEntries.restoreUncounted(Collections.emptySet()); + + // Case 8d: App rewrite failure -> asyncExecutors must be false. + ServerEntries.setHookStatusForTests(false, false, false, true); + JsonObject h8d = parseHello(connectAndReadHello(true)); + assertFalse("app rewrite failure must declare asyncExecutors=false", + h8d.get("asyncExecutors").getAsBoolean()); + ServerEntries.setHookStatusForTests(false, false, false, false); + + // Case 9: classpath fallback (executorCallSitesEnabled=false) -> asyncExecutors must be false. + KeployDedupAgent.executorCallSitesEnabled = false; + JsonObject h9 = parseHello(connectAndReadHello(true)); + assertTrue(h9.get("windowCut").getAsBoolean()); + assertFalse(h9.get("asyncExecutors").getAsBoolean()); + } + + @Test(timeout = 60000) + public void earlyConnectBeforeJacocoAndServerInitDoesNotLatchFailureRefreshesHelloAndMarksNoServerEntry() + throws Exception { + byte[] shopBytes = new byte[] {11, 12, 13}; + File shop = new File(tmp.newFolder("classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + ServerEntries.setHookStatusForTests(false, false, false); + + InProcessScanTest.Agent realAgent = new InProcessScanTest.Agent(); + boolean[] probes = realAgent.probes(IndexReport.classId(shopBytes), "com/acme/Shop", 2); + DeferredRtLoader.agent = null; // triggers IllegalStateException("JaCoCo agent not started.") + savedContextLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(new DeferredRtLoader(getClass().getClassLoader())); + System.setProperty(JACOCO_PORT_PROPERTY, "1"); + + collector = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(30000); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + + assertTrue(KeployDedupAgent.start()); + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(30000); + OutputStream out = sdk.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + + // Initial HELLO: cold-start windowCut=true, background=false (JaCoCo not started yet). + JsonObject initial = parseHello(in.readLine()); + assertTrue(initial.get("windowCut").getAsBoolean()); + assertFalse(initial.get("background").getAsBoolean()); + + send(out, "ACK_ID"); + send(out, "BACKGROUND"); + + // External JaCoCo premain finishes. + DeferredRtLoader.agent = realAgent; + + // Next START refreshes HELLO with background=true. + send(out, "START ts/test-1"); + JsonObject updated = parseHello(in.readLine()); + assertTrue("HELLO must refresh background=true once JaCoCo is live", + updated.get("background").getAsBoolean()); + assertEquals("ACK ts/test-1", in.readLine()); + + // Normal counted request (RequestGate.enter()/exit()) -> clean COV! + Object req = RequestGate.enter(); + probes[1] = true; + RequestGate.exit(req); + send(out, "END ts/test-1"); + String cov1 = in.readLine(); + assertEquals("COV {\"id\":\"ts/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}}", cov1); + assertEquals("ACK ts/test-1", in.readLine()); + + // Early BACKGROUND opt-in emits BACKGROUND frame on START ts/test-2. + probes[0] = true; + send(out, "START ts/test-2"); + assertEquals("ACK ts/test-2", in.readLine()); + String bg = in.readLine(); + assertTrue("early BACKGROUND opt-in must take effect once JaCoCo starts, got: " + bg, + bg != null && bg.startsWith("BACKGROUND ") && bg.contains("\"com/acme/Shop\":[0]")); + + // Uncounted server (probes > 0 while enteredCount == 0, e.g. Armeria/Helidon/Play) -> + // latches observedNoServerEntry, refreshes HELLO with windowCut=false BEFORE COV, + // and emits unverified: ["no-server-entry"] with NO "contaminated" field! + probes[1] = true; + send(out, "END ts/test-2"); + JsonObject downgradedHello = parseHello(in.readLine()); + assertFalse("no-server-entry END must refresh HELLO with windowCut=false before COV", + downgradedHello.get("windowCut").getAsBoolean()); + assertFalse("no-server-entry END must refresh HELLO with asyncExecutors=false before COV", + downgradedHello.get("asyncExecutors").getAsBoolean()); + String cov2 = in.readLine(); + assertEquals("COV {\"id\":\"ts/test-2\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}," + + "\"unverified\":[\"no-server-entry\"]}", cov2); + assertFalse("no contaminated field for old enterprise notMeasuredBy compat", + cov2.contains("\"contaminated\"")); + assertEquals("ACK ts/test-2", in.readLine()); + + // Gap after no-server-entry test-2 MUST suppress BACKGROUND on TCP and increment lost! + probes[0] = true; + send(out, "START ts/test-3"); + assertEquals("ACK ts/test-3", in.readLine()); + send(out, "NOP after-unverified-start"); + assertEquals("no BACKGROUND emitted on TCP after no-server-entry test-2", + "ACK after-unverified-start", in.readLine()); + + // Counted test-3 -> clean gap test-3->test-4 emits BACKGROUND carrying lost:1! + Object req3 = RequestGate.enter(); + try { + probes[1] = true; + } finally { + RequestGate.exit(req3); + } + send(out, "END ts/test-3"); + assertEquals("COV {\"id\":\"ts/test-3\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}}", + in.readLine()); + assertEquals("ACK ts/test-3", in.readLine()); + + probes[0] = true; + send(out, "START ts/test-4"); + assertEquals("ACK ts/test-4", in.readLine()); + String bg34 = in.readLine(); + assertTrue("clean TCP gap after test-3 must emit BACKGROUND with lost:1, got: " + bg34, + bg34 != null && bg34.startsWith("BACKGROUND ") + && bg34.contains("\"after\":\"ts/test-3\"") + && bg34.contains("\"lost\":1")); + } finally { + DeferredRtLoader.agent = null; + } + } + + @Test(timeout = 60000) + public void defaultBareAckOptInAckIdBareAndTokenNopAndReconnectStateReset() throws Exception { + byte[] shopBytes = new byte[] {7, 8, 9}; + File shop = new File(tmp.newFolder("classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + boolean[] probes = inProcessJacoco().probes(IndexReport.classId(shopBytes), "com/acme/Shop", 4); + + collector = new ServerSocket(0, 2, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(30000); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + + assertTrue(KeployDedupAgent.start()); + + // Connection 1: verify bare ACK by default, bare NOP, token NOP, then ACK_ID + BACKGROUND opt-in. + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(30000); + OutputStream out = sdk.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + + String hello = in.readLine(); + assertTrue(hello, hello != null && hello.startsWith("HELLO {\"proto\":3,")); + assertTrue(hello, hello.contains("\"background\":true")); + + // Bare NOP (no token) and whitespace-only NOP must reply bare ACK so collector never hangs. + send(out, "NOP"); + assertEquals("ACK", in.readLine()); + send(out, "NOP "); + assertEquals("ACK", in.readLine()); + // Token NOP echoes token even before ACK_ID. + send(out, "NOP resync-1"); + assertEquals("ACK resync-1", in.readLine()); + + // Without ACK_ID: older-collector backwards-compatible bare ACK. + send(out, "START ts/test-0"); + assertEquals("ACK", in.readLine()); + send(out, "END ts/test-0"); + String cov0 = in.readLine(); + assertTrue(cov0, cov0 != null && cov0.startsWith("COV ") && cov0.contains("\"id\":\"ts/test-0\"")); + assertEquals("ACK", in.readLine()); + + // Opt in to correlated ACK_ID + BACKGROUND. + send(out, "ACK_ID"); + send(out, "BACKGROUND"); + + send(out, "START ts/test-1"); + assertEquals("ACK ts/test-1", in.readLine()); + // NOP mid-test must not clear activeTestId. + send(out, "NOP resync-2"); + assertEquals("ACK resync-2", in.readLine()); + probes[0] = true; + send(out, "END ts/test-1"); + String cov1 = in.readLine(); + assertTrue(cov1, cov1 != null && cov1.startsWith("COV ") && cov1.contains("\"id\":\"ts/test-1\"")); + assertEquals("ACK ts/test-1", in.readLine()); + + // Mismatched END echoes IGNORED + ACK once ACK_ID is active. + send(out, "END ts/unknown"); + assertEquals("IGNORED ts/unknown", in.readLine()); + assertEquals("ACK ts/unknown", in.readLine()); + + // Set a background probe before closing the socket to test reconnect reset. + probes[3] = true; + } + + // Connection 2 (after reconnect): ackWithId, backgroundRequested, lastEndedTestId must all be reset. + try (Socket sdk2 = collector.accept()) { + sdk2.setSoTimeout(30000); + OutputStream out = sdk2.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk2.getInputStream(), StandardCharsets.UTF_8)); + + String hello2 = in.readLine(); + assertTrue(hello2, hello2 != null && hello2.startsWith("HELLO {\"proto\":3,")); + + send(out, "START ts/after-reconnect"); + assertEquals("ackWithId must reset to bare ACK on reconnect", "ACK", in.readLine()); + // Confirm no BACKGROUND frame was emitted after reconnect even though probes[3] was true. + send(out, "NOP verify-no-bg"); + assertEquals("ACK verify-no-bg", in.readLine()); + send(out, "END ts/after-reconnect"); + String cov = in.readLine(); + assertTrue(cov, cov != null && cov.startsWith("COV ") && cov.contains("\"id\":\"ts/after-reconnect\"")); + assertEquals("ACK", in.readLine()); + } + } + + @Test(timeout = 60000) + public void backgroundCommandWithProbeScanOffEmitsNoBackgroundFrame() throws Exception { + byte[] shopBytes = new byte[] {4, 5, 6}; + File shop = new File(tmp.newFolder("classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + System.setProperty(SCAN_PROPERTY, "off"); + boolean[] probes = inProcessJacoco().probes(IndexReport.classId(shopBytes), "com/acme/Shop", 4); + + collector = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(30000); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + + assertTrue(KeployDedupAgent.start()); + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(30000); + OutputStream out = sdk.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + + String hello = in.readLine(); + assertTrue(hello, hello.contains("\"background\":false")); + send(out, "ACK_ID"); + send(out, "BACKGROUND"); + + send(out, "START ts/t1"); + assertEquals("ACK ts/t1", in.readLine()); + send(out, "END ts/t1"); + assertTrue(in.readLine().startsWith("COV ")); + assertEquals("ACK ts/t1", in.readLine()); + + probes[2] = true; + send(out, "START ts/t2"); + assertEquals("ACK ts/t2", in.readLine()); + send(out, "NOP no-bg-when-scan-off"); + assertEquals("ACK no-bg-when-scan-off", in.readLine()); + } + } + + @Test(timeout = 60000) + public void appOnlyAllowListExcludesThirdPartyLibrariesAndNonMatchingClassesReturnNull() throws Exception { + Set allowed = new HashSet<>(Arrays.asList( + "com/example/MyApp", + "org/apache/fineract/MyApp", + "io/netty/util/concurrent/SingleThreadEventExecutor", + "okhttp3/internal/concurrent/TaskRunner", + "io/lettuce/core/Client", + "io/grpc/Channel", + "software/amazon/awssdk/Client", + "com/amazonaws/Client", + "org/springframework/core/task/Custom", + "com/zaxxer/hikari/Pool")); + ServerEntries entries = new ServerEntries(true, allowed); + ClassLoader loader = getClass().getClassLoader(); + + // Indexed app classes (including org/apache/fineract/*) are eligible. + assertTrue(entries.shouldRewriteExecutorCalls("com/example/MyApp")); + assertTrue(entries.shouldRewriteExecutorCalls("org/apache/fineract/MyApp")); + + // Unindexed classes are never rewritten. + assertFalse(entries.shouldRewriteExecutorCalls("com/example/Unindexed")); + assertNull(entries.transform(loader, "com/example/Unindexed", null, null, + generateExecutorCaller("com/example/Unindexed"))); + + // Third-party libraries are NEVER rewritten even if accidentally placed in the allow-list. + for (String lib : new String[] { + "io/netty/util/concurrent/SingleThreadEventExecutor", + "okhttp3/internal/concurrent/TaskRunner", + "io/lettuce/core/Client", + "io/grpc/Channel", + "software/amazon/awssdk/Client", + "com/amazonaws/Client", + "org/springframework/core/task/Custom", + "com/zaxxer/hikari/Pool", + "kotlinx/coroutines/DefaultExecutor", + "com/google/common/util/concurrent/MoreExecutors", + "io/opentelemetry/sdk/trace/BatchSpanProcessor", + "com/github/benmanes/caffeine/cache/BoundedLocalCache" + }) { + assertFalse("library must never be rewritten: " + lib, entries.shouldRewriteExecutorCalls(lib)); + assertNull("library transform must return null: " + lib, + entries.transform(loader, lib, null, null, generateExecutorCaller(lib))); + } + + // Package-prefix mode (used when external JaCoCo defers premain index scan): + ServerEntries prefixed = new ServerEntries(true, Collections.emptySet(), "com/example/"); + assertTrue(prefixed.shouldRewriteExecutorCalls("com/example/MyApp")); + assertFalse(prefixed.shouldRewriteExecutorCalls("com/other/Other")); + assertFalse(prefixed.shouldRewriteExecutorCalls("io/netty/util/concurrent/SingleThreadEventExecutor")); + + // Plain class with no executor references returns null via constant-pool fast path. + byte[] plain = generatePlainClass("com/example/MyApp"); + assertFalse(ServerEntries.hasExecutorReference(new org.objectweb.asm.ClassReader(plain))); + assertNull(entries.transform(loader, "com/example/MyApp", null, null, plain)); + + // Class that references Executor in a field/method descriptor but invokes no executor method returns null. + byte[] fieldOnly = generateExecutorFieldOnlyClass("com/example/MyApp"); + assertNull(entries.transform(loader, "com/example/MyApp", null, null, fieldOnly)); + } + + @Test(timeout = 60000) + public void rewritesAllExecutorAndCompletableFutureFormsWithFramesAndPreservesOnRetransform() throws Exception { + String className = "com/example/AllAsyncForms"; + byte[] original = generateAllAsyncFormsClass(className); + ServerEntries entries = new ServerEntries(true, Collections.singleton(className)); + ClassLoader loader = getClass().getClassLoader(); + + // Before initial load, retransform must return null. + assertNull(entries.transform(loader, className, Object.class, null, original)); + + // Initial load rewrites call sites. + byte[] transformed = entries.transform(loader, className, null, null, original); + assertNotNull("all async forms class must be rewritten", transformed); + + // Retransform with original pre-rewrite bytes must re-apply the rewrite. + byte[] retransformed = entries.transform(loader, className, Object.class, null, original); + assertNotNull("retransform must re-apply call-site rewrites", retransformed); + + // Retransform with already-rewritten bytes returns null (idempotent). + assertNull("already-rewritten bytes need no re-rewrite", + entries.transform(loader, className, Object.class, null, retransformed)); + + Class loaded = new ByteLoader(loader).define(className.replace('/', '.'), retransformed); + ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); + ForkJoinPool fjp = new ForkJoinPool(1); + try { + // 1. INVOKEINTERFACE Executor.execute (branch=0), ExecutorService.execute (branch=1), + // ScheduledExecutorService.execute (branch=2), INVOKEVIRTUAL ThreadPoolExecutor.execute (branch=3), + // INVOKEVIRTUAL ScheduledThreadPoolExecutor.execute (branch=4), ForkJoinPool.execute (branch=5). + for (int branch = 0; branch <= 5; branch++) { + RequestGate.open(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Object req = RequestGate.enter(); + try { + Runnable task = latchTask(started, release); + loaded.getMethod("dispatchExecute", int.class, Executor.class, ExecutorService.class, + ScheduledExecutorService.class, ThreadPoolExecutor.class, + ScheduledThreadPoolExecutor.class, ForkJoinPool.class, Runnable.class) + .invoke(null, branch, tpe, tpe, stpe, tpe, stpe, fjp, task); + } finally { + RequestGate.exit(req); + } + assertTrue("branch " + branch + " started", started.await(10, TimeUnit.SECONDS)); + assertEquals("branch " + branch + " keeps window open", 1, RequestGate.running()); + assertFalse("branch " + branch + " causes windowCut", + RequestGate.await(TimeUnit.MILLISECONDS.toNanos(25))); + release.countDown(); + } + + // 2. INVOKEINTERFACE ExecutorService.submit(Runnable/Runnable+result/Callable) & + // INVOKEVIRTUAL ThreadPoolExecutor.submit(Runnable). + for (int mode = 0; mode <= 3; mode++) { + RequestGate.open(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Object req = RequestGate.enter(); + Future f; + try { + f = (Future) loaded.getMethod("dispatchSubmit", int.class, ExecutorService.class, + ThreadPoolExecutor.class, Runnable.class, Callable.class) + .invoke(null, mode, tpe, tpe, latchTask(started, release), + (Callable) () -> { + started.countDown(); + release.await(10, TimeUnit.SECONDS); + return "res"; + }); + } finally { + RequestGate.exit(req); + } + assertTrue("submit mode " + mode + " started", started.await(10, TimeUnit.SECONDS)); + assertEquals("submit mode " + mode + " keeps window open", 1, RequestGate.running()); + release.countDown(); + f.get(10, TimeUnit.SECONDS); + assertTrue("submit mode " + mode + " drains", RequestGate.await(TimeUnit.SECONDS.toNanos(5))); + } + + // 3. CompletableFuture.runAsync (1-arg and 2-arg) & supplyAsync (1-arg and 2-arg). + for (int mode = 0; mode <= 3; mode++) { + RequestGate.open(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Object req = RequestGate.enter(); + CompletableFuture cf; + try { + cf = (CompletableFuture) loaded.getMethod("dispatchCompletable", int.class, Executor.class, + Runnable.class, Supplier.class) + .invoke(null, mode, tpe, latchTask(started, release), + (Supplier) () -> { + started.countDown(); + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return "val"; + }); + } finally { + RequestGate.exit(req); + } + assertTrue("cf mode " + mode + " started", started.await(10, TimeUnit.SECONDS)); + assertEquals("cf mode " + mode + " keeps window open", 1, RequestGate.running()); + release.countDown(); + cf.get(10, TimeUnit.SECONDS); + assertTrue("cf mode " + mode + " drains", RequestGate.await(TimeUnit.SECONDS.toNanos(5))); + } + + // 4. Rewritten ThreadPoolExecutor.remove and ExecutorService.shutdownNow via bytecode. + ThreadPoolExecutor single = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + CountDownLatch blockStart = new CountDownLatch(1); + CountDownLatch blockRel = new CountDownLatch(1); + try { + single.execute(latchTask(blockStart, blockRel)); + assertTrue(blockStart.await(10, TimeUnit.SECONDS)); + + RequestGate.open(); + MyAppTask toRemove = new MyAppTask("bc-remove"); + MyAppTask toDrain = new MyAppTask("bc-drain"); + Object req = RequestGate.enter(); + try { + loaded.getMethod("dispatchExecute", int.class, Executor.class, ExecutorService.class, + ScheduledExecutorService.class, ThreadPoolExecutor.class, + ScheduledThreadPoolExecutor.class, ForkJoinPool.class, Runnable.class) + .invoke(null, 3, single, single, stpe, single, stpe, fjp, toRemove); + loaded.getMethod("dispatchExecute", int.class, Executor.class, ExecutorService.class, + ScheduledExecutorService.class, ThreadPoolExecutor.class, + ScheduledThreadPoolExecutor.class, ForkJoinPool.class, Runnable.class) + .invoke(null, 3, single, single, stpe, single, stpe, fjp, toDrain); + } finally { + RequestGate.exit(req); + } + assertEquals(2, RequestGate.running()); + boolean removed = (Boolean) loaded.getMethod("removeTask", ThreadPoolExecutor.class, Runnable.class) + .invoke(null, single, toRemove); + assertTrue("rewritten remove must succeed", removed); + assertEquals(1, RequestGate.running()); + @SuppressWarnings("unchecked") + List drained = (List) loaded.getMethod("drainAll", ExecutorService.class) + .invoke(null, single); + assertEquals(1, drained.size()); + assertSame("rewritten shutdownNow must unwrap Handed", toDrain, drained.get(0)); + assertEquals(0, RequestGate.running()); + } finally { + blockRel.countDown(); + single.shutdownNow(); + } + + // 5. INVOKESPECIAL (super.execute) must NOT be rewritten (no recursion). + String subName = "com/example/SubTpe"; + byte[] subBytes = generateSuperExecuteSubclass(subName); + ServerEntries subEntries = new ServerEntries(true, Collections.singleton(subName)); + assertNull("INVOKESPECIAL super.execute must not be rewritten", + subEntries.transform(loader, subName, null, null, subBytes)); + } finally { + tpe.shutdownNow(); + stpe.shutdownNow(); + fjp.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void cancelledTimedOutRemovedAndShutdownNowTasksNeverLeakRequestWindow() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + CountDownLatch blockerStarted = new CountDownLatch(1); + CountDownLatch blockerRelease = new CountDownLatch(1); + try { + // Occupy the single worker thread so subsequent tasks stay queued (pending). + pool.execute(latchTask(blockerStarted, blockerRelease)); + assertTrue(blockerStarted.await(10, TimeUnit.SECONDS)); + + // 1. Future.cancel() before task runs releases window immediately. + RequestGate.open(); + Object req = RequestGate.enter(); + Future f1; + Future f2; + CompletableFuture cfRun; + CompletableFuture cfSupply; + MyAppTask removable = new MyAppTask("removable"); + try { + f1 = RequestGate.submit(pool, () -> { }); + f2 = RequestGate.submit(pool, (Callable) () -> "x"); + cfRun = RequestGate.runAsync(() -> { }, pool); + cfSupply = RequestGate.supplyAsync(() -> "y", pool); + RequestGate.execute(pool, removable); + } finally { + RequestGate.exit(req); + } + assertEquals(5, RequestGate.running()); + + assertTrue(f1.cancel(false)); + assertTrue(f2.cancel(false)); + assertTrue(cfRun.cancel(false)); + assertTrue(cfSupply.complete("timed-out-fallback")); + assertTrue("remove must find and remove wrapped task", RequestGate.remove(pool, removable)); + assertEquals("all 5 cancelled/completed/removed tasks released immediately", 0, RequestGate.running()); + assertTrue(RequestGate.await(TimeUnit.SECONDS.toNanos(2))); + assertFalse("removed task must not run", removable.ran.get()); + + // 2. Completing a CompletableFuture WHILE its task is ALREADY RUNNING keeps window open until done. + blockerRelease.countDown(); + CountDownLatch runningStarted = new CountDownLatch(1); + CountDownLatch runningRelease = new CountDownLatch(1); + RequestGate.open(); + Object req2 = RequestGate.enter(); + CompletableFuture inFlight; + try { + inFlight = RequestGate.supplyAsync(() -> { + runningStarted.countDown(); + try { + runningRelease.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return "real"; + }, pool); + } finally { + RequestGate.exit(req2); + } + assertTrue(runningStarted.await(10, TimeUnit.SECONDS)); + assertTrue(inFlight.complete("early-override")); + assertEquals("in-flight task still holds window until finally exits", 1, RequestGate.running()); + runningRelease.countDown(); + assertTrue(RequestGate.await(TimeUnit.SECONDS.toNanos(5))); + + // 3. shutdownNow() unwraps queued execute() tasks (no ClassCastException) AND releases + // pending permits for submit()-ed FutureTasks and ScheduledThreadPoolExecutor tasks. + CountDownLatch hold2 = new CountDownLatch(1); + CountDownLatch rel2 = new CountDownLatch(1); + pool.execute(latchTask(hold2, rel2)); + assertTrue(hold2.await(10, TimeUnit.SECONDS)); + + RequestGate.open(); + MyAppTask queuedAppTask = new MyAppTask("queued"); + Object req3 = RequestGate.enter(); + Future submittedRunnable; + Future submittedCallable; + try { + RequestGate.execute(pool, queuedAppTask); + submittedRunnable = RequestGate.submit(pool, () -> { }); + submittedCallable = RequestGate.submit(pool, (Callable) () -> "val"); + // Casting submit() result to Runnable (FutureTask) must work without ClassCastException! + assertTrue("submit() must return executor's own RunnableFuture", submittedRunnable instanceof Runnable); + assertTrue("submit(Callable) must return executor's own RunnableFuture", + submittedCallable instanceof Runnable); + } finally { + RequestGate.exit(req3); + } + assertEquals(3, RequestGate.running()); + List drained = RequestGate.shutdownNow(pool); + rel2.countDown(); + assertEquals(3, drained.size()); + MyAppTask castBack = (MyAppTask) drained.get(0); + assertSame("shutdownNow must return the app's original Runnable", queuedAppTask, castBack); + assertEquals("shutdownNow must release pending permits for execute + submit tasks", + 0, RequestGate.running()); + assertTrue(RequestGate.await(TimeUnit.SECONDS.toNanos(2))); + + // 4. ScheduledThreadPoolExecutor: cast submit() to ScheduledFuture, remove((Runnable) f), + // and shutdownNow() releasing pending permits for both execute() and submit(). + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); + CountDownLatch stpeHold = new CountDownLatch(1); + CountDownLatch stpeRel = new CountDownLatch(1); + try { + stpe.execute(latchTask(stpeHold, stpeRel)); + assertTrue(stpeHold.await(10, TimeUnit.SECONDS)); + + RequestGate.open(); + Object req4 = RequestGate.enter(); + Future sf1; + Future sf2; + try { + sf1 = RequestGate.submit(stpe, () -> { }); + // Must preserve ScheduledFuture cast! + ScheduledFuture asScheduled = (ScheduledFuture) sf1; + assertNotNull(asScheduled); + // tpe.remove((Runnable) f) idiom must work and release permit! + assertTrue(RequestGate.remove(stpe, (Runnable) sf1)); + assertEquals("only request remains after remove((Runnable) sf1)", 1, RequestGate.running()); + + RequestGate.execute(stpe, () -> { }); + sf2 = RequestGate.submit(stpe, (Callable) () -> "s"); + } finally { + RequestGate.exit(req4); + } + assertEquals(2, RequestGate.running()); + RequestGate.shutdownNow(stpe); + stpeRel.countDown(); + assertEquals("shutdownNow on STPE must release both execute and submit pending permits", + 0, RequestGate.running()); + assertTrue(RequestGate.await(TimeUnit.SECONDS.toNanos(2))); + } finally { + stpeRel.countDown(); + stpe.shutdownNow(); + } + + // 5. dropped() must NOT release a task that has already started running. + RequestGate.open(); + CountDownLatch runningDropStart = new CountDownLatch(1); + CountDownLatch runningDropRel = new CountDownLatch(1); + Object req5 = RequestGate.enter(); + Runnable raw = latchTask(runningDropStart, runningDropRel); + Runnable handed = RequestGate.hand(null, raw); + RequestGate.exit(req5); + Thread t = new Thread(handed); + t.start(); + try { + assertTrue(runningDropStart.await(10, TimeUnit.SECONDS)); + RequestGate.dropped(handed, raw); + assertEquals("dropped() on already-running task must not close window early", + 1, RequestGate.running()); + } finally { + runningDropRel.countDown(); + t.join(10000); + } + assertEquals(0, RequestGate.running()); + } finally { + blockerRelease.countDown(); + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void orderedPoolsGuardsDiscardPoliciesTaskHooksConcurrentTaskExecutorAndPassThroughDecorators() + throws Exception { + // 1. PriorityBlockingQueue raw pool. + ThreadPoolExecutor priority = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new PriorityBlockingQueue()); + // 2. DiscardPolicy & DiscardOldestPolicy pools. + ThreadPoolExecutor discard = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue(1), new ThreadPoolExecutor.DiscardPolicy()); + ThreadPoolExecutor discardOldest = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue(1), new ThreadPoolExecutor.DiscardOldestPolicy()); + // 3. ThreadPoolExecutor subclasses overriding beforeExecute or newTaskFor that cast Runnable to MyAppTask, + // and a pool with a custom log-and-drop RejectedExecutionHandler. + AtomicReference hookSaw = new AtomicReference<>(); + ThreadPoolExecutor customHookPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()) { + @Override + protected void beforeExecute(Thread t, Runnable r) { + hookSaw.set(((MyAppTask) r).name); + } + }; + AtomicReference newTaskForSaw = new AtomicReference<>(); + ThreadPoolExecutor customNewTaskForPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()) { + @Override + protected RunnableFuture newTaskFor(Runnable runnable, T value) { + newTaskForSaw.set(((MyAppTask) runnable).name); + return super.newTaskFor(runnable, value); + } + }; + ThreadPoolExecutor customDropHandlerPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue(1), (r, e) -> { /* custom log-and-drop */ }); + ThreadPoolExecutor callerRunsPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue(1), new ThreadPoolExecutor.CallerRunsPolicy()); + // 4. Exact ScheduledThreadPoolExecutor & Spring ThreadPoolTaskScheduler ARE safe. + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); + ThreadPoolTaskScheduler springScheduler = new ThreadPoolTaskScheduler(); + springScheduler.initialize(); + // 5. ConcurrentTaskExecutor wrapping priority pool vs opaque executor vs normal pool vs default single-thread. + ThreadPoolExecutor normalPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + ConcurrentTaskExecutor ctePriority = new ConcurrentTaskExecutor(priority); + ConcurrentTaskExecutor cteOpaque = new ConcurrentTaskExecutor(Runnable::run); + ConcurrentTaskExecutor cteNormal = new ConcurrentTaskExecutor(normalPool); + ConcurrentTaskExecutor cteDefault = new ConcurrentTaskExecutor(); + ExecutorService unconfigurable = Executors.unconfigurableExecutorService(priority); + + try { + assertTrue(OrderedPools.orders(priority)); + assertTrue(OrderedPools.orders(discard)); + assertTrue(OrderedPools.orders(discardOldest)); + assertTrue(OrderedPools.orders(customHookPool)); + assertTrue("newTaskFor override must be skipped", OrderedPools.orders(customNewTaskForPool)); + assertTrue("custom RejectedExecutionHandler must be skipped", OrderedPools.orders(customDropHandlerPool)); + assertTrue("CallerRunsPolicy silently drops after shutdown so must be skipped", + OrderedPools.orders(callerRunsPool)); + assertFalse("exact ScheduledThreadPoolExecutor is safe", OrderedPools.orders(stpe)); + assertFalse("Spring ThreadPoolTaskScheduler is safe", OrderedPools.orders(springScheduler)); + assertTrue("ConcurrentTaskExecutor wrapping priority pool must not wrap", + OrderedPools.orders(ctePriority)); + assertTrue("ConcurrentTaskExecutor wrapping opaque delegate must not wrap", + OrderedPools.orders(cteOpaque)); + assertFalse("ConcurrentTaskExecutor wrapping LinkedBlockingQueue pool is safe", + OrderedPools.orders(cteNormal)); + assertFalse("default ConcurrentTaskExecutor (newSingleThreadExecutor) is safe on JDK 8-21+", + OrderedPools.orders(cteDefault)); + assertTrue("unconfigurableExecutorService cannot be inspected", + OrderedPools.orders(unconfigurable)); + + // Custom beforeExecute & newTaskFor pools receive original MyAppTask without ClassCastException. + RequestGate.open(); + MyAppTask appTask = new MyAppTask("hooked"); + MyAppTask submittedTask = new MyAppTask("newTaskFor"); + Object req = RequestGate.enter(); + Future submittedFuture; + try { + RequestGate.execute(customHookPool, appTask); + submittedFuture = RequestGate.submit(customNewTaskForPool, submittedTask); + } finally { + RequestGate.exit(req); + } + customHookPool.shutdown(); + assertTrue(customHookPool.awaitTermination(10, TimeUnit.SECONDS)); + assertEquals("hooked", hookSaw.get()); + assertTrue(appTask.ran.get()); + submittedFuture.get(10, TimeUnit.SECONDS); + assertEquals("newTaskFor", newTaskForSaw.get()); + assertTrue(submittedTask.ran.get()); + + // Fail-closed: unknown/library executors (e.g. Hazelcast Serializable-checking executor, + // custom ExecutorService subclass, pass-through lambda decorator) are NEVER wrapped and + // mark the current window contaminated ("untracked-executor:"). + AtomicReference unknownSaw = new AtomicReference<>(); + ExecutorService serializableOnlyExec = new AbstractExecutorService() { + @Override + public void execute(Runnable command) { + if (!(command instanceof Serializable)) { + throw new IllegalStateException("task must be Serializable, got: " + command.getClass()); + } + unknownSaw.set(command); + command.run(); + } + + @Override public void shutdown() { } + @Override public List shutdownNow() { return Collections.emptyList(); } + @Override public boolean isShutdown() { return false; } + @Override public boolean isTerminated() { return false; } + @Override public boolean awaitTermination(long t, TimeUnit u) { return true; } + }; + assertTrue("unknown custom ExecutorService must fail closed", + OrderedPools.orders(serializableOnlyExec)); + + RequestGate.open("t-unknown", null); + Runnable serTask = (Runnable & Serializable) () -> { }; + Object reqUnknown = RequestGate.enter(); + try { + RequestGate.execute(serializableOnlyExec, serTask); + assertSame("unknown executor must receive original task untouched", serTask, unknownSaw.get()); + } finally { + RequestGate.exit(reqUnknown); + } + RequestGate.WindowOutcome unknownOutcome = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("unknown executor must contaminate window: " + unknownOutcome.contaminations, + unknownOutcome.contaminations.contains("untracked-executor:" + serializableOnlyExec.getClass().getName())); + + // Pass-through app decorator wrapping a PriorityBlockingQueue pool: + // fails closed at the outer unknown decorator too (never wraps!). + CountDownLatch ran = new CountDownLatch(1); + Runnable plainTask = ran::countDown; + Executor decorator = r -> RequestGate.execute(priority, r); + RequestGate.open("t-decorator", null); + Object req2 = RequestGate.enter(); + try { + RequestGate.execute(decorator, plainTask); + assertEquals("fail-closed decorator never wraps, only request remains counted", + 1, RequestGate.running()); + } finally { + RequestGate.exit(req2); + } + RequestGate.WindowOutcome decOutcome = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("unknown decorator carries tail from prior untracked window: " + decOutcome.contaminations, + decOutcome.contaminations.contains("tail:t-unknown")); + assertTrue("unknown decorator contaminates window: " + decOutcome.contaminations, + decOutcome.contaminations.stream().anyMatch(s -> s.startsWith("untracked-executor:"))); + assertTrue(ran.await(10, TimeUnit.SECONDS)); + } finally { + priority.shutdownNow(); + discard.shutdownNow(); + discardOldest.shutdownNow(); + customHookPool.shutdownNow(); + customNewTaskForPool.shutdownNow(); + customDropHandlerPool.shutdownNow(); + callerRunsPool.shutdownNow(); + stpe.shutdownNow(); + springScheduler.shutdown(); + normalPool.shutdownNow(); + if (cteDefault.getConcurrentExecutor() instanceof ExecutorService) { + ((ExecutorService) cteDefault.getConcurrentExecutor()).shutdownNow(); + } + unconfigurable.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void firstHopQueueWaitDoesNotEatBudgetWhileChainedSelfResubmissionExpiresAtHop1Deadline() + throws Exception { + JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(120); + ExecutorService pool = Executors.newSingleThreadExecutor(); + try { + // 1. First-hop task waits in queue LONGER than handedJobMaxNanos: + // its budget must start when it begins running, not at hand-off time. + CountDownLatch blockerStart = new CountDownLatch(1); + CountDownLatch blockerRel = new CountDownLatch(1); + pool.execute(latchTask(blockerStart, blockerRel)); + assertTrue(blockerStart.await(10, TimeUnit.SECONDS)); + + AtomicReference firstHopRunning = new AtomicReference<>(); + CountDownLatch firstHopDone = new CountDownLatch(1); + Object job = JobGate.enter(new Object(), "scheduled"); + try { + RequestGate.execute(pool, () -> { + firstHopRunning.set(JobGate.running()); + firstHopDone.countDown(); + }); + } finally { + JobGate.exit(job); + } + // Wait longer than handedJobMaxNanos while task sits in the queue. + Thread.sleep(160); + JobGate.open(); + blockerRel.countDown(); + assertTrue(firstHopDone.await(10, TimeUnit.SECONDS)); + assertNotNull("first hop must still be attributed after long queue wait", firstHopRunning.get()); + assertEquals("first hop marks window contaminated when it runs", 1, JobGate.close().size()); + + // 2. Chained self-resubmitting loop starts its budget at hop 1 and MUST expire at hop 1's deadline. + JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(200); + AtomicInteger hops = new AtomicInteger(); + CountDownLatch hop1Attributed = new CountDownLatch(1); + CountDownLatch expiredHopSeen = new CountDownLatch(1); + AtomicBoolean keepLooping = new AtomicBoolean(true); + Runnable[] self = new Runnable[1]; + self[0] = () -> { + int hop = hops.incrementAndGet(); + String current = JobGate.running(); + if (current != null) { + if (hop == 1) { + hop1Attributed.countDown(); + } + } else if (hop > 1) { + expiredHopSeen.countDown(); + keepLooping.set(false); + return; + } + if (keepLooping.get()) { + try { + Thread.sleep(40); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + RequestGate.execute(pool, self[0]); + } + }; + Object job2 = JobGate.enter(new Object(), "scheduled"); + try { + RequestGate.execute(pool, self[0]); + } finally { + JobGate.exit(job2); + } + assertTrue("hop 1 must be attributed", hop1Attributed.await(10, TimeUnit.SECONDS)); + assertTrue("chained self-resubmitting job task must expire at hop 1 deadline, hops=" + hops.get(), + expiredHopSeen.await(10, TimeUnit.SECONDS)); + assertTrue("multiple hops executed before expiry", hops.get() >= 2); + // Wait briefly for the expired hop's finally block to call JobGate.exit(). + long exitDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (JobGate.activeRunCount() > 0 && System.nanoTime() < exitDeadline) { + Thread.sleep(5); + } + JobGate.open(); + assertEquals("no contamination after expired chain hop exits", + Collections.emptyList(), JobGate.close()); + } finally { + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void trackingStructuresStayBoundedWithoutEndAndBehindLongRunningTasks() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + CountDownLatch sseStarted = new CountDownLatch(1); + CountDownLatch sseStop = new CountDownLatch(1); + try { + // Start 1 long-running task (simulating an SSE stream) on the pool inside a request window. + RequestGate.open(); + Object req = RequestGate.enter(); + try { + RequestGate.execute(pool, latchTask(sseStarted, sseStop)); + assertTrue(sseStarted.await(10, TimeUnit.SECONDS)); + + // Now execute & submit 200 short tasks on the SAME pool without calling END! + for (int i = 0; i < 200; i++) { + Future f = RequestGate.submit(pool, () -> 1); + assertEquals(Integer.valueOf(1), f.get(10, TimeUnit.SECONDS)); + CountDownLatch done = new CountDownLatch(1); + RequestGate.execute(pool, done::countDown); + assertTrue(done.await(10, TimeUnit.SECONDS)); + } + + // All 400 finished tasks must self-remove promptly even behind the live SSE task. + int execAfterCompleted = -1; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + execAfterCompleted = RequestGate.pendingByExecutorSize(pool); + if (execAfterCompleted == 1) { + break; + } + Thread.sleep(1); + } + assertEquals("all 400 finished tasks must self-remove immediately behind live SSE task", + 1, execAfterCompleted); + assertEquals("PENDING_BY_FUTURE must be empty after completed submits", + 0, RequestGate.pendingByFutureSize()); + + // Also submit & cancel 100 futures without calling END (exercises periodic sweep). + CountDownLatch holdStart = new CountDownLatch(1); + CountDownLatch holdRel = new CountDownLatch(1); + pool.execute(latchTask(holdStart, holdRel)); + assertTrue(holdStart.await(10, TimeUnit.SECONDS)); + for (int i = 0; i < 100; i++) { + Future cf = RequestGate.submit(pool, () -> { }); + assertTrue(cf.cancel(false)); + } + holdRel.countDown(); + } finally { + RequestGate.exit(req); + } + + // Inspect current Window's futures map & PENDING_BY_EXECUTOR before END sweep: + // periodic sweep (stride 64) must keep both bounded even without END. + Field currentField = RequestGate.class.getDeclaredField("current"); + currentField.setAccessible(true); + Object currentWindow = currentField.get(null); + Field futuresField = currentWindow.getClass().getDeclaredField("futures"); + futuresField.setAccessible(true); + Map futuresMap = (Map) futuresField.get(currentWindow); + int beforeSweepSize = futuresMap == null ? 0 : futuresMap.size(); + assertTrue("window futures map must stay bounded by sweep stride (64) without END, was " + beforeSweepSize, + beforeSweepSize <= 64); + + // Once running() sweeps the remaining cancelled futures, only the 1 live SSE task remains. + assertEquals("only the 1 live SSE task remains counted", 1, RequestGate.running()); + assertEquals("all cancelled futures swept from window map", 0, futuresMap.size()); + assertEquals("only the 1 live SSE task remains in PENDING_BY_EXECUTOR", + 1, RequestGate.pendingByExecutorSize(pool)); + assertEquals("all cancelled futures removed from PENDING_BY_FUTURE", + 0, RequestGate.pendingByFutureSize()); + + // Spring executor submit() futures cancelled before running must also release window permits (N7). + String schedClass = "org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler"; + byte[] schedWrapped = new ServerEntries(true).transform( + getClass().getClassLoader(), schedClass, null, null, generateSpringSubmitStandIn(schedClass)); + assertNotNull(schedWrapped); + Class loadedSched = new ByteLoader(getClass().getClassLoader()) + .define(schedClass.replace('/', '.'), schedWrapped); + Object schedInstance = loadedSched.getDeclaredConstructor().newInstance(); + RequestGate.open(); + Object reqSpring = RequestGate.enter(); + Future springFuture; + try { + springFuture = (Future) loadedSched.getMethod("submit", Runnable.class) + .invoke(schedInstance, (Runnable) () -> { }); + } finally { + RequestGate.exit(reqSpring); + } + assertEquals(1, RequestGate.running()); + assertTrue(springFuture.cancel(false)); + assertEquals("cancelled Spring submit() future must release window permit", 0, RequestGate.running()); + } finally { + sseStop.countDown(); + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void namedModuleClassViaClassDirsIsSkippedAndDoesNotThrowIllegalAccessError() throws Exception { + String spec = System.getProperty("java.specification.version"); + Assume.assumeTrue("JPMS named modules require Java 9+", + !spec.startsWith("1.") && Integer.parseInt(spec) >= 9); + + // 1. In-process check: boot-layer unreadable module locations must be populated and blocked. + Set unreadable = ServerEntries.unreadableModuleLocations(); + assertFalse("Java 9+ boot layer must have unreadable named module locations", unreadable.isEmpty()); + String anyBootLocation = unreadable.iterator().next(); + java.net.URL blockedUrl = anyBootLocation.startsWith("jrt:") + ? URI.create(anyBootLocation).toURL() + : new File(anyBootLocation).toURI().toURL(); + ProtectionDomain blockedPd = new ProtectionDomain( + new CodeSource(blockedUrl, (Certificate[]) null), null); + assertFalse("canAccessGate must reject unreadable named module location: " + anyBootLocation, + ServerEntries.canAccessGate(getClass().getClassLoader(), blockedPd)); + + // 2. End-to-end forked JVM check: run a real modular jar on --module-path with -javaagent:sdk.jar + // and KEPLOY_JAVA_CLASS_DIRS pointing to the modular jar. If ServerEntries rewrote the + // Executor.execute call site inside the named module, the JVM would throw IllegalAccessError! + File modJar = tmp.newFile("modapp-" + System.nanoTime() + ".jar"); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(modJar))) { + jos.putNextEntry(new ZipEntry("module-info.class")); + jos.write(generateModuleInfo("com.example.modapp")); + jos.closeEntry(); + jos.putNextEntry(new ZipEntry("com/example/modapp/ModCaller.class")); + jos.write(generateModularExecutorMain("com/example/modapp/ModCaller")); + jos.closeEntry(); + } + File sdkJar = tmp.newFile("keploy-sdk-mod-" + System.nanoTime() + ".jar"); + Manifest manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + manifest.getMainAttributes().putValue("Premain-Class", KeployDedupAgent.class.getName()); + manifest.getMainAttributes().putValue("Can-Retransform-Classes", "true"); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(sdkJar), manifest)) { + jos.putNextEntry(new ZipEntry("META-INF/keploy-test")); + jos.closeEntry(); + } + + List cmd = new ArrayList<>(); + cmd.add(new File(System.getProperty("java.home"), "bin/java").getPath()); + cmd.add("-javaagent:" + sdkJar.getPath()); + cmd.add("-cp"); + cmd.add(System.getProperty("java.class.path")); + cmd.add("--module-path"); + cmd.add(modJar.getPath()); + cmd.add("-m"); + cmd.add("com.example.modapp/com.example.modapp.ModCaller"); + + File outFile = tmp.newFile("modapp-out.log"); + ProcessBuilder pb = new ProcessBuilder(cmd).redirectErrorStream(true).redirectOutput(outFile); + Map env = pb.environment(); + env.keySet().removeIf(k -> k.startsWith("KEPLOY_") || k.equals("JAVA_TOOL_OPTIONS") + || k.equals("JDK_JAVA_OPTIONS") || k.equals("_JAVA_OPTIONS")); + env.put("KEPLOY_JAVA_CLASS_DIRS", modJar.getPath()); + env.put("KEPLOY_COVERAGE_ENDPOINT", "127.0.0.1:1"); + env.put("KEPLOY_JAVA_DEDUP_WARMUP_DISABLED", "true"); + Process proc = pb.start(); + assertTrue("modular JVM timed out", proc.waitFor(30, TimeUnit.SECONDS)); + String output = new String(Files.readAllBytes(outFile.toPath()), StandardCharsets.UTF_8); + assertEquals("modular JVM must exit 0 without IllegalAccessError: " + output, 0, proc.exitValue()); + // Positive control: prove KEPLOY_JAVA_CLASS_DIRS actually indexed the modular class, so + // it was the named-module guard (not an empty index) that prevented rewriting. + assertTrue("expected modular jar class to be indexed: " + output, + output.contains("fingerprinting the app's 1 classes")); + assertTrue("expected MOD_OK in output: " + output, output.contains("MOD_OK")); + assertFalse("must not throw IllegalAccessError: " + output, output.contains("IllegalAccessError")); + } + + @Test(timeout = 60000) + public void longLivedWorkerLoopStartedFromJobDoesNotKeepJobGateOpenForever() throws Exception { + JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(60); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch stop = new CountDownLatch(1); + AtomicReference runningWhileFresh = new AtomicReference<>(); + AtomicReference runningAfterExpiry = new AtomicReference<>(); + CountDownLatch checkExpiry = new CountDownLatch(1); + CountDownLatch checkedExpiry = new CountDownLatch(1); + + Runnable handed; + Object job = JobGate.enter(new Object(), "scheduled"); + try { + handed = RequestGate.hand(null, () -> { + runningWhileFresh.set(JobGate.running()); + started.countDown(); + try { + checkExpiry.await(10, TimeUnit.SECONDS); + runningAfterExpiry.set(JobGate.running()); + checkedExpiry.countDown(); + stop.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } finally { + JobGate.exit(job); + } + + Thread worker = new Thread(handed, "long-lived-worker"); + worker.start(); + try { + assertTrue(started.await(10, TimeUnit.SECONDS)); + assertNotNull("attributed while fresh", runningWhileFresh.get()); + + // Before expiry: window IS marked contaminated with job's name. + JobGate.open(); + List beforeExp = JobGate.close(); + assertEquals(1, beforeExp.size()); + assertFalse(beforeExp.get(0).startsWith("job-tail:")); + + // Wait past handedJobMaxNanos while the worker is STILL EXECUTING: + // overlapping windows must be marked with "job-tail:" + // until exit() actually runs! + Thread.sleep(100); + JobGate.open(); + List whileStillRunning = JobGate.close(); + assertEquals("still-running expired job must mark overlapping window with job-tail:: " + + whileStillRunning, 1, whileStillRunning.size()); + assertTrue(whileStillRunning.get(0), whileStillRunning.get(0).startsWith("job-tail:")); + + checkExpiry.countDown(); + assertTrue(checkedExpiry.await(10, TimeUnit.SECONDS)); + assertNull("worker thread JobGate.running() clears after expiry so chained hops stop", + runningAfterExpiry.get()); + } finally { + stop.countDown(); + worker.join(10000); + } + // Once the expired worker actually exits (exit() ran), subsequent windows are clean. + JobGate.open(); + assertEquals("clean once expired worker actually finishes", + Collections.emptyList(), JobGate.close()); + } + + @Test(timeout = 60000) + public void kafkaRabbitMqAndJmsListenerHooksMarkWindowContaminatedAndAdapterIsNotHooked() throws Exception { + ClassLoader loader = getClass().getClassLoader(); + ServerEntries entries = new ServerEntries(true); + + // MessagingMessageListenerAdapter must NOT be hooked (spurious duplicate removed). + String adapter = "org/springframework/kafka/listener/adapter/MessagingMessageListenerAdapter"; + assertNull("MessagingMessageListenerAdapter hook was removed", + entries.transform(loader, adapter, null, null, + generateListenerClass(adapter, Opcodes.ACC_PUBLIC, "onMessage", "(Ljava/lang/Object;)V", false))); + + // Kafka ListenerConsumer with realistic private method signature and nested invokeOnMessage call. + String kafka = "org/springframework/kafka/listener/KafkaMessageListenerContainer$ListenerConsumer"; + byte[] kafkaWrapped = entries.transform(loader, kafka, null, null, + generateListenerClass(kafka, Opcodes.ACC_PRIVATE, "invokeRecordListener", "(Ljava/lang/Object;)V", true)); + assertNotNull(kafkaWrapped); + Class kafkaClass = new ByteLoader(loader).define(kafka.replace('/', '.'), kafkaWrapped); + Object kafkaInstance = kafkaClass.getDeclaredConstructor().newInstance(); + Method kafkaInvoke = kafkaClass.getDeclaredMethod("invokeRecordListener", Object.class); + kafkaInvoke.setAccessible(true); + JobGate.open(); + kafkaInvoke.invoke(kafkaInstance, "record"); + List kafkaContam = JobGate.close(); + assertEquals(1, kafkaContam.size()); + assertTrue(kafkaContam.toString(), kafkaContam.get(0).startsWith("kafka:")); + + // RabbitMQ and JMS AbstractMessageListenerContainer.doInvokeListener (protected signature). + for (String container : new String[] { + "org/springframework/amqp/rabbit/listener/AbstractMessageListenerContainer", + "org/springframework/jms/listener/AbstractMessageListenerContainer" + }) { + byte[] wrapped = entries.transform(loader, container, null, null, + generateListenerClass(container, Opcodes.ACC_PROTECTED, "doInvokeListener", + "(Ljava/lang/Object;Ljava/lang/Object;)V", false)); + assertNotNull(container, wrapped); + Class cls = new ByteLoader(loader).define(container.replace('/', '.'), wrapped); + Object instance = cls.getDeclaredConstructor().newInstance(); + Method m = cls.getDeclaredMethod("doInvokeListener", Object.class, Object.class); + m.setAccessible(true); + JobGate.open(); + m.invoke(instance, "listener", "msg"); + List contam = JobGate.close(); + assertEquals(container, 1, contam.size()); + assertTrue(container + ": " + contam, contam.get(0).startsWith("listener:")); + } + } + + @Test(timeout = 60000) + public void unixControlSocketDeclaresProto3CapsMatchingLiveState() throws Exception { + File sockDir = tmp.newFolder("unix-caps"); + KeployDedupAgent.controlSocketPath = new File(sockDir, "control.sock").getAbsolutePath(); + KeployDedupAgent.dataSocketPath = new File(sockDir, "data.sock").getAbsolutePath(); + System.clearProperty(ENDPOINT_PROPERTY); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + jacoco = new FakeJacoco(); + System.setProperty(JACOCO_PORT_PROPERTY, String.valueOf(jacoco.server.getLocalPort())); + + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + ServerEntries.restoreUncounted(Collections.emptySet()); + ServerEntries.setHookStatusForTests(false, false, false); + assertTrue(KeployDedupAgent.start()); + + String reply1 = sendUnix(KeployDedupAgent.controlSocketPath, "START ts/u1"); + assertEquals("ACK proto=3 caps=windowCut=true,contaminated=true,classMismatch=true," + + "background=false,ackId=true,asyncExecutors=true,listenerContamination=true\n", reply1); + assertTrue("unix reply must stay well under 1024 bytes", reply1.length() < 1024); + assertFalse("caps token must contain no spaces", + reply1.trim().substring("ACK proto=3 ".length()).contains(" ")); + + // Flip KEPLOY_JAVA_ASYNC_CALLSITES=off and verify live caps update on next command. + System.setProperty(ASYNC_CALLSITES_PROPERTY, "off"); + String reply2 = sendUnix(KeployDedupAgent.controlSocketPath, "START ts/u2"); + assertEquals("ACK proto=3 caps=windowCut=true,contaminated=true,classMismatch=true," + + "background=false,ackId=true,asyncExecutors=false,listenerContamination=true\n", reply2); + System.clearProperty(ASYNC_CALLSITES_PROPERTY); + } + + @Test(timeout = 60000) + public void completableFutureDependentStagesAndAsyncInstanceMethodsAreTrackedAndUntrackedSitesContaminate() + throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); + try { + // 1. Fast supplier with slow synchronous dependent: supplyAsync(fast, pool).thenAccept(slowAudit) + // registered before completion MUST hold window permit until slowAudit finishes! + CountDownLatch supplierDone = new CountDownLatch(1); + CountDownLatch auditStarted = new CountDownLatch(1); + CountDownLatch auditRelease = new CountDownLatch(1); + AtomicInteger runningDuringAudit = new AtomicInteger(-1); + + RequestGate.open("cf-dep", null); + Object req = RequestGate.enter(); + CompletableFuture chain; + CountDownLatch gateSupplier = new CountDownLatch(1); + try { + CompletableFuture base = RequestGate.supplyAsync(() -> { + try { + gateSupplier.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + supplierDone.countDown(); + return "ok"; + }, pool); + chain = base.thenAccept(v -> { + runningDuringAudit.set(RequestGate.running()); + auditStarted.countDown(); + try { + auditRelease.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } finally { + RequestGate.exit(req); + } + // Release supplier AFTER RequestGate.exit(req) so audit deterministically + // observes count == 1 (only the supplier's deferred permit, never req + permit). + gateSupplier.countDown(); + assertTrue("supplier completed", supplierDone.await(10, TimeUnit.SECONDS)); + assertTrue("dependent audit stage started", auditStarted.await(10, TimeUnit.SECONDS)); + assertEquals("window count must stay 1 while dependent thenAccept(audit) runs", + 1, runningDuringAudit.get()); + assertEquals("window still open while audit runs", 1, RequestGate.running()); + assertFalse("END must cut if audit outruns wait", + RequestGate.await(TimeUnit.MILLISECONDS.toNanos(30))); + auditRelease.countDown(); + chain.get(10, TimeUnit.SECONDS); + + // 2. Chained *Async instance methods (thenApplyAsync, thenAcceptAsync, thenRunAsync, + // thenComposeAsync, thenCombineAsync, handleAsync, whenCompleteAsync). + RequestGate.open("cf-async-stages", null); + CountDownLatch stageStarted = new CountDownLatch(1); + CountDownLatch stageRelease = new CountDownLatch(1); + Object req2 = RequestGate.enter(); + CompletableFuture chained; + try { + CompletableFuture seed = CompletableFuture.completedFuture("seed"); + CompletableFuture s1 = RequestGate.thenApplyAsync(seed, x -> { + stageStarted.countDown(); + try { + stageRelease.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return x + "+1"; + }, pool); + chained = RequestGate.thenComposeAsync(s1, + x -> CompletableFuture.completedFuture(x + "+2"), pool); + } finally { + RequestGate.exit(req2); + } + assertTrue(stageStarted.await(10, TimeUnit.SECONDS)); + assertTrue("chained *Async stages keep window open", RequestGate.running() >= 1); + stageRelease.countDown(); + assertEquals("seed+1+2", chained.get(10, TimeUnit.SECONDS)); + assertTrue("chained *Async stages drain cleanly", + RequestGate.await(TimeUnit.SECONDS.toNanos(5))); + + // 3. Upstream failure releases *Async stage permit immediately (no leak!). + RequestGate.open("cf-upstream-fail", null); + Object req3 = RequestGate.enter(); + CompletableFuture failed = new CompletableFuture<>(); + CompletableFuture downstream; + try { + downstream = RequestGate.thenApplyAsync(failed, s -> s + "!", pool); + } finally { + RequestGate.exit(req3); + } + assertEquals(1, RequestGate.running()); + failed.completeExceptionally(new RuntimeException("boom")); + assertTrue("downstream completed exceptionally", downstream.isCompletedExceptionally()); + assertTrue("upstream failure releases permit without waiting", + RequestGate.await(TimeUnit.SECONDS.toNanos(2))); + + // 4. Untracked async submission sites (schedule, invokeAny, Thread.start) contaminate + // window without changing app behavior. + RequestGate.open("untracked-sites", null); + Object req4 = RequestGate.enter(); + CountDownLatch threadRan = new CountDownLatch(1); + try { + ScheduledFuture sf = RequestGate.schedule(stpe, () -> { }, 1, TimeUnit.MILLISECONDS); + sf.get(5, TimeUnit.SECONDS); + String any = RequestGate.invokeAny(pool, Collections.>singletonList(() -> "win")); + assertEquals("win", any); + Thread t = new Thread(threadRan::countDown); + RequestGate.startThread(t); + t.join(5000); + } finally { + RequestGate.exit(req4); + } + assertTrue(threadRan.await(5, TimeUnit.SECONDS)); + RequestGate.WindowOutcome out4 = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("schedule contaminated: " + out4.contaminations, + out4.contaminations.contains("untracked-async:schedule")); + assertTrue("invokeAny contaminated: " + out4.contaminations, + out4.contaminations.contains("untracked-async:invokeAny")); + assertTrue("thread-start contaminated: " + out4.contaminations, + out4.contaminations.contains("untracked-async:thread-start")); + } finally { + pool.shutdownNow(); + stpe.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void pendingByFutureDoesNotLeakSelfReferencingCancellableJob() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + CountDownLatch blockStart = new CountDownLatch(1); + CountDownLatch blockRel = new CountDownLatch(1); + try { + // Block the single worker so job sits queued and actually enters PENDING_BY_FUTURE. + pool.execute(latchTask(blockStart, blockRel)); + assertTrue(blockStart.await(10, TimeUnit.SECONDS)); + + RequestGate.open("leak-check", null); + Object req = RequestGate.enter(); + WeakReference weakJob; + try { + SelfReferencingJob job = new SelfReferencingJob(); + weakJob = new WeakReference<>(job); + job.future = RequestGate.submit(pool, job); + assertEquals("queued submit must actually populate PENDING_BY_FUTURE", + 1, RequestGate.pendingByFutureSize()); + blockRel.countDown(); + job.future.get(10, TimeUnit.SECONDS); + job = null; + } finally { + blockRel.countDown(); + RequestGate.exit(req); + } + assertTrue(RequestGate.await(TimeUnit.SECONDS.toNanos(5))); + assertEquals("PENDING_BY_FUTURE must be empty immediately after job ran", + 0, RequestGate.pendingByFutureSize()); + + for (int i = 0; i < 40 && weakJob.get() != null; i++) { + System.gc(); + Thread.sleep(25); + } + assertNull("self-referencing job.future = exec.submit(job) must be GC'd with no leak", + weakJob.get()); + } finally { + blockRel.countDown(); + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void referenceQueueReleasesAbandonedHandPermitOnGc() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + CountDownLatch blockStart = new CountDownLatch(1); + CountDownLatch blockRel = new CountDownLatch(1); + try { + pool.execute(latchTask(blockStart, blockRel)); + assertTrue(blockStart.await(10, TimeUnit.SECONDS)); + + RequestGate.open("abandoned-hand", null); + Object req = RequestGate.enter(); + try { + RequestGate.execute(pool, () -> { }); + } finally { + RequestGate.exit(req); + } + assertEquals(1, RequestGate.running()); + + // Simulate unrewritten getQueue().clear(): Hand is dropped without running or drop(). + pool.getQueue().clear(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (RequestGate.running() > 0 && System.nanoTime() < deadline) { + System.gc(); + Thread.sleep(25); + } + assertEquals("ReferenceQueue cleanup must release permit for GC'd abandoned Hand", + 0, RequestGate.running()); + } finally { + blockRel.countDown(); + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void unarmedKeployAbsentIsNoOpAndMarksArmedMidFlightWhileUnarmedWorkRemainsInFlight() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + long savedTailWindow = RequestGate.untrackedTailWindowNanos; + try { + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(30); + RequestGate.disarm(); + assertFalse(RequestGate.isArmed()); + + // While unarmed: RequestGate.enter and JobGate.enter return the same static + // zero-allocation sentinel token, tasks are NOT wrapped, and JobGate has 0 active runs. + Object reqTok = RequestGate.enter(); + assertTrue("unarmed RequestGate.enter returns static sentinel", RequestGate.isUnarmedToken(reqTok)); + Runnable raw = () -> { }; + assertSame("unarmed RequestGate.hand must not wrap", raw, RequestGate.hand(pool, raw)); + Object jobTok = JobGate.enter(new Object(), "quartz"); + assertSame("unarmed JobGate.enter returns the same zero-allocation sentinel", reqTok, jobTok); + assertEquals("unarmed JobGate has zero active runs", 0, JobGate.activeRunCount()); + assertEquals("unarmed PENDING_BY_FUTURE stays 0", 0, RequestGate.pendingByFutureSize()); + RequestGate.exit(reqTok); + + // Long-running job started BEFORE arming stays in flight across Tests 1 AND 2 -> + // BOTH Test 1 AND Test 2 MUST be marked "armed-mid-flight"! + RequestGate.open("first-armed", null); + assertTrue(RequestGate.isArmed()); + RequestGate.WindowOutcome first = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals(Collections.singletonList("armed-mid-flight"), first.contaminations); + + RequestGate.open("second-armed-still-in-flight", null); + RequestGate.WindowOutcome second = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals("in-flight unarmed job must keep marking subsequent windows armed-mid-flight", + Collections.singletonList("armed-mid-flight"), second.contaminations); + + // Once the pre-arming job finally exits (and the short unarmed hand-off tail elapses), Test 3 is clean. + JobGate.exit(jobTok); + assertEquals(0L, RequestGate.unarmedInFlight()); + Thread.sleep(50); + RequestGate.open("third-armed-after-exit", null); + RequestGate.WindowOutcome third = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals(Collections.emptyList(), third.contaminations); + } finally { + RequestGate.untrackedTailWindowNanos = savedTailWindow; + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void listenerAttributionExtractsTopicsQueuesDestinationAndCachesPerInstance() { + KafkaContainerStub kafka = new KafkaContainerStub(new String[] {"orders", "payments"}, + new AdapterStub(new OrdersBean())); + String k1 = JobGate.name(kafka, "kafka"); + String k2 = JobGate.name(kafka, "kafka"); + assertSame("cached listener name must return identical String instance", k1, k2); + assertEquals("kafka:orders,payments@" + OrdersBean.class.getName(), k1); + + AmqpContainerStub amqp = new AmqpContainerStub(new String[] {"q.billing"}, new AdapterStub(new BillingBean())); + String a1 = JobGate.name(amqp, "listener"); + assertSame(a1, JobGate.name(amqp, "listener")); + assertEquals("listener:q.billing@" + BillingBean.class.getName(), a1); + + JmsContainerStub jms = new JmsContainerStub("topic.audit", new AuditBean()); + String j1 = JobGate.name(jms, "listener"); + assertSame(j1, JobGate.name(jms, "listener")); + assertEquals("listener:topic.audit@" + AuditBean.class.getName(), j1); + } + + @Test(timeout = 60000) + public void shadedAndRelocatedPackagesAreSkippedOnlyInPrefixModeAndVendorIsNotSkipped() { + ServerEntries prefixed = new ServerEntries(true, Collections.emptySet(), "com/acme/"); + assertTrue(prefixed.shouldRewriteExecutorCalls("com/acme/service/OrderService")); + assertTrue("app package /vendor/ must NOT be skipped", + prefixed.shouldRewriteExecutorCalls("com/acme/vendor/VendorService")); + assertTrue("app package /shadow/ must NOT be skipped", + prefixed.shouldRewriteExecutorCalls("com/acme/shadow/ShadowService")); + assertFalse(prefixed.shouldRewriteExecutorCalls("com/acme/shaded/io/grpc/Channel")); + assertFalse(prefixed.shouldRewriteExecutorCalls("com/acme/internal/shaded/Foo")); + assertFalse(prefixed.shouldRewriteExecutorCalls("com/acme/relocated/netty/Loop")); + assertFalse(prefixed.shouldRewriteExecutorCalls("com/acme/repackaged/Pool")); + + // In exact appClasses index mode, shaded filter does NOT drop indexed app classes. + ServerEntries indexed = new ServerEntries(true, + new HashSet<>(Arrays.asList("com/acme/shaded/AppClass", "com/acme/vendor/VendorService")), null); + assertTrue(indexed.shouldRewriteExecutorCalls("com/acme/shaded/AppClass")); + assertTrue(indexed.shouldRewriteExecutorCalls("com/acme/vendor/VendorService")); + } + + @Test(timeout = 60000) + public void untrackedTailsJobDeferredCfSpringSubclassFailClosedAndBytecodeForms() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + long savedTailWindow = RequestGate.untrackedTailWindowNanos; + try { + // Untracked async hand-off marks current window AND immediately following window + // "tail:" until untrackedTailWindowNanos elapses. + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(120); + RequestGate.open("untracked-tail-1", null); + Object req1 = RequestGate.enter(); + try { + RequestGate.noteUntrackedAsync("untracked-executor:com.acme.CustomPool"); + } finally { + RequestGate.exit(req1); + } + RequestGate.WindowOutcome out1 = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals(Collections.singletonList("untracked-executor:com.acme.CustomPool"), out1.contaminations); + + RequestGate.open("untracked-tail-next", null); + RequestGate.WindowOutcome out2 = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals("next window immediately after untracked hand-off must carry tail", + Collections.singletonList("tail:untracked-tail-1"), out2.contaminations); + + Thread.sleep(160); + RequestGate.open("untracked-tail-after-expiry", null); + RequestGate.WindowOutcome out3 = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals("clean after untracked tail window expires", + Collections.emptyList(), out3.contaminations); + + // Job-originated CompletableFuture.supplyAsync().thenAccept(audit) keeps JobGate run + // active until audit finishes, and job-originated unknown executor flags contamination! + CountDownLatch gateSupplier = new CountDownLatch(1); + CountDownLatch auditEntered = new CountDownLatch(1); + CountDownLatch auditRelease = new CountDownLatch(1); + RequestGate.open("job-cf-arm", null); + JobGate.open(); + Object jt = JobGate.enter(new Object(), "scheduled"); + CompletableFuture jobChain; + try { + CompletableFuture base = RequestGate.supplyAsync(() -> { + try { + gateSupplier.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return "job-val"; + }, pool); + jobChain = base.thenAccept(v -> { + auditEntered.countDown(); + try { + auditRelease.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } finally { + JobGate.exit(jt); + } + JobGate.close(); + gateSupplier.countDown(); + assertTrue("job CF audit entered", auditEntered.await(10, TimeUnit.SECONDS)); + // While audit is still running AFTER supplier returned, JobGate MUST still be active! + JobGate.open(); + List duringAudit = JobGate.close(); + assertEquals("job CF dependent stage must remain attributed in JobGate: " + duringAudit, + 1, duringAudit.size()); + auditRelease.countDown(); + jobChain.get(10, TimeUnit.SECONDS); + long jobDoneDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (JobGate.activeRunCount() > 0 && System.nanoTime() < jobDoneDeadline) { + Thread.sleep(5); + } + assertEquals("JobGate run exits once job CF dependent completes", 0, JobGate.activeRunCount()); + + // Job-originated unknown executor flags active JobGate window AND next RequestGate window! + Object unknownExec = new Object(); + JobGate.open(); + Object jt2 = JobGate.enter(new Object(), "quartz"); + try { + Runnable task = () -> { }; + assertSame("unknown executor stays unwrapped for job", task, RequestGate.hand(unknownExec, task)); + } finally { + JobGate.exit(jt2); + } + List jobContams = JobGate.close(); + assertTrue("job window must contain untracked-executor: " + jobContams, + jobContams.contains("untracked-executor:java.lang.Object")); + RequestGate.open("after-job-unknown", null); + RequestGate.WindowOutcome afterJobUnknown = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("next request window carries tail from job untracked hand-off: " + + afterJobUnknown.contaminations, + afterJobUnknown.contaminations.contains("tail:untracked-executor:java.lang.Object")); + + // App subclass of ThreadPoolTaskExecutor overriding execute() MUST fail closed, + // and arbitrary non-Spring class with getThreadPoolExecutor() MUST fail closed! + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor overridingSpring = + new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor() { + private static final long serialVersionUID = 1L; + + @Override + public void execute(Runnable task) { + super.execute(task); + } + }; + overridingSpring.initialize(); + try { + assertTrue("Spring subclass overriding execute() must fail closed", + OrderedPools.orders(overridingSpring)); + } finally { + overridingSpring.shutdown(); + } + Object nonSpringWithPoolMethod = new Object() { + @SuppressWarnings("unused") + public ThreadPoolExecutor getThreadPoolExecutor() { + return pool; + } + }; + assertTrue("non-Spring class with getThreadPoolExecutor() must fail closed", + OrderedPools.orders(nonSpringWithPoolMethod)); + + // Non-Thread start() must NOT false-positive, while Thread subclass start() DOES flag. + RequestGate.disarm(); + RequestGate.open("non-thread-start-check", null); + Object reqStart = RequestGate.enter(); + try { + RequestGate.noteIfThread(new Object()); + RequestGate.noteIfThread(null); + } finally { + RequestGate.exit(reqStart); + } + assertEquals("non-Thread start() must not contaminate", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Direct raw KafkaConsumer.poll in an app class flips hasUnhookedConsumer()! + ServerEntries.setHookStatusForTests(false, false, false, false); + assertFalse(ServerEntries.hasUnhookedConsumer()); + ClassWriter kafkaApp = new ClassWriter(ClassWriter.COMPUTE_MAXS); + kafkaApp.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "com/acme/RawKafkaPoller", null, + "java/lang/Object", null); + emitDefaultCtor(kafkaApp); + MethodVisitor pollMv = kafkaApp.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, + "pollOnce", "(Lorg/apache/kafka/clients/consumer/KafkaConsumer;)V", null, null); + pollMv.visitCode(); + pollMv.visitVarInsn(Opcodes.ALOAD, 0); + pollMv.visitLdcInsn(100L); + pollMv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/apache/kafka/clients/consumer/KafkaConsumer", + "poll", "(J)Ljava/lang/Object;", false); + pollMv.visitInsn(Opcodes.POP); + pollMv.visitInsn(Opcodes.RETURN); + pollMv.visitMaxs(3, 1); + pollMv.visitEnd(); + kafkaApp.visitEnd(); + ServerEntries.wrapExecutorCalls(kafkaApp.toByteArray()); + assertTrue("direct KafkaConsumer.poll in app class must flag unhooked consumer", + ServerEntries.hasUnhookedConsumer()); + ServerEntries.setHookStatusForTests(false, false, false, false); + } finally { + RequestGate.untrackedTailWindowNanos = savedTailWindow; + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void minimalStageNoUoeMinimalFutureTrackedAbandonedStageGcAndConsumerScanChecks() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); + long savedTailWindow = RequestGate.untrackedTailWindowNanos; + long savedMaxLingering = RequestGate.maxLingeringNanos; + long savedJobMax = JobGate.handedJobMaxNanos; + try { + // JDK 9+ MinimalStage (completedStage / failedStage / minimalCompletionStage) + // throws UnsupportedOperationException on isDone(). Rewritten plain dependents + // MUST NEVER throw UOE either outside or inside a request! + RequestGate.open("minimal-stage-check", null); + try { + Method completedStageM = CompletableFuture.class.getMethod("completedStage", Object.class); + Method failedStageM = CompletableFuture.class.getMethod("failedStage", Throwable.class); + Method minimalStageM = CompletableFuture.class.getMethod("minimalCompletionStage"); + + @SuppressWarnings("unchecked") + java.util.concurrent.CompletionStage cs = + (java.util.concurrent.CompletionStage) completedStageM.invoke(null, "hi"); + // Outside a request: + assertEquals("hi!", RequestGate.stageThenApply(cs, s -> s + "!").toCompletableFuture().get()); + CompletableFuture base = CompletableFuture.completedFuture("a"); + assertEquals("a+hi", RequestGate.thenCombine(base, cs, (a, b) -> a + "+" + b).get()); + + // Inside an active armed request: + Object req = RequestGate.enter(); + try { + assertEquals("hi?", RequestGate.stageThenApply(cs, s -> s + "?").toCompletableFuture().get()); + CompletableFuture incomplete = new CompletableFuture<>(); + CompletableFuture combined = RequestGate.thenCombine(incomplete, cs, (a, b) -> a + ":" + b); + incomplete.complete("ok"); + assertEquals("ok:hi", combined.get(5, TimeUnit.SECONDS)); + + @SuppressWarnings("unchecked") + java.util.concurrent.CompletionStage failed = + (java.util.concurrent.CompletionStage) failedStageM.invoke( + null, new RuntimeException("boom")); + assertEquals("recovered", RequestGate.stageExceptionally(failed, e -> "recovered") + .toCompletableFuture().get(5, TimeUnit.SECONDS)); + + CompletableFuture live = new CompletableFuture<>(); + @SuppressWarnings("unchecked") + java.util.concurrent.CompletionStage minimal = + (java.util.concurrent.CompletionStage) minimalStageM.invoke(live); + java.util.concurrent.CompletionStage mapped = + RequestGate.stageThenApply(minimal, s -> s + "-done"); + live.complete("val"); + assertEquals("val-done", mapped.toCompletableFuture().get(5, TimeUnit.SECONDS)); + } finally { + RequestGate.exit(req); + } + RequestGate.WindowOutcome minimalStageOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("MinimalStage dependents must drain cleanly", minimalStageOut.drained); + assertEquals("MinimalStage must not spuriously contaminate: " + minimalStageOut.contaminations, + Collections.emptyList(), minimalStageOut.contaminations); + } catch (NoSuchMethodException java8Skip) { + // Java 8 has no completedStage/minimalCompletionStage. + } + + // CompletableFuture subclass inheriting thenAccept/whenComplete (like JDK HttpClient's + // MinimalFuture) IS tracked instead of flagged; subclass overriding thenAccept fails closed! + class MinimalFutureLike extends CompletableFuture { + @SuppressWarnings("unused") + public CompletableFuture newIncompleteFuture() { + return new MinimalFutureLike(); + } + } + class OverridingCf extends CompletableFuture { + @Override + public CompletableFuture thenAccept(java.util.function.Consumer action) { + return super.thenAccept(action); + } + } + RequestGate.open("minimal-future-sub", null); + Object reqMinimal = RequestGate.enter(); + MinimalFutureLike httpCf = new MinimalFutureLike<>(); + AtomicBoolean auditRan = new AtomicBoolean(); + try { + RequestGate.thenAccept(httpCf, v -> auditRan.set(true)); + assertEquals("MinimalFuture-like subclass must be tracked", 2, RequestGate.running()); + } finally { + RequestGate.exit(reqMinimal); + } + assertEquals("window still waits for MinimalFuture-like dependent", 1, RequestGate.running()); + httpCf.complete("200"); + assertTrue(auditRan.get()); + RequestGate.WindowOutcome minimalOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue(minimalOut.drained); + assertEquals("MinimalFuture-like dependent must NOT contaminate", + Collections.emptyList(), minimalOut.contaminations); + + RequestGate.open("override-cf-sub", null); + Object reqOverride = RequestGate.enter(); + try { + RequestGate.thenAccept(new OverridingCf(), v -> { }); + } finally { + RequestGate.exit(reqOverride); + } + RequestGate.WindowOutcome overrideOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("CF subclass overriding thenAccept must fail closed: " + overrideOut.contaminations, + overrideOut.contaminations.stream().anyMatch(s -> s.startsWith("untracked-executor:"))); + + // Abandoned plain dependent whose future is GC'd releases its permit via DEAD_HANDS, + // AND a stuck strongly-referenced future stops poisoning windows after maxLingeringNanos. + RequestGate.disarm(); + RequestGate.open("abandoned-cf-gc", null); + Object reqGc = RequestGate.enter(); + try { + CompletableFuture abandoned = new CompletableFuture<>(); + RequestGate.thenAccept(abandoned, v -> { }); + assertEquals(2, RequestGate.running()); + abandoned = null; + } finally { + RequestGate.exit(reqGc); + } + long gcDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (RequestGate.running() > 0 && System.nanoTime() < gcDeadline) { + System.gc(); + Thread.sleep(20); + } + assertEquals("GC'd abandoned plain-dependent future must release window permit", + 0, RequestGate.running()); + + RequestGate.maxLingeringNanos = TimeUnit.MILLISECONDS.toNanos(100); + CompletableFuture neverCompletes = new CompletableFuture<>(); + RequestGate.open("stuck-cf", null); + Object reqStuck = RequestGate.enter(); + try { + RequestGate.thenAccept(neverCompletes, v -> { }); + } finally { + RequestGate.exit(reqStuck); + } + assertFalse("stuck future cuts window", RequestGate.await(TimeUnit.MILLISECONDS.toNanos(30))); + RequestGate.open("while-stuck", null); + assertEquals(Collections.singletonList("tail:stuck-cf"), + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(50), true).contaminations); + Thread.sleep(140); + RequestGate.open("after-stuck-bound", null); + assertEquals("stuck lingering window must stop poisoning after maxLingeringNanos", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(50), true).contaminations); + RequestGate.maxLingeringNanos = savedMaxLingering; + + // Runtime receiver check for hooked Spring executor vs custom TaskExecutor + + // TaskScheduler.schedule / Timer.schedule / ForkJoinPool.execute(ForkJoinTask) / Guava. + RequestGate.disarm(); + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor springExec = + new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor(); + springExec.initialize(); + try { + ServerEntries.markSpringExecutorHookedForTests(springExec.getClass().getName()); + RequestGate.open("spring-hooked-ok", null); + Object reqSp = RequestGate.enter(); + try { + RequestGate.noteIfUntrackedExecutor(springExec); + } finally { + RequestGate.exit(reqSp); + } + assertEquals("hooked & verified Spring executor must NOT false-positive", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + RequestGate.open("custom-task-exec", null); + Object reqCustom = RequestGate.enter(); + org.springframework.core.task.TaskExecutor customTe = r -> r.run(); + try { + RequestGate.noteIfUntrackedExecutor(customTe); + } finally { + RequestGate.exit(reqCustom); + } + RequestGate.WindowOutcome customOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("unhooked TaskExecutor impl must be flagged by runtime class: " + + customOut.contaminations, + customOut.contaminations.contains("untracked-executor:" + customTe.getClass().getName())); + } finally { + springExec.shutdown(); + } + + // schedule(r, delay, unit) extends untracked tail window by delay! + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(50); + RequestGate.open("sched-delay-check", null); + Object reqSched = RequestGate.enter(); + try { + RequestGate.schedule(stpe, () -> { }, 300, TimeUnit.MILLISECONDS); + } finally { + RequestGate.exit(reqSched); + } + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + Thread.sleep(100); // past 50ms base window, still inside 350ms delay-extended tail! + RequestGate.open("sched-during-delay", null); + assertEquals("scheduled delay must keep next window contaminated past base tail", + Collections.singletonList("tail:sched-delay-check"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.untrackedTailWindowNanos = savedTailWindow; + + // Expired job hop that fans out to an unverified executor flags job-tail on active & next window, + // and on a verified executor propagates expired Attribution through gen 2 & gen 3! + RequestGate.disarm(); + JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(40); + RequestGate.open("expired-hop-arm", null); + Object unknownExecHop = new Object(); + Runnable hop1; + Object jTok = JobGate.enter(new Object(), "scheduled"); + try { + hop1 = RequestGate.hand(pool, () -> { + try { + Thread.sleep(70); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + assertNull("hop1 expired so running() is null", JobGate.running()); + assertNotNull("hop1 expiredRunningName() still knows job", JobGate.expiredRunningName()); + JobGate.open(); + RequestGate.hand(unknownExecHop, () -> { }); + }); + } finally { + JobGate.exit(jTok); + } + hop1.run(); + List expiredJobContams = JobGate.close(); + assertTrue("expired hop unverified fan-out must mark JobGate window job-tail: " + expiredJobContams, + expiredJobContams.stream().anyMatch(s -> s.startsWith("job-tail:"))); + RequestGate.open("expired-hop-next", null); + RequestGate.WindowOutcome expiredHopNext = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("expired hop unverified fan-out must mark next RequestGate window tail:job-tail: " + + expiredHopNext.contaminations, + expiredHopNext.contaminations.stream().anyMatch(s -> s.startsWith("tail:job-tail:"))); + + // Unarmed hand-off made while unarmed keeps marking armed-mid-flight within tail window! + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(200); + Object unarmedReq = RequestGate.enter(); + CountDownLatch unarmedDone = new CountDownLatch(1); + RequestGate.execute(pool, unarmedDone::countDown); + RequestGate.exit(unarmedReq); + assertTrue(unarmedDone.await(5, TimeUnit.SECONDS)); + RequestGate.open("unarmed-tail-w1", null); + assertEquals(Collections.singletonList("armed-mid-flight"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.open("unarmed-tail-w2", null); + assertEquals("unarmed hand-off keeps marking armed-mid-flight within tail window", + Collections.singletonList("armed-mid-flight"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.untrackedTailWindowNanos = savedTailWindow; + + // Expanded unhooked consumers + read-only scan works even with empty appClasses! + for (String consumerCls : new String[] { + "org/springframework/data/redis/listener/RedisMessageListenerContainer", + "software/amazon/awssdk/services/sqs/DefaultSqsAsyncClient", + "org/apache/pulsar/client/impl/ConsumerImpl", + "com/google/cloud/pubsub/v1/Subscriber" + }) { + ServerEntries.setHookStatusForTests(false, false, false, false); + new ServerEntries(true).transform(getClass().getClassLoader(), consumerCls, null, null, + generatePlainClass(consumerCls)); + assertTrue(consumerCls + " must flip hasUnhookedConsumer", + ServerEntries.hasUnhookedConsumer()); + } + // Read-only raw JMS setMessageListener scan with NO appClasses / callsites off: + ServerEntries.setHookStatusForTests(false, false, false, false); + ClassWriter jmsApp = new ClassWriter(ClassWriter.COMPUTE_MAXS); + jmsApp.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "com/acme/RawJmsApp", null, "java/lang/Object", null); + emitDefaultCtor(jmsApp); + MethodVisitor jmsMv = jmsApp.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, + "wire", "(Ljavax/jms/MessageConsumer;Ljava/lang/Object;)V", null, null); + jmsMv.visitCode(); + jmsMv.visitVarInsn(Opcodes.ALOAD, 0); + jmsMv.visitVarInsn(Opcodes.ALOAD, 1); + jmsMv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "javax/jms/MessageConsumer", + "setMessageListener", "(Ljava/lang/Object;)V", true); + jmsMv.visitInsn(Opcodes.RETURN); + jmsMv.visitMaxs(2, 2); + jmsMv.visitEnd(); + jmsApp.visitEnd(); + assertNull("callsites-off ServerEntries must not modify bytecode", + new ServerEntries(true, Collections.emptySet(), null) + .transform(getClass().getClassLoader(), "com/acme/RawJmsApp", null, null, + jmsApp.toByteArray())); + assertTrue("raw JMS setMessageListener must be detected even with callsites off", + ServerEntries.hasUnhookedConsumer()); + ServerEntries.setHookStatusForTests(false, false, false, false); + + // Exact indexed app classes under org/springframework/samples/... must NOT be dropped! + ServerEntries petclinic = new ServerEntries(true, + Collections.singleton("org/springframework/samples/petclinic/owner/OwnerController"), null); + assertTrue("indexed PetClinic class under org/springframework/samples must be rewritten", + petclinic.shouldRewriteExecutorCalls( + "org/springframework/samples/petclinic/owner/OwnerController")); + } finally { + RequestGate.untrackedTailWindowNanos = savedTailWindow; + RequestGate.maxLingeringNanos = savedMaxLingering; + JobGate.handedJobMaxNanos = savedJobMax; + pool.shutdownNow(); + stpe.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void executingPastMaxLingeringLiveUntrackedHandlesMultiHopExpiredJobAndBytecodeFlagSites() + throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); + java.util.concurrent.ForkJoinPool fjp = new java.util.concurrent.ForkJoinPool(2); + java.util.Timer timer = new java.util.Timer(true); + long savedTailWindow = RequestGate.untrackedTailWindowNanos; + long savedMaxLingering = RequestGate.maxLingeringNanos; + long savedJobMax = JobGate.handedJobMaxNanos; + try { + // Actively executing task running PAST maxLingeringNanos MUST keep marking tail: + // until it actually exits, then clear cleanly! + RequestGate.disarm(); + RequestGate.maxLingeringNanos = TimeUnit.MILLISECONDS.toNanos(50); + CountDownLatch taskStarted = new CountDownLatch(1); + CountDownLatch taskRelease = new CountDownLatch(1); + RequestGate.open("exec-active", null); + Object reqActive = RequestGate.enter(); + try { + RequestGate.execute(pool, latchTask(taskStarted, taskRelease)); + } finally { + RequestGate.exit(reqActive); + } + assertTrue(taskStarted.await(5, TimeUnit.SECONDS)); + assertFalse("cut while task executes", RequestGate.await(TimeUnit.MILLISECONDS.toNanos(20))); + Thread.sleep(100); // Well past 50ms maxLingeringNanos while task is STILL executing! + RequestGate.open("exec-past-cap", null); + assertEquals("actively executing task past maxLingeringNanos must STILL flag tail", + Collections.singletonList("tail:exec-active"), + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(50), true).contaminations); + taskRelease.countDown(); + long drainDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (RequestGate.pendingByExecutorSize(pool) > 0 && System.nanoTime() < drainDeadline) { + Thread.sleep(5); + } + Thread.sleep(20); + RequestGate.open("exec-after-exit", null); + assertEquals("clean after actively executing task finishes", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(50), true).contaminations); + RequestGate.maxLingeringNanos = savedMaxLingering; + + // Untracked Thread.start() and periodic ScheduledFuture stay flagged past base tail + // for as long as Thread.isAlive() / !ScheduledFuture.isDone()! + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(30); + CountDownLatch rawStarted = new CountDownLatch(1); + CountDownLatch rawRelease = new CountDownLatch(1); + Thread rawThread = new Thread(latchTask(rawStarted, rawRelease), "live-raw-thread"); + rawThread.setDaemon(true); + RequestGate.open("live-thread", null); + Object reqT = RequestGate.enter(); + try { + RequestGate.startThread(rawThread); + } finally { + RequestGate.exit(reqT); + } + assertTrue(rawStarted.await(5, TimeUnit.SECONDS)); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + // Consume one-time report first so the next window depends strictly on Thread.isAlive(). + RequestGate.open("live-thread-consume-once", null); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + Thread.sleep(80); // Past 30ms base tail while rawThread.isAlive() is STILL true! + RequestGate.open("live-thread-still-alive", null); + assertEquals("live raw thread must keep marking tail past base window", + Collections.singletonList("tail:live-thread"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + rawRelease.countDown(); + rawThread.join(5000); + RequestGate.open("live-thread-dead", null); + assertEquals("clean once raw thread terminates", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Periodic ScheduledFuture: + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(30); + RequestGate.open("periodic-sched", null); + Object reqP = RequestGate.enter(); + ScheduledFuture periodic; + try { + periodic = RequestGate.scheduleAtFixedRate(stpe, () -> { }, 5, 40, TimeUnit.MILLISECONDS); + } finally { + RequestGate.exit(reqP); + } + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + // Consume one-time report first so the next window depends strictly on !ScheduledFuture.isDone(). + RequestGate.open("periodic-sched-consume-once", null); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + Thread.sleep(100); // Past 30ms base tail + 45ms delay/period while periodic is still uncancelled! + RequestGate.open("periodic-sched-alive", null); + assertEquals("uncancelled periodic ScheduledFuture keeps marking tail", + Collections.singletonList("tail:periodic-sched"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + periodic.cancel(false); + RequestGate.open("periodic-sched-cancelled", null); + assertEquals("clean once periodic ScheduledFuture is cancelled", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.untrackedTailWindowNanos = savedTailWindow; + + // Multi-hop expired self-resubmitting job loop (gen 1 -> gen 2 -> gen 3) on verified + // executor MUST stay marked job-tail across ALL generations until it stops! + RequestGate.disarm(); + JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(35); + RequestGate.open("multihop-arm", null); + CountDownLatch gen3Entered = new CountDownLatch(1); + CountDownLatch gen3Release = new CountDownLatch(1); + CountDownLatch gen1Exited = new CountDownLatch(1); + CountDownLatch gen2Exited = new CountDownLatch(1); + AtomicReference gen1Running = new AtomicReference<>("unset"); + AtomicReference gen2Running = new AtomicReference<>("unset"); + AtomicReference gen3Running = new AtomicReference<>("unset"); + Object jTokC = JobGate.enter(new Object(), "scheduled"); + try { + RequestGate.execute(pool, () -> { + try { + Thread.sleep(60); // Gen 1 expires past 35ms budget! + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + gen1Running.set(JobGate.running()); + RequestGate.execute(pool, () -> { + try { + gen1Exited.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + gen2Running.set(JobGate.running()); + RequestGate.execute(pool, () -> { + try { + gen2Exited.await(5, TimeUnit.SECONDS); + gen3Running.set(JobGate.running()); + gen3Entered.countDown(); + gen3Release.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + gen2Exited.countDown(); + }); + gen1Exited.countDown(); + }); + } finally { + JobGate.exit(jTokC); + } + assertTrue("gen 3 entered after gen 1 and gen 2 exited", gen3Entered.await(10, TimeUnit.SECONDS)); + assertNull("gen 1 expired so JobGate.running() must be null", gen1Running.get()); + assertNull("gen 2 expired so JobGate.running() must be null", gen2Running.get()); + assertNull("gen 3 expired so JobGate.running() must be null", gen3Running.get()); + long waitSingleRun = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (JobGate.activeRunCount() > 1 && System.nanoTime() < waitSingleRun) { + Thread.sleep(5); + } + assertEquals("only gen 3 run remains active after gen 1 and gen 2 exited", 1, JobGate.activeRunCount()); + JobGate.open(); + List gen3Contams = JobGate.close(); + gen3Release.countDown(); + assertTrue("gen 3 of expired self-resubmitting loop must STILL carry job-tail: " + gen3Contams, + gen3Contams.stream().anyMatch(s -> s.startsWith("job-tail:"))); + long jobDrain = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (JobGate.activeRunCount() > 0 && System.nanoTime() < jobDrain) { + Thread.sleep(5); + } + + // Real bytecode-rewritten call sites via ServerEntries.wrapExecutorCalls for + // TaskExecutor interface, TaskScheduler.schedule, Timer.schedule, + // ForkJoinPool.execute(ForkJoinTask), and ListenableFuture.addListener! + byte[] asyncSiteBytes = ServerEntries.wrapExecutorCalls( + generateAsyncFlagSiteBytecodeClass("com/acme/AsyncFlagCallSites")); + assertNotNull("AsyncFlagCallSites must be rewritten by ServerEntries.wrapExecutorCalls", asyncSiteBytes); + Class asyncSiteClass = new ByteLoader(getClass().getClassLoader()) + .define("com.acme.AsyncFlagCallSites", asyncSiteBytes); + + // 1. TaskExecutor interface with hooked+verified ThreadPoolTaskExecutor (CLEAN) + // vs unhooked custom TaskExecutor (FLAGGED). + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor springTe = + new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor(); + springTe.initialize(); + try { + ServerEntries.markSpringExecutorHookedForTests(springTe.getClass().getName()); + RequestGate.disarm(); + RequestGate.open("spring-te-check", null); + Object r1 = RequestGate.enter(); + CountDownLatch teRan = new CountDownLatch(1); + try { + asyncSiteClass.getMethod("callTaskExecutor", + org.springframework.core.task.TaskExecutor.class, Runnable.class) + .invoke(null, springTe, (Runnable) teRan::countDown); + } finally { + RequestGate.exit(r1); + } + assertTrue(teRan.await(5, TimeUnit.SECONDS)); + assertEquals("rewritten TaskExecutor.execute on hooked Spring pool must stay clean", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + RequestGate.disarm(); + RequestGate.open("custom-te-check", null); + Object r2 = RequestGate.enter(); + org.springframework.core.task.TaskExecutor customTe = r -> r.run(); + try { + asyncSiteClass.getMethod("callTaskExecutor", + org.springframework.core.task.TaskExecutor.class, Runnable.class) + .invoke(null, customTe, (Runnable) () -> { }); + } finally { + RequestGate.exit(r2); + } + List customTeContams = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations; + assertTrue("rewritten TaskExecutor.execute on unhooked impl must flag: " + customTeContams, + customTeContams.contains("untracked-executor:" + customTe.getClass().getName())); + } finally { + ServerEntries.unmarkSpringExecutorHookedForTests(springTe.getClass().getName()); + springTe.shutdown(); + } + + // 2. Spring TaskScheduler.schedule(Runnable, Date) flags AND tracks returned ScheduledFuture! + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(30); + org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler springTs = + new org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler(); + springTs.initialize(); + try { + RequestGate.open("task-scheduler-check", null); + Object rTs = RequestGate.enter(); + ScheduledFuture tsFut; + try { + tsFut = (ScheduledFuture) asyncSiteClass.getMethod("callTaskScheduler", + org.springframework.scheduling.TaskScheduler.class, Runnable.class, java.util.Date.class) + .invoke(null, springTs, (Runnable) () -> { }, + new java.util.Date(System.currentTimeMillis() + 5000)); + } finally { + RequestGate.exit(rTs); + } + List tsContams = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations; + assertTrue("rewritten TaskScheduler.schedule must flag: " + tsContams, + tsContams.contains("untracked-async:schedule")); + // Consume one-time report first so the next window depends strictly on !ScheduledFuture.isDone(). + RequestGate.open("ts-consume-once", null); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + Thread.sleep(60); // Past 30ms base tail while ScheduledFuture is still pending! + RequestGate.open("ts-alive", null); + assertEquals("TaskScheduler ScheduledFuture keeps tail active until cancelled", + Collections.singletonList("tail:task-scheduler-check"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + tsFut.cancel(false); + } finally { + springTs.shutdown(); + RequestGate.untrackedTailWindowNanos = savedTailWindow; + } + + // 3. Timer.schedule(TimerTask, long) flags untracked-async:timer! + RequestGate.disarm(); + RequestGate.open("timer-flag-check", null); + Object rTimer = RequestGate.enter(); + CountDownLatch timerRan = new CountDownLatch(1); + try { + asyncSiteClass.getMethod("callTimer", java.util.Timer.class, java.util.TimerTask.class, long.class) + .invoke(null, timer, new java.util.TimerTask() { + @Override + public void run() { + timerRan.countDown(); + } + }, 1L); + } finally { + RequestGate.exit(rTimer); + } + assertTrue(timerRan.await(5, TimeUnit.SECONDS)); + assertTrue("rewritten Timer.schedule must flag untracked-async:timer", + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations + .contains("untracked-async:timer")); + + // 4. ForkJoinPool.execute(ForkJoinTask) flags untracked-async:forkjoin-task! + RequestGate.disarm(); + RequestGate.open("fjp-flag-check", null); + Object rFjp = RequestGate.enter(); + CountDownLatch fjpRan = new CountDownLatch(1); + try { + asyncSiteClass.getMethod("callFjpTask", java.util.concurrent.ForkJoinPool.class, + java.util.concurrent.ForkJoinTask.class) + .invoke(null, fjp, java.util.concurrent.ForkJoinTask.adapt(fjpRan::countDown)); + } finally { + RequestGate.exit(rFjp); + } + assertTrue(fjpRan.await(5, TimeUnit.SECONDS)); + assertTrue("rewritten ForkJoinPool.execute(ForkJoinTask) must flag", + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations + .contains("untracked-async:forkjoin-task")); + + // 5. Guava ListenableFuture.addListener(Runnable, Executor) flags untracked-async:guava-future! + RequestGate.disarm(); + RequestGate.open("guava-flag-check", null); + Object rGuava = RequestGate.enter(); + try { + asyncSiteClass.getMethod("callGuavaListener", FakeListenableFuture.class, Runnable.class, Executor.class) + .invoke(null, (FakeListenableFuture) (r, e) -> r.run(), (Runnable) () -> { }, pool); + } finally { + RequestGate.exit(rGuava); + } + assertTrue("rewritten addListener(Runnable, Executor) must flag untracked-async:guava-future", + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations + .contains("untracked-async:guava-future")); + } finally { + RequestGate.untrackedTailWindowNanos = savedTailWindow; + RequestGate.maxLingeringNanos = savedMaxLingering; + JobGate.handedJobMaxNanos = savedJobMax; + timer.cancel(); + fjp.shutdownNow(); + pool.shutdownNow(); + stpe.shutdownNow(); + } + } + + public interface FakeListenableFuture { + void addListener(Runnable listener, Executor executor); + } + + private static byte[] generateAsyncFlagSiteBytecodeClass(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null); + emitDefaultCtor(cw); + + // callTaskExecutor(TaskExecutor, Runnable) -> INVOKEINTERFACE TaskExecutor.execute(Runnable)V + MethodVisitor te = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "callTaskExecutor", + "(Lorg/springframework/core/task/TaskExecutor;Ljava/lang/Runnable;)V", null, null); + te.visitCode(); + te.visitVarInsn(Opcodes.ALOAD, 0); + te.visitVarInsn(Opcodes.ALOAD, 1); + te.visitMethodInsn(Opcodes.INVOKEINTERFACE, "org/springframework/core/task/TaskExecutor", + "execute", "(Ljava/lang/Runnable;)V", true); + te.visitInsn(Opcodes.RETURN); + te.visitMaxs(2, 2); + te.visitEnd(); + + // callTaskScheduler(TaskScheduler, Runnable, Date) -> ScheduledFuture + MethodVisitor ts = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "callTaskScheduler", + "(Lorg/springframework/scheduling/TaskScheduler;Ljava/lang/Runnable;Ljava/util/Date;)" + + "Ljava/util/concurrent/ScheduledFuture;", null, null); + ts.visitCode(); + ts.visitVarInsn(Opcodes.ALOAD, 0); + ts.visitVarInsn(Opcodes.ALOAD, 1); + ts.visitVarInsn(Opcodes.ALOAD, 2); + ts.visitMethodInsn(Opcodes.INVOKEINTERFACE, "org/springframework/scheduling/TaskScheduler", + "schedule", "(Ljava/lang/Runnable;Ljava/util/Date;)Ljava/util/concurrent/ScheduledFuture;", true); + ts.visitInsn(Opcodes.ARETURN); + ts.visitMaxs(3, 3); + ts.visitEnd(); + + // callTimer(Timer, TimerTask, long) -> void + MethodVisitor tm = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "callTimer", + "(Ljava/util/Timer;Ljava/util/TimerTask;J)V", null, null); + tm.visitCode(); + tm.visitVarInsn(Opcodes.ALOAD, 0); + tm.visitVarInsn(Opcodes.ALOAD, 1); + tm.visitVarInsn(Opcodes.LLOAD, 2); + tm.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Timer", + "schedule", "(Ljava/util/TimerTask;J)V", false); + tm.visitInsn(Opcodes.RETURN); + tm.visitMaxs(4, 4); + tm.visitEnd(); + + // callFjpTask(ForkJoinPool, ForkJoinTask) -> void + MethodVisitor fj = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "callFjpTask", + "(Ljava/util/concurrent/ForkJoinPool;Ljava/util/concurrent/ForkJoinTask;)V", null, null); + fj.visitCode(); + fj.visitVarInsn(Opcodes.ALOAD, 0); + fj.visitVarInsn(Opcodes.ALOAD, 1); + fj.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/ForkJoinPool", + "execute", "(Ljava/util/concurrent/ForkJoinTask;)V", false); + fj.visitInsn(Opcodes.RETURN); + fj.visitMaxs(2, 2); + fj.visitEnd(); + + // callGuavaListener(FakeListenableFuture, Runnable, Executor) -> void + String flf = FakeListenableFuture.class.getName().replace('.', '/'); + MethodVisitor gv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "callGuavaListener", + "(L" + flf + ";Ljava/lang/Runnable;Ljava/util/concurrent/Executor;)V", null, null); + gv.visitCode(); + gv.visitVarInsn(Opcodes.ALOAD, 0); + gv.visitVarInsn(Opcodes.ALOAD, 1); + gv.visitVarInsn(Opcodes.ALOAD, 2); + gv.visitMethodInsn(Opcodes.INVOKEINTERFACE, flf, + "addListener", "(Ljava/lang/Runnable;Ljava/util/concurrent/Executor;)V", true); + gv.visitInsn(Opcodes.RETURN); + gv.visitMaxs(3, 3); + gv.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + + @Test(timeout = 60000) + public void lateStartContaminatesCurrentWindowTimerDelayAndPeriodicMultiHopScheduledRetryAndBranchyFrames() + throws Exception { + ThreadPoolExecutor singlePool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + ThreadPoolExecutor workerPool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2); + java.util.Timer oneShotTimer = new java.util.Timer(true); + java.util.Timer periodicTimer = new java.util.Timer(true); + long savedTailWindow = RequestGate.untrackedTailWindowNanos; + long savedMaxLingering = RequestGate.maxLingeringNanos; + try { + // A queued task from an old window A whose idle permit expired + // and was dropped from LINGERING MUST immediately contaminate + // the CURRENT open window M when it finally starts executing + // (even if it both starts and exits completely inside M)! + RequestGate.disarm(); + RequestGate.maxLingeringNanos = TimeUnit.MILLISECONDS.toNanos(50); + CountDownLatch blockerRunning = new CountDownLatch(1); + CountDownLatch releaseBlocker = new CountDownLatch(1); + // External untracked blocker occupying singlePool's sole worker thread. + singlePool.execute(latchTask(blockerRunning, releaseBlocker)); + assertTrue(blockerRunning.await(5, TimeUnit.SECONDS)); + + CountDownLatch lateTaskDone = new CountDownLatch(1); + RequestGate.open("late-start-orig", null); + Object reqA = RequestGate.enter(); + try { + RequestGate.execute(singlePool, lateTaskDone::countDown); + } finally { + RequestGate.exit(reqA); + } + assertFalse("A is cut while late task sits queued", RequestGate.await(TimeUnit.MILLISECONDS.toNanos(15))); + Thread.sleep(90); // Past 50ms maxLingeringNanos while executing == 0. + // First open past cap reports cut once & drops A from LINGERING. + RequestGate.open("late-start-dropper", null); + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(20), true); + + // Open window M: A is already gone from LINGERING so M opens clean! + RequestGate.open("late-start-target-m", null); + // Release blocker so A's late task starts AND completes inside M! + releaseBlocker.countDown(); + assertTrue("late task completed inside M", lateTaskDone.await(5, TimeUnit.SECONDS)); + List mContams = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations; + assertTrue("window M open when late task ran must be flagged tail:late-start-orig: " + mContams, + mContams.contains("tail:late-start-orig")); + RequestGate.maxLingeringNanos = savedMaxLingering; + + // Rewritten java.util.Timer one-shot (delay-aware tail) and + // periodic scheduleAtFixedRate (weak TimerTask liveness). + byte[] timerBytes = ServerEntries.wrapExecutorCalls(generateTimerAndBranchyClass("com/acme/TimerAndBranchy")); + assertNotNull("TimerAndBranchy must be rewritten by ServerEntries.wrapExecutorCalls", timerBytes); + Class timerClass = new ByteLoader(getClass().getClassLoader()) + .define("com.acme.TimerAndBranchy", timerBytes); + + // One-shot Timer.schedule(TimerTask, long delay) past 30ms base tail + // remains flagged through delay + base tail! + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(30); + CountDownLatch oneShotRan = new CountDownLatch(1); + RequestGate.open("timer-oneshot", null); + Object reqT1 = RequestGate.enter(); + try { + timerClass.getMethod("scheduleOneShot", java.util.Timer.class, java.util.TimerTask.class, long.class) + .invoke(null, oneShotTimer, new java.util.TimerTask() { + @Override + public void run() { + oneShotRan.countDown(); + } + }, 180L); + } finally { + RequestGate.exit(reqT1); + } + assertTrue("one-shot Timer.schedule flags untracked-async:timer", + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations + .contains("untracked-async:timer")); + // Consume one-time report first so the next window proves delay-extended expiry (> 30ms base tail). + RequestGate.open("timer-oneshot-consume-once", null); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + Thread.sleep(75); // Past 30ms base tail, well before 180ms + 30ms extended tail! + RequestGate.open("timer-oneshot-next", null); + assertEquals("one-shot Timer delay must extend tail past base window", + Collections.singletonList("tail:timer-oneshot"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + assertTrue(oneShotRan.await(5, TimeUnit.SECONDS)); + + // Periodic Timer.scheduleAtFixedRate(TimerTask, long, long) stays + // flagged past base tail + delay + period while scheduled! + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(30); + RequestGate.open("timer-periodic", null); + Object reqT2 = RequestGate.enter(); + try { + timerClass.getMethod("schedulePeriodic", java.util.Timer.class, long.class, long.class) + .invoke(null, periodicTimer, 5L, 25L); + } finally { + RequestGate.exit(reqT2); + } + assertTrue("periodic Timer.scheduleAtFixedRate flags untracked-async:timer", + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations + .contains("untracked-async:timer")); + // Consume one-time report first so the next window depends strictly on periodic TimerTask liveness. + RequestGate.open("timer-periodic-consume-once", null); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + Thread.sleep(100); // Past 30ms + 5ms + 25ms tail while TimerTask is still in Timer's queue! + RequestGate.open("timer-periodic-alive", null); + assertEquals("periodic TimerTask held by Timer queue keeps tail active", + Collections.singletonList("tail:timer-periodic"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + periodicTimer.cancel(); + + // Multi-hop self-rescheduling retry loop on ScheduledThreadPoolExecutor + // (gen 1 -> gen 2 -> downstream workerPool.execute) propagates window + // context across hops without making END wait for delayed tasks! + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(30); + CountDownLatch gen1Done = new CountDownLatch(1); + CountDownLatch gen2Started = new CountDownLatch(1); + CountDownLatch gen2Release = new CountDownLatch(1); + CountDownLatch downstreamStarted = new CountDownLatch(1); + CountDownLatch downstreamRelease = new CountDownLatch(1); + RequestGate.open("sched-retry", null); + Object reqSchedRetry = RequestGate.enter(); + try { + RequestGate.schedule(stpe, () -> { + // Gen 1 finishes quickly after scheduling Gen 2 with a 120ms delay. + RequestGate.schedule(stpe, () -> { + gen2Started.countDown(); + try { + gen2Release.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + RequestGate.execute(workerPool, latchTask(downstreamStarted, downstreamRelease)); + }, 120, TimeUnit.MILLISECONDS); + gen1Done.countDown(); + }, 10, TimeUnit.MILLISECONDS); + } finally { + RequestGate.exit(reqSchedRetry); + } + RequestGate.WindowOutcome retryOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("END must not block on delayed scheduled task", retryOut.drained); + assertTrue("flags untracked-async:schedule", retryOut.contaminations.contains("untracked-async:schedule")); + assertTrue("gen 1 completed", gen1Done.await(5, TimeUnit.SECONDS)); + // Consume one-time report first so the next window proves gen-2 ScheduledFuture / delay tracking! + RequestGate.open("sched-retry-consume-once", null); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + Thread.sleep(50); // Past gen 1 completion + 30ms base tail while gen 2 is still pending! + RequestGate.open("sched-retry-gen2-pending", null); + assertEquals("gen 2 scheduled via propagated context keeps tail active past gen 1 base tail", + Collections.singletonList("tail:sched-retry"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + assertTrue("gen 2 started", gen2Started.await(5, TimeUnit.SECONDS)); + gen2Release.countDown(); + assertTrue("downstream workerPool task started from gen 2", downstreamStarted.await(5, TimeUnit.SECONDS)); + Thread.sleep(50); // Past 30ms base tail after gen 2 exited while downstream workerPool task still runs! + RequestGate.open("sched-retry-downstream", null); + assertEquals("downstream workerPool task launched by gen 2 keeps tail:sched-retry", + Collections.singletonList("tail:sched-retry"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + downstreamRelease.countDown(); + + // Branchy + try/catch StackMapTable verifier fixture (V17 on JDK 17+, V1_8 on JDK 8): + // proves post-call DUP + trackUntrackedFuture passes strict JVM verification with + // branches and exception handlers! + org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler springTs = + new org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler(); + springTs.initialize(); + try { + RequestGate.disarm(); + RequestGate.open("branchy-schedule", null); + Object reqBr = RequestGate.enter(); + ScheduledFuture brFut; + try { + brFut = (ScheduledFuture) timerClass.getMethod("branchySchedule", + org.springframework.scheduling.TaskScheduler.class, Runnable.class, + java.util.Date.class, boolean.class) + .invoke(null, springTs, (Runnable) () -> { }, + new java.util.Date(System.currentTimeMillis() + 5000), Boolean.TRUE); + } finally { + RequestGate.exit(reqBr); + } + assertNotNull(brFut); + brFut.cancel(false); + assertTrue("branchy rewritten TaskScheduler.schedule flags untracked-async:schedule", + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations + .contains("untracked-async:schedule")); + } finally { + springTs.shutdown(); + } + } finally { + RequestGate.untrackedTailWindowNanos = savedTailWindow; + RequestGate.maxLingeringNanos = savedMaxLingering; + oneShotTimer.cancel(); + periodicTimer.cancel(); + singlePool.shutdownNow(); + workerPool.shutdownNow(); + stpe.shutdownNow(); + } + } + + public static final class PlainSyncTxHelper { + public void execute(Runnable action) { + action.run(); + } + + public Object submit(Runnable action) { + action.run(); + return "ok"; + } + + public Object submit(Runnable action, Object result) { + action.run(); + return result; + } + } + + public interface SubtypeFuture extends Future { + } + + public interface ListenableLikeExecutorService extends ExecutorService { + SubtypeFuture submit(Runnable task, T result); + } + + public static final class CustomListenableLikeExecutor extends AbstractExecutorService + implements ListenableLikeExecutorService { + @Override + public void shutdown() { + } + + @Override + public List shutdownNow() { + return Collections.emptyList(); + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + + @Override + public void execute(Runnable command) { + command.run(); + } + + @Override + public SubtypeFuture submit(Runnable task, T result) { + task.run(); + final FutureTask ft = new FutureTask<>(task, result); + ft.run(); + return new SubtypeFuture() { + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return ft.cancel(mayInterruptIfRunning); + } + + @Override + public boolean isCancelled() { + return ft.isCancelled(); + } + + @Override + public boolean isDone() { + return ft.isDone(); + } + + @Override + public T get() throws InterruptedException, java.util.concurrent.ExecutionException { + return ft.get(); + } + + @Override + public T get(long timeout, TimeUnit unit) + throws InterruptedException, java.util.concurrent.ExecutionException, + java.util.concurrent.TimeoutException { + return ft.get(timeout, unit); + } + }; + } + } + + public static final class CustomWorkerThread extends Thread { + public CustomWorkerThread(Runnable r) { + super(r, "custom-worker-thread"); + setDaemon(true); + } + } + + @Test(timeout = 60000) + public void nonExecutorSyncHelperTrackedHandleLivenessInlineExecutorsAndBackgroundSuppression() + throws Exception { + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); + java.util.Timer timer = new java.util.Timer(true); + long savedTailWindow = RequestGate.untrackedTailWindowNanos; + try { + // Bytecode-rewritten plain synchronous helper TxHelper.execute(Runnable) + // and TxHelper.submit(Runnable) (NOT implementing Executor/ExecutorService) MUST NOT + // contaminate the current window or any subsequent window! + byte[] callerRaw = generateTxHelperAndTimerCancelCaller("com/acme/SyncHelperAndTimerCaller"); + byte[] callerRewritten = ServerEntries.wrapExecutorCalls(callerRaw); + assertNotNull("SyncHelperAndTimerCaller must be rewritten by ServerEntries.wrapExecutorCalls", callerRewritten); + Class caller = new ByteLoader(getClass().getClassLoader()) + .define("com.acme.SyncHelperAndTimerCaller", callerRewritten); + + RequestGate.disarm(); + RequestGate.open("sync-helper", null); + Object reqSync = RequestGate.enter(); + AtomicBoolean execRan = new AtomicBoolean(false); + AtomicBoolean submitRan = new AtomicBoolean(false); + try { + PlainSyncTxHelper helper = new PlainSyncTxHelper(); + caller.getMethod("callSyncHelper", PlainSyncTxHelper.class, Runnable.class, Runnable.class) + .invoke(null, helper, + (Runnable) () -> execRan.set(true), + (Runnable) () -> submitRan.set(true)); + } finally { + RequestGate.exit(reqSync); + } + assertTrue("TxHelper.execute ran", execRan.get()); + assertTrue("TxHelper.submit ran", submitRan.get()); + assertEquals("non-Executor TxHelper.execute/submit must NOT contaminate current window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.open("sync-helper-next", null); + assertEquals("non-Executor TxHelper.execute/submit must NOT taint subsequent window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Positive control: a real custom Executor/ExecutorService still gets flagged! + RequestGate.open("real-custom-exec", null); + Object reqCustomExec = RequestGate.enter(); + Executor customExec = r -> r.run(); + try { + RequestGate.noteIfUntrackedExecutor(customExec); + } finally { + RequestGate.exit(reqCustomExec); + } + RequestGate.WindowOutcome customExecOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("real custom Executor must still be flagged: " + customExecOut.contaminations, + customExecOut.contaminations.contains("untracked-executor:" + customExec.getClass().getName())); + + // Request schedules a 30s timeout and cancels it before returning -> + // next request MUST be CLEAN (no 32s tail: taint)! + RequestGate.disarm(); + RequestGate.open("cancelled-timeout", null); + Object reqTimeout = RequestGate.enter(); + try { + ScheduledFuture timeout = RequestGate.schedule(stpe, () -> { }, 30, TimeUnit.SECONDS); + assertTrue("30s timeout cancelled before returning", timeout.cancel(false)); + } finally { + RequestGate.exit(reqTimeout); + } + RequestGate.WindowOutcome timeoutOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("originating window still notes schedule", + timeoutOut.contaminations.contains("untracked-async:schedule")); + RequestGate.open("cancelled-timeout-next", null); + assertEquals("cancelled 30s timeout must NOT taint subsequent window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Thread.start() + join() before response -> next request MUST be CLEAN! + RequestGate.disarm(); + RequestGate.open("thread-join", null); + Object reqJoin = RequestGate.enter(); + try { + Thread t = new Thread(() -> { }, "joined-worker"); + RequestGate.startThread(t); + t.join(5000); + assertFalse("thread terminated before END", t.isAlive()); + } finally { + RequestGate.exit(reqJoin); + } + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + RequestGate.open("thread-join-next", null); + assertEquals("joined Thread.start() must NOT leave 2s tail taint on next window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Also verify bytecode-rewritten Thread subclass start() + join() before response -> CLEAN! + RequestGate.disarm(); + RequestGate.open("subthread-join", null); + Object reqSubJoin = RequestGate.enter(); + try { + CustomWorkerThread sub = new CustomWorkerThread(() -> { }); + caller.getMethod("startCustomThread", CustomWorkerThread.class).invoke(null, sub); + sub.join(5000); + assertFalse("subclass thread terminated before END", sub.isAlive()); + } finally { + RequestGate.exit(reqSubJoin); + } + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + RequestGate.open("subthread-join-next", null); + assertEquals("joined Thread subclass must NOT taint next window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // TimerTask cancellation & running-body liveness: + // (i) Periodic TimerTask cancelled BEFORE first fire (retained strongly in a field) -> CLEAN immediately! + RequestGate.disarm(); + java.util.TimerTask retainedTask = new NoopTimerTask(); + RequestGate.open("timer-cancel-before-fire", null); + Object reqTimer = RequestGate.enter(); + try { + caller.getMethod("scheduleAndCancelPeriodic", java.util.Timer.class, java.util.TimerTask.class) + .invoke(null, timer, retainedTask); + } finally { + RequestGate.exit(reqTimer); + } + RequestGate.WindowOutcome timerCancelOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("originating window notes untracked-async:timer", + timerCancelOut.contaminations.contains("untracked-async:timer")); + RequestGate.open("timer-cancel-next", null); + assertEquals("cancelled periodic TimerTask retained in a field must NOT taint next window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + assertNotNull("keep strong reference alive past assertion", retainedTask); + + // (ii) One-shot TimerTask(delay=0) with a 300ms body STILL RUNNING + // at +100ms MUST contaminate t2 (never dropped at 50ms or on state=EXECUTED)! + RequestGate.disarm(); + CountDownLatch bodyStarted = new CountDownLatch(1); + CountDownLatch releaseBody = new CountDownLatch(1); + java.util.TimerTask slowOneShot = new java.util.TimerTask() { + @Override + public void run() { + bodyStarted.countDown(); + try { + releaseBody.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }; + RequestGate.open("slow-oneshot", null); + Object reqSlowOneShot = RequestGate.enter(); + try { + caller.getMethod("scheduleOneShotDelay", java.util.Timer.class, java.util.TimerTask.class, long.class) + .invoke(null, timer, slowOneShot, 0L); + } finally { + RequestGate.exit(reqSlowOneShot); + } + assertTrue("slow one-shot TimerTask started", bodyStarted.await(5, TimeUnit.SECONDS)); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + Thread.sleep(100); // Well past old 50ms grace while body is STILL running! + RequestGate.open("during-slow-body", null); + assertEquals("running one-shot TimerTask body MUST contaminate t2", + Collections.singletonList("tail:slow-oneshot"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + // Calling cancel() while body is running returns false -> MUST STILL keep tail active! + boolean cancelWhileRunning = (Boolean) caller.getMethod("cancelTask", java.util.TimerTask.class) + .invoke(null, slowOneShot); + assertFalse("cancel() on already-running one-shot returns false", cancelWhileRunning); + RequestGate.open("after-cancel-while-running", null); + assertEquals("cancel() while body is running MUST NOT drop tail immediately", + Collections.singletonList("tail:slow-oneshot"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + releaseBody.countDown(); + + // (iii) Periodic TimerTask that ran >= 1 tick, then cancelled & retained in a field -> + // active during untrackedTailWindowNanos, then CLEAN (never stuck forever)! + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(80); + CountDownLatch periodicRanOnce = new CountDownLatch(1); + java.util.TimerTask retainedRanPeriodic = new java.util.TimerTask() { + @Override + public void run() { + periodicRanOnce.countDown(); + } + }; + RequestGate.open("periodic-ran-then-cancel", null); + Object reqRanPer = RequestGate.enter(); + try { + caller.getMethod("schedulePeriodicDelay", java.util.Timer.class, java.util.TimerTask.class, + long.class, long.class).invoke(null, timer, retainedRanPeriodic, 0L, 20L); + } finally { + RequestGate.exit(reqRanPer); + } + assertTrue("periodic TimerTask ran at least once", periodicRanOnce.await(5, TimeUnit.SECONDS)); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + caller.getMethod("cancelTask", java.util.TimerTask.class).invoke(null, retainedRanPeriodic); + // Immediately after cancelling a periodic task that already ticked, the tail MUST + // stay active during untrackedTailWindowNanos (proving curExec != initial guards a + // potentially running tick body!). + RequestGate.open("periodic-right-after-cancel", null); + assertEquals("periodic TimerTask cancelled after ticking MUST keep tail active during tail window", + Collections.singletonList("tail:periodic-ran-then-cancel"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + Thread.sleep(120); // Past 80ms untrackedTailWindowNanos after cancel! + RequestGate.open("periodic-clean-after-tail", null); + assertEquals("cancelled periodic TimerTask retained in field must become clean after tail window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + assertNotNull("keep strong reference alive", retainedRanPeriodic); + RequestGate.untrackedTailWindowNanos = savedTailWindow; + + // (iii-b) Rewritten Timer.cancel()V: + // 1. Cancelling a 30s one-shot Timer BEFORE it fires -> immediately CLEAN! + // 2. Cancelling a Timer while a 0ms one-shot body is STILL RUNNING -> keeps tail active! + RequestGate.disarm(); + java.util.Timer cancelBeforeFireTimer = new java.util.Timer(true); + RequestGate.open("timer-cancel-before-fire-2", null); + Object reqTcb = RequestGate.enter(); + try { + caller.getMethod("scheduleOneShotDelay", java.util.Timer.class, java.util.TimerTask.class, long.class) + .invoke(null, cancelBeforeFireTimer, new NoopTimerTask(), 30000L); + caller.getMethod("cancelTimer", java.util.Timer.class).invoke(null, cancelBeforeFireTimer); + } finally { + RequestGate.exit(reqTcb); + } + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + RequestGate.open("timer-cancel-before-fire-2-next", null); + assertEquals("Timer.cancel() well before scheduled fire time leaves next window clean", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + RequestGate.disarm(); + java.util.Timer cancelWhileRunningTimer = new java.util.Timer(true); + CountDownLatch timerBodyStarted = new CountDownLatch(1); + CountDownLatch timerBodyRelease = new CountDownLatch(1); + RequestGate.open("timer-cancel-running", null); + Object reqTcr = RequestGate.enter(); + try { + caller.getMethod("scheduleOneShotDelay", java.util.Timer.class, java.util.TimerTask.class, long.class) + .invoke(null, cancelWhileRunningTimer, new java.util.TimerTask() { + @Override + public void run() { + timerBodyStarted.countDown(); + try { + timerBodyRelease.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }, 0L); + assertTrue("Timer body started before Timer.cancel()", timerBodyStarted.await(5, TimeUnit.SECONDS)); + caller.getMethod("cancelTimer", java.util.Timer.class).invoke(null, cancelWhileRunningTimer); + } finally { + RequestGate.exit(reqTcr); + } + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + RequestGate.open("timer-cancel-running-next", null); + assertEquals("Timer.cancel() while body is running MUST keep tail active", + Collections.singletonList("tail:timer-cancel-running"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + timerBodyRelease.countDown(); + + // (iv) One-shot TimerTask with 30s delay cancelled before returning -> immediately CLEAN! + RequestGate.disarm(); + java.util.TimerTask retainedOneShot = new NoopTimerTask(); + RequestGate.open("oneshot-cancel", null); + Object reqOneShot = RequestGate.enter(); + try { + caller.getMethod("scheduleAndCancelOneShot", java.util.Timer.class, java.util.TimerTask.class) + .invoke(null, timer, retainedOneShot); + } finally { + RequestGate.exit(reqOneShot); + } + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + RequestGate.open("oneshot-next-clean", null); + assertEquals("cancelled one-shot 30s TimerTask must NOT taint next window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + assertNotNull("keep strong reference alive", retainedOneShot); + + // Two-arg submit(Runnable, T) returning a Future subtype (like Guava ListenableFuture) + // MUST flag untracked-executor on a custom ExecutorService, while ignoring PlainSyncTxHelper! + RequestGate.disarm(); + RequestGate.open("listenable-submit2", null); + Object reqSubmit2 = RequestGate.enter(); + CustomListenableLikeExecutor listenableExec = new CustomListenableLikeExecutor(); + try { + Object res = caller.getMethod("callTwoArgSubmit", ListenableLikeExecutorService.class, + Runnable.class, Object.class).invoke(null, listenableExec, (Runnable) () -> { }, "val"); + assertNotNull("two-arg submit returned SubtypeFuture", res); + } finally { + RequestGate.exit(reqSubmit2); + } + RequestGate.WindowOutcome submit2Out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("two-arg ListenableFuture submit must flag untracked-executor: " + submit2Out.contaminations, + submit2Out.contaminations.contains("untracked-executor:" + listenableExec.getClass().getName())); + + // Known same-thread inline executors (Spring SyncTaskExecutor, + // ConcurrentTaskExecutor(SyncTaskExecutor), Guava DirectExecutor, and DirectExecutorService) + // are NEITHER wrapped NOR flagged untracked-executor, AND *Async(fn, inlineExec) holds permit + // while upstream CF is incomplete! + RequestGate.disarm(); + org.springframework.core.task.SyncTaskExecutor syncExec = + new org.springframework.core.task.SyncTaskExecutor(); + org.springframework.scheduling.concurrent.ConcurrentTaskExecutor concurrentDefault = + new org.springframework.scheduling.concurrent.ConcurrentTaskExecutor(syncExec); + Class guavaDirectCls = new ByteLoader(getClass().getClassLoader()).define( + "com.google.common.util.concurrent.DirectExecutor", + generateInlineExecutorClass("com/google/common/util/concurrent/DirectExecutor")); + Executor guavaDirect = (Executor) guavaDirectCls.getDeclaredConstructor().newInstance(); + Class guavaDirectSvcCls = new ByteLoader(getClass().getClassLoader()).define( + "com.google.common.util.concurrent.DirectExecutorService", + generateInlineExecutorServiceClass("com/google/common/util/concurrent/DirectExecutorService")); + ExecutorService guavaDirectSvc = (ExecutorService) guavaDirectSvcCls.getDeclaredConstructor().newInstance(); + Class legacyGuavaDirectSvcCls = new ByteLoader(getClass().getClassLoader()).define( + "com.google.common.util.concurrent.MoreExecutors$DirectExecutorService", + generateInlineExecutorServiceClass( + "com/google/common/util/concurrent/MoreExecutors$DirectExecutorService")); + ExecutorService legacyGuavaDirectSvc = + (ExecutorService) legacyGuavaDirectSvcCls.getDeclaredConstructor().newInstance(); + + RequestGate.open("inline-exec-check", null); + Object reqInline = RequestGate.enter(); + AtomicBoolean inlineRan1 = new AtomicBoolean(false); + AtomicBoolean inlineRan2 = new AtomicBoolean(false); + AtomicBoolean inlineRan3 = new AtomicBoolean(false); + CompletableFuture upstream = new CompletableFuture<>(); + CompletableFuture asyncWithInline; + try { + Runnable raw1 = () -> inlineRan1.set(true); + Runnable raw2 = () -> inlineRan2.set(true); + Runnable raw3 = () -> inlineRan3.set(true); + assertSame("SyncTaskExecutor must NOT wrap task", raw1, RequestGate.hand(syncExec, raw1)); + assertSame("Guava DirectExecutor must NOT wrap task", raw2, RequestGate.hand(guavaDirect, raw2)); + assertSame("Guava DirectExecutorService must NOT wrap task", raw3, + RequestGate.hand(guavaDirectSvc, raw3)); + assertSame("Guava MoreExecutors$DirectExecutorService must NOT wrap task", raw3, + RequestGate.hand(legacyGuavaDirectSvc, raw3)); + RequestGate.execute(syncExec, raw1); + RequestGate.execute(guavaDirect, raw2); + RequestGate.submit(guavaDirectSvc, raw3); + RequestGate.noteIfUntrackedExecutor(syncExec); + RequestGate.noteIfUntrackedExecutor(guavaDirect); + RequestGate.noteIfUntrackedSubmit(guavaDirectSvc); + RequestGate.noteIfUntrackedSubmit(legacyGuavaDirectSvc); + assertFalse("ConcurrentTaskExecutor(SyncTaskExecutor) must be allow-listed", + OrderedPools.orders(concurrentDefault)); + asyncWithInline = RequestGate.thenApplyAsync(upstream, v -> v + "-done", syncExec); + } finally { + RequestGate.exit(reqInline); + } + assertTrue("SyncTaskExecutor task executed", inlineRan1.get()); + assertTrue("Guava DirectExecutor task executed", inlineRan2.get()); + assertTrue("Guava DirectExecutorService task executed", inlineRan3.get()); + assertEquals("thenApplyAsync(fn, inlineExec) must hold permit while upstream CF is incomplete", + 1, RequestGate.running()); + upstream.complete("ok"); + assertEquals("ok-done", asyncWithInline.get(5, TimeUnit.SECONDS)); + assertEquals("permit released once upstream CF completes", 0, RequestGate.running()); + assertEquals("known inline executors must NOT contaminate current window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.open("inline-exec-next", null); + assertEquals("known inline executors must NOT taint next window", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Real CoverageTcpClient connect test with injected RuntimeException in + // helloFrame() -> falls back to minimal empty-identity HELLO, stays connected (NO reconnect loop), + // and serves NOP on the first connection! + collector = new ServerSocket(0, 2, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(15000); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + KeployDedupAgent.testHelloFailure = new RuntimeException("simulated connect-time HELLO failure"); + try { + assertTrue(KeployDedupAgent.start()); + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(15000); + OutputStream out = sdk.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + String fallbackHello = in.readLine(); + JsonObject minObj = parseHello(fallbackHello); + assertEquals(3, minObj.get("proto").getAsInt()); + assertEquals("", minObj.get("sdkVersion").getAsString()); + assertEquals("", minObj.get("jvmNonce").getAsString()); + assertEquals("", minObj.get("buildId").getAsString()); + assertFalse(minObj.get("windowCut").getAsBoolean()); + assertTrue(minObj.get("ackId").getAsBoolean()); + assertTrue(minObj.get("nopResync").getAsBoolean()); + // Must stay connected and serve commands without disconnect/reconnect loop! + send(out, "NOP after-hello-fallback"); + assertEquals("ACK after-hello-fallback", in.readLine()); + } + } finally { + KeployDedupAgent.testHelloFailure = null; + KeployDedupAgent.stop(); + collector.close(); + collector = null; + System.clearProperty(ENDPOINT_PROPERTY); + } + } finally { + RequestGate.untrackedTailWindowNanos = savedTailWindow; + timer.cancel(); + stpe.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostOnTcpAndUnix() throws Exception { + byte[] shopBytes = new byte[] {31, 32, 33}; + File shop = new File(tmp.newFolder("bg-suppress-classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + boolean[] probes = inProcessJacoco().probes(IndexReport.classId(shopBytes), "com/acme/Shop", 4); + + // 1. TCP transport: test-1 calls RequestGate.startThread(audit), audit hits probe[2] + // in the gap after END test-1 -> START test-2 MUST NOT emit BACKGROUND(after=test-1, before=test-2) + // and MUST increment backgroundLost so the next clean gap reports "lost":1! + collector = new ServerSocket(0, 2, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(30000); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + assertTrue(KeployDedupAgent.start()); + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(30000); + OutputStream out = sdk.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertNotNull(parseHello(in.readLine())); + send(out, "ACK_ID"); + send(out, "BACKGROUND"); + + send(out, "START ts/test-1"); + assertEquals("ACK ts/test-1", in.readLine()); + CountDownLatch allowAudit = new CountDownLatch(1); + CountDownLatch auditDone = new CountDownLatch(1); + Object req1 = RequestGate.enter(); + try { + probes[0] = true; + Thread audit = new Thread(() -> { + try { + allowAudit.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + probes[2] = true; + auditDone.countDown(); + }, "tcp-audit-thread"); + audit.setDaemon(true); + RequestGate.startThread(audit); + } finally { + RequestGate.exit(req1); + } + send(out, "END ts/test-1"); + String cov1 = in.readLine(); + assertTrue("test-1 flags untracked-async:thread-start: " + cov1, + cov1.contains("\"untracked-async:thread-start\"")); + assertEquals("ACK ts/test-1", in.readLine()); + + // Audit thread runs in the gap between END test-1 and START test-2 and finishes. + allowAudit.countDown(); + assertTrue("audit ran in gap", auditDone.await(5, TimeUnit.SECONDS)); + + // START test-2 clears probe[2] but MUST NOT emit BACKGROUND! + send(out, "START ts/test-2"); + assertEquals("ACK ts/test-2", in.readLine()); + assertFalse("gap probe cleared", probes[2]); + send(out, "NOP check-no-bg"); + assertEquals("no BACKGROUND emitted for gap holding test-1's audit tail", + "ACK check-no-bg", in.readLine()); + + // Clean test-2 -> END test-2 -> real background hit -> START test-3 emits BACKGROUND with lost:1! + Object req2 = RequestGate.enter(); + try { + probes[1] = true; + } finally { + RequestGate.exit(req2); + } + send(out, "END ts/test-2"); + String cov2 = in.readLine(); + assertTrue("test-2 COV received", cov2.startsWith("COV ")); + assertEquals("ACK ts/test-2", in.readLine()); + + probes[3] = true; // genuine background hit between test-2 and test-3 + send(out, "START ts/test-3"); + assertEquals("ACK ts/test-3", in.readLine()); + String bgLine = in.readLine(); + assertNotNull("clean gap emits BACKGROUND", bgLine); + assertTrue("BACKGROUND frame expected, got: " + bgLine, bgLine.startsWith("BACKGROUND ")); + assertTrue("BACKGROUND carries after=ts/test-2: " + bgLine, + bgLine.contains("\"after\":\"ts/test-2\"")); + assertTrue("BACKGROUND reports lost:1 from suppressed gap: " + bgLine, + bgLine.contains("\"lost\":1")); + + // Active lingering thread across A -> B -> C: test-3 starts a live thread still alive at END test-4, + // finishing inside the test-4 -> test-5 gap! BOTH gaps (test-3->test-4 AND + // test-4->test-5) MUST be suppressed! + CountDownLatch allowLongAudit = new CountDownLatch(1); + CountDownLatch longAuditDone = new CountDownLatch(1); + Object req3 = RequestGate.enter(); + try { + probes[0] = true; + Thread longAudit = new Thread(() -> { + try { + allowLongAudit.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + probes[2] = true; + longAuditDone.countDown(); + }, "tcp-long-audit"); + longAudit.setDaemon(true); + RequestGate.startThread(longAudit); + } finally { + RequestGate.exit(req3); + } + send(out, "END ts/test-3"); + assertTrue(in.readLine().startsWith("COV ")); + assertEquals("ACK ts/test-3", in.readLine()); + + // test-4 runs while longAudit is STILL ALIVE at END test-4. + send(out, "START ts/test-4"); + assertEquals("ACK ts/test-4", in.readLine()); + Object req4 = RequestGate.enter(); + try { + probes[1] = true; + } finally { + RequestGate.exit(req4); + } + send(out, "END ts/test-4"); + String cov4 = in.readLine(); + assertTrue("test-4 carries tail:ts/test-3: " + cov4, cov4.contains("\"tail:ts/test-3\"")); + assertEquals("ACK ts/test-4", in.readLine()); + + // Now longAudit finishes in the gap between END test-4 and START test-5! + allowLongAudit.countDown(); + assertTrue(longAuditDone.await(5, TimeUnit.SECONDS)); + send(out, "START ts/test-5"); + assertEquals("ACK ts/test-5", in.readLine()); + send(out, "NOP check-no-bg-bc"); + assertEquals("B->C gap holding A's finishing audit MUST suppress BACKGROUND", + "ACK check-no-bg-bc", in.readLine()); + + // Opposite case: test-5 starts a thread AND joins it before END -> + // next gap IS clean and DOES emit BACKGROUND (with lost:1 from test-4->test-5)! + Object req5 = RequestGate.enter(); + try { + probes[1] = true; + Thread joined = new Thread(() -> { }, "tcp-joined-thread"); + RequestGate.startThread(joined); + joined.join(5000); + } finally { + RequestGate.exit(req5); + } + send(out, "END ts/test-5"); + assertTrue(in.readLine().startsWith("COV ")); + assertEquals("ACK ts/test-5", in.readLine()); + + probes[3] = true; + send(out, "START ts/test-6"); + assertEquals("ACK ts/test-6", in.readLine()); + String bg56 = in.readLine(); + assertTrue("joined thread before END must NOT suppress next clean BACKGROUND: " + bg56, + bg56 != null && bg56.startsWith("BACKGROUND ") + && bg56.contains("\"after\":\"ts/test-5\"") + && bg56.contains("\"lost\":1")); + + // Independent suppressBackground[0] branch: test-6 ends completely clean + // (prevMayEmitTail == false), then an expired job starts in the gap before START test-7 + // so ONLY suppressBackground[0] suppresses BACKGROUND! + Object req6 = RequestGate.enter(); + try { + probes[0] = true; + } finally { + RequestGate.exit(req6); + } + send(out, "END ts/test-6"); + assertTrue(in.readLine().startsWith("COV ")); + assertEquals("ACK ts/test-6", in.readLine()); + + long savedJobMax = JobGate.handedJobMaxNanos; + Object expiredToken = null; + try { + JobGate.handedJobMaxNanos = 1L; + expiredToken = JobGate.enterAs(new JobGate.Attribution("scheduled:gap.Job.run", false, 0L)); + Thread.sleep(5); + probes[2] = true; + send(out, "START ts/test-7"); + assertEquals("ACK ts/test-7", in.readLine()); + send(out, "NOP check-suppress-only"); + assertEquals("suppressBackground[0] alone MUST suppress BACKGROUND when expired job active", + "ACK check-suppress-only", in.readLine()); + } finally { + JobGate.exit(expiredToken); + JobGate.handedJobMaxNanos = savedJobMax; + } + Object req7 = RequestGate.enter(); + try { + probes[1] = true; + } finally { + RequestGate.exit(req7); + } + send(out, "END ts/test-7"); + String cov7 = in.readLine(); + assertTrue("test-7 carries job-tail: " + cov7, cov7.contains("\"job-tail:scheduled:gap.Job.run\"")); + assertEquals("ACK ts/test-7", in.readLine()); + + probes[3] = true; + send(out, "START ts/test-8"); + assertEquals("ACK ts/test-8", in.readLine()); + String bg78 = in.readLine(); + assertTrue("next clean gap after suppressBackground[0] reports lost:1: " + bg78, + bg78 != null && bg78.startsWith("BACKGROUND ") && bg78.contains("\"lost\":1")); + } finally { + KeployDedupAgent.stop(); + collector.close(); + collector = null; + } + + // 2. Unix transport: verify BOTH (a) BACKGROUND suppression + lost:1 AND + // (b) no-server-entry end-to-end on Unix (unverified: ["no-server-entry"], NO "contaminated")! + System.clearProperty(ENDPOINT_PROPERTY); + KeployDedupAgent.transformerAdded = true; + File sockDir = tmp.newFolder("unix-bg-suppress"); + KeployDedupAgent.controlSocketPath = new File(sockDir, "ctrl.sock").getAbsolutePath(); + KeployDedupAgent.dataSocketPath = new File(sockDir, "data.sock").getAbsolutePath(); + java.util.concurrent.BlockingQueue records = new java.util.concurrent.LinkedBlockingQueue<>(); + org.newsclub.net.unix.AFUNIXServerSocket dataServer = org.newsclub.net.unix.AFUNIXServerSocket.newInstance(); + dataServer.bind(org.newsclub.net.unix.AFUNIXSocketAddress.of(new File(KeployDedupAgent.dataSocketPath))); + Thread dataReader = new Thread(() -> { + while (!dataServer.isClosed()) { + try (Socket conn = dataServer.accept(); + BufferedReader r = new BufferedReader( + new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { + StringBuilder sb = new StringBuilder(); + String l; + while ((l = r.readLine()) != null) { + sb.append(l); + } + if (sb.length() > 0) { + records.add(sb.toString()); + } + } catch (IOException ignored) { + } + } + }, "unix-data-reader"); + dataReader.setDaemon(true); + dataReader.start(); + try { + assertTrue(KeployDedupAgent.start()); + assertTrue(sendUnixControl("BACKGROUND").startsWith("ACK proto=3")); + assertTrue(sendUnixControl("START ts/u1").startsWith("ACK proto=3")); + CountDownLatch allowAudit = new CountDownLatch(1); + CountDownLatch auditDone = new CountDownLatch(1); + Object req1 = RequestGate.enter(); + try { + probes[0] = true; + Thread audit = new Thread(() -> { + try { + allowAudit.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + probes[2] = true; + auditDone.countDown(); + }, "unix-audit-thread"); + audit.setDaemon(true); + RequestGate.startThread(audit); + } finally { + RequestGate.exit(req1); + } + assertTrue(sendUnixControl("END ts/u1").startsWith("ACK proto=3")); + allowAudit.countDown(); + assertTrue(auditDone.await(5, TimeUnit.SECONDS)); + + assertTrue(sendUnixControl("START ts/u2").startsWith("ACK proto=3")); + // Clean counted request on Unix -> emits BACKGROUND(u2->u3) with lost:1 from u1->u2! + Object reqU2 = RequestGate.enter(); + try { + probes[1] = true; + } finally { + RequestGate.exit(reqU2); + } + assertTrue(sendUnixControl("END ts/u2").startsWith("ACK proto=3")); + + probes[3] = true; + String startU3Reply = sendUnixControl("START ts/u3"); + assertTrue("Unix START before no-server-entry reports windowCut=true: " + startU3Reply, + startU3Reply.startsWith("ACK proto=3") && startU3Reply.contains("windowCut=true")); + // Uncounted server on Unix (probes > 0 while enteredCount == 0): + // MUST emit "unverified":["no-server-entry"] with NO "contaminated" field, + // MUST latch windowCut=false on this END ACK and subsequent ACKs, + // AND MUST suppress BACKGROUND(u3->u4) because an uncounted request's tail may run in the gap! + probes[1] = true; + String endU3Reply = sendUnixControl("END ts/u3"); + assertTrue("Unix END seeing no-server-entry must report windowCut=false: " + endU3Reply, + endU3Reply.startsWith("ACK proto=3") && endU3Reply.contains("windowCut=false") + && endU3Reply.contains("asyncExecutors=false")); + + probes[3] = true; // gap after uncounted u3: MUST be suppressed (lost increments to 1)! + String startU4Reply = sendUnixControl("START ts/u4"); + assertTrue("Unix subsequent START after no-server-entry stays windowCut=false: " + startU4Reply, + startU4Reply.startsWith("ACK proto=3") && startU4Reply.contains("windowCut=false")); + Object reqU4 = RequestGate.enter(); + try { + probes[0] = true; + } finally { + RequestGate.exit(reqU4); + } + String endU4Reply = sendUnixControl("END ts/u4"); + assertTrue("Unix subsequent END stays windowCut=false: " + endU4Reply, + endU4Reply.startsWith("ACK proto=3") && endU4Reply.contains("windowCut=false")); + + probes[3] = true; // clean gap u4->u5 carries lost:1 from suppressed u3->u4! + assertTrue(sendUnixControl("START ts/u5").startsWith("ACK proto=3")); + + // Drain data records and verify: + // - no BACKGROUND for u1->u2 or u3->u4 + // - BACKGROUND for u2->u3 has lost:1 + // - u3 carries "unverified":["no-server-entry"] and NO "contaminated" + // - BACKGROUND for u4->u5 has lost:1 (proving u3 no-server-entry suppressed u3->u4!) + String recU3 = null; + String bgU2U3 = null; + String bgU4U5 = null; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline && (recU3 == null || bgU2U3 == null || bgU4U5 == null)) { + String rec = records.poll(200, TimeUnit.MILLISECONDS); + if (rec == null) { + continue; + } + assertFalse("must NOT emit BACKGROUND for gap after u1: " + rec, + rec.contains("\"kind\":\"background\"") && rec.contains("\"after\":\"ts/u1\"")); + assertFalse("must NOT emit BACKGROUND for gap after no-server-entry u3: " + rec, + rec.contains("\"kind\":\"background\"") && rec.contains("\"after\":\"ts/u3\"")); + if (rec.contains("\"id\":\"ts/u3\"")) { + recU3 = rec; + } + if (rec.contains("\"kind\":\"background\"") && rec.contains("\"after\":\"ts/u2\"")) { + bgU2U3 = rec; + } + if (rec.contains("\"kind\":\"background\"") && rec.contains("\"after\":\"ts/u4\"")) { + bgU4U5 = rec; + } + } + assertNotNull("expected Unix record for ts/u3", recU3); + assertTrue("Unix uncounted-server record must carry unverified no-server-entry: " + recU3, + recU3.contains("\"unverified\":[\"no-server-entry\"]")); + assertFalse("Unix uncounted-server record must NOT carry contaminated: " + recU3, + recU3.contains("\"contaminated\"")); + assertNotNull("expected BACKGROUND for clean gap u2->u3", bgU2U3); + assertTrue("Unix BACKGROUND u2->u3 must carry lost:1 for suppressed u1->u2 gap: " + bgU2U3, + bgU2U3.contains("\"lost\":1")); + assertNotNull("expected BACKGROUND for clean gap u4->u5", bgU4U5); + assertTrue("Unix BACKGROUND u4->u5 must carry lost:1 for suppressed no-server-entry u3->u4 gap: " + bgU4U5, + bgU4U5.contains("\"lost\":1")); + } finally { + KeployDedupAgent.stop(); + dataServer.close(); + } + } + + public static final class MethodRefTxHelper { + public void execute(Runnable r) { + r.run(); + } + + public Object submit(Runnable r) { + r.run(); + return "ok1"; + } + + public Object submit(Runnable r, Object result) { + r.run(); + return result; + } + } + + public static final class CustomMethodRefExecutor implements Executor { + @Override + public void execute(Runnable command) { + command.run(); + } + } + + public static final class CustomMethodRefExecutorService extends AbstractExecutorService { + @Override + public void shutdown() { + } + + @Override + public List shutdownNow() { + return Collections.emptyList(); + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + + @Override + public void execute(Runnable command) { + command.run(); + } + + @Override + public Future submit(Runnable task) { + return super.submit(task); + } + + @Override + public Future submit(Runnable task, T result) { + return super.submit(task, result); + } + } + + @FunctionalInterface + public interface TriSubmitFn { + R apply(A a, B b, C c); + } + + public static final class BoundExecuteMethodRefCaller { + public static void run(MethodRefTxHelper h, Runnable r) { + java.util.function.Consumer c = h::execute; + c.accept(r); + } + } + + public static final class UnboundExecuteMethodRefCaller { + public static void run(MethodRefTxHelper h, Runnable r) { + java.util.function.BiConsumer b = MethodRefTxHelper::execute; + b.accept(h, r); + } + } + + public static final class BoundSubmitMethodRefCaller { + public static Object run(MethodRefTxHelper h, Runnable r) { + java.util.function.Function f = h::submit; + Object r1 = f.apply(r); + java.util.function.BiFunction f2 = h::submit; + return r1 + ":" + f2.apply(r, "ok2"); + } + } + + public static final class UnboundSubmitMethodRefCaller { + public static Object run(MethodRefTxHelper h, Runnable r) { + java.util.function.BiFunction bf = MethodRefTxHelper::submit; + Object r1 = bf.apply(h, r); + TriSubmitFn bf2 = MethodRefTxHelper::submit; + return r1 + ":" + bf2.apply(h, r, "ok2"); + } + } + + public static final class RealBoundExecMethodRefCaller { + public static void run(Executor e, Runnable r) { + java.util.function.Consumer c = e::execute; + c.accept(r); + } + } + + public static final class RealUnboundExecMethodRefCaller { + public static void run(CustomMethodRefExecutor e, Runnable r) { + java.util.function.BiConsumer b = CustomMethodRefExecutor::execute; + b.accept(e, r); + } + } + + public static final class RealBoundSubmitMethodRefCaller { + public static Object run(ExecutorService s, Runnable r) { + java.util.function.Function> f = s::submit; + Future f1 = f.apply(r); + java.util.function.BiFunction> f2 = s::submit; + Future res2 = f2.apply(r, "res"); + return f1 != null && res2 != null ? "ok" : "bad"; + } + } + + public static final class RealUnboundSubmitMethodRefCaller { + public static Object run(CustomMethodRefExecutorService s, Runnable r) { + java.util.function.BiFunction> bf = + CustomMethodRefExecutorService::submit; + Future f1 = bf.apply(s, r); + TriSubmitFn> bf2 = + CustomMethodRefExecutorService::submit; + Future f2 = bf2.apply(s, r, "res"); + return f1 != null && f2 != null ? "ok" : "bad"; + } + } + + public static final class UnboundInlineExecMethodRefCaller { + public static void run(org.springframework.core.task.SyncTaskExecutor e, Runnable r) { + java.util.function.BiConsumer b = + org.springframework.core.task.SyncTaskExecutor::execute; + b.accept(e, r); + } + } + + private static final class ChildFirstClassLoader extends ClassLoader { + private final String targetName; + private final byte[] bytes; + + ChildFirstClassLoader(ClassLoader parent, String targetName, byte[] bytes) { + super(parent); + this.targetName = targetName; + this.bytes = bytes; + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (targetName.equals(name)) { + synchronized (getClassLoadingLock(name)) { + Class loaded = findLoadedClass(name); + if (loaded == null) { + loaded = defineClass(name, bytes, 0, bytes.length); + } + if (resolve) { + resolveClass(loaded); + } + return loaded; + } + } + return super.loadClass(name, resolve); + } + } + + private static Class rewriteClassWithWrapExecutorCalls(Class cls) throws Exception { + String name = cls.getName(); + byte[] raw; + try (java.io.InputStream in = cls.getClassLoader().getResourceAsStream(name.replace('.', '/') + ".class")) { + assertNotNull("class bytes not found for " + name, in); + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + for (int n; (n = in.read(buf)) > 0; ) { + out.write(buf, 0, n); + } + raw = out.toByteArray(); + } + byte[] rewritten = ServerEntries.wrapExecutorCalls(raw); + assertNotNull("ServerEntries.wrapExecutorCalls must rewrite " + cls.getSimpleName(), rewritten); + return new ChildFirstClassLoader(cls.getClassLoader(), name, rewritten).loadClass(name); + } + + @Test(timeout = 60000) + public void methodReferencesToNonExecutorHelpersAreNotFlaggedWhileRealExecutorsStillFlag() throws Exception { + Class boundExec = rewriteClassWithWrapExecutorCalls(BoundExecuteMethodRefCaller.class); + Class unboundExec = rewriteClassWithWrapExecutorCalls(UnboundExecuteMethodRefCaller.class); + Class boundSubmit = rewriteClassWithWrapExecutorCalls(BoundSubmitMethodRefCaller.class); + Class unboundSubmit = rewriteClassWithWrapExecutorCalls(UnboundSubmitMethodRefCaller.class); + Class realBoundExec = rewriteClassWithWrapExecutorCalls(RealBoundExecMethodRefCaller.class); + Class realUnboundExec = rewriteClassWithWrapExecutorCalls(RealUnboundExecMethodRefCaller.class); + Class realBoundSubmit = rewriteClassWithWrapExecutorCalls(RealBoundSubmitMethodRefCaller.class); + Class realUnboundSubmit = rewriteClassWithWrapExecutorCalls(RealUnboundSubmitMethodRefCaller.class); + Class unboundInlineExec = rewriteClassWithWrapExecutorCalls(UnboundInlineExecMethodRefCaller.class); + + MethodRefTxHelper helper = new MethodRefTxHelper(); + + // 1. Disarmed non-Executor method refs must be complete no-ops (must NOT touch unarmed hand-off state). + RequestGate.disarm(); + Object unarmedTok = RequestGate.enter(); + try { + boundExec.getMethod("run", MethodRefTxHelper.class, Runnable.class).invoke(null, helper, (Runnable) () -> { }); + unboundExec.getMethod("run", MethodRefTxHelper.class, Runnable.class).invoke(null, helper, (Runnable) () -> { }); + boundSubmit.getMethod("run", MethodRefTxHelper.class, Runnable.class).invoke(null, helper, (Runnable) () -> { }); + unboundSubmit.getMethod("run", MethodRefTxHelper.class, Runnable.class).invoke(null, helper, (Runnable) () -> { }); + } finally { + RequestGate.exit(unarmedTok); + } + // First armed window sees the one-time armed-mid-flight from unarmedTok, second window MUST be clean + // (proving lastUnarmedHandOffNanos was NOT set by non-Executor method refs). + RequestGate.open("disarmed-check-1", null); + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + RequestGate.open("disarmed-check-2", null); + assertEquals("non-Executor method refs while disarmed must NOT trigger unarmed hand-off tail", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // 2. Bound & unbound execute/submit method refs on plain non-Executor helper -> 0 contamination, 0 tail:! + Class[] helperCallers = new Class[] {boundExec, unboundExec, boundSubmit, unboundSubmit}; + for (Class caller : helperCallers) { + String label = caller.getName(); + RequestGate.disarm(); + RequestGate.open("mref-helper-" + label + "-1", null); + AtomicInteger ran = new AtomicInteger(); + Object tok = RequestGate.enter(); + try { + caller.getMethod("run", MethodRefTxHelper.class, Runnable.class) + .invoke(null, helper, (Runnable) ran::incrementAndGet); + } finally { + RequestGate.exit(tok); + } + assertTrue(label + " invoked target", ran.get() > 0); + RequestGate.WindowOutcome out1 = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals(label + " must have 0 contamination", + Collections.emptyList(), out1.contaminations); + assertFalse(label + " must have tailActiveAtEnd=false", out1.tailActiveAtEnd); + + RequestGate.open("mref-helper-" + label + "-2", null); + Object tok2 = RequestGate.enter(); + RequestGate.exit(tok2); + RequestGate.WindowOutcome out2 = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals(label + " must leave 0 tail: on next window", + Collections.emptyList(), out2.contaminations); + } + + // 3. Unbound inline executor method ref (SyncTaskExecutor::execute) -> 0 contamination, 0 tail:! + RequestGate.disarm(); + RequestGate.open("mref-inline-1", null); + AtomicBoolean inlineRan = new AtomicBoolean(false); + Object tokInline = RequestGate.enter(); + try { + unboundInlineExec.getMethod("run", org.springframework.core.task.SyncTaskExecutor.class, Runnable.class) + .invoke(null, new org.springframework.core.task.SyncTaskExecutor(), + (Runnable) () -> inlineRan.set(true)); + } finally { + RequestGate.exit(tokInline); + } + assertTrue("SyncTaskExecutor::execute ran", inlineRan.get()); + assertEquals("unbound SyncTaskExecutor::execute must NOT contaminate", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // 4. Positive controls: bound & unbound method refs to real custom Executor / ExecutorService STILL flag! + CustomMethodRefExecutor customExec = new CustomMethodRefExecutor(); + CustomMethodRefExecutorService customSvc = new CustomMethodRefExecutorService(); + + RequestGate.disarm(); + RequestGate.open("mref-real-bound-exec", null); + Object tokRbe = RequestGate.enter(); + try { + realBoundExec.getMethod("run", Executor.class, Runnable.class) + .invoke(null, customExec, (Runnable) () -> { }); + } finally { + RequestGate.exit(tokRbe); + } + RequestGate.WindowOutcome rbeOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("bound real Executor::execute must flag untracked-executor: " + rbeOut.contaminations, + rbeOut.contaminations.contains("untracked-executor:" + CustomMethodRefExecutor.class.getName())); + + RequestGate.disarm(); + RequestGate.open("mref-real-unbound-exec", null); + Object tokRue = RequestGate.enter(); + try { + realUnboundExec.getMethod("run", CustomMethodRefExecutor.class, Runnable.class) + .invoke(null, customExec, (Runnable) () -> { }); + } finally { + RequestGate.exit(tokRue); + } + RequestGate.WindowOutcome rueOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("unbound real Executor::execute must flag untracked-executor: " + rueOut.contaminations, + rueOut.contaminations.contains("untracked-executor:" + CustomMethodRefExecutor.class.getName())); + + RequestGate.disarm(); + RequestGate.open("mref-real-bound-submit", null); + Object tokRbs = RequestGate.enter(); + try { + realBoundSubmit.getMethod("run", ExecutorService.class, Runnable.class) + .invoke(null, customSvc, (Runnable) () -> { }); + } finally { + RequestGate.exit(tokRbs); + } + RequestGate.WindowOutcome rbsOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("bound real ExecutorService::submit must flag untracked-executor: " + rbsOut.contaminations, + rbsOut.contaminations.contains("untracked-executor:" + CustomMethodRefExecutorService.class.getName())); + + RequestGate.disarm(); + RequestGate.open("mref-real-unbound-submit", null); + Object tokRus = RequestGate.enter(); + try { + realUnboundSubmit.getMethod("run", CustomMethodRefExecutorService.class, Runnable.class) + .invoke(null, customSvc, (Runnable) () -> { }); + } finally { + RequestGate.exit(tokRus); + } + RequestGate.WindowOutcome rusOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("unbound real ExecutorService::submit must flag untracked-executor: " + rusOut.contaminations, + rusOut.contaminations.contains("untracked-executor:" + CustomMethodRefExecutorService.class.getName())); + assertFalse("in-window method refs must NOT trip pre-captured executor latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor); + } + + public static final class PreCapturedBoundExecCaller { + private static volatile java.util.function.Consumer captured; + + public static void capture(Object e) { + captured = ((Executor) e)::execute; + } + + public static void invoke(Runnable r) { + captured.accept(r); + } + } + + public static final class PreCapturedBoundSubmitCaller { + private static volatile java.util.function.Function> captured; + + public static void capture(Object s) { + captured = ((ExecutorService) s)::submit; + } + + public static Future invoke(Runnable r) { + return captured.apply(r); + } + } + + public static final class PreCapturedUnboundExecCaller { + private static volatile java.util.function.BiConsumer captured; + + public static void capture() { + captured = Executor::execute; + } + + public static void invoke(Executor e, Runnable r) { + captured.accept(e, r); + } + } + + public static final class PreCapturedUnboundSubmitCaller { + private static volatile java.util.function.BiFunction> captured; + + public static void capture() { + captured = ExecutorService::submit; + } + + public static Future invoke(ExecutorService s, Runnable r) { + return captured.apply(s, r); + } + } + + public static final class PreCapturedNonExecHelperCaller { + private static volatile java.util.function.Consumer boundExec; + private static volatile java.util.function.BiConsumer unboundExec; + private static volatile java.util.function.Function boundSubmit; + private static volatile java.util.function.BiFunction unboundSubmit; + + public static void capture(MethodRefTxHelper h) { + boundExec = h::execute; + unboundExec = MethodRefTxHelper::execute; + boundSubmit = h::submit; + unboundSubmit = MethodRefTxHelper::submit; + } + + public static void invokeAll(MethodRefTxHelper h, Runnable r) { + boundExec.accept(r); + unboundExec.accept(h, r); + boundSubmit.apply(r); + unboundSubmit.apply(h, r); + } + } + + public static final class PreCapturedInlineAndSpringCaller { + private static volatile java.util.function.Consumer boundInline; + private static volatile java.util.function.BiConsumer unboundInline; + private static volatile java.util.function.Consumer boundSpring; + + public static void capture(org.springframework.core.task.SyncTaskExecutor inline, + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor spring) { + boundInline = ((Executor) inline)::execute; + unboundInline = org.springframework.core.task.SyncTaskExecutor::execute; + boundSpring = ((Executor) spring)::execute; + } + + public static void invokeInline(org.springframework.core.task.SyncTaskExecutor inline, Runnable r) { + boundInline.accept(r); + unboundInline.accept(inline, r); + } + + public static void invokeSpring(Runnable r) { + boundSpring.accept(r); + } + } + + @Test(timeout = 60000) + public void preCapturedExecutorMethodRefLatchesAsyncExecutorsFalseOnTcpAndUnix() throws Exception { + Class boundExec = rewriteClassWithWrapExecutorCalls(PreCapturedBoundExecCaller.class); + Class boundSubmit = rewriteClassWithWrapExecutorCalls(PreCapturedBoundSubmitCaller.class); + Class unboundExec = rewriteClassWithWrapExecutorCalls(PreCapturedUnboundExecCaller.class); + Class unboundSubmit = rewriteClassWithWrapExecutorCalls(PreCapturedUnboundSubmitCaller.class); + + byte[] shopBytes = new byte[] {61, 62, 63}; + File shop = new File(tmp.newFolder("precaptured-exec-classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + boolean[] probes = inProcessJacoco().probes(IndexReport.classId(shopBytes), "com/acme/Shop", 2); + + ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + try { + // 1. TCP transport: initial HELLO declares asyncExecutors=true; capturing ((Executor) tpe)::execute + // outside any window latches asyncExecutors=false, refreshes HELLO before START/COV, + // and stays permanently latched across reconnect and subsequent windows. + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + KeployDedupAgent.observedNoServerEntry = false; + KeployDedupAgent.observedPreCapturedUntrackedExecutor = false; + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + + collector = new ServerSocket(0, 2, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(30000); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + assertTrue(KeployDedupAgent.start()); + try { + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(30000); + OutputStream out = sdk.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + JsonObject initial = parseHello(in.readLine()); + assertTrue("initial HELLO starts with windowCut=true", + initial.get("windowCut").getAsBoolean()); + assertTrue("initial HELLO starts with asyncExecutors=true", + initial.get("asyncExecutors").getAsBoolean()); + + send(out, "ACK_ID"); + // Capture bound ((Executor) tpe)::execute outside any request window (no RequestGate.enter). + boundExec.getMethod("capture", Object.class).invoke(null, tpe); + assertTrue("pre-captured bound Executor::execute must latch observedPreCapturedUntrackedExecutor", + KeployDedupAgent.observedPreCapturedUntrackedExecutor); + + // Next START refreshes HELLO with asyncExecutors=false BEFORE ACK! + send(out, "START ts/precaptured-1"); + JsonObject refreshed = parseHello(in.readLine()); + assertTrue("windowCut stays true when only pre-captured executor latches", + refreshed.get("windowCut").getAsBoolean()); + assertFalse("HELLO must refresh asyncExecutors=false after pre-capture", + refreshed.get("asyncExecutors").getAsBoolean()); + assertEquals("ACK ts/precaptured-1", in.readLine()); + + // Invoke the pre-captured method ref inside a request window. + CountDownLatch ran = new CountDownLatch(1); + Object tok = RequestGate.enter(); + try { + probes[1] = true; + boundExec.getMethod("invoke", Runnable.class).invoke(null, (Runnable) ran::countDown); + } finally { + RequestGate.exit(tok); + } + assertTrue("pre-captured executor ran task", ran.await(5, TimeUnit.SECONDS)); + send(out, "END ts/precaptured-1"); + String cov1 = in.readLine(); + assertTrue("COV emitted for precaptured-1", cov1.startsWith("COV ")); + assertEquals("ACK ts/precaptured-1", in.readLine()); + + // Subsequent clean window keeps asyncExecutors=false (no revert HELLO). + send(out, "START ts/precaptured-2"); + assertEquals("ACK ts/precaptured-2", in.readLine()); + Object tok2 = RequestGate.enter(); + try { + probes[1] = true; + } finally { + RequestGate.exit(tok2); + } + send(out, "END ts/precaptured-2"); + assertTrue(in.readLine().startsWith("COV ")); + assertEquals("ACK ts/precaptured-2", in.readLine()); + } + + // Connection 2 (after reconnect): asyncExecutors=false stays permanently latched! + try (Socket sdk2 = collector.accept()) { + sdk2.setSoTimeout(30000); + BufferedReader in2 = new BufferedReader( + new InputStreamReader(sdk2.getInputStream(), StandardCharsets.UTF_8)); + JsonObject reconnected = parseHello(in2.readLine()); + assertTrue("windowCut remains true after reconnect", + reconnected.get("windowCut").getAsBoolean()); + assertFalse("asyncExecutors=false stays permanently latched across reconnect", + reconnected.get("asyncExecutors").getAsBoolean()); + } + } finally { + KeployDedupAgent.stop(); + collector.close(); + collector = null; + System.clearProperty(ENDPOINT_PROPERTY); + } + + // 2. Startup (disarmed) capture for bound submit, unbound execute, and unbound submit + // all latch asyncExecutors=false BEFORE any collector connects! + String[] variants = new String[] {"boundSubmit", "unboundExec", "unboundSubmit"}; + for (String variant : variants) { + KeployDedupAgent.observedPreCapturedUntrackedExecutor = false; + RequestGate.disarm(); + if ("boundSubmit".equals(variant)) { + boundSubmit.getMethod("capture", Object.class).invoke(null, tpe); + } else if ("unboundExec".equals(variant)) { + unboundExec.getMethod("capture").invoke(null); + } else { + unboundSubmit.getMethod("capture").invoke(null); + } + assertTrue(variant + " captured while disarmed must latch observedPreCapturedUntrackedExecutor", + KeployDedupAgent.observedPreCapturedUntrackedExecutor); + JsonObject h = parseHello(connectAndReadHello(true)); + assertTrue(variant + " keeps windowCut=true", h.get("windowCut").getAsBoolean()); + assertFalse(variant + " must report asyncExecutors=false on initial HELLO", + h.get("asyncExecutors").getAsBoolean()); + } + + // 3. Unix transport: caps flip from asyncExecutors=true to asyncExecutors=false after + // pre-capture and stay false on subsequent windows. + KeployDedupAgent.observedPreCapturedUntrackedExecutor = false; + System.clearProperty(ENDPOINT_PROPERTY); + File sockDir = tmp.newFolder("unix-precaptured-exec"); + KeployDedupAgent.controlSocketPath = new File(sockDir, "ctrl.sock").getAbsolutePath(); + KeployDedupAgent.dataSocketPath = new File(sockDir, "data.sock").getAbsolutePath(); + org.newsclub.net.unix.AFUNIXServerSocket dataServer = + org.newsclub.net.unix.AFUNIXServerSocket.newInstance(); + dataServer.bind(org.newsclub.net.unix.AFUNIXSocketAddress.of(new File(KeployDedupAgent.dataSocketPath))); + Thread dataReader = new Thread(() -> { + while (!dataServer.isClosed()) { + try (Socket conn = dataServer.accept(); + BufferedReader r = new BufferedReader( + new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { + while (r.readLine() != null) { + // Drain published Unix coverage records. + } + } catch (IOException ignored) { + } + } + }, "unix-precaptured-data-reader"); + dataReader.setDaemon(true); + dataReader.start(); + try { + assertTrue(KeployDedupAgent.start()); + String ack1 = sendUnixControl("START ts/u-pre-1"); + assertTrue("Unix START before pre-capture reports asyncExecutors=true: " + ack1, + ack1.startsWith("ACK proto=3") && ack1.contains("windowCut=true") + && ack1.contains("asyncExecutors=true")); + String end1 = sendUnixControl("END ts/u-pre-1"); + assertTrue("Unix END before pre-capture reports asyncExecutors=true: " + end1, + end1.startsWith("ACK proto=3") && end1.contains("asyncExecutors=true")); + + // Capture outside any window. + boundExec.getMethod("capture", Object.class).invoke(null, tpe); + assertTrue(KeployDedupAgent.observedPreCapturedUntrackedExecutor); + + String ack2 = sendUnixControl("START ts/u-pre-2"); + assertTrue("Unix START after pre-capture must refresh asyncExecutors=false: " + ack2, + ack2.startsWith("ACK proto=3") && ack2.contains("windowCut=true") + && ack2.contains("asyncExecutors=false")); + CountDownLatch unixRan = new CountDownLatch(1); + Object tokU = RequestGate.enter(); + try { + boundExec.getMethod("invoke", Runnable.class).invoke(null, (Runnable) unixRan::countDown); + } finally { + RequestGate.exit(tokU); + } + assertTrue(unixRan.await(5, TimeUnit.SECONDS)); + String end2 = sendUnixControl("END ts/u-pre-2"); + assertTrue("Unix END stays asyncExecutors=false: " + end2, + end2.startsWith("ACK proto=3") && end2.contains("asyncExecutors=false")); + + String ack3 = sendUnixControl("START ts/u-pre-3"); + assertTrue("Unix subsequent window stays asyncExecutors=false: " + ack3, + ack3.startsWith("ACK proto=3") && ack3.contains("asyncExecutors=false")); + } finally { + KeployDedupAgent.stop(); + dataServer.close(); + } + } finally { + tpe.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void preCapturedNonExecutorAndInlineMethodRefsDoNotLatchAsyncExecutors() throws Exception { + Class helperCaller = rewriteClassWithWrapExecutorCalls(PreCapturedNonExecHelperCaller.class); + Class inlineAndSpringCaller = rewriteClassWithWrapExecutorCalls(PreCapturedInlineAndSpringCaller.class); + + byte[] shopBytes = new byte[] {64, 65, 66}; + File shop = new File(tmp.newFolder("nonexec-precaptured-classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + + MethodRefTxHelper helper = new MethodRefTxHelper(); + org.springframework.core.task.SyncTaskExecutor syncExec = new org.springframework.core.task.SyncTaskExecutor(); + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor springExec = + new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor(); + springExec.initialize(); + try { + ServerEntries.markSpringExecutorHookedForTests(springExec.getClass().getName()); + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + KeployDedupAgent.observedNoServerEntry = false; + KeployDedupAgent.observedPreCapturedUntrackedExecutor = false; + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + + // 1. Capture outside any window while DISARMED (startup) -> must NOT latch! + RequestGate.disarm(); + helperCaller.getMethod("capture", MethodRefTxHelper.class).invoke(null, helper); + inlineAndSpringCaller.getMethod("capture", + org.springframework.core.task.SyncTaskExecutor.class, + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.class) + .invoke(null, syncExec, springExec); + assertFalse("disarmed pre-capture of TxHelper/inline/hooked-Spring must NOT latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor); + + // 2. Capture outside any window while ARMED -> must NOT latch! + RequestGate.arm(); + helperCaller.getMethod("capture", MethodRefTxHelper.class).invoke(null, helper); + inlineAndSpringCaller.getMethod("capture", + org.springframework.core.task.SyncTaskExecutor.class, + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.class) + .invoke(null, syncExec, springExec); + assertFalse("armed outside-window capture of TxHelper/inline/hooked-Spring must NOT latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor); + + // 3. TCP HELLO keeps asyncExecutors=true! + JsonObject hello = parseHello(connectAndReadHello(true)); + assertTrue("windowCut stays true", hello.get("windowCut").getAsBoolean()); + assertTrue("asyncExecutors stays true for non-Executor/inline/hooked-Spring pre-captures", + hello.get("asyncExecutors").getAsBoolean()); + + // 4. Unix ACK keeps asyncExecutors=true! + File sockDir = tmp.newFolder("unix-nonexec-precaptured"); + KeployDedupAgent.controlSocketPath = new File(sockDir, "ctrl.sock").getAbsolutePath(); + KeployDedupAgent.dataSocketPath = new File(sockDir, "data.sock").getAbsolutePath(); + System.clearProperty(ENDPOINT_PROPERTY); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + assertTrue(KeployDedupAgent.start()); + try { + String ack = sendUnixControl("START ts/u-nonexec-pre"); + assertTrue("Unix ACK keeps asyncExecutors=true: " + ack, + ack.startsWith("ACK proto=3") && ack.contains("asyncExecutors=true")); + } finally { + KeployDedupAgent.stop(); + } + + // 5. Invoking all captured non-Executor and inline refs inside a window produces 0 contaminations! + RequestGate.disarm(); + RequestGate.open("nonexec-precaptured-call", null); + AtomicInteger count = new AtomicInteger(); + Object tok = RequestGate.enter(); + try { + helperCaller.getMethod("invokeAll", MethodRefTxHelper.class, Runnable.class) + .invoke(null, helper, (Runnable) count::incrementAndGet); + inlineAndSpringCaller.getMethod("invokeInline", + org.springframework.core.task.SyncTaskExecutor.class, Runnable.class) + .invoke(null, syncExec, (Runnable) count::incrementAndGet); + } finally { + RequestGate.exit(tok); + } + assertEquals("all 6 helper + inline invocations ran", 6, count.get()); + RequestGate.WindowOutcome out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals("pre-captured TxHelper/inline must produce 0 contaminations", + Collections.emptyList(), out.contaminations); + assertFalse("pre-captured TxHelper/inline must leave tailActiveAtEnd=false", out.tailActiveAtEnd); + assertFalse("latch remains false after in-window invocations", + KeployDedupAgent.observedPreCapturedUntrackedExecutor); + } finally { + ServerEntries.unmarkSpringExecutorHookedForTests(springExec.getClass().getName()); + springExec.shutdown(); + } + } + + @Test(timeout = 60000) + public void observedNoServerEntryLatchesWindowCutFalseBeforeCovAndAcrossReconnect() throws Exception { + byte[] shopBytes = new byte[] {41, 42, 43}; + File shop = new File(tmp.newFolder("armeria-uncounted-classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + boolean[] probes = inProcessJacoco().probes(IndexReport.classId(shopBytes), "com/acme/Shop", 2); + + // Simulate Armeria / Helidon / Play: -javaagent attached, endWait > 0, and server is NOT + // in ServerEntries.UNCOUNTED so initial HELLO starts with windowCut=true, asyncExecutors=true. + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + KeployDedupAgent.observedNoServerEntry = false; + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + + collector = new ServerSocket(0, 2, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(30000); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + assertTrue(KeployDedupAgent.start()); + + // Connection 1: initial HELLO has windowCut=true; first uncounted END refreshes HELLO + // with windowCut=false BEFORE COV and emits "unverified":["no-server-entry"] without "contaminated". + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(30000); + OutputStream out = sdk.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + JsonObject initial = parseHello(in.readLine()); + assertTrue("initial cold-start HELLO starts with windowCut=true", + initial.get("windowCut").getAsBoolean()); + assertTrue("initial cold-start HELLO starts with asyncExecutors=true", + initial.get("asyncExecutors").getAsBoolean()); + + send(out, "ACK_ID"); + send(out, "START ts/armeria-1"); + assertEquals("ACK ts/armeria-1", in.readLine()); + // Uncounted server executes app code without calling RequestGate.enter(). + probes[1] = true; + send(out, "END ts/armeria-1"); + + String beforeCov = in.readLine(); + JsonObject refreshed = parseHello(beforeCov); + assertFalse("END seeing noServerEntry must refresh HELLO windowCut=false BEFORE COV", + refreshed.get("windowCut").getAsBoolean()); + assertFalse("END seeing noServerEntry must refresh HELLO asyncExecutors=false BEFORE COV", + refreshed.get("asyncExecutors").getAsBoolean()); + + String cov = in.readLine(); + assertEquals("COV {\"id\":\"ts/armeria-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}," + + "\"unverified\":[\"no-server-entry\"]}", cov); + assertFalse("unverified no-server-entry must NOT emit contaminated field", + cov.contains("\"contaminated\"")); + assertEquals("ACK ts/armeria-1", in.readLine()); + } + + // Connection 2 (after reconnect): observedNoServerEntry stays permanently latched so the + // new connection's initial HELLO immediately declares windowCut=false! + try (Socket sdk2 = collector.accept()) { + sdk2.setSoTimeout(30000); + BufferedReader in2 = new BufferedReader( + new InputStreamReader(sdk2.getInputStream(), StandardCharsets.UTF_8)); + JsonObject reconnected = parseHello(in2.readLine()); + assertFalse("windowCut=false must stay permanently latched after reconnect", + reconnected.get("windowCut").getAsBoolean()); + assertFalse("asyncExecutors=false must stay permanently latched after reconnect", + reconnected.get("asyncExecutors").getAsBoolean()); + } + } + + @Test(timeout = 60000) + public void lateStartingExpiredLingeringTaskSuppressesBackgroundViaRequestGateOpenOnTcp() + throws Exception { + byte[] shopBytes = new byte[] {51, 52, 53}; + File shop = new File(tmp.newFolder("open-tail-tcp-bg-classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + System.setProperty(END_WAIT_PROPERTY, "20"); + boolean[] probes = inProcessJacoco().probes(IndexReport.classId(shopBytes), "com/acme/Shop", 4); + + long savedMaxLingering = RequestGate.maxLingeringNanos; + ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + try { + RequestGate.maxLingeringNanos = TimeUnit.MILLISECONDS.toNanos(40); + + // TCP transport: older lingering window L expires past maxLingeringNanos with a queued + // task not yet running at END N (so hasActiveLingering == false -> lastEndedMayEmitTail == false). + // The task starts in the N->N+1 gap (Hand.enter retains L again and hits probe[2]); + // START N+1 adds tail:L and MUST suppress BACKGROUND(N->N+1) via RequestGate.open() + // alone, incrementing lost to 1! + collector = new ServerSocket(0, 2, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(30000); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + assertTrue(KeployDedupAgent.start()); + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(30000); + OutputStream out = sdk.getOutputStream(); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertNotNull(parseHello(in.readLine())); + send(out, "ACK_ID"); + send(out, "BACKGROUND"); + + // Window L: creates a queued task (handed, not yet started) and cuts at END L. + send(out, "START ts/open-tail-L"); + assertEquals("ACK ts/open-tail-L", in.readLine()); + CountDownLatch taskStarted = new CountDownLatch(1); + CountDownLatch allowTaskFinish = new CountDownLatch(1); + Runnable handed; + Object reqL = RequestGate.enter(); + try { + probes[0] = true; + handed = RequestGate.hand(pool, () -> { + probes[2] = true; + taskStarted.countDown(); + try { + allowTaskFinish.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } finally { + RequestGate.exit(reqL); + } + send(out, "END ts/open-tail-L"); + String covL = in.readLine(); + assertTrue("L must be cut while queued task is pending: " + covL, + covL.contains("\"windowCut\":true")); + assertEquals("ACK ts/open-tail-L", in.readLine()); + + // Wait strictly past maxLingeringNanos so idle window L expires. + Thread.sleep(70); + + // Window N: consumes L's one-time cut report and evicts expired idle L from LINGERING; + // END N drains cleanly with hasActiveLingering == false (lastEndedMayEmitTail == false). + send(out, "START ts/open-tail-N"); + assertEquals("ACK ts/open-tail-N", in.readLine()); + Object reqN = RequestGate.enter(); + try { + probes[0] = true; + } finally { + RequestGate.exit(reqN); + } + send(out, "END ts/open-tail-N"); + String covN = in.readLine(); + assertTrue("N reports one-time cut tail from L: " + covN, covN.contains("\"tail:ts/open-tail-L\"")); + assertFalse("N itself is not cut: " + covN, covN.contains("\"windowCut\":true")); + assertEquals("ACK ts/open-tail-N", in.readLine()); + + // Gap N -> N+1: queued task from L now starts! Hand.enter() re-retains L with executing=1 + // and records L's probe[2] in the gap. + Future handedFuture = pool.submit(handed); + assertTrue("queued task from L started in N->N+1 gap", taskStarted.await(5, TimeUnit.SECONDS)); + + // START N+1: ONLY RequestGate.open()'s return value (next.hasOpeningTail()) can suppress + // BACKGROUND(N->N+1) here because prevMayEmitTail == false and JobGate.open() == false! + send(out, "START ts/open-tail-N1"); + assertEquals("ACK ts/open-tail-N1", in.readLine()); + send(out, "NOP check-open-tail-no-bg"); + assertEquals("RequestGate.open open-time tail MUST suppress TCP BACKGROUND(N->N+1)", + "ACK check-open-tail-no-bg", in.readLine()); + + allowTaskFinish.countDown(); + // Wait on Future.get() so Hand.exit() (executing=0, running=0) happens-before END N+1. + handedFuture.get(5, TimeUnit.SECONDS); + + Object reqN1 = RequestGate.enter(); + try { + probes[1] = true; + } finally { + RequestGate.exit(reqN1); + } + send(out, "END ts/open-tail-N1"); + String covN1 = in.readLine(); + assertTrue("N+1 carries tail:ts/open-tail-L: " + covN1, covN1.contains("\"tail:ts/open-tail-L\"")); + assertEquals("ACK ts/open-tail-N1", in.readLine()); + + // Clean gap N+1 -> N+2 emits BACKGROUND carrying lost:1 from suppressed N->N+1! + probes[3] = true; + send(out, "START ts/open-tail-N2"); + assertEquals("ACK ts/open-tail-N2", in.readLine()); + String bgN1N2 = in.readLine(); + assertTrue("clean TCP gap after N+1 must emit BACKGROUND with lost:1, got: " + bgN1N2, + bgN1N2 != null && bgN1N2.startsWith("BACKGROUND ") + && bgN1N2.contains("\"after\":\"ts/open-tail-N1\"") + && bgN1N2.contains("\"lost\":1")); + } finally { + KeployDedupAgent.stop(); + collector.close(); + collector = null; + } + } finally { + RequestGate.maxLingeringNanos = savedMaxLingering; + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void lateStartingExpiredLingeringTaskSuppressesBackgroundViaRequestGateOpenOnUnix() + throws Exception { + byte[] shopBytes = new byte[] {54, 55, 56}; + File shop = new File(tmp.newFolder("open-tail-unix-bg-classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + System.setProperty(END_WAIT_PROPERTY, "20"); + boolean[] probes = inProcessJacoco().probes(IndexReport.classId(shopBytes), "com/acme/Shop", 4); + + long savedMaxLingering = RequestGate.maxLingeringNanos; + ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + try { + RequestGate.maxLingeringNanos = TimeUnit.MILLISECONDS.toNanos(40); + System.clearProperty(ENDPOINT_PROPERTY); + File sockDir = tmp.newFolder("unix-open-tail-bg"); + KeployDedupAgent.controlSocketPath = new File(sockDir, "ctrl.sock").getAbsolutePath(); + KeployDedupAgent.dataSocketPath = new File(sockDir, "data.sock").getAbsolutePath(); + java.util.concurrent.BlockingQueue records = new java.util.concurrent.LinkedBlockingQueue<>(); + org.newsclub.net.unix.AFUNIXServerSocket dataServer = + org.newsclub.net.unix.AFUNIXServerSocket.newInstance(); + dataServer.bind(org.newsclub.net.unix.AFUNIXSocketAddress.of(new File(KeployDedupAgent.dataSocketPath))); + Thread dataReader = new Thread(() -> { + while (!dataServer.isClosed()) { + try (Socket conn = dataServer.accept(); + BufferedReader r = new BufferedReader( + new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { + StringBuilder sb = new StringBuilder(); + String l; + while ((l = r.readLine()) != null) { + sb.append(l); + } + if (sb.length() > 0) { + records.add(sb.toString()); + } + } catch (IOException ignored) { + } + } + }, "unix-open-tail-data-reader"); + dataReader.setDaemon(true); + dataReader.start(); + try { + assertTrue(KeployDedupAgent.start()); + assertTrue(sendUnixControl("BACKGROUND").startsWith("ACK proto=3")); + assertTrue(sendUnixControl("START ts/u-open-tail-L").startsWith("ACK proto=3")); + CountDownLatch uTaskStarted = new CountDownLatch(1); + CountDownLatch uAllowFinish = new CountDownLatch(1); + Runnable uHanded; + Object reqUL = RequestGate.enter(); + try { + probes[0] = true; + uHanded = RequestGate.hand(pool, () -> { + probes[2] = true; + uTaskStarted.countDown(); + try { + uAllowFinish.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } finally { + RequestGate.exit(reqUL); + } + assertTrue(sendUnixControl("END ts/u-open-tail-L").startsWith("ACK proto=3")); + Thread.sleep(70); + + assertTrue(sendUnixControl("START ts/u-open-tail-N").startsWith("ACK proto=3")); + Object reqUN = RequestGate.enter(); + try { + probes[0] = true; + } finally { + RequestGate.exit(reqUN); + } + assertTrue(sendUnixControl("END ts/u-open-tail-N").startsWith("ACK proto=3")); + + Future uHandedFuture = pool.submit(uHanded); + assertTrue("Unix queued task from L started in N->N+1 gap", uTaskStarted.await(5, TimeUnit.SECONDS)); + + assertTrue(sendUnixControl("START ts/u-open-tail-N1").startsWith("ACK proto=3")); + uAllowFinish.countDown(); + uHandedFuture.get(5, TimeUnit.SECONDS); + + Object reqUN1 = RequestGate.enter(); + try { + probes[1] = true; + } finally { + RequestGate.exit(reqUN1); + } + assertTrue(sendUnixControl("END ts/u-open-tail-N1").startsWith("ACK proto=3")); + + probes[3] = true; + assertTrue(sendUnixControl("START ts/u-open-tail-N2").startsWith("ACK proto=3")); + + String recN1 = null; + String bgN1N2 = null; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline && (recN1 == null || bgN1N2 == null)) { + String rec = records.poll(200, TimeUnit.MILLISECONDS); + if (rec == null) { + continue; + } + assertFalse("RequestGate.open open-time tail MUST suppress Unix BACKGROUND(u-open-tail-N->u-open-tail-N1): " + rec, + rec.contains("\"kind\":\"background\"") && rec.contains("\"after\":\"ts/u-open-tail-N\"")); + if (rec.contains("\"id\":\"ts/u-open-tail-N1\"")) { + recN1 = rec; + } + if (rec.contains("\"kind\":\"background\"") && rec.contains("\"after\":\"ts/u-open-tail-N1\"")) { + bgN1N2 = rec; + } + } + assertNotNull("expected Unix record for ts/u-open-tail-N1", recN1); + assertTrue("Unix ts/u-open-tail-N1 carries tail:ts/u-open-tail-L: " + recN1, + recN1.contains("\"tail:ts/u-open-tail-L\"")); + assertNotNull("expected Unix BACKGROUND for clean gap u-open-tail-N1->u-open-tail-N2", bgN1N2); + assertTrue("Unix BACKGROUND u-open-tail-N1->u-open-tail-N2 must carry lost:1: " + bgN1N2, + bgN1N2.contains("\"lost\":1")); + } finally { + KeployDedupAgent.stop(); + dataServer.close(); + } + } finally { + RequestGate.maxLingeringNanos = savedMaxLingering; + pool.shutdownNow(); + } + } + + private static String sendUnixControl(String command) throws IOException { + try (org.newsclub.net.unix.AFUNIXSocket s = org.newsclub.net.unix.AFUNIXSocket.newInstance()) { + s.connect(org.newsclub.net.unix.AFUNIXSocketAddress.of(new File(KeployDedupAgent.controlSocketPath))); + s.setSoTimeout(10000); + OutputStream out = s.getOutputStream(); + out.write((command + "\n").getBytes(StandardCharsets.UTF_8)); + out.flush(); + BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8)); + return r.readLine(); + } + } + + private static byte[] generateInlineExecutorClass(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", + new String[] {"java/util/concurrent/Executor"}); + emitDefaultCtor(cw); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "execute", "(Ljava/lang/Runnable;)V", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/lang/Runnable", "run", "()V", true); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(1, 2); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateInlineExecutorServiceClass(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, + "java/util/concurrent/AbstractExecutorService", null); + MethodVisitor ctor = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + ctor.visitCode(); + ctor.visitVarInsn(Opcodes.ALOAD, 0); + ctor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/concurrent/AbstractExecutorService", + "", "()V", false); + ctor.visitInsn(Opcodes.RETURN); + ctor.visitMaxs(1, 1); + ctor.visitEnd(); + + MethodVisitor exec = cw.visitMethod(Opcodes.ACC_PUBLIC, "execute", "(Ljava/lang/Runnable;)V", null, null); + exec.visitCode(); + exec.visitVarInsn(Opcodes.ALOAD, 1); + exec.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/lang/Runnable", "run", "()V", true); + exec.visitInsn(Opcodes.RETURN); + exec.visitMaxs(1, 2); + exec.visitEnd(); + + MethodVisitor sh = cw.visitMethod(Opcodes.ACC_PUBLIC, "shutdown", "()V", null, null); + sh.visitCode(); + sh.visitInsn(Opcodes.RETURN); + sh.visitMaxs(0, 1); + sh.visitEnd(); + + MethodVisitor shNow = cw.visitMethod(Opcodes.ACC_PUBLIC, "shutdownNow", "()Ljava/util/List;", null, null); + shNow.visitCode(); + shNow.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false); + shNow.visitInsn(Opcodes.ARETURN); + shNow.visitMaxs(1, 1); + shNow.visitEnd(); + + for (String boolMethod : new String[] {"isShutdown", "isTerminated"}) { + MethodVisitor bm = cw.visitMethod(Opcodes.ACC_PUBLIC, boolMethod, "()Z", null, null); + bm.visitCode(); + bm.visitInsn(Opcodes.ICONST_0); + bm.visitInsn(Opcodes.IRETURN); + bm.visitMaxs(1, 1); + bm.visitEnd(); + } + + MethodVisitor aw = cw.visitMethod(Opcodes.ACC_PUBLIC, "awaitTermination", + "(JLjava/util/concurrent/TimeUnit;)Z", null, null); + aw.visitCode(); + aw.visitInsn(Opcodes.ICONST_1); + aw.visitInsn(Opcodes.IRETURN); + aw.visitMaxs(1, 4); + aw.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateTxHelperAndTimerCancelCaller(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null); + emitDefaultCtor(cw); + + String txOwner = PlainSyncTxHelper.class.getName().replace('.', '/'); + MethodVisitor m1 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "callSyncHelper", + "(L" + txOwner + ";Ljava/lang/Runnable;Ljava/lang/Runnable;)V", null, null); + m1.visitCode(); + m1.visitVarInsn(Opcodes.ALOAD, 0); + m1.visitVarInsn(Opcodes.ALOAD, 1); + m1.visitMethodInsn(Opcodes.INVOKEVIRTUAL, txOwner, "execute", "(Ljava/lang/Runnable;)V", false); + m1.visitVarInsn(Opcodes.ALOAD, 0); + m1.visitVarInsn(Opcodes.ALOAD, 2); + m1.visitMethodInsn(Opcodes.INVOKEVIRTUAL, txOwner, "submit", + "(Ljava/lang/Runnable;)Ljava/lang/Object;", false); + m1.visitInsn(Opcodes.POP); + m1.visitVarInsn(Opcodes.ALOAD, 0); + m1.visitVarInsn(Opcodes.ALOAD, 2); + m1.visitLdcInsn("res"); + m1.visitMethodInsn(Opcodes.INVOKEVIRTUAL, txOwner, "submit", + "(Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/lang/Object;", false); + m1.visitInsn(Opcodes.POP); + m1.visitInsn(Opcodes.RETURN); + m1.visitMaxs(0, 0); + m1.visitEnd(); + + String subOwner = CustomWorkerThread.class.getName().replace('.', '/'); + MethodVisitor m2 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "startCustomThread", + "(L" + subOwner + ";)V", null, null); + m2.visitCode(); + m2.visitVarInsn(Opcodes.ALOAD, 0); + m2.visitMethodInsn(Opcodes.INVOKEVIRTUAL, subOwner, "start", "()V", false); + m2.visitInsn(Opcodes.RETURN); + m2.visitMaxs(0, 0); + m2.visitEnd(); + + // Schedule with 5s initial delay and cancel immediately (before first tick) + MethodVisitor m3 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "scheduleAndCancelPeriodic", + "(Ljava/util/Timer;Ljava/util/TimerTask;)V", null, null); + m3.visitCode(); + m3.visitVarInsn(Opcodes.ALOAD, 0); + m3.visitVarInsn(Opcodes.ALOAD, 1); + m3.visitLdcInsn(5000L); + m3.visitLdcInsn(5000L); + m3.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Timer", + "scheduleAtFixedRate", "(Ljava/util/TimerTask;JJ)V", false); + m3.visitVarInsn(Opcodes.ALOAD, 1); + m3.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/TimerTask", "cancel", "()Z", false); + m3.visitInsn(Opcodes.POP); + m3.visitInsn(Opcodes.RETURN); + m3.visitMaxs(0, 0); + m3.visitEnd(); + + MethodVisitor m4 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "scheduleAndCancelOneShot", + "(Ljava/util/Timer;Ljava/util/TimerTask;)V", null, null); + m4.visitCode(); + m4.visitVarInsn(Opcodes.ALOAD, 0); + m4.visitVarInsn(Opcodes.ALOAD, 1); + m4.visitLdcInsn(30000L); + m4.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Timer", + "schedule", "(Ljava/util/TimerTask;J)V", false); + m4.visitVarInsn(Opcodes.ALOAD, 1); + m4.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/TimerTask", "cancel", "()Z", false); + m4.visitInsn(Opcodes.POP); + m4.visitInsn(Opcodes.RETURN); + m4.visitMaxs(0, 0); + m4.visitEnd(); + + MethodVisitor m5 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "scheduleOneShotDelay", + "(Ljava/util/Timer;Ljava/util/TimerTask;J)V", null, null); + m5.visitCode(); + m5.visitVarInsn(Opcodes.ALOAD, 0); + m5.visitVarInsn(Opcodes.ALOAD, 1); + m5.visitVarInsn(Opcodes.LLOAD, 2); + m5.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Timer", + "schedule", "(Ljava/util/TimerTask;J)V", false); + m5.visitInsn(Opcodes.RETURN); + m5.visitMaxs(0, 0); + m5.visitEnd(); + + MethodVisitor m6 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "schedulePeriodicDelay", + "(Ljava/util/Timer;Ljava/util/TimerTask;JJ)V", null, null); + m6.visitCode(); + m6.visitVarInsn(Opcodes.ALOAD, 0); + m6.visitVarInsn(Opcodes.ALOAD, 1); + m6.visitVarInsn(Opcodes.LLOAD, 2); + m6.visitVarInsn(Opcodes.LLOAD, 4); + m6.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Timer", + "scheduleAtFixedRate", "(Ljava/util/TimerTask;JJ)V", false); + m6.visitInsn(Opcodes.RETURN); + m6.visitMaxs(0, 0); + m6.visitEnd(); + + MethodVisitor m7 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "cancelTask", + "(Ljava/util/TimerTask;)Z", null, null); + m7.visitCode(); + m7.visitVarInsn(Opcodes.ALOAD, 0); + m7.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/TimerTask", "cancel", "()Z", false); + m7.visitInsn(Opcodes.IRETURN); + m7.visitMaxs(0, 0); + m7.visitEnd(); + + MethodVisitor m7b = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "cancelTimer", + "(Ljava/util/Timer;)V", null, null); + m7b.visitCode(); + m7b.visitVarInsn(Opcodes.ALOAD, 0); + m7b.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Timer", "cancel", "()V", false); + m7b.visitInsn(Opcodes.RETURN); + m7b.visitMaxs(0, 0); + m7b.visitEnd(); + + String listenableIface = ListenableLikeExecutorService.class.getName().replace('.', '/'); + String subFutureIface = SubtypeFuture.class.getName().replace('.', '/'); + MethodVisitor m8 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "callTwoArgSubmit", + "(L" + listenableIface + ";Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/lang/Object;", null, null); + m8.visitCode(); + m8.visitVarInsn(Opcodes.ALOAD, 0); + m8.visitVarInsn(Opcodes.ALOAD, 1); + m8.visitVarInsn(Opcodes.ALOAD, 2); + m8.visitMethodInsn(Opcodes.INVOKEINTERFACE, listenableIface, "submit", + "(Ljava/lang/Runnable;Ljava/lang/Object;)L" + subFutureIface + ";", true); + m8.visitInsn(Opcodes.ARETURN); + m8.visitMaxs(0, 0); + m8.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateTimerAndBranchyClass(String className) { + String spec = System.getProperty("java.specification.version", "1.8"); + int classVersion = (!spec.startsWith("1.") && Integer.parseInt(spec) >= 17) ? Opcodes.V17 : Opcodes.V1_8; + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(classVersion, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null); + emitDefaultCtor(cw); + + // scheduleOneShot(Timer, TimerTask, long) -> void + MethodVisitor m1 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "scheduleOneShot", + "(Ljava/util/Timer;Ljava/util/TimerTask;J)V", null, null); + m1.visitCode(); + m1.visitVarInsn(Opcodes.ALOAD, 0); + m1.visitVarInsn(Opcodes.ALOAD, 1); + m1.visitVarInsn(Opcodes.LLOAD, 2); + m1.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Timer", "schedule", "(Ljava/util/TimerTask;J)V", false); + m1.visitInsn(Opcodes.RETURN); + m1.visitMaxs(0, 0); + m1.visitEnd(); + + // schedulePeriodic(Timer, long delay, long period) -> creates unreferenced TimerTask so only Timer holds it + MethodVisitor m2 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "schedulePeriodic", + "(Ljava/util/Timer;JJ)V", null, null); + m2.visitCode(); + m2.visitVarInsn(Opcodes.ALOAD, 0); + String noopTask = NoopTimerTask.class.getName().replace('.', '/'); + m2.visitTypeInsn(Opcodes.NEW, noopTask); + m2.visitInsn(Opcodes.DUP); + m2.visitMethodInsn(Opcodes.INVOKESPECIAL, noopTask, "", "()V", false); + m2.visitVarInsn(Opcodes.LLOAD, 1); + m2.visitVarInsn(Opcodes.LLOAD, 3); + m2.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Timer", + "scheduleAtFixedRate", "(Ljava/util/TimerTask;JJ)V", false); + m2.visitInsn(Opcodes.RETURN); + m2.visitMaxs(0, 0); + m2.visitEnd(); + + // branchySchedule(TaskScheduler, Runnable, Date, boolean) with if/else + try/catch + StackMapTable frames + MethodVisitor m3 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "branchySchedule", + "(Lorg/springframework/scheduling/TaskScheduler;Ljava/lang/Runnable;Ljava/util/Date;Z)" + + "Ljava/util/concurrent/ScheduledFuture;", null, null); + m3.visitCode(); + org.objectweb.asm.Label tryStart = new org.objectweb.asm.Label(); + org.objectweb.asm.Label tryEnd = new org.objectweb.asm.Label(); + org.objectweb.asm.Label catchBlock = new org.objectweb.asm.Label(); + org.objectweb.asm.Label elseBranch = new org.objectweb.asm.Label(); + m3.visitTryCatchBlock(tryStart, tryEnd, catchBlock, "java/lang/RuntimeException"); + m3.visitLabel(tryStart); + m3.visitVarInsn(Opcodes.ILOAD, 3); + m3.visitJumpInsn(Opcodes.IFEQ, elseBranch); + m3.visitVarInsn(Opcodes.ALOAD, 0); + m3.visitVarInsn(Opcodes.ALOAD, 1); + m3.visitVarInsn(Opcodes.ALOAD, 2); + m3.visitMethodInsn(Opcodes.INVOKEINTERFACE, "org/springframework/scheduling/TaskScheduler", + "schedule", "(Ljava/lang/Runnable;Ljava/util/Date;)Ljava/util/concurrent/ScheduledFuture;", true); + m3.visitLabel(tryEnd); + m3.visitInsn(Opcodes.ARETURN); + m3.visitLabel(elseBranch); + m3.visitInsn(Opcodes.ACONST_NULL); + m3.visitInsn(Opcodes.ARETURN); + m3.visitLabel(catchBlock); + m3.visitInsn(Opcodes.POP); + m3.visitInsn(Opcodes.ACONST_NULL); + m3.visitInsn(Opcodes.ARETURN); + m3.visitMaxs(0, 0); + m3.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + + public static final class NoopTimerTask extends java.util.TimerTask { + @Override + public void run() { + } + } + + @Test(timeout = 60000) + public void concurrentRequestExecutorAndJobGateContentionStaysBoundedAndLeakFree() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(4, 4, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + try { + RequestGate.open("contention", null); + JobGate.open(); + int threads = 8; + int iterations = 1000; + CountDownLatch start = new CountDownLatch(1); + Thread[] workers = new Thread[threads]; + AtomicReference failure = new AtomicReference<>(); + for (int t = 0; t < threads; t++) { + final KafkaContainerStub stub = new KafkaContainerStub(new String[] {"t-" + t}, new OrdersBean()); + workers[t] = new Thread(() -> { + try { + start.await(); + for (int i = 0; i < iterations; i++) { + Object req = RequestGate.enter(); + try { + Future f = RequestGate.submit(pool, () -> { }); + f.get(10, TimeUnit.SECONDS); + } finally { + RequestGate.exit(req); + } + Object jt = JobGate.enter(stub, "kafka"); + JobGate.exit(jt); + } + } catch (Throwable err) { + failure.compareAndSet(null, err); + } + }); + workers[t].start(); + } + long t0 = System.nanoTime(); + start.countDown(); + for (Thread w : workers) { + w.join(30000); + } + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0); + assertNull("no concurrent failure: " + failure.get(), failure.get()); + assertTrue("window drains cleanly", RequestGate.await(TimeUnit.SECONDS.toNanos(10))); + assertEquals("zero leaked PENDING_BY_FUTURE entries", 0, RequestGate.pendingByFutureSize()); + assertEquals("zero leaked PENDING_BY_EXECUTOR entries", 0, RequestGate.pendingByExecutorSize(pool)); + assertEquals("zero leaked JobGate runs", 0, JobGate.activeRunCount()); + assertEquals("all 8 listeners attributed", 8, JobGate.close().size()); + assertTrue("contention benchmark finished promptly: " + elapsedMs + " ms", elapsedMs < 30_000); + } finally { + pool.shutdownNow(); + } + } + + private static String sendUnix(String socketPath, String command) throws IOException { + try (AFUNIXSocket socket = AFUNIXSocket.newInstance()) { + socket.connect(AFUNIXSocketAddress.of(new File(socketPath)), 3000); + socket.setSoTimeout(30000); + OutputStream out = socket.getOutputStream(); + out.write((command + "\n").getBytes(StandardCharsets.UTF_8)); + out.flush(); + BufferedReader in = new BufferedReader( + new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); + String line = in.readLine(); + return line == null ? "" : line + "\n"; + } + } + + private static final class SelfReferencingJob implements Runnable { + Future future; + + @Override + public void run() { + // Self-referencing cancellable job pattern. + } + } + + public static final class OrdersBean { } + public static final class BillingBean { } + public static final class AuditBean { } + + public static final class AdapterStub { + private final Object bean; + AdapterStub(Object bean) { this.bean = bean; } + public Object getBean() { return bean; } + } + + public static final class KafkaPropsStub { + private final String[] topics; + private final Object listener; + KafkaPropsStub(String[] topics, Object listener) { this.topics = topics; this.listener = listener; } + public String[] getTopics() { return topics; } + public Object getMessageListener() { return listener; } + } + + public static final class KafkaContainerStub { + private final KafkaPropsStub props; + KafkaContainerStub(String[] topics, Object listener) { this.props = new KafkaPropsStub(topics, listener); } + public KafkaPropsStub getContainerProperties() { return props; } + } + + public static final class AmqpContainerStub { + private final String[] queues; + private final Object listener; + AmqpContainerStub(String[] queues, Object listener) { this.queues = queues; this.listener = listener; } + public String[] getQueueNames() { return queues; } + public Object getMessageListener() { return listener; } + } + + public static final class JmsContainerStub { + private final String dest; + private final Object listener; + JmsContainerStub(String dest, Object listener) { this.dest = dest; this.listener = listener; } + public String getDestinationName() { return dest; } + public Object getMessageListener() { return listener; } + } + + private String connectAndReadHello(boolean withInProcessJacoco) throws Exception { + KeployDedupAgent.stop(); + if (savedContextLoader != null) { + Thread.currentThread().setContextClassLoader(savedContextLoader); + savedContextLoader = null; + } + if (collector != null) { + collector.close(); + } + if (jacoco != null) { + jacoco.close(); + jacoco = null; + } + collector = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(30000); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + if (withInProcessJacoco) { + inProcessJacoco(); + } else { + jacoco = new FakeJacoco(); + System.setProperty(JACOCO_PORT_PROPERTY, String.valueOf(jacoco.server.getLocalPort())); + } + assertTrue(KeployDedupAgent.start()); + try (Socket sdk = collector.accept()) { + sdk.setSoTimeout(30000); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + return in.readLine(); + } finally { + KeployDedupAgent.stop(); + } + } + + private InProcessScanTest.Agent inProcessJacoco() throws ReflectiveOperationException { + System.setProperty(JACOCO_PORT_PROPERTY, "1"); + savedContextLoader = Thread.currentThread().getContextClassLoader(); + InProcessScanTest.Agent agent = new InProcessScanTest.Agent(); + Thread.currentThread().setContextClassLoader( + new InProcessScanTest.RtLoader(agent, getClass().getClassLoader())); + return agent; + } + + private static Runnable latchTask(CountDownLatch started, CountDownLatch release) { + return () -> { + started.countDown(); + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }; + } + + private static void send(OutputStream out, String command) throws IOException { + out.write((command + "\n").getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + + private static byte[] generatePlainClass(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null); + emitDefaultCtor(cw); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "noop", "()I", null, null); + mv.visitCode(); + mv.visitInsn(Opcodes.ICONST_1); + mv.visitInsn(Opcodes.IRETURN); + mv.visitMaxs(1, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateExecutorFieldOnlyClass(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null); + cw.visitField(Opcodes.ACC_PRIVATE, "exec", "Ljava/util/concurrent/Executor;", null, null).visitEnd(); + emitDefaultCtor(cw); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getExec", "()Ljava/util/concurrent/Executor;", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn(Opcodes.GETFIELD, className, "exec", "Ljava/util/concurrent/Executor;"); + mv.visitInsn(Opcodes.ARETURN); + mv.visitMaxs(1, 1); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateExecutorCaller(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null); + emitDefaultCtor(cw); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "fire", + "(Ljava/util/concurrent/Executor;Ljava/lang/Runnable;)V", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/Executor", "execute", + "(Ljava/lang/Runnable;)V", true); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(2, 2); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + // Generates a Java 8 class WITH branches and real StackMapTable frames (COMPUTE_FRAMES) + // exercising Executor/ExecutorService/ScheduledExecutorService/ThreadPoolExecutor/ + // ScheduledThreadPoolExecutor/ForkJoinPool execute & submit, plus CompletableFuture.runAsync/supplyAsync. + private static byte[] generateAllAsyncFormsClass(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null); + emitDefaultCtor(cw); + + // dispatchExecute(int branch, Executor, ExecutorService, ScheduledExecutorService, + // ThreadPoolExecutor, ScheduledThreadPoolExecutor, ForkJoinPool, Runnable) + MethodVisitor exec = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "dispatchExecute", + "(ILjava/util/concurrent/Executor;Ljava/util/concurrent/ExecutorService;" + + "Ljava/util/concurrent/ScheduledExecutorService;Ljava/util/concurrent/ThreadPoolExecutor;" + + "Ljava/util/concurrent/ScheduledThreadPoolExecutor;Ljava/util/concurrent/ForkJoinPool;" + + "Ljava/lang/Runnable;)V", + null, null); + exec.visitCode(); + Label b1 = new Label(), b2 = new Label(), b3 = new Label(), b4 = new Label(), b5 = new Label(), end = new Label(); + exec.visitVarInsn(Opcodes.ILOAD, 0); + exec.visitJumpInsn(Opcodes.IFNE, b1); + exec.visitVarInsn(Opcodes.ALOAD, 1); + exec.visitVarInsn(Opcodes.ALOAD, 7); + exec.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/Executor", "execute", + "(Ljava/lang/Runnable;)V", true); + exec.visitJumpInsn(Opcodes.GOTO, end); + + exec.visitLabel(b1); + exec.visitVarInsn(Opcodes.ILOAD, 0); + exec.visitInsn(Opcodes.ICONST_1); + exec.visitJumpInsn(Opcodes.IF_ICMPNE, b2); + exec.visitVarInsn(Opcodes.ALOAD, 2); + exec.visitVarInsn(Opcodes.ALOAD, 7); + exec.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/ExecutorService", "execute", + "(Ljava/lang/Runnable;)V", true); + exec.visitJumpInsn(Opcodes.GOTO, end); + + exec.visitLabel(b2); + exec.visitVarInsn(Opcodes.ILOAD, 0); + exec.visitInsn(Opcodes.ICONST_2); + exec.visitJumpInsn(Opcodes.IF_ICMPNE, b3); + exec.visitVarInsn(Opcodes.ALOAD, 3); + exec.visitVarInsn(Opcodes.ALOAD, 7); + exec.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/ScheduledExecutorService", "execute", + "(Ljava/lang/Runnable;)V", true); + exec.visitJumpInsn(Opcodes.GOTO, end); + + exec.visitLabel(b3); + exec.visitVarInsn(Opcodes.ILOAD, 0); + exec.visitInsn(Opcodes.ICONST_3); + exec.visitJumpInsn(Opcodes.IF_ICMPNE, b4); + exec.visitVarInsn(Opcodes.ALOAD, 4); + exec.visitVarInsn(Opcodes.ALOAD, 7); + exec.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/ThreadPoolExecutor", "execute", + "(Ljava/lang/Runnable;)V", false); + exec.visitJumpInsn(Opcodes.GOTO, end); + + exec.visitLabel(b4); + exec.visitVarInsn(Opcodes.ILOAD, 0); + exec.visitInsn(Opcodes.ICONST_4); + exec.visitJumpInsn(Opcodes.IF_ICMPNE, b5); + exec.visitVarInsn(Opcodes.ALOAD, 5); + exec.visitVarInsn(Opcodes.ALOAD, 7); + exec.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/ScheduledThreadPoolExecutor", "execute", + "(Ljava/lang/Runnable;)V", false); + exec.visitJumpInsn(Opcodes.GOTO, end); + + exec.visitLabel(b5); + exec.visitVarInsn(Opcodes.ALOAD, 6); + exec.visitVarInsn(Opcodes.ALOAD, 7); + exec.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/ForkJoinPool", "execute", + "(Ljava/lang/Runnable;)V", false); + + exec.visitLabel(end); + exec.visitInsn(Opcodes.RETURN); + exec.visitMaxs(0, 0); + exec.visitEnd(); + + // dispatchSubmit(int mode, ExecutorService, ThreadPoolExecutor, Runnable, Callable) -> Future + MethodVisitor sub = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "dispatchSubmit", + "(ILjava/util/concurrent/ExecutorService;Ljava/util/concurrent/ThreadPoolExecutor;" + + "Ljava/lang/Runnable;Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future;", + null, null); + sub.visitCode(); + Label s1 = new Label(), s2 = new Label(), s3 = new Label(); + sub.visitVarInsn(Opcodes.ILOAD, 0); + sub.visitJumpInsn(Opcodes.IFNE, s1); + sub.visitVarInsn(Opcodes.ALOAD, 1); + sub.visitVarInsn(Opcodes.ALOAD, 3); + sub.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/ExecutorService", "submit", + "(Ljava/lang/Runnable;)Ljava/util/concurrent/Future;", true); + sub.visitInsn(Opcodes.ARETURN); + + sub.visitLabel(s1); + sub.visitVarInsn(Opcodes.ILOAD, 0); + sub.visitInsn(Opcodes.ICONST_1); + sub.visitJumpInsn(Opcodes.IF_ICMPNE, s2); + sub.visitVarInsn(Opcodes.ALOAD, 1); + sub.visitVarInsn(Opcodes.ALOAD, 3); + sub.visitLdcInsn("ok"); + sub.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/ExecutorService", "submit", + "(Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Future;", true); + sub.visitInsn(Opcodes.ARETURN); + + sub.visitLabel(s2); + sub.visitVarInsn(Opcodes.ILOAD, 0); + sub.visitInsn(Opcodes.ICONST_2); + sub.visitJumpInsn(Opcodes.IF_ICMPNE, s3); + sub.visitVarInsn(Opcodes.ALOAD, 1); + sub.visitVarInsn(Opcodes.ALOAD, 4); + sub.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/ExecutorService", "submit", + "(Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future;", true); + sub.visitInsn(Opcodes.ARETURN); + + sub.visitLabel(s3); + sub.visitVarInsn(Opcodes.ALOAD, 2); + sub.visitVarInsn(Opcodes.ALOAD, 3); + sub.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/ThreadPoolExecutor", "submit", + "(Ljava/lang/Runnable;)Ljava/util/concurrent/Future;", false); + sub.visitInsn(Opcodes.ARETURN); + sub.visitMaxs(0, 0); + sub.visitEnd(); + + // dispatchCompletable(int mode, Executor, Runnable, Supplier) -> CompletableFuture + MethodVisitor cf = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "dispatchCompletable", + "(ILjava/util/concurrent/Executor;Ljava/lang/Runnable;Ljava/util/function/Supplier;)" + + "Ljava/util/concurrent/CompletableFuture;", + null, null); + cf.visitCode(); + Label c1 = new Label(), c2 = new Label(), c3 = new Label(); + cf.visitVarInsn(Opcodes.ILOAD, 0); + cf.visitJumpInsn(Opcodes.IFNE, c1); + cf.visitVarInsn(Opcodes.ALOAD, 2); + cf.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/concurrent/CompletableFuture", "runAsync", + "(Ljava/lang/Runnable;)Ljava/util/concurrent/CompletableFuture;", false); + cf.visitInsn(Opcodes.ARETURN); + + cf.visitLabel(c1); + cf.visitVarInsn(Opcodes.ILOAD, 0); + cf.visitInsn(Opcodes.ICONST_1); + cf.visitJumpInsn(Opcodes.IF_ICMPNE, c2); + cf.visitVarInsn(Opcodes.ALOAD, 2); + cf.visitVarInsn(Opcodes.ALOAD, 1); + cf.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/concurrent/CompletableFuture", "runAsync", + "(Ljava/lang/Runnable;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;", false); + cf.visitInsn(Opcodes.ARETURN); + + cf.visitLabel(c2); + cf.visitVarInsn(Opcodes.ILOAD, 0); + cf.visitInsn(Opcodes.ICONST_2); + cf.visitJumpInsn(Opcodes.IF_ICMPNE, c3); + cf.visitVarInsn(Opcodes.ALOAD, 3); + cf.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/concurrent/CompletableFuture", "supplyAsync", + "(Ljava/util/function/Supplier;)Ljava/util/concurrent/CompletableFuture;", false); + cf.visitInsn(Opcodes.ARETURN); + + cf.visitLabel(c3); + cf.visitVarInsn(Opcodes.ALOAD, 3); + cf.visitVarInsn(Opcodes.ALOAD, 1); + cf.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/concurrent/CompletableFuture", "supplyAsync", + "(Ljava/util/function/Supplier;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;", + false); + cf.visitInsn(Opcodes.ARETURN); + cf.visitMaxs(0, 0); + cf.visitEnd(); + + // removeTask(ThreadPoolExecutor, Runnable) -> boolean + MethodVisitor rem = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "removeTask", + "(Ljava/util/concurrent/ThreadPoolExecutor;Ljava/lang/Runnable;)Z", null, null); + rem.visitCode(); + rem.visitVarInsn(Opcodes.ALOAD, 0); + rem.visitVarInsn(Opcodes.ALOAD, 1); + rem.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/ThreadPoolExecutor", "remove", + "(Ljava/lang/Runnable;)Z", false); + rem.visitInsn(Opcodes.IRETURN); + rem.visitMaxs(0, 0); + rem.visitEnd(); + + // drainAll(ExecutorService) -> List + MethodVisitor drain = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "drainAll", + "(Ljava/util/concurrent/ExecutorService;)Ljava/util/List;", null, null); + drain.visitCode(); + drain.visitVarInsn(Opcodes.ALOAD, 0); + drain.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/ExecutorService", "shutdownNow", + "()Ljava/util/List;", true); + drain.visitInsn(Opcodes.ARETURN); + drain.visitMaxs(0, 0); + drain.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSuperExecuteSubclass(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, + "java/util/concurrent/ThreadPoolExecutor", null); + MethodVisitor exec = cw.visitMethod(Opcodes.ACC_PUBLIC, "execute", "(Ljava/lang/Runnable;)V", null, null); + exec.visitCode(); + exec.visitVarInsn(Opcodes.ALOAD, 0); + exec.visitVarInsn(Opcodes.ALOAD, 1); + exec.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/concurrent/ThreadPoolExecutor", "execute", + "(Ljava/lang/Runnable;)V", false); + exec.visitInsn(Opcodes.RETURN); + exec.visitMaxs(2, 2); + exec.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateListenerClass(String className, int access, String methodName, + String descriptor, boolean nestedOnMessage) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null); + emitDefaultCtor(cw); + if (nestedOnMessage) { + MethodVisitor inner = cw.visitMethod(Opcodes.ACC_PRIVATE, "invokeOnMessage", + "(Ljava/lang/Object;)V", null, null); + inner.visitCode(); + inner.visitInsn(Opcodes.RETURN); + inner.visitMaxs(0, 2); + inner.visitEnd(); + } + MethodVisitor mv = cw.visitMethod(access, methodName, descriptor, null, null); + mv.visitCode(); + if (nestedOnMessage) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, className, "invokeOnMessage", + "(Ljava/lang/Object;)V", false); + } + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(2, 3); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static void emitDefaultCtor(ClassWriter cw) { + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(1, 1); + init.visitEnd(); + } + + public static Future makePendingFuture(Runnable task) { + return new FutureTask(task, null); + } + + private static final ScheduledThreadPoolExecutor STANDIN_STPE = new ScheduledThreadPoolExecutor(1); + + public static ScheduledThreadPoolExecutor standInScheduledPool() { + return STANDIN_STPE; + } + + private static byte[] generateSpringSubmitStandIn(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null); + emitDefaultCtor(cw); + MethodVisitor pool = cw.visitMethod(Opcodes.ACC_PUBLIC, "getScheduledThreadPoolExecutor", + "()Ljava/util/concurrent/ScheduledThreadPoolExecutor;", null, null); + pool.visitCode(); + pool.visitMethodInsn(Opcodes.INVOKESTATIC, + HonestProtocolAndAsyncTest.class.getName().replace('.', '/'), + "standInScheduledPool", "()Ljava/util/concurrent/ScheduledThreadPoolExecutor;", false); + pool.visitInsn(Opcodes.ARETURN); + pool.visitMaxs(1, 1); + pool.visitEnd(); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "submit", + "(Ljava/lang/Runnable;)Ljava/util/concurrent/Future;", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + HonestProtocolAndAsyncTest.class.getName().replace('.', '/'), + "makePendingFuture", "(Ljava/lang/Runnable;)Ljava/util/concurrent/Future;", false); + mv.visitInsn(Opcodes.ARETURN); + mv.visitMaxs(1, 2); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateModuleInfo(String moduleName) { + ClassWriter cw = new ClassWriter(0); + cw.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null); + ModuleVisitor mv = cw.visitModule(moduleName, 0, null); + mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + // Generates a modular main class implementing Executor & Runnable whose + // main() calls INVOKEINTERFACE Executor.execute(Runnable)V and prints MOD_OK. + private static byte[] generateModularExecutorMain(String className) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V9, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", + new String[] {"java/util/concurrent/Executor", "java/lang/Runnable"}); + emitDefaultCtor(cw); + + MethodVisitor exec = cw.visitMethod(Opcodes.ACC_PUBLIC, "execute", "(Ljava/lang/Runnable;)V", null, null); + exec.visitCode(); + exec.visitVarInsn(Opcodes.ALOAD, 1); + exec.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/lang/Runnable", "run", "()V", true); + exec.visitInsn(Opcodes.RETURN); + exec.visitMaxs(1, 2); + exec.visitEnd(); + + MethodVisitor run = cw.visitMethod(Opcodes.ACC_PUBLIC, "run", "()V", null, null); + run.visitCode(); + run.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); + run.visitLdcInsn("MOD_OK"); + run.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); + run.visitInsn(Opcodes.RETURN); + run.visitMaxs(2, 1); + run.visitEnd(); + + MethodVisitor main = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "main", + "([Ljava/lang/String;)V", null, null); + main.visitCode(); + main.visitTypeInsn(Opcodes.NEW, className); + main.visitInsn(Opcodes.DUP); + main.visitMethodInsn(Opcodes.INVOKESPECIAL, className, "", "()V", false); + main.visitVarInsn(Opcodes.ASTORE, 1); + main.visitVarInsn(Opcodes.ALOAD, 1); + main.visitVarInsn(Opcodes.ALOAD, 1); + main.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/Executor", "execute", + "(Ljava/lang/Runnable;)V", true); + main.visitInsn(Opcodes.RETURN); + main.visitMaxs(2, 2); + main.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + + private static final class MyAppTask implements Runnable { + final String name; + final AtomicBoolean ran = new AtomicBoolean(false); + + MyAppTask(String name) { + this.name = name; + } + + @Override + public void run() { + ran.set(true); + } + } + + private static final class ByteLoader extends ClassLoader { + ByteLoader(ClassLoader parent) { + super(parent); + } + + Class define(String name, byte[] bytes) { + return defineClass(name, bytes, 0, bytes.length); + } + } + + // Simulates org.jacoco.agent.rt.RT being on the classpath before its + // premain starts the agent: getAgent() throws IllegalStateException while + // DeferredRtLoader.agent is null, then returns the live agent once set. + public static final class DeferredRtLoader extends ClassLoader { + + public static volatile Object agent; + + public static Object resolveAgent() { + Object current = agent; + if (current == null) { + throw new IllegalStateException("JaCoCo agent not started."); + } + return current; + } + + DeferredRtLoader(ClassLoader parent) { + super(parent); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if ("org.jacoco.agent.rt.RT".equals(name)) { + Class loaded = findLoadedClass(name); + if (loaded == null) { + byte[] bytes = generateDeferredRt(); + loaded = defineClass(name, bytes, 0, bytes.length); + } + if (resolve) { + resolveClass(loaded); + } + return loaded; + } + return super.loadClass(name, resolve); + } + + private static byte[] generateDeferredRt() { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "org/jacoco/agent/rt/RT", null, "java/lang/Object", null); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "getAgent", + "()Ljava/lang/Object;", null, null); + mv.visitCode(); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + DeferredRtLoader.class.getName().replace('.', '/'), + "resolveAgent", "()Ljava/lang/Object;", false); + mv.visitInsn(Opcodes.ARETURN); + mv.visitMaxs(1, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + } +} diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/InProcessScanTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/InProcessScanTest.java index 4f1ed6f..ade6d56 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/InProcessScanTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/InProcessScanTest.java @@ -55,8 +55,8 @@ public class InProcessScanTest { private static final String[] PROPERTIES = {"keploy.java.dedup.diagnostics", "keploy.java.class.dirs", "keploy.jacoco.port", "keploy.coverage.endpoint", "keploy.java.dedup.warmup.disabled", "keploy.build.tag", "keploy.java.scan", "keploy.java.end.wait.ms"}; - private static final String TAKEN = "ACK proto=2\n"; - private static final String IGNORED = "IGNORED proto=2\n"; + private static final String TAKEN = "ACK proto=3\n"; + private static final String IGNORED = "IGNORED proto=3\n"; private static final String SHOP = "com/acme/Shop"; private static final String CART = "com/acme/Cart"; // The JaCoCo ids of the bytes setUp writes for the two classes: the ids @@ -416,7 +416,8 @@ public void whatAStartClearsAfterNoTakenEndIsNoBackground() throws Exception { assertEquals(TAKEN, send("START test-set-0/test-4")); shop[3] = true; assertEquals(TAKEN, send("END test-set-0/test-4")); - assertEquals("{\"id\":\"test-set-0/test-4\",\"executedLinesByFile\":{\"" + SHOP + "\":[3]}}", + assertEquals("{\"id\":\"test-set-0/test-4\",\"executedLinesByFile\":{\"" + SHOP + "\":[3]}," + + "\"contaminated\":[\"tail:test-set-0/test-3\"]}", data.next()); assertNull(data.background.poll()); } @@ -1043,7 +1044,8 @@ public void anEndWhoseRequestOutrunsTheWaitIsCutAndOpensNoWindow() throws Except assertEquals(TAKEN, send("START test-set-0/test-2")); assertFalse("cleared", shop[2]); assertEquals(TAKEN, send("END test-set-0/test-2")); - assertEquals("{\"id\":\"test-set-0/test-2\",\"executedLinesByFile\":{}}", data.next()); + assertEquals("{\"id\":\"test-set-0/test-2\",\"executedLinesByFile\":{}," + + "\"contaminated\":[\"tail:test-set-0/test-1\"]}", data.next()); // The windows after it count as usual. cart[1] = true; assertEquals(TAKEN, send("START test-set-0/test-3")); @@ -1070,7 +1072,10 @@ public void anEndDoesNotWaitForARequestThatCameInBeforeItsStart() throws Excepti long began = System.nanoTime(); assertEquals(TAKEN, send("END test-set-0/test-1")); assertTrue(System.nanoTime() - began < TimeUnit.MILLISECONDS.toNanos(1500)); - assertEquals("{\"id\":\"test-set-0/test-1\",\"executedLinesByFile\":{\"" + SHOP + "\":[1]}}", + // stream entered before start() (while unarmed) and is still in flight, + // so END does not wait for it but marks the window armed-mid-flight. + assertEquals("{\"id\":\"test-set-0/test-1\",\"executedLinesByFile\":{\"" + SHOP + + "\":[1]},\"contaminated\":[\"armed-mid-flight\"]}", data.next()); } } @@ -1208,7 +1213,14 @@ private static String send(String command) throws IOException { OutputStream out = socket.getOutputStream(); out.write((command + "\n").getBytes(StandardCharsets.UTF_8)); out.flush(); - return new String(readAll(socket.getInputStream()), StandardCharsets.UTF_8); + String reply = new String(readAll(socket.getInputStream()), StandardCharsets.UTF_8); + if (reply.startsWith("ACK proto=3 caps=") && reply.endsWith("\n")) { + String caps = reply.substring("ACK proto=3 caps=".length(), reply.length() - 1); + assertFalse("caps must contain no spaces: " + reply, caps.contains(" ")); + assertTrue("reply must stay well under 1024 bytes: " + reply, reply.length() < 1024); + return TAKEN; + } + return reply; } } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/JobGateTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/JobGateTest.java index 2ff0516..c46233a 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/JobGateTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/JobGateTest.java @@ -36,6 +36,7 @@ public class JobGateTest { @Before public void setUp() { + JobGate.arm(); JobGate.close(); } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/JobTailTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/JobTailTest.java index 74304cc..84e8e72 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/JobTailTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/JobTailTest.java @@ -297,6 +297,9 @@ private final class App implements AutoCloseable { sdk.setSoTimeout(60000); sdkOut = sdk.getOutputStream(); sdkIn = new BufferedReader(new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + String hello = sdkIn.readLine(); + assertTrue("expected HELLO frame on connect, got " + hello, + hello != null && hello.startsWith("HELLO ")); commands = new Socket(InetAddress.getLoopbackAddress(), port); commands.setSoTimeout(60000); commandOut = commands.getOutputStream(); @@ -311,12 +314,13 @@ private final class App implements AutoCloseable { // test runs one test that fires these jobs between its START and its // END, and returns its record. String test(String id, String... jobs) throws IOException { - send(sdkOut, "START test-set-0/" + id); + String fullId = "test-set-0/" + id; + send(sdkOut, "START " + fullId); assertEquals("ACK", sdkIn.readLine()); for (String job : jobs) { command(job); } - send(sdkOut, "END test-set-0/" + id); + send(sdkOut, "END " + fullId); String cov = sdkIn.readLine(); assertTrue(cov, cov != null && cov.startsWith("COV ")); String line; @@ -324,7 +328,7 @@ String test(String id, String... jobs) throws IOException { assertTrue(line, line.startsWith("CLASSES ") || line.startsWith("MANIFEST ")); } cov = cov.substring("COV ".length()); - assertTrue(cov, cov.contains("\"id\":\"test-set-0/" + id + "\"")); + assertTrue(cov, cov.contains("\"id\":\"" + fullId + "\"")); return cov; } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java index c668697..9d6c914 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java @@ -49,7 +49,9 @@ public class PhasesTest { private static final String[] PROPERTIES = {"keploy.java.dedup.diagnostics", "keploy.java.class.dirs", "keploy.jacoco.port", "keploy.coverage.endpoint", "keploy.java.dedup.warmup.disabled", "keploy.build.tag"}; - private static final String TAKEN = "ACK proto=2\n"; + private static final String TAKEN = + "ACK proto=3 caps=windowCut=false,contaminated=false,classMismatch=true," + + "background=false,ackId=true,asyncExecutors=false,listenerContamination=false\n"; private static final String MS = "\\d+\\.\\d\\d"; // The one app class, and the probes a test ran in it. private static final String SHOP = "com/acme/Shop"; @@ -140,6 +142,9 @@ public void overTcpEachCommandSaysHowLongEachStepTookToo() throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + String hello = in.readLine(); + assertTrue("expected HELLO frame, got " + hello, + hello != null && hello.startsWith("HELLO {\"proto\":3,")); out.write("START test-set-0/test-1\n".getBytes(StandardCharsets.UTF_8)); out.flush(); assertEquals("ACK", in.readLine()); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ServerEntriesTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ServerEntriesTest.java index dba62b8..92747b6 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ServerEntriesTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ServerEntriesTest.java @@ -97,6 +97,7 @@ public void setUp() { @After public void tearDown() { + ServerEntries.setHookStatusForTests(false, false, false); Logger.getLogger(KeployDedupAgent.class.getName()).removeHandler(handler); } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java index 00a5f66..036fdbe 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java @@ -296,7 +296,7 @@ public void springSixCountsTheSameHandOffs() throws Exception { // Spring, then one for each poller named: each hand-off's work lands in // its test, and no poller's is waited for. private void assertSpringHandOffs(Fork fork, String... pollers) throws Exception { - String[] counted = {"event", "pool", "execute", "listenable", "async", "completable", "throttled"}; + String[] counted = {"event", "pool", "execute", "listenable", "async", "completable", "throttled", "scheduler"}; for (String how : counted) { fork.queries.add("async=" + how + "&sleep=500"); } @@ -321,6 +321,7 @@ private void assertSpringHandOffs(Fork fork, String... pollers) throws Exception } for (String executor : new String[] {"org.springframework.core.task.SimpleAsyncTaskExecutor", "org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor", + "org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler", "org.springframework.aop.interceptor.AsyncExecutionAspectSupport"}) { assertTrue(result.log, result.log.contains("Keploy dedup counts Spring's async tasks (" + executor + "): a test's END waits for the tasks its requests hand off to finish")); @@ -516,13 +517,24 @@ private Result run(Fork fork) throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + String hello = in.readLine(); + assertTrue("expected HELLO frame on connect, got " + hello, + hello != null && hello.startsWith("HELLO ")); for (int test = 1; test <= tests; test++) { - send(out, "START test-set-0/test-" + test); - assertEquals("ACK", in.readLine()); + String fullId = "test-set-0/test-" + test; + send(out, "START " + fullId); + String startReply = in.readLine(); + while (startReply != null && startReply.startsWith("HELLO ")) { + startReply = in.readLine(); + } + assertEquals("ACK", startReply); String query = fork.queries.isEmpty() ? "tail=" + tailMillis : fork.queries.get(test - 1); assertEquals("hello", get(port, "/hello?" + query)); - send(out, "END test-set-0/test-" + test); + send(out, "END " + fullId); String cov = in.readLine(); + while (cov != null && cov.startsWith("HELLO ")) { + cov = in.readLine(); + } assertTrue(cov, cov != null && cov.startsWith("COV ")); result.covs.add(cov.substring("COV ".length())); String line; diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/WarmupTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/WarmupTest.java index 63d1c64..93375bf 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/WarmupTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/WarmupTest.java @@ -125,6 +125,9 @@ public void setUp() throws IOException { public void tearDown() throws Exception { slow.countDown(); KeployDedupAgent.stop(); + KeployDedupAgent.transformerAdded = false; + KeployDedupAgent.executorCallSitesEnabled = false; + ServerEntries.setHookStatusForTests(false, false, false); appEnds.countDown(); if (appMain != null) { appMain.join(5000); @@ -155,7 +158,7 @@ public void aFatJarsClassesWarmUpThroughTheLoaderTheAppRunsThem() throws Excepti System.setProperty("keploy.java.class.dirs", classes.getPath()); assertTrue(KeployDedupAgent.start()); - assertEquals("ACK proto=2\n", send("START test-set-0/test-1")); + assertTaken(send("START test-set-0/test-1")); assertLogged("INFO Keploy dedup: warmed up application classes (initialized=2, skipped=0) in "); assertNotLogged("the warmup of the app's classes was still"); @@ -181,7 +184,7 @@ public void aSlowStaticInitializerHoldsTheFirstStartOnlySoLong() throws Exceptio assertTrue(KeployDedupAgent.start()); long began = System.nanoTime(); - assertEquals("ACK proto=2\n", send("START test-set-0/test-1")); + assertTaken(send("START test-set-0/test-1")); long tookMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - began); assertTrue("the START was answered after " + tookMillis + " ms", @@ -203,7 +206,7 @@ public void aSlowStaticInitializerHoldsTheFirstStartOnlySoLong() throws Exceptio // bounded or not, lasts until Slow's 20 s hold ends. KeployDedupAgent.warmupWaitMillis = 60000; began = System.nanoTime(); - assertEquals("ACK proto=2\n", send("START test-set-0/test-2")); + assertTaken(send("START test-set-0/test-2")); tookMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - began); assertTrue("the second START was answered after " + tookMillis + " ms", tookMillis < 10000); assertEquals(1, countLogged("WARNING Keploy dedup: the warmup of the app's classes was still ")); @@ -237,7 +240,7 @@ public void premainsInstrumentationFindsTheLoaderOfTheAppsLoadedClasses() throws KeployDedupAgent.premain(null, instrumentation(main)); assertTrue(KeployDedupAgent.isStarted()); - assertEquals("ACK proto=2\n", send("START test-set-0/test-1")); + assertTaken(send("START test-set-0/test-1")); assertLogged("INFO Keploy dedup: warmed up application classes (initialized=2, skipped=0) in "); assertSame(app, INITIALIZED.get(MAIN)); @@ -417,11 +420,16 @@ public synchronized void start() { }; assertTrue(KeployDedupAgent.start()); - assertEquals("ACK proto=2\n", send("START test-set-0/test-1")); + assertTaken(send("START test-set-0/test-1")); assertLogged("WARNING Keploy dedup: no warmup, as its thread could not start"); assertTrue(INITIALIZED.isEmpty()); // The control server still answers. - assertEquals("ACK proto=2\n", send("START test-set-0/test-2")); + assertTaken(send("START test-set-0/test-2")); + } + + private static void assertTaken(String reply) { + assertTrue("expected ACK proto=3 caps=..., got: " + reply, + reply != null && reply.startsWith("ACK proto=3 caps=") && reply.endsWith("\n")); } @Test diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java new file mode 100644 index 0000000..9fdbd97 --- /dev/null +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -0,0 +1,534 @@ +package org.example.servers; + +import com.sun.net.httpserver.HttpServer; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.catalina.Context; +import org.apache.catalina.startup.Tomcat; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +/** + * Real application process launched in forked {@code -javaagent:keploy-sdk.jar} + * JVMs by {@code ForkedAsyncAndHonestyTest} to verify v3 protocol honesty end-to-end + * (premain -> index OR appPackagePrefix external-JaCoCo mode -> real app + * bytecode -> TCP START/END -> HELLO + COV). + */ +public final class AsyncHonestyApp { + + private static final ExecutorService PLAIN_POOL = Executors.newFixedThreadPool(4, r -> { + Thread t = new Thread(r, "app-plain-pool"); + t.setDaemon(true); + return t; + }); + private static final ScheduledExecutorService SCHED = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "app-sched"); + t.setDaemon(true); + return t; + }); + private static final ExecutorService SERIALIZABLE_ONLY_POOL = new SerializableOnlyExecutor(false); + private static final ExecutorService ASYNC_SERIALIZABLE_POOL = new SerializableOnlyExecutor(true); + private static final ConcreteCustomPool CONCRETE_POOL = new ConcreteCustomPool(); + private static volatile java.util.concurrent.CountDownLatch VIRTUAL_RELEASE_LATCH; + private static volatile Thread VIRTUAL_THREAD; + // Simulates an external library's event loop (e.g. HttpClient/Netty/AWS SDK) + // started outside any request, completing CompletableFutures asynchronously. + private static final LinkedBlockingQueue EXTERNAL_LIBRARY_LOOP = new LinkedBlockingQueue<>(); + + static { + Thread externalLoop = new Thread(() -> { + while (!Thread.currentThread().isInterrupted()) { + try { + EXTERNAL_LIBRARY_LOOP.take().run(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + }, "fake-external-http-loop"); + externalLoop.setDaemon(true); + externalLoop.start(); + } + + private AsyncHonestyApp() { + } + + public static void main(String[] args) throws Exception { + String mode = args[0]; + AutoCloseable server; + int port; + if ("tomcat".equals(mode)) { + File base = Files.createTempDirectory("tomcat-honesty").toFile(); + Tomcat tomcat = new Tomcat(); + tomcat.setBaseDir(base.getPath()); + tomcat.setPort(0); + Context context = tomcat.addContext("", base.getPath()); + Tomcat.addServlet(context, "async", new AsyncServlet()); + context.addServletMappingDecoded("/*", "async"); + tomcat.start(); + port = tomcat.getConnector().getLocalPort(); + server = tomcat::stop; + } else if ("jetty".equals(mode)) { + Server jetty = new Server(0); + ServletContextHandler context = new ServletContextHandler(); + context.addServlet(new ServletHolder(new AsyncServlet()), "/*"); + jetty.setHandler(context); + jetty.start(); + port = ((ServerConnector) jetty.getConnectors()[0]).getLocalPort(); + server = jetty::stop; + } else if ("uncounted".equals(mode)) { + HttpServer http = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + http.createContext("/clean", exchange -> { + AsyncTail.ran(); + byte[] body = "ok".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + }); + http.start(); + port = http.getAddress().getPort(); + server = () -> http.stop(0); + } else if ("kafka".equals(mode)) { + ServerSocket cmdServer = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + port = cmdServer.getLocalPort(); + Thread cmdThread = new Thread(() -> runKafkaCommandLoop(cmdServer), "kafka-cmd"); + cmdThread.setDaemon(true); + cmdThread.start(); + server = cmdServer; + } else { + // "whole-jar" or idle mode: just wait for stdin close. + System.out.println("PORT 0"); + System.out.flush(); + while (System.in.read() >= 0) { + // Wait for test to close stdin. + } + System.exit(0); + return; + } + System.out.println("PORT " + port); + System.out.flush(); + while (System.in.read() >= 0) { + // Wait for test to close stdin. + } + server.close(); + PLAIN_POOL.shutdownNow(); + SCHED.shutdownNow(); + System.exit(0); + } + + private static void sleepQuietly(long ms) { + if (ms <= 0) { + return; + } + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + public static final class AsyncServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + String path = req.getPathInfo() == null ? "/" : req.getPathInfo(); + long ms = req.getParameter("ms") == null ? 0L : Long.parseLong(req.getParameter("ms")); + if ("/submit-tail".equals(path)) { + PLAIN_POOL.submit(() -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + } else if ("/cf-then-accept".equals(path)) { + // Fast supplier followed by a slow synchronous thenAccept(audit) dependent. + CompletableFuture.supplyAsync(() -> { + sleepQuietly(20); + return "result"; + }, PLAIN_POOL).thenAccept(v -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + } else if ("/cf-then-apply-async".equals(path)) { + CompletableFuture.supplyAsync(() -> "seed", PLAIN_POOL) + .thenApplyAsync(v -> { + sleepQuietly(ms); + AsyncTail.ran(); + return v + "-done"; + }, PLAIN_POOL); + } else if ("/unknown-serializable".equals(path)) { + Runnable serializableTask = (Runnable & Serializable) () -> AsyncTail.ran(); + SERIALIZABLE_ONLY_POOL.execute(serializableTask); + java.util.concurrent.Callable serializableCall = + (java.util.concurrent.Callable & Serializable) () -> { + AsyncTail.ran(); + return "ok"; + }; + SERIALIZABLE_ONLY_POOL.submit(serializableCall); + } else if ("/unknown-serializable-async".equals(path)) { + final long delay = ms; + Runnable serializableTask = (Runnable & Serializable) () -> { + sleepQuietly(delay); + AsyncTail.ran(); + }; + ASYNC_SERIALIZABLE_POOL.execute(serializableTask); + } else if ("/external-cf-dependent".equals(path)) { + // Simulates an external library future (e.g., HttpClient.sendAsync) + // completed on an external event-loop thread, with app code attaching + // a plain .thenAccept(audit) dependent. + final CompletableFuture externalFuture = new CompletableFuture<>(); + EXTERNAL_LIBRARY_LOOP.offer(() -> { + sleepQuietly(25); + externalFuture.complete("http-200"); + }); + externalFuture.thenAccept(v -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + } else if ("/completion-stage-async".equals(path)) { + CompletionStage stage = CompletableFuture.completedFuture("seed"); + stage.thenApplyAsync(v -> { + sleepQuietly(ms); + AsyncTail.ran(); + return v + "-stage"; + }, PLAIN_POOL); + } else if ("/concrete-pool".equals(path)) { + CONCRETE_POOL.execute(() -> AsyncTail.ran()); + } else if ("/subclassed-thread".equals(path)) { + MyWorkerThread t = new MyWorkerThread(() -> AsyncTail.ran()); + t.setDaemon(true); + t.start(); + } else if ("/fork-join-fork".equals(path)) { + ForkJoinTask.adapt(() -> AsyncTail.ran()).fork(); + } else if ("/completion-service".equals(path)) { + ExecutorCompletionService ecs = new ExecutorCompletionService<>(PLAIN_POOL); + ecs.submit(() -> { + AsyncTail.ran(); + return "ecs"; + }); + } else if ("/method-ref".equals(path)) { + Collections.singletonList(() -> AsyncTail.ran()).forEach(PLAIN_POOL::execute); + } else if ("/virtual-thread-latch".equals(path)) { + final java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); + VIRTUAL_RELEASE_LATCH = release; + VIRTUAL_THREAD = VirtualThreadLauncher.launchDirect(() -> { + try { + release.await(30, TimeUnit.SECONDS); + AsyncTail.ran(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } else if ("/virtual-builder-latch".equals(path)) { + final java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); + VIRTUAL_RELEASE_LATCH = release; + VIRTUAL_THREAD = VirtualThreadLauncher.launchBuilder(() -> { + try { + release.await(30, TimeUnit.SECONDS); + AsyncTail.ran(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } else if ("/release-virtual".equals(path)) { + java.util.concurrent.CountDownLatch release = VIRTUAL_RELEASE_LATCH; + Thread vt = VIRTUAL_THREAD; + if (release != null) { + release.countDown(); + } + if (vt != null) { + try { + vt.join(5000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } else if ("/untracked-schedule".equals(path)) { + SCHED.schedule(() -> AsyncTail.ran(), 1, TimeUnit.MILLISECONDS); + } else if ("/untracked-thread".equals(path)) { + Thread t = new Thread(() -> AsyncTail.ran(), "app-raw-thread"); + t.setDaemon(true); + t.start(); + } else { + Tail.ran(); + } + byte[] body = "ok".getBytes(StandardCharsets.UTF_8); + resp.setContentType("text/plain"); + resp.setContentLength(body.length); + resp.getOutputStream().write(body); + resp.flushBuffer(); + } + } + + public static final class ConcreteCustomPool extends ThreadPoolExecutor { + public ConcreteCustomPool() { + super(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), r -> { + Thread t = new Thread(r, "app-concrete-pool"); + t.setDaemon(true); + return t; + }); + } + } + + /** + * Dynamically defines a class in {@code org.example.servers} containing real + * JDK 21 {@code Thread.startVirtualThread(Runnable)} and + * {@code Thread.ofVirtual().start(Runnable)} bytecode so tests compiled with + * {@code --release 8} still exercise {@code ServerEntries} rewriting those + * exact opcodes in a forked JDK 21 JVM. + */ + public static final class VirtualThreadLauncher { + private static volatile Class helperClass; + + private static Class helper() throws Exception { + Class c = helperClass; + if (c != null) { + return c; + } + String internal = "org/example/servers/VirtualThreadHelper"; + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, internal, null, "java/lang/Object", null); + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(1, 1); + init.visitEnd(); + + MethodVisitor direct = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "startDirect", + "(Ljava/lang/Runnable;)Ljava/lang/Thread;", null, null); + direct.visitCode(); + direct.visitVarInsn(Opcodes.ALOAD, 0); + direct.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Thread", "startVirtualThread", + "(Ljava/lang/Runnable;)Ljava/lang/Thread;", false); + direct.visitInsn(Opcodes.ARETURN); + direct.visitMaxs(1, 1); + direct.visitEnd(); + + MethodVisitor builder = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "startBuilder", + "(Ljava/lang/Runnable;)Ljava/lang/Thread;", null, null); + builder.visitCode(); + builder.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Thread", "ofVirtual", + "()Ljava/lang/Thread$Builder$OfVirtual;", false); + builder.visitVarInsn(Opcodes.ALOAD, 0); + builder.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/lang/Thread$Builder$OfVirtual", "start", + "(Ljava/lang/Runnable;)Ljava/lang/Thread;", true); + builder.visitInsn(Opcodes.ARETURN); + builder.visitMaxs(2, 1); + builder.visitEnd(); + + cw.visitEnd(); + byte[] bytes = cw.toByteArray(); + c = new ClassLoader(AsyncHonestyApp.class.getClassLoader()) { + Class define() { + return defineClass("org.example.servers.VirtualThreadHelper", bytes, 0, bytes.length); + } + }.define(); + helperClass = c; + return c; + } + + public static Thread launchDirect(Runnable r) { + try { + return (Thread) helper().getMethod("startDirect", Runnable.class).invoke(null, r); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static Thread launchBuilder(Runnable r) { + try { + return (Thread) helper().getMethod("startBuilder", Runnable.class).invoke(null, r); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + public static final class MyWorkerThread extends Thread { + public MyWorkerThread(Runnable r) { + super(r, "app-my-worker-thread"); + } + } + + /** + * Hazelcast/Ignite-style custom ExecutorService that requires tasks to be + * {@link Serializable} (throws if wrapped in a non-Serializable wrapper). + */ + public static final class SerializableOnlyExecutor extends AbstractExecutorService { + private final boolean async; + + public SerializableOnlyExecutor(boolean async) { + this.async = async; + } + + @Override + public void execute(Runnable command) { + if (!(command instanceof Serializable)) { + throw new IllegalStateException("Expected Serializable task, got " + command.getClass().getName()); + } + if (async) { + Thread t = new Thread(command, "serializable-async"); + t.setDaemon(true); + t.start(); + } else { + command.run(); + } + } + + @Override + public java.util.concurrent.Future submit(java.util.concurrent.Callable task) { + if (!(task instanceof Serializable)) { + throw new IllegalStateException("Expected Serializable callable, got " + task.getClass().getName()); + } + java.util.concurrent.FutureTask f = new java.util.concurrent.FutureTask<>(task); + f.run(); + return f; + } + + @Override + public void shutdown() { } + + @Override + public List shutdownNow() { + return Collections.emptyList(); + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + } + + // --- Realistic Spring Kafka ListenerConsumer class loaded AFTER premain --- + + public static final class OrdersListenerBean { } + + public static final class FakeKafkaProps { + public String[] getTopics() { + return new String[] {"orders-topic"}; + } + + public Object getMessageListener() { + return new OrdersListenerBean(); + } + } + + public static Object makeKafkaProps() { + return new FakeKafkaProps(); + } + + public static void runListenerBody() { + AsyncTail.ran(); + } + + private static void runKafkaCommandLoop(ServerSocket server) { + try { + // Define org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer + // via a child ClassLoader so the JVM invokes ServerEntries.transform() on it! + byte[] consumerBytes = generateKafkaListenerConsumer(); + Class consumerClass = new ClassLoader(AsyncHonestyApp.class.getClassLoader()) { + Class define() { + return defineClass( + "org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer", + consumerBytes, 0, consumerBytes.length); + } + }.define(); + Object consumer = consumerClass.getDeclaredConstructor().newInstance(); + Method invokeRecord = consumerClass.getDeclaredMethod("invokeRecordListener", Object.class); + invokeRecord.setAccessible(true); + + try (Socket client = server.accept(); + BufferedReader in = new BufferedReader( + new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); + OutputStream out = client.getOutputStream()) { + String line; + while ((line = in.readLine()) != null) { + if ("fire".equals(line.trim())) { + invokeRecord.invoke(consumer, "record-1"); + out.write("DONE\n".getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + } + } + } catch (Throwable t) { + t.printStackTrace(System.err); + } + } + + private static byte[] generateKafkaListenerConsumer() { + String name = "org/springframework/kafka/listener/KafkaMessageListenerContainer$ListenerConsumer"; + String app = AsyncHonestyApp.class.getName().replace('.', '/'); + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, name, null, "java/lang/Object", null); + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(1, 1); + init.visitEnd(); + + MethodVisitor props = cw.visitMethod(Opcodes.ACC_PUBLIC, "getContainerProperties", "()Ljava/lang/Object;", + null, null); + props.visitCode(); + props.visitMethodInsn(Opcodes.INVOKESTATIC, app, "makeKafkaProps", "()Ljava/lang/Object;", false); + props.visitInsn(Opcodes.ARETURN); + props.visitMaxs(1, 1); + props.visitEnd(); + + MethodVisitor invoke = cw.visitMethod(Opcodes.ACC_PRIVATE, "invokeRecordListener", "(Ljava/lang/Object;)V", + null, null); + invoke.visitCode(); + invoke.visitMethodInsn(Opcodes.INVOKESTATIC, app, "runListenerBody", "()V", false); + invoke.visitInsn(Opcodes.RETURN); + invoke.visitMaxs(1, 2); + invoke.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } +} diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncWork.java b/keploy-sdk/src/test/java/org/example/servers/AsyncWork.java index 0b4d0cc..c64e739 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncWork.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncWork.java @@ -122,6 +122,12 @@ public static void hand(String how, long millis) throws Exception { case "throttled": THROTTLED.execute(() -> sleepThenTail(millis)); break; + case "scheduler": + SCHEDULER.submit((Callable) () -> { + sleepThenTail(millis); + return null; + }); + break; case "scheduled": fire(FIRE, millis); break; diff --git a/scripts/smoke-javaagent.sh b/scripts/smoke-javaagent.sh index 974df3a..b98d7a4 100755 --- a/scripts/smoke-javaagent.sh +++ b/scripts/smoke-javaagent.sh @@ -312,7 +312,7 @@ public final class SmokeHarness { String json = next(records, mode); if (!json.contains("\"id\":\"" + id + "\"") || !json.contains("\"smoke/Work\":[") - || !json.contains(",\"classMismatch\":[\"smoke/Work\"]}")) { + || !json.contains(",\"classMismatch\":[\"smoke/Work\"]")) { throw new IllegalStateException("the record of a test that ran another copy of smoke/Work does" + " not name it, alone, in classMismatch in " + mode + ": " + json); } @@ -381,10 +381,10 @@ public final class SmokeHarness { OutputStream output = socket.getOutputStream(); output.write((command + "\n").getBytes(StandardCharsets.UTF_8)); output.flush(); - // The whole answer: one line saying the command was taken, then - // the close. + // The whole answer: one line saying the command was taken (proto=3 + // with capability flags), then the close. String ack = readAll(socket.getInputStream()); - if (!"ACK proto=2\n".equals(ack)) { + if (!ack.startsWith("ACK proto=3 ") || !ack.contains("caps=") || !ack.endsWith("\n")) { throw new IllegalStateException("not taken: " + command + ": " + ack); } } @@ -781,7 +781,7 @@ public final class TomcatHarness { output.write((command + "\n").getBytes(StandardCharsets.UTF_8)); output.flush(); String ack = readAll(socket.getInputStream()); - if (!"ACK proto=2\n".equals(ack)) { + if (!ack.startsWith("ACK proto=3 ") || !ack.contains("caps=") || !ack.endsWith("\n")) { throw new IllegalStateException("not taken: " + command + ": " + ack); } }