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 @@ -33,7 +33,7 @@ Executor wrapping is **fail-closed**: only positively verified safe executors (e

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:<group>.<name>" | "scheduled:<class>.<method>" | "kafka:<topics>@<listener>" | "listener:<queues/dest>@<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:<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`, 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.
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.

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.

Expand Down
12 changes: 11 additions & 1 deletion keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ static boolean hasExpiredRunning() {
* No-op when Keploy is unarmed.
*
* @param job the object whose {@code run()} runs the job
* @param kind "quartz", "scheduled", "kafka", or "listener"
* @param kind "quartz", "scheduled", "kafka", "listener", or "session-listener"
* @return the token to pass to {@link #exit(Object)} when it is done
*/
public static Object enter(Object job, String kind) {
Expand All @@ -125,6 +125,13 @@ public static Object enter(Object job, String kind) {
// whose window already closed; fail closed on asyncExecutors.
KeployDedupAgent.noteObservedUntrackedAsyncLibrary(
"scheduled job (" + run.name + ")", true);
} else if ("session-listener".equals(kind)) {
// A container session-expiry listener firing outside any tracked
// request or job may be executing application cleanup for a
// session created by an earlier HTTP test; fail closed on
// asyncExecutors in addition to contaminating overlapping windows.
KeployDedupAgent.noteObservedUntrackedAsyncLibrary(
"session listener outside request window (" + run.name + ")", true);
}
} catch (Throwable t) {
// The job runs on. A run counted as going on before this (an
Expand Down Expand Up @@ -391,6 +398,9 @@ static String name(Object job, String kind) {
if ("kafka".equals(kind) || "listener".equals(kind)) {
return cachedListenerName(job, kind);
}
if ("session-listener".equals(kind) && job instanceof String) {
return kind + ":" + job;
}
String name;
try {
if ("quartz".equals(kind)) {
Expand Down
94 changes: 94 additions & 0 deletions keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,35 @@ public final class RequestGate {
// 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();

// Exact container-internal listener bridge classes skipped ONLY on
// container-native listener interfaces (never on Servlet HttpSession*Listener
// interfaces), because these bridges either delegate into hooked Servlet
// session listener dispatchers or perform container-only SSO bookkeeping.
private static final Set<String> INTERNAL_CONTAINER_SESSION_LISTENERS = Collections.unmodifiableSet(
new java.util.HashSet<>(java.util.Arrays.asList(
"io.undertow.servlet.core.SessionListenerBridge",
"org.eclipse.jetty.ee11.servlet.SessionHandler",
"org.eclipse.jetty.ee10.servlet.SessionHandler",
"org.eclipse.jetty.ee9.nested.SessionHandler",
"org.eclipse.jetty.ee8.nested.SessionHandler",
"org.apache.catalina.authenticator.SingleSignOnListener"
)));

// Exact container-internal Servlet session listener classes auto-registered
// by default container initializers skipped ONLY on exact class name (never
// subclasses) so listener-free session expiry does not falsely contaminate or
// latch: Tomcat's WsSci (Spring Boot and standalone Tomcat) registers
// WsSessionListener; Undertow's JSR-356 Bootstrap (any deployment with a
// WebSocketDeploymentInfo, which Spring Boot's starter-undertow adds by
// default) registers JsrWebSocketFilter$LogoutListener, whose sessionDestroyed
// only queues close frames (WebSockets.sendClose, no callback) on the
// session's stored WebSocket channels (undertow-websockets-jsr 2.2.37 / 2.3.18).
private static final Set<String> INTERNAL_SERVLET_SESSION_LISTENERS = Collections.unmodifiableSet(
new java.util.HashSet<>(java.util.Arrays.asList(
"org.apache.tomcat.websocket.server.WsSessionListener",
"io.undertow.websockets.jsr.JsrWebSocketFilter$LogoutListener"
)));
// 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.
Expand Down Expand Up @@ -555,6 +584,7 @@ static void disarm() {
unarmedEntered = false;
pendingArmedMidFlight = false;
lastUnarmedHandOffNanos = 0L;
UNARMED_REQUEST_DEPTH.remove();
ARMED_MID_FLIGHT_CONSUMED.set(false);
externalUntrackedTailPending = false;
externalUntrackedTailExpiresAtNanos = 0L;
Expand Down Expand Up @@ -5665,6 +5695,70 @@ public String toString() {
}
}

/**
* Guards a container session-listener invocation (e.g.
* {@code HttpSessionListener.sessionDestroyed},
* {@code HttpSessionAttributeListener.attributeRemoved},
* {@code HttpSessionBindingListener.valueUnbound}). When invoked on a
* thread already inside a tracked request/dispatch or tracked job (such as
* synchronous {@code session.invalidate()} inside a handler), returns
* {@code null} with zero latch and zero contamination. When invoked on a
* background expiry thread outside any tracked request or job, enters
* {@link JobGate} so overlapping test windows are marked contaminated and
* latches {@code asyncExecutors=false}.
*
* @param listener the session listener instance being invoked
* @param eventName the listener method name (e.g. {@code "sessionDestroyed"})
* @param containerNative {@code true} for container-native listener
* interfaces where exact container-internal bridge listeners are
* skipped; {@code false} for standard Servlet session listener
* interfaces
* @return a token to pass to {@link #exitSessionListener(Object)}, or
* {@code null} when no background tracking was needed
*/
public static Object enterSessionListener(Object listener, String eventName, boolean containerNative) {
if (listener == null) {
return null;
}
String listenerClass = listener.getClass().getName();
if (containerNative && INTERNAL_CONTAINER_SESSION_LISTENERS.contains(listenerClass)) {
return null;
}
if (!containerNative && INTERNAL_SERVLET_SESSION_LISTENERS.contains(listenerClass)) {
return null;
}
if (isInsideUnarmedRequest()) {
return null;
}
String label = (eventName == null || eventName.isEmpty())
? listenerClass
: listenerClass + "#" + eventName;
if (!armed) {
KeployDedupAgent.noteObservedUntrackedAsyncLibrary(
"session listener outside request window (" + label + ")", false);
return enterUnarmed();
}
if (INSIDE.get() != null
|| JobGate.runningAttribution() != null
|| JobGate.expiredRunningName() != null) {
return null;
}
return JobGate.enter(label, "session-listener");
}

/**
* Completes a background session-listener run started by
* {@link #enterSessionListener(Object, String, boolean)}.
*
* @param token the token returned by {@code enterSessionListener}, or {@code null}
*/
public static void exitSessionListener(Object token) {
if (token == null) {
return;
}
JobGate.exit(token);
}

private static final class HandedSupplier<T> extends Hand implements Supplier<T> {

final Supplier<T> task;
Expand Down
Loading
Loading