Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ The work a request hands to a Spring executor (Spring 5.3 to 6.2) or to verified

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:<class>"`). 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:<kind>"` / `"untracked-executor:<runtimeClass>"`). When a concrete handle (`ScheduledFuture`, `Thread`, `TimerTask`) is tracked, its liveness alone drives subsequent `tail:<id>` 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, Kotlin coroutines, OkHttp's `Dispatcher`, JDK NIO `Asynchronous*Channel` / `AsynchronousChannelGroup`, and Spring's `SimpleApplicationEventMulticaster` configured with a non-hooked executor (such as a plain JDK pool) are not intercepted; when any of them is detected (or when an untracked executor/async method reference is captured anywhere in the application), the agent permanently drops `asyncExecutors=false` in `HELLO` and Unix `ACK` caps so deduplication fails closed to soft-mark only. 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"`).
When Keploy is absent (no collector connected, no `KEPLOY_DEDUP_ATTACH=via-proc` declaration, 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"`). When Keploy launches a replay with a deferred via-proc collector (where the data receiver socket is bound on the first control command rather than before JVM startup), setting `KEPLOY_DEDUP_ATTACH=via-proc` (or system property `-Dkeploy.dedup.attach=via-proc`) arms the runtime gate immediately after binding `/tmp/coverage_control.sock` so pre-test readiness probes complete cleanly without marking the first testcase `"armed-mid-flight"`, while any pre-test request still in flight at `START` still contaminates that window. 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. Background HTTP session listeners invoked outside any tracked request or job (such as container session-expiry timers firing `HttpSessionListener`, `HttpSessionAttributeListener`, `HttpSessionBindingListener`, `HttpSessionActivationListener`, `HttpSessionIdListener`, or container-native session listeners across Tomcat 8.5–11, Jetty 9.4–12.1 including `ee8`/`ee9`/`ee10`/`ee11`, and Undertow 2.2–2.3) are hooked alike: overlapping windows are marked `"session-listener:<listenerClass>#<methodName>"` and `asyncExecutors=false` is latched so dedup fails closed, while synchronous in-request `HttpSession.invalidate()` and listener-free session expiries (including Tomcat's default `WsSessionListener` and Undertow's JSR-356 `JsrWebSocketFilter$LogoutListener`, which Spring Boot's Undertow starter registers by default) remain clean. 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:<group>.<name>" | "scheduled:<class>.<method>" | "kafka:<topics>@<listener>" | "listener:<queues/dest>@<listener>" | "session-listener:<listenerClass>#<methodName>", ...]` 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:<name>"` 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`, a reactive/Kotlin `suspend` `@Scheduled` method, or external session-store adapters that dispatch Servlet session listeners outside the servlet container (such as Spring Session's `SessionEventHttpSessionListenerAdapter` / `HttpSessionAdapter`) 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.

Expand Down
22 changes: 18 additions & 4 deletions keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java
Original file line number Diff line number Diff line change
Expand Up @@ -536,8 +536,9 @@ 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).
// as a collector connects (TCP connect, live unix data socket,
// KEPLOY_DEDUP_ATTACH=via-proc at unix bind, or first control
// command/START).
RequestGate.disarm();
CoverageCollector collector = new CoverageCollector(
new JacocoClient(resolveHost(), resolvePort()), index, instrumentation);
Expand Down Expand Up @@ -924,6 +925,17 @@ private static String resolveEndpoint() {
return value.trim().isEmpty() ? null : value.trim();
}

/**
* Returns whether the launcher declared a deferred via-proc collector
* ({@code KEPLOY_DEDUP_ATTACH=via-proc} / {@code -Dkeploy.dedup.attach=via-proc}).
* In via-proc mode the collector binds the data socket only at the first
* command, so the SDK arms {@link RequestGate} immediately after binding
* its Unix control socket before the app serves any pre-test probe traffic.
*/
private static boolean isViaProcAttachDeclared() {
return "via-proc".equalsIgnoreCase(envOrProperty("KEPLOY_DEDUP_ATTACH", "keploy.dedup.attach", ""));
}

private static String envOrProperty(String envKey, String propertyKey, String defaultValue) {
String value = System.getenv(envKey);
if (value == null || value.trim().isEmpty()) {
Expand Down Expand Up @@ -1123,8 +1135,10 @@ void bind() throws IOException {
throw t;
}
serverSocket = socket;
// Arm immediately if Keploy's data receiver is already listening.
if (receiverKey(publisher.socketFile) != null) {
// Arm immediately if Keploy's data receiver is already listening,
// or if the launcher declared a via-proc collector will attach
// before tests run (KEPLOY_DEDUP_ATTACH=via-proc).
if (receiverKey(publisher.socketFile) != null || isViaProcAttachDeclared()) {
RequestGate.arm();
}
}
Expand Down
Loading
Loading