From f43dbeaa9f6e3ce505be1a81605acebc0e39d09f Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 01:58:15 +0530 Subject: [PATCH 01/26] feat(dedup): v3 honest TCP protocol, async executor tails, and listener contamination Signed-off-by: slayerjain --- .../main/java/io/keploy/dedup/JobGate.java | 11 +- .../io/keploy/dedup/KeployDedupAgent.java | 121 +++++++- .../java/io/keploy/dedup/OrderedPools.java | 16 + .../java/io/keploy/dedup/RequestGate.java | 146 +++++++++ .../java/io/keploy/dedup/ServerEntries.java | 150 +++++++++ .../keploy/dedup/CoverageTcpClientTest.java | 204 +++++++++--- .../dedup/HonestProtocolAndAsyncTest.java | 292 ++++++++++++++++++ .../java/io/keploy/dedup/JobTailTest.java | 14 +- .../test/java/io/keploy/dedup/PhasesTest.java | 5 +- .../java/io/keploy/dedup/ServerTailTest.java | 12 +- 10 files changed, 899 insertions(+), 72 deletions(-) create mode 100644 keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java 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 08d10a70..d9ce1aec 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -178,13 +178,20 @@ static List close() { // 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 + // method, "kafka:" / "listener:" for a message listener, + // 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. static String name(Object job, String 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(); } 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 1c482353..75fba7aa 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -155,6 +155,19 @@ static String encodeBytecodeFrame(String buildTag, String manifestJson, byte[] z // 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"; + // Resync barrier command over TCP: "NOP " -> "ACK ". Does not + // touch activeTestId, lastEndedTestId, or JaCoCo counters. + static final String NOP_COMMAND = "NOP"; + // Capability declaration sent immediately on TCP connect (proto=3): tells + // k8s-proxy this SDK emits honest windowCut/contaminated/classMismatch flags, + // supports TCP BACKGROUND, correlated ACK , NOP resync, JDK executor + // handoffs, and listener contamination. Older SDKs send no HELLO line and + // are downgraded to soft-mark-only by k8s-proxy. + static final int TCP_PROTOCOL_VERSION = 3; + static final String HELLO_FRAME = "HELLO {\"proto\":" + TCP_PROTOCOL_VERSION + + ",\"windowCut\":true,\"contaminated\":true,\"classMismatch\":true" + + ",\"background\":true,\"ackId\":true,\"nopResync\":true" + + ",\"asyncExecutors\":true,\"listenerContamination\":true}"; private static final AtomicBoolean STARTED = new AtomicBoolean(false); private static final AtomicBoolean SHUTDOWN_HOOK_REGISTERED = new AtomicBoolean(false); @@ -1011,14 +1024,18 @@ 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)
+     *   collector -> SDK : "BACKGROUND" | "START <id>" | "END <id>"
+     *   SDK -> collector : ["BACKGROUND <compact-json>"] + "ACK <id>"
+     *                                                      (after a START cleared the counters)
+     *                      "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)
      * 
+ * Echoing {@code <id>} on every {@code ACK} lets the collector correlate each + * barrier with the exact test it issued, so a late {@code ACK} for test N can + * never satisfy test N+1's barrier. * The collector starts listening only when replay begins, so the connect loop * retries until it is reachable. */ @@ -1038,6 +1055,14 @@ 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; + // Opt-in per TCP connection via "BACKGROUND" command so older collectors + // never receive unexpected BACKGROUND frames. + private boolean backgroundRequested; + 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; @@ -1094,6 +1119,12 @@ private void connectAndServe() throws IOException { // 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; + backgroundRequested = false; + backgroundLost = 0; + } log(Level.INFO, "Keploy dedup: connected to collector at " + host + ":" + port, null); try (Socket active = open; BufferedReader reader = new BufferedReader( @@ -1101,12 +1132,38 @@ 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 protocol + honesty capabilities immediately on connect. + // Older collectors ignore unrecognized lines; newer collectors gate + // removal eligibility on this declaration. + writeLine(out, HELLO_FRAME); + out.flush(); String line; while (running.get() && (line = reader.readLine()) != null) { String trimmed = line.trim(); if (trimmed.isEmpty()) { continue; } + if (BACKGROUND_COMMAND.equals(trimmed)) { + synchronized (testCaseLock) { + if (collector.probeScan() != null) { + backgroundRequested = true; + } else { + 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 (trimmed.startsWith(NOP_COMMAND + " ")) { + String token = trimmed.substring(NOP_COMMAND.length() + 1).trim(); + if (!token.isEmpty()) { + synchronized (testCaseLock) { + ack(out, token); + } + } + continue; + } CoverageCommand command = CoverageCommand.parse(trimmed); if (command == null) { continue; @@ -1131,13 +1188,16 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // of the tests before this one, so this START is not taken // and its END is ignored too. activeTestId = ""; + String after = lastEndedTestId; + lastEndedTestId = null; boolean reset; + List cleared = new ArrayList<>(); 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(phases, cleared); } catch (RuntimeException e) { // Not taken, and the connection goes on: thrown past // here, it ended this thread, and no later command @@ -1147,16 +1207,23 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) } if (reset) { activeTestId = command.testId; + if (after != null && !cleared.isEmpty() && backgroundRequested) { + writeBackgroundFrame(out, after, command.testId, cleared); + } } else { // Said before the ACK, as for an END not taken: the // collector has no other sign this test went unmeasured. writeLine(out, IGNORED_REPLY + " " + command.testId); } - ack(out); + ack(out, command.testId); 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; if (!command.testId.equals(activeTestId)) { log(Level.SEVERE, "Ignoring mismatched END command. expected=" + activeTestId + ", actual=" @@ -1167,7 +1234,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,8 +1243,9 @@ 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; try { - boolean cut = !collector.awaitRequests(command.testId, phases); + cut = !collector.awaitRequests(command.testId, phases); coverage = collector.capture(phases).ended(cut, JobGate.close()); } catch (Exception e) { // Not taken, as on the unix socket: an empty COV is @@ -1185,7 +1253,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) 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()) { @@ -1203,6 +1271,7 @@ 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; // 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 +1285,43 @@ 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) { + try { + BackgroundRecord record = new BackgroundRecord( + collector.coverageIndex.report().build, after, before, + collector.backgroundProbes(cleared)); + if (backgroundLost > 0) { + record.lost = backgroundLost; + } + writeLine(out, BACKGROUND_COMMAND + " " + GSON.toJson(record)); + backgroundLost = 0; + if (diagnosticsEnabled()) { + diagnostic("BACKGROUND frame sent over TCP: after=" + after + ", before=" + before + + ", classes=" + record.executedLinesByFile.size()); + } + } catch (Throwable t) { + backgroundLost++; + log(backgroundLost == 1 ? Level.WARNING : Level.FINE, + "Keploy dedup: could not send BACKGROUND frame before " + before, t); + } + } + // 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 static void ack(OutputStream out, String testId) throws IOException { + writeLine(out, "ACK " + testId); out.flush(); } 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 814a77c3..5d76f5dd 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -98,6 +98,22 @@ private static boolean read(Object executor) { if (executor == null) { return false; } + if (executor instanceof ThreadPoolExecutor) { + Class queue; + try { + queue = ((ThreadPoolExecutor) executor).getQueue().getClass(); + } catch (Throwable e) { + if (e instanceof VirtualMachineError) { + return true; + } + return uncounted(executor, "its pool's queue cannot be read (" + e + ")"); + } + if (IN_ORDER.contains(queue)) { + return false; + } + return uncounted(executor, "its pool's queue, a " + queue.getName() + + ", may order its tasks by their own type"); + } Object pool = POOL.get(executor.getClass()); if (pool == NONE) { return false; 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 98f0dc94..70a4e69c 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -1,7 +1,10 @@ package io.keploy.dedup; import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; 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.TimeUnit; @@ -9,6 +12,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.locks.LockSupport; +import java.util.function.Supplier; /** * RequestGate counts the requests the app's server is running, so that a @@ -157,6 +161,123 @@ public static Callable hand(Object executor, Callable task) { return handed; } + /** + * Counts a {@link Supplier} handed to {@link CompletableFuture#supplyAsync} + * on a request or job thread until it completes. + * + * @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 Supplier handSupplier(Object executor, Supplier supplier) { + if (supplier == null || supplier instanceof HandedSupplier || supplier instanceof Comparable) { + return supplier; + } + Window window = INSIDE.get(); + String job = window == null ? JobGate.running() : null; + if ((window == null && job == null) || OrderedPools.orders(executor)) { + return supplier; + } + HandedSupplier handed = new HandedSupplier<>(window, job, supplier); + if (window != null) { + window.running.incrementAndGet(); + } + return handed; + } + + /** + * Call-site wrapper for {@link Executor#execute(Runnable)}: propagates the + * current request window (or job run) across standard JDK executors whose + * classes live in the bootstrap loader. + */ + public static void execute(Executor executor, Runnable task) { + Runnable handed = hand(executor, task); + try { + executor.execute(handed); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + } + + /** Call-site wrapper for {@link ExecutorService#submit(Runnable)}. */ + public static Future submit(ExecutorService executor, Runnable task) { + Runnable handed = hand(executor, task); + try { + return executor.submit(handed); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + } + + /** Call-site wrapper for {@link ExecutorService#submit(Runnable, Object)}. */ + public static Future submit(ExecutorService executor, Runnable task, T result) { + Runnable handed = hand(executor, task); + try { + return executor.submit(handed, result); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + } + + /** Call-site wrapper for {@link ExecutorService#submit(Callable)}. */ + public static Future submit(ExecutorService executor, Callable task) { + Callable handed = hand(executor, task); + try { + return executor.submit(handed); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + } + + /** Call-site wrapper for {@link CompletableFuture#runAsync(Runnable)}. */ + public static CompletableFuture runAsync(Runnable task) { + Runnable handed = hand(null, task); + try { + return CompletableFuture.runAsync(handed); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + } + + /** Call-site wrapper for {@link CompletableFuture#runAsync(Runnable, Executor)}. */ + public static CompletableFuture runAsync(Runnable task, Executor executor) { + Runnable handed = hand(executor, task); + try { + return CompletableFuture.runAsync(handed, executor); + } catch (Throwable t) { + dropped(handed, task); + throw t; + } + } + + /** Call-site wrapper for {@link CompletableFuture#supplyAsync(Supplier)}. */ + public static CompletableFuture supplyAsync(Supplier supplier) { + Supplier handed = handSupplier(null, supplier); + try { + return CompletableFuture.supplyAsync(handed); + } catch (Throwable t) { + dropped(handed, supplier); + throw t; + } + } + + /** Call-site wrapper for {@link CompletableFuture#supplyAsync(Supplier, Executor)}. */ + public static CompletableFuture supplyAsync(Supplier supplier, Executor executor) { + Supplier handed = handSupplier(executor, supplier); + try { + return CompletableFuture.supplyAsync(handed, executor); + } catch (Throwable t) { + dropped(handed, supplier); + throw t; + } + } + /** * Counts a task {@link #hand(Object, Runnable)} counted as done when the * executor threw instead of taking it (it rejected it, or was shut @@ -381,4 +502,29 @@ public String toString() { return String.valueOf(task); } } + + private static final class HandedSupplier extends Hand implements Supplier { + + private final Supplier task; + + HandedSupplier(Window window, String job, Supplier task) { + super(window, job); + 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 688c64ab..40417733 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -111,6 +111,17 @@ 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"); + // Message listeners (F10 listener contamination): 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("Kafka", "org/springframework/kafka/listener/adapter/MessagingMessageListenerAdapter", + "kafka", "onMessage"); + 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: SimpleAsyncTaskExecutor // (an async event multicaster's, and Spring's default for @Async) // starts each task in doExecute, whatever method it was handed in; @@ -122,6 +133,10 @@ final class ServerEntries implements ClassFileTransformer { addAsync("org/springframework/core/task/SimpleAsyncTaskExecutor", "doExecute"); addAsync("org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor", "execute", "submit", "submitListenable"); + addAsync("org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler", "execute", "submit", + "submitListenable"); + addAsync("org/springframework/scheduling/concurrent/ConcurrentTaskExecutor", "execute", "submit", + "submitListenable"); addAsync("org/springframework/aop/interceptor/AsyncExecutionAspectSupport", "doSubmit"); } @@ -192,6 +207,13 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (uncounted != null) { SEEN_UNCOUNTED.add(uncounted); } + if (className != null && shouldRewriteExecutorCalls(className) && seesGate(loader)) { + try { + return wrapExecutorCalls(classfileBuffer); + } catch (Throwable t) { + LOGGER.log(Level.FINE, "Keploy dedup skipped executor call-site wrap for " + className, t); + } + } return null; } // With the wait off, servers are left as they are, and so no task @@ -328,6 +350,134 @@ private static byte[] wrap(byte[] classfile, Entry entry) { return wrap(classfile, entry.methods, entry.job, entry.async); } + // shouldRewriteExecutorCalls filters out JDK, agent, server, and Spring + // executor internals so call-site wrapping targets application and library + // classes that submit async tasks to standard JDK Executor/ExecutorService/ + // CompletableFuture APIs. + static boolean shouldRewriteExecutorCalls(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/") + && !className.startsWith("org/springframework/core/task/") + && !className.startsWith("org/springframework/scheduling/concurrent/") + && !className.startsWith("org/springframework/aop/interceptor/") + && !className.startsWith("org/apache/catalina/") + && !className.startsWith("org/eclipse/jetty/") + && !className.startsWith("io/undertow/") + && !className.startsWith("org/quartz/"); + } + + // wrapExecutorCalls redirects standard JDK executor hand-off call sites + // (Executor.execute, ExecutorService.submit, ThreadPoolExecutor.execute, + // AbstractExecutorService.submit, CompletableFuture.runAsync/supplyAsync) + // to RequestGate's identically-stacked static helpers so async tails count + // in the request's (or job's) window without touching bootstrap JDK classes. + // 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; + } + 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) { + @Override + public void visitMethodInsn(int opcode, String owner, String mname, String desc, + boolean isInterface) { + if (opcode == Opcodes.INVOKEINTERFACE && "java/util/concurrent/Executor".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/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 (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; + } + } + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + } + }; + } + }, 0); + return changed[0] ? writer.toByteArray() : null; + } + // 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 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 9a0cbb94..f18c4b78 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java @@ -108,15 +108,16 @@ public void endWithNoStartNamesTheTestThenAnswersAck() throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertEquals(KeployDedupAgent.HELLO_FRAME, 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)); out.flush(); assertEquals("IGNORED test-set-0/test-47", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-47", in.readLine()); assertEquals("IGNORED test-set-0/test-48", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-48", in.readLine()); } } @@ -130,31 +131,32 @@ public void aStartWhoseResetFailedNamesTheTestThenAnswersAckAndSoDoesItsEnd() th OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); send(out, "START test-set-0/test-1"); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); // JaCoCo goes away for the next reset: the counters still hold // test-1's lines, so test-2 is not measured. jacoco.dropNext.set(1); send(out, "START test-set-0/test-2"); assertEquals("IGNORED test-set-0/test-2", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-2", in.readLine()); // test-1 was left when test-2 started, and test-2 never began. send(out, "END test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); send(out, "END test-set-0/test-2"); assertEquals("IGNORED test-set-0/test-2", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-2", in.readLine()); // JaCoCo is back: the next test is measured as before. send(out, "START test-set-0/test-3"); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-3", in.readLine()); send(out, "END test-set-0/test-3"); String cov = in.readLine(); assertTrue("a COV for test-3, got " + cov, cov != null && cov.startsWith("COV ") && cov.contains("test-set-0/test-3")); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-3", in.readLine()); } } @@ -168,28 +170,29 @@ public void anEndWhoseDumpFailedNamesTheTestThenAnswersAckAndEndsTheTest() throw OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); send(out, "START test-set-0/test-1"); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); // JaCoCo goes away for the dump: test-1's lines never reach the // SDK. Before, it sent an empty COV, as for a test that ran no // line of the app. jacoco.dropNext.set(1); send(out, "END test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); // That END ended test-1. send(out, "END test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); send(out, "START test-set-0/test-2"); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-2", in.readLine()); send(out, "END test-set-0/test-2"); String cov = in.readLine(); assertTrue("a COV for test-2, got " + cov, cov != null && cov.startsWith("COV ") && cov.contains("test-set-0/test-2")); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-2", in.readLine()); } } @@ -203,13 +206,14 @@ public void aStartThatThrowsNamesTheTestThenAnswersAckAndTheConnectionGoesOn() t OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); send(out, "START test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); send(out, "END test-set-0/test-1"); assertEquals("the connection still answers", "IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); } } @@ -232,9 +236,10 @@ public void theManifestWritesAClassIdAs16HexDigitsAndTheCovNamesAClassJacocoSawO OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); send(out, "START test-set-0/test-1"); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); send(out, "END test-set-0/test-1"); assertEquals("COV {\"id\":\"test-set-0/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[0]}," + "\"classMismatch\":[\"com/acme/Shop\"]}", in.readLine()); @@ -242,7 +247,7 @@ public void theManifestWritesAClassIdAs16HexDigitsAndTheCovNamesAClassJacocoSawO assertTrue(classes, classes.startsWith("CLASSES ")); String manifest = new String(Base64.getDecoder().decode(classes.split(" ")[2]), StandardCharsets.UTF_8); assertEquals("{\"com/acme/Shop\":{\"id\":\"0000000000000099\",\"probeCount\":2}}", manifest); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); } } @@ -262,9 +267,10 @@ public void aCutEndSaysSoInItsCovAfterClassMismatch() throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); send(out, "START test-set-0/test-1"); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); // The test's request is still running when its END comes, and // past END's wait. Object request = RequestGate.enter(); @@ -272,16 +278,17 @@ public void aCutEndSaysSoInItsCovAfterClassMismatch() throws Exception { send(out, "END test-set-0/test-1"); assertEquals("COV {\"id\":\"test-set-0/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[0]}," + "\"classMismatch\":[\"com/acme/Shop\"],\"windowCut\":true}", in.readLine()); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); } finally { RequestGate.exit(request); } // Its request done, the next test's END is not cut. send(out, "START test-set-0/test-2"); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-2", in.readLine()); send(out, "END test-set-0/test-2"); String cov = in.readLine(); assertTrue(cov, cov.startsWith("COV ") && !cov.contains("windowCut")); + assertEquals("ACK test-set-0/test-2", in.readLine()); } } @@ -296,15 +303,18 @@ public void anEndIsAnsweredWithoutWaitingForTheCollectorsDelayedAck() throws Exc sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); + assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); long[] micros = new long[ROUND_TRIPS]; for (int i = 0; i < ROUND_TRIPS; i++) { - send(out, "START test-set-0/test-" + i); - assertEquals("ACK\n", readReply(in)); + String id = "test-set-0/test-" + i; + send(out, "START " + id); + assertEquals("ACK " + id + "\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 " + id + "\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(); + assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); byte[] buf = new byte[64 * 1024]; for (int i = 0; i < ROUND_TRIPS; i++) { - send(out, "START test-set-0/test-" + i); - assertEquals("ACK\n", readOnce(in, buf)); - send(out, "END test-set-0/test-" + i); + String id = "test-set-0/test-" + i; + send(out, "START " + id); + assertEquals("ACK " + id + "\n", readOnce(in, buf)); + 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 " + id + "\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 " + id + "\n", readOnce(in, buf)); } } } @@ -347,8 +359,9 @@ public void theSocketToKeployHasNagleOff() throws Exception { try (Socket sdk = collector.accept()) { sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); + assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(sdk.getInputStream())); send(out, "END test-set-0/test-1"); - assertEquals("IGNORED test-set-0/test-1\nACK\n", readReply(sdk.getInputStream())); + assertEquals("IGNORED test-set-0/test-1\nACK test-set-0/test-1\n", readReply(sdk.getInputStream())); Field worker = KeployDedupAgent.class.getDeclaredField("coverageWorker"); worker.setAccessible(true); Object client = worker.get(null); @@ -379,8 +392,9 @@ public void aFrameLargerThanTheReplyBufferArrivesWholeAndTheRepliesAfterItStayFa sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); + assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); send(out, "START test-set-0/test-0"); - assertEquals("ACK\n", readReply(in)); + assertEquals("ACK test-set-0/test-0\n", readReply(in)); probes[0] = true; send(out, "END test-set-0/test-0"); String reply = readReply(in); @@ -394,19 +408,20 @@ public void aFrameLargerThanTheReplyBufferArrivesWholeAndTheRepliesAfterItStayFa assertTrue("the frame is larger than the reply buffer: " + lines[1].length() + " bytes", lines[1].length() > 64 * 1024); assertArrayEquals(classBytes, unzipped(Base64.getDecoder().decode(classes[3]), "com/acme/Big.class")); - assertEquals("ACK", lines[2]); + assertEquals("ACK test-set-0/test-0", lines[2]); assertEquals("", lines[3]); long[] micros = new long[ROUND_TRIPS]; for (int i = 1; i <= ROUND_TRIPS; i++) { - send(out, "START test-set-0/test-" + i); - assertEquals("ACK\n", readReply(in)); + String id = "test-set-0/test-" + i; + send(out, "START " + id); + assertEquals("ACK " + id + "\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 + "\"") - && reply.endsWith("}\nACK\n")); + assertTrue(reply, reply.startsWith("COV {\"id\":\"" + id + "\"") + && reply.endsWith("}\nACK " + id + "\n")); } long[] sorted = micros.clone(); Arrays.sort(sorted); @@ -435,8 +450,9 @@ public void aJobThatStartsWhileEndWaitsForTheRequestsOrReadsTheHitsIsNamed() thr sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); + assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); send(out, "START test-set-0/test-1"); - assertEquals("ACK\n", readReply(in)); + assertEquals("ACK test-set-0/test-1\n", readReply(in)); jacoco.onDump = () -> JobGate.exit(JobGate.enter(new Object(), "scheduled")); Object request = RequestGate.enter(); try { @@ -454,7 +470,7 @@ public void aJobThatStartsWhileEndWaitsForTheRequestsOrReadsTheHitsIsNamed() thr String reply = readReply(in); assertFalse("END did not reach its bound: " + reply, reply.contains("windowCut")); assertTrue(reply, reply.endsWith( - ",\"contaminated\":[\"quartz:java.lang.Object\",\"scheduled:java.lang.Object\"]}\nACK\n")); + ",\"contaminated\":[\"quartz:java.lang.Object\",\"scheduled:java.lang.Object\"]}\nACK test-set-0/test-1\n")); } } @@ -491,16 +507,18 @@ public void close() { sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); + assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); for (int last = test + (connection == 1 ? 2 : 1); test < last; test++) { String id = "test-set-0/test-" + test; System.setProperties(jvm); send(out, "START " + id); - assertEquals("ACK\n", readReply(in)); + assertEquals("ACK " + id + "\n", readReply(in)); System.setProperties(unreadable); 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 " + id + "\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,82 @@ 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)); + assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); + + // 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. + probes[3] = true; + send(out, "START test-set-0/test-2"); + String bgLine = in.readLine(); + assertTrue("expected BACKGROUND frame before 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]")); + assertEquals("ACK test-set-0/test-2", in.readLine()); + 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("no BACKGROUND frame after cut END", "ACK test-set-0/test-4", in.readLine()); + } + } + // 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 +701,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/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java new file mode 100644 index 00000000..26659ac3 --- /dev/null +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -0,0 +1,292 @@ +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.assertTrue; + +import java.io.BufferedReader; +import java.io.IOException; +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.util.List; +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.Future; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +/** + * Covers the v3 honest TCP protocol (HELLO capability declaration, NOP resync), + * JDK executor call-site async-tail tracking (RequestGate + ServerEntries), and + * Kafka/message listener contamination (JobGate + ServerEntries). + */ +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 ServerSocket collector; + private FakeJacoco jacoco; + + @Before + public void setUp() { + RequestGate.open(); + JobGate.close(); + } + + @After + public void tearDown() throws IOException { + KeployDedupAgent.stop(); + System.clearProperty(ENDPOINT_PROPERTY); + System.clearProperty(JACOCO_PORT_PROPERTY); + System.clearProperty(WARMUP_DISABLED_PROPERTY); + if (collector != null) { + collector.close(); + collector = null; + } + if (jacoco != null) { + jacoco.close(); + jacoco = null; + } + JobGate.close(); + RequestGate.open(); + } + + @Test(timeout = 60000) + public void tcpConnectDeclaresHonestyHelloAndAnswersNopResyncWithoutDisturbingActiveTest() throws Exception { + collector = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(30000); + jacoco = new FakeJacoco(); + System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); + System.setProperty(JACOCO_PORT_PROPERTY, String.valueOf(jacoco.server.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(); + assertEquals(KeployDedupAgent.HELLO_FRAME, hello); + assertTrue(hello, hello.contains("\"proto\":3")); + assertTrue(hello, hello.contains("\"windowCut\":true")); + assertTrue(hello, hello.contains("\"contaminated\":true")); + assertTrue(hello, hello.contains("\"classMismatch\":true")); + assertTrue(hello, hello.contains("\"background\":true")); + assertTrue(hello, hello.contains("\"ackId\":true")); + assertTrue(hello, hello.contains("\"nopResync\":true")); + + // NOP before any test + send(out, "NOP resync-1"); + assertEquals("ACK resync-1", in.readLine()); + + // NOP mid-test must not clear activeTestId + send(out, "START ts/test-1"); + assertEquals("ACK ts/test-1", in.readLine()); + send(out, "NOP resync-2"); + assertEquals("ACK resync-2", in.readLine()); + send(out, "END ts/test-1"); + String cov = in.readLine(); + assertNotNull(cov); + assertTrue("expected COV for ts/test-1, got " + cov, + cov.startsWith("COV ") && cov.contains("\"id\":\"ts/test-1\"")); + assertEquals("ACK ts/test-1", in.readLine()); + } + } + + @Test(timeout = 60000) + public void jdkExecutorAndCompletableFutureAsyncTailsCountInRequestWindow() throws Exception { + ExecutorService pool = Executors.newSingleThreadExecutor(); + try { + // 1. Executor.execute async tail outlives request -> END await returns false (windowCut) + CountDownLatch release = new CountDownLatch(1); + CountDownLatch started = new CountDownLatch(1); + Object req = RequestGate.enter(); + try { + RequestGate.execute(pool, () -> { + started.countDown(); + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } finally { + RequestGate.exit(req); + } + assertTrue(started.await(10, TimeUnit.SECONDS)); + assertEquals("async tail still counted after request exit", 1, RequestGate.running()); + assertFalse("END cuts window while async tail still runs", + RequestGate.await(TimeUnit.MILLISECONDS.toNanos(40))); + release.countDown(); + + // 2. ExecutorService.submit(Callable) and CompletableFuture.supplyAsync + RequestGate.open(); + CountDownLatch release2 = new CountDownLatch(1); + CountDownLatch started2 = new CountDownLatch(1); + Object req2 = RequestGate.enter(); + Future submitted; + CompletableFuture supplied; + try { + submitted = RequestGate.submit(pool, (Callable) () -> { + started2.countDown(); + release2.await(10, TimeUnit.SECONDS); + return "ok"; + }); + supplied = RequestGate.supplyAsync(() -> "done", pool); + } finally { + RequestGate.exit(req2); + } + assertTrue(started2.await(10, TimeUnit.SECONDS)); + assertFalse("END cuts while submitted Callable + supplyAsync still run", + RequestGate.await(TimeUnit.MILLISECONDS.toNanos(40))); + release2.countDown(); + assertEquals("ok", submitted.get(10, TimeUnit.SECONDS)); + assertEquals("done", supplied.get(10, TimeUnit.SECONDS)); + } finally { + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void rawPriorityThreadPoolExecutorIsNotWrappedByRequestGate() { + ThreadPoolExecutor priority = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new PriorityBlockingQueue()); + try { + assertTrue("OrderedPools must recognize raw ThreadPoolExecutor with PriorityBlockingQueue", + OrderedPools.orders(priority)); + } finally { + priority.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void serverEntriesRewritesAppExecutorCallSitesToRequestGate() throws Exception { + // Generate an app class com/example/AsyncCaller whose fire(Executor, Runnable) + // invokes INVOKEINTERFACE java/util/concurrent/Executor.execute(Runnable)V. + String className = "com/example/AsyncCaller"; + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, 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 fire = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "fire", + "(Ljava/util/concurrent/Executor;Ljava/lang/Runnable;)V", null, null); + fire.visitCode(); + fire.visitVarInsn(Opcodes.ALOAD, 0); + fire.visitVarInsn(Opcodes.ALOAD, 1); + fire.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/Executor", "execute", + "(Ljava/lang/Runnable;)V", true); + fire.visitInsn(Opcodes.RETURN); + fire.visitMaxs(2, 2); + fire.visitEnd(); + cw.visitEnd(); + + byte[] transformed = new ServerEntries(true).transform( + getClass().getClassLoader(), className, null, null, cw.toByteArray()); + assertNotNull("ServerEntries must rewrite Executor.execute call site", transformed); + + Class loaded = new ByteLoader(getClass().getClassLoader()).define("com.example.AsyncCaller", transformed); + ExecutorService pool = Executors.newSingleThreadExecutor(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + try { + Object req = RequestGate.enter(); + try { + Runnable task = () -> { + started.countDown(); + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }; + loaded.getMethod("fire", Executor.class, Runnable.class).invoke(null, pool, task); + } finally { + RequestGate.exit(req); + } + assertTrue(started.await(10, TimeUnit.SECONDS)); + assertEquals("rewritten Executor.execute must keep request window open", 1, RequestGate.running()); + assertFalse("END must detect async tail and report windowCut", + RequestGate.await(TimeUnit.MILLISECONDS.toNanos(40))); + } finally { + release.countDown(); + pool.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void kafkaListenerInvocationMarksWindowContaminated() throws Exception { + String className = "org/springframework/kafka/listener/KafkaMessageListenerContainer$ListenerConsumer"; + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, 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 invoke = cw.visitMethod(Opcodes.ACC_PUBLIC, "invokeRecordListener", "()V", null, null); + invoke.visitCode(); + invoke.visitInsn(Opcodes.RETURN); + invoke.visitMaxs(0, 1); + invoke.visitEnd(); + cw.visitEnd(); + + byte[] transformed = new ServerEntries(true).transform( + getClass().getClassLoader(), className, null, null, cw.toByteArray()); + assertNotNull("ServerEntries must wrap Kafka ListenerConsumer.invokeRecordListener", transformed); + + Class loaded = new ByteLoader(getClass().getClassLoader()) + .define(className.replace('/', '.'), transformed); + Object consumer = loaded.getDeclaredConstructor().newInstance(); + + JobGate.open(); + loaded.getMethod("invokeRecordListener").invoke(consumer); + List contaminated = JobGate.close(); + assertEquals(1, contaminated.size()); + assertTrue("expected kafka: contamination entry, got " + contaminated, + contaminated.get(0).startsWith("kafka:")); + } + + private static void send(OutputStream out, String command) throws IOException { + out.write((command + "\n").getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + + 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); + } + } +} 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 74304cc8..8067b431 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,20 +314,21 @@ 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); - assertEquals("ACK", sdkIn.readLine()); + String fullId = "test-set-0/" + id; + send(sdkOut, "START " + fullId); + assertEquals("ACK " + fullId, 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; - while (!(line = sdkIn.readLine()).equals("ACK")) { + while (!(line = sdkIn.readLine()).equals("ACK " + fullId)) { 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 c668697e..46224811 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java @@ -140,14 +140,15 @@ public void overTcpEachCommandSaysHowLongEachStepTookToo() throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); out.write("START test-set-0/test-1\n".getBytes(StandardCharsets.UTF_8)); out.flush(); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); out.write("END test-set-0/test-1\n".getBytes(StandardCharsets.UTF_8)); out.flush(); String cov = in.readLine(); assertTrue(cov, cov != null && cov.startsWith("COV ") && cov.contains("\"" + SHOP + "\":[0,2]")); - assertEquals("ACK", in.readLine()); + assertEquals("ACK test-set-0/test-1", in.readLine()); } } // Said once the command is answered: waited for. 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 00a5f66f..72ecf8cc 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java @@ -516,17 +516,21 @@ 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); + assertEquals("ACK " + fullId, in.readLine()); 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(); assertTrue(cov, cov != null && cov.startsWith("COV ")); result.covs.add(cov.substring("COV ".length())); String line; - while (!(line = in.readLine()).equals("ACK")) { + while (!(line = in.readLine()).equals("ACK " + fullId)) { assertTrue(line, line.startsWith("CLASSES ") || line.startsWith("MANIFEST ")); } } From 3b9e07dcde5b0f272c694e8982f0feb1d4addad8 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 03:22:00 +0530 Subject: [PATCH 02/26] =?UTF-8?q?fix(dedup):=20address=20r1=20review=20?= =?UTF-8?q?=E2=80=94=20app-only=20rewrites,=20dynamic=20HELLO,=20opt-in=20?= =?UTF-8?q?ACK=5FID,=20cancel/pool=20guards?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: slayerjain --- .../main/java/io/keploy/dedup/JobGate.java | 115 +- .../io/keploy/dedup/KeployDedupAgent.java | 169 ++- .../java/io/keploy/dedup/OrderedPools.java | 266 +++- .../java/io/keploy/dedup/RequestGate.java | 253 +++- .../java/io/keploy/dedup/ServerEntries.java | 272 +++- .../keploy/dedup/CoverageTcpClientTest.java | 119 +- .../dedup/HonestProtocolAndAsyncTest.java | 1149 +++++++++++++++-- .../java/io/keploy/dedup/JobTailTest.java | 4 +- .../test/java/io/keploy/dedup/PhasesTest.java | 8 +- .../java/io/keploy/dedup/ServerTailTest.java | 4 +- 10 files changed, 1957 insertions(+), 402 deletions(-) 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 d9ce1aec..a8310153 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -5,50 +5,65 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; +import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +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). + *

ServerEntries makes Quartz's {@code JobRunShell.run()}, Spring's + * {@code ScheduledMethodRunnable.run()}, Spring Kafka's + * {@code ListenerConsumer}, and Spring AMQP/JMS's + * {@code AbstractMessageListenerContainer.doInvokeListener} call + * {@link #enter(Object, String)} where a 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). * - *

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 + *

The work a job's or listener's run hands to a Spring TaskExecutor or a + * rewritten application executor call site 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. + * 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. Handed-off attribution is bounded by {@link #handedJobMaxNanos} + * so a long-lived worker loop started from a job cannot keep {@code RUNNING} + * open forever. * - *

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. + *

Jobs the app runs on plain threads of its own, uninstrumented custom + * executors, a {@code java.util.Timer}, or unhooked messaging clients are not + * seen, nor is a request's async work that runs past its END. * *

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 a job open in + // RUNNING before it is evicted as a long-lived worker loop. Not final so + // tests can shorten it. + 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 @@ -69,13 +84,13 @@ private JobGate() { * if one is open. Never throws: the job runs whatever happens here. * * @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) { 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 +102,14 @@ 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. + // enter does, from when the task starts; exit counts it done. Bounded by + // handedJobMaxNanos so a long-lived worker loop started from a job cannot + // contaminate every later test forever. Never throws, as enter. static Object enterAs(String name) { Run run = null; try { - run = new Run(name, CURRENT.get()); + long expiresAt = System.nanoTime() + handedJobMaxNanos; + run = new Run(name, CURRENT.get(), true, expiresAt); begin(run); } catch (Throwable t) { // As in enter: the task runs on, and a run counted is handed back. @@ -113,9 +130,16 @@ private static void begin(Run run) { } // 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() { Run run = CURRENT.get(); + if (run == null) { + return null; + } + long now = System.nanoTime(); + while (run != null && (run.over || run.isExpired(now))) { + run = run.outer; + } return run == null ? null : run.name; } @@ -153,15 +177,37 @@ 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. + // here on lands in the test. Handed-off tasks that have run past + // handedJobMaxNanos are evicted so a long-lived worker loop started from a + // job cannot mark every later test contaminated forever. static void open() { + long now = System.nanoTime(); + List expired = null; synchronized (LOCK) { Window opened = new Window(); - for (Run run : RUNNING) { + for (Iterator it = RUNNING.iterator(); it.hasNext(); ) { + Run run = it.next(); + if (run.isExpired(now)) { + it.remove(); + if (EXPIRED_LOGGED.add(run.name)) { + if (expired == null) { + expired = new ArrayList<>(); + } + expired.add(run.name); + } + continue; + } opened.mark(run.name); } window = opened; } + if (expired != null) { + for (String jobName : expired) { + LOGGER.log(Level.INFO, "Keploy dedup stopped attributing a long-lived handed-off task to " + + jobName + " after " + TimeUnit.NANOSECONDS.toMillis(handedJobMaxNanos) + + " ms so it does not mark every later test contaminated"); + } + } } // close ends the window, after its END read the test's hits, and names @@ -234,12 +280,21 @@ 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; + // True for tasks handed off via enterAs (bounded by expiresAtNanos). + private final boolean handed; + private final long expiresAtNanos; // Whether its exit came; only its own thread reads or sets it. private 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; } } 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 75fba7aa..ef7c6bbf 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -42,6 +42,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; @@ -133,6 +134,9 @@ 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; // 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 @@ -155,19 +159,32 @@ static String encodeBytecodeFrame(String buildTag, String manifestJson, byte[] z // 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"; - // Resync barrier command over TCP: "NOP " -> "ACK ". Does not - // touch activeTestId, lastEndedTestId, or JaCoCo counters. + // 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"; - // Capability declaration sent immediately on TCP connect (proto=3): tells - // k8s-proxy this SDK emits honest windowCut/contaminated/classMismatch flags, - // supports TCP BACKGROUND, correlated ACK , NOP resync, JDK executor - // handoffs, and listener contamination. Older SDKs send no HELLO line and - // are downgraded to soft-mark-only by k8s-proxy. + // Protocol version declared in the dynamic HELLO frame sent immediately on + // TCP connect. Each capability boolean is computed from live runtime state + // at connect time so collectors never act on false promises. static final int TCP_PROTOCOL_VERSION = 3; - static final String HELLO_FRAME = "HELLO {\"proto\":" + TCP_PROTOCOL_VERSION - + ",\"windowCut\":true,\"contaminated\":true,\"classMismatch\":true" - + ",\"background\":true,\"ackId\":true,\"nopResync\":true" - + ",\"asyncExecutors\":true,\"listenerContamination\":true}"; + + static String buildHelloFrame(boolean windowCut, boolean contaminated, boolean classMismatch, + boolean background, boolean ackId, boolean nopResync, + boolean asyncExecutors, boolean listenerContamination) { + return "HELLO {\"proto\":" + TCP_PROTOCOL_VERSION + + ",\"windowCut\":" + windowCut + + ",\"contaminated\":" + contaminated + + ",\"classMismatch\":" + classMismatch + + ",\"background\":" + background + + ",\"ackId\":" + ackId + + ",\"nopResync\":" + nopResync + + ",\"asyncExecutors\":" + asyncExecutors + + ",\"listenerContamination\":" + listenerContamination + + "}"; + } private static final AtomicBoolean STARTED = new AtomicBoolean(false); private static final AtomicBoolean SHUTDOWN_HOOK_REGISTERED = new AtomicBoolean(false); @@ -316,7 +333,29 @@ 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); + for (ClassEntry entry : loadedEntries) { + names.add(entry.className); + } + 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 @@ -348,7 +387,15 @@ 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; + Set allowed = appClasses == null ? Collections.emptySet() : appClasses; + boolean hasCallSiteRewrites = !allowed.isEmpty() + || (appPackagePrefix != null && !appPackagePrefix.isEmpty()); try { boolean retransformable = instrumentation.isRetransformClassesSupported(); if (!retransformable && jacocoAttached) { @@ -356,12 +403,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, appPackagePrefix), 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); @@ -1024,18 +1074,22 @@ 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 : "BACKGROUND" | "START <id>" | "END <id>"
-     *   SDK -> collector : ["BACKGROUND <compact-json>"] + "ACK <id>"
-     *                                                      (after a START cleared the counters)
-     *                      "COV <compact-json>" + "ACK <id>" (after an END read the test's hits)
-     *                      "IGNORED <id>" + "ACK <id>"    (after a START that could not
+     *   SDK -> collector (on connect): "HELLO {<dynamic capabilities json>}"
+     *   collector -> SDK : "ACK_ID" | "BACKGROUND" | "NOP [<token>]" | "START <id>" | "END <id>"
+     *   SDK -> collector : "ACK [id]" [+ "BACKGROUND <compact-json>"]
+     *                                                      (after a START cleared the counters;
+     *                                                      BACKGROUND follows ACK so START is
+     *                                                      never delayed by index reporting)
+     *                      "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)
      * 
- * Echoing {@code <id>} on every {@code ACK} lets the collector correlate each - * barrier with the exact test it issued, so a late {@code ACK} for test N can - * never satisfy test N+1's barrier. + * 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. */ @@ -1062,6 +1116,9 @@ private static final class CoverageTcpClient implements CoverageWorker { // 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; 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. @@ -1073,6 +1130,15 @@ private static final class CoverageTcpClient implements CoverageWorker { this.port = port; } + private String helloFrame() { + boolean agentAttached = transformerAdded; + boolean windowCut = agentAttached && collector.endWaitMillis > 0 && !ServerEntries.countsNone(); + boolean background = collector.probeScan() != null; + boolean asyncExecutors = agentAttached && executorCallSitesEnabled; + return buildHelloFrame(windowCut, agentAttached, true, background, true, true, + asyncExecutors, agentAttached); + } + @Override public void run() { while (running.get()) { @@ -1123,6 +1189,7 @@ private void connectAndServe() throws IOException { activeTestId = ""; lastEndedTestId = null; backgroundRequested = false; + ackWithId = false; backgroundLost = 0; } log(Level.INFO, "Keploy dedup: connected to collector at " + host + ":" + port, null); @@ -1132,10 +1199,10 @@ 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 protocol + honesty capabilities immediately on connect. + // Declare live protocol + honesty capabilities immediately on connect. // Older collectors ignore unrecognized lines; newer collectors gate // removal eligibility on this declaration. - writeLine(out, HELLO_FRAME); + writeLine(out, helloFrame()); out.flush(); String line; while (running.get() && (line = reader.readLine()) != null) { @@ -1143,6 +1210,12 @@ private void connectAndServe() throws IOException { if (trimmed.isEmpty()) { continue; } + if (ACK_ID_COMMAND.equals(trimmed)) { + synchronized (testCaseLock) { + ackWithId = true; + } + continue; + } if (BACKGROUND_COMMAND.equals(trimmed)) { synchronized (testCaseLock) { if (collector.probeScan() != null) { @@ -1155,12 +1228,13 @@ private void connectAndServe() throws IOException { } continue; } - if (trimmed.startsWith(NOP_COMMAND + " ")) { - String token = trimmed.substring(NOP_COMMAND.length() + 1).trim(); - if (!token.isEmpty()) { - synchronized (testCaseLock) { - ack(out, token); - } + 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; } @@ -1207,15 +1281,18 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) } if (reset) { activeTestId = command.testId; - if (after != null && !cleared.isEmpty() && backgroundRequested) { - writeBackgroundFrame(out, after, command.testId, cleared); - } } else { // Said before the ACK, as for an END not taken: the // collector has no other sign this test went unmeasured. writeLine(out, IGNORED_REPLY + " " + command.testId); } 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. + if (reset && after != null && !cleared.isEmpty() && backgroundRequested) { + writeBackgroundFrame(out, after, command.testId, cleared); + } return; } @@ -1293,7 +1370,9 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) } private void writeBackgroundFrame(OutputStream out, String after, String before, - List cleared) { + List cleared) throws IOException { + String frame; + int classes; try { BackgroundRecord record = new BackgroundRecord( collector.coverageIndex.report().build, after, before, @@ -1301,16 +1380,20 @@ private void writeBackgroundFrame(OutputStream out, String after, String before, if (backgroundLost > 0) { record.lost = backgroundLost; } - writeLine(out, BACKGROUND_COMMAND + " " + GSON.toJson(record)); - backgroundLost = 0; - if (diagnosticsEnabled()) { - diagnostic("BACKGROUND frame sent over TCP: after=" + after + ", before=" + before - + ", classes=" + record.executedLinesByFile.size()); - } + 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 send BACKGROUND frame before " + before, t); + "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); } } @@ -1320,8 +1403,8 @@ private static void writeLine(OutputStream out, String message) throws IOExcepti out.write('\n'); } - private static void ack(OutputStream out, String testId) throws IOException { - writeLine(out, "ACK " + testId); + private void ack(OutputStream out, String testId) throws IOException { + writeLine(out, ackWithId && testId != null && !testId.isEmpty() ? "ACK " + testId : "ACK"); out.flush(); } 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 5d76f5dd..d626061f 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -7,10 +7,15 @@ 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; @@ -18,27 +23,36 @@ /** * 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. + * handed by their type, inspect/cast tasks in overridden lifecycle hooks, + * silently discard tasks without throwing, or wrap an opaque delegate whose + * queue cannot be inspected — so that a task handed to it must reach it as it + * is. * - *

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. + *

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. A custom ThreadPoolExecutor + * subclass that overrides {@code beforeExecute}/{@code afterExecute} (or + * {@code decorateTask} on ScheduledThreadPoolExecutor) may likewise cast the + * task. A pool configured with {@link ThreadPoolExecutor.DiscardPolicy} or + * {@link ThreadPoolExecutor.DiscardOldestPolicy} can drop a task without + * throwing, which would otherwise leave a request window open until END times + * out. + * + *

Exact {@link ScheduledThreadPoolExecutor} instances are safe for + * immediate {@code execute}/{@code submit} calls (unless configured with a + * discard policy) because they always wrap each task in their own + * {@code ScheduledFutureTask} before enqueueing into {@code DelayedWorkQueue}. + * Spring's {@code ConcurrentTaskExecutor} and {@code ThreadPoolTaskScheduler} + * are inspected through their public delegate accessors; an opaque delegate + * whose queue cannot be verified is left unwrapped. 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. */ 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 +60,20 @@ 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. + // 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_SIMPLE_ASYNC = "org.springframework.core.task.SimpleAsyncTaskExecutor"; + private static final String JDK_FINALIZABLE_DELEGATED = + "java.util.concurrent.Executors$FinalizableDelegatedExecutorService"; + private static final String JDK_DELEGATED_SCHEDULED = + "java.util.concurrent.Executors$DelegatedScheduledExecutorService"; + private static final String JDK_DELEGATED = + "java.util.concurrent.Executors$DelegatedExecutorService"; // 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 +83,36 @@ 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"); + + // Whether a ThreadPoolExecutor subclass overrides beforeExecute, + // afterExecute, or (for ScheduledThreadPoolExecutor) decorateTask, which + // may cast the queued Runnable/Callable to an app-specific subtype. + // Spring 6's ThreadPoolTaskExecutor inner ThreadPoolExecutor subclass only + // tracks Spring lifecycle hooks and never casts the task, so it is allowed. + private static final ClassValue OVERRIDES_TASK_HOOKS = 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(); + 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; + } + if (c.getName().startsWith(SPRING_POOL + "$")) { + continue; + } + if (declares(c, "beforeExecute", Thread.class, Runnable.class) + || declares(c, "afterExecute", Runnable.class, Throwable.class) + || declares(c, "decorateTask", Runnable.class, RunnableScheduledFuture.class) + || declares(c, "decorateTask", Callable.class, RunnableScheduledFuture.class)) { + return Boolean.TRUE; + } } + return Boolean.FALSE; } }; @@ -80,73 +122,177 @@ protected Object computeValue(Class type) { private OrderedPools() { } + 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 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 + // type (or override task hooks, silently discard tasks, or wrap an opaque + // delegate); 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. static boolean orders(Object executor) { try { - return read(executor); + return read(executor, 0, false); } catch (Throwable e) { return true; } } - private static boolean read(Object executor) { + private static boolean read(Object executor, int depth, boolean requireVerified) { if (executor == null) { - return false; + return requireVerified; + } + if (depth > MAX_DELEGATE_DEPTH) { + return uncounted(executor, "its delegate executor chain is too deep to inspect"); } if (executor instanceof ThreadPoolExecutor) { - Class queue; - try { - queue = ((ThreadPoolExecutor) executor).getQueue().getClass(); - } catch (Throwable e) { - if (e instanceof VirtualMachineError) { - return true; - } - return uncounted(executor, "its pool's queue cannot be read (" + e + ")"); - } - if (IN_ORDER.contains(queue)) { - return false; - } - return uncounted(executor, "its pool's queue, a " + queue.getName() - + ", may order its tasks by their own type"); + return checkThreadPool((ThreadPoolExecutor) executor, executor); + } + if (executor instanceof ForkJoinPool) { + return false; + } + String className = executor.getClass().getName(); + if (JDK_FINALIZABLE_DELEGATED.equals(className) + || JDK_DELEGATED_SCHEDULED.equals(className)) { + return false; + } + if (JDK_DELEGATED.equals(className)) { + return uncounted(executor, "its wrapped ExecutorService cannot be inspected for queue ordering"); } Object pool = POOL.get(executor.getClass()); - if (pool == NONE) { + if (pool != NONE) { + return readViaPoolMethod(executor, pool, SPRING_POOL); + } + if (SPRING_SIMPLE_ASYNC.equals(className)) { return false; } - if (pool instanceof String) { - return uncounted(executor, "its pool's queue cannot be read (" + pool + ")"); + Object scheduled = SCHEDULED_POOL.get(executor.getClass()); + if (scheduled != NONE) { + return readViaPoolMethod(executor, scheduled, SPRING_SCHEDULER); } - Class queue; + Object concurrent = CONCURRENT_EXECUTOR.get(executor.getClass()); + if (concurrent != NONE) { + return readViaConcurrentExecutor(executor, concurrent, depth); + } + if (requireVerified) { + return uncounted(executor, "its delegate executor cannot be inspected for queue ordering"); + } + return false; + } + + 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 { - queue = ((ThreadPoolExecutor) ((Method) pool).invoke(executor)).getQueue().getClass(); + 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 checkThreadPool(ThreadPoolExecutor pool, Object reportedOwner) { + if (Boolean.TRUE.equals(OVERRIDES_TASK_HOOKS.get(pool.getClass()))) { + return uncounted(reportedOwner, "its pool (" + pool.getClass().getName() + + ") overrides task hooks that may inspect or cast the task"); + } + try { + RejectedExecutionHandler handler = pool.getRejectedExecutionHandler(); + if (handler instanceof ThreadPoolExecutor.DiscardPolicy + || handler instanceof ThreadPoolExecutor.DiscardOldestPolicy) { + return uncounted(reportedOwner, "its rejected execution handler, a " + + handler.getClass().getName() + ", may silently discard tasks"); + } + } catch (Throwable e) { + if (e instanceof VirtualMachineError) { + return true; + } + return uncounted(reportedOwner, "its pool's rejected execution handler cannot be read (" + e + ")"); + } + if (pool.getClass() == ScheduledThreadPoolExecutor.class) { + // Exact ScheduledThreadPoolExecutor 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 (IN_ORDER.contains(queue)) { return false; } - return uncounted(executor, "its pool's queue, a " + queue.getName() + if (pool instanceof ScheduledThreadPoolExecutor) { + return uncounted(reportedOwner, "it is a ScheduledThreadPoolExecutor subclass (" + + pool.getClass().getName() + ") whose task handling cannot be assumed safe"); + } + 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 70a4e69c..7af176f1 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -1,5 +1,7 @@ package io.keploy.dedup; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -7,6 +9,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.RunnableFuture; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; @@ -29,21 +32,36 @@ * *

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. + * a ThreadPoolTaskExecutor) or to standard JDK executors/CompletableFuture + * from rewritten application classes counts as that request's until it is done: + * ServerEntries passes each task, and the executor it is for, to + * {@link #hand(Object, Runnable)}, {@link #hand(Object, Callable)}, or the + * static call-site helpers ({@link #execute}, {@link #submit}, + * {@link #runAsync}, {@link #supplyAsync}), 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, throws, is rejected, or is + * cancelled/timed out before running. On a thread in a scheduled job's or + * message listener'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 tasks, override task hooks, silently discard tasks, or + * delegate opaquely (OrderedPools), is not counted. * - *

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

Note on pool queue visibility: for {@code submit} and + * {@code CompletableFuture}, the JDK already wraps user tasks in + * {@code FutureTask}/{@code AsyncRun}; for direct {@code execute(Runnable)} + * call sites in rewritten application classes, {@link #remove} and + * {@link #shutdownNow} preserve identity and unwrap queued wrappers, while + * custom {@code ThreadPoolExecutor} subclasses that override + * {@code beforeExecute}/{@code afterExecute} are skipped by + * {@link OrderedPools}. Direct inspection of {@code getQueue()} on a plain + * {@code ThreadPoolExecutor} that casts elements to an app-private subtype + * without {@link Comparable} is the only case where the wrapper could be + * visible. + * + *

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 { @@ -104,19 +122,23 @@ public static void exit(Object token) { * 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. + * task (and unwraps an already-wrapped task if the inner executor is + * ordered/unsafe, releasing its pending window permit). * * @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) { + if (task == null || task instanceof Comparable) { + return task; + } + if (task instanceof Handed) { + if (OrderedPools.orders(executor)) { + Handed existing = (Handed) task; + existing.releaseIfPending(); + return existing.task; + } return task; } Window window = INSIDE.get(); @@ -146,7 +168,16 @@ 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 (task == null || task instanceof Comparable) { + return task; + } + if (task instanceof HandedCall) { + if (OrderedPools.orders(executor)) { + @SuppressWarnings("unchecked") + HandedCall existing = (HandedCall) task; + existing.releaseIfPending(); + return existing.task; + } return task; } Window window = INSIDE.get(); @@ -171,7 +202,16 @@ public static Callable hand(Object executor, Callable task) { * @return what runs instead */ public static Supplier handSupplier(Object executor, Supplier supplier) { - if (supplier == null || supplier instanceof HandedSupplier || supplier instanceof Comparable) { + if (supplier == null || supplier instanceof Comparable) { + return supplier; + } + if (supplier instanceof HandedSupplier) { + if (OrderedPools.orders(executor)) { + @SuppressWarnings("unchecked") + HandedSupplier existing = (HandedSupplier) supplier; + existing.releaseIfPending(); + return existing.task; + } return supplier; } Window window = INSIDE.get(); @@ -204,78 +244,159 @@ public static void execute(Executor executor, Runnable task) { /** Call-site wrapper for {@link ExecutorService#submit(Runnable)}. */ public static Future submit(ExecutorService executor, Runnable task) { Runnable handed = hand(executor, task); + Future future; try { - return executor.submit(handed); + future = executor.submit(handed); } catch (Throwable t) { dropped(handed, task); throw t; } + return wrapFuture(future, handed, task); } /** Call-site wrapper for {@link ExecutorService#submit(Runnable, Object)}. */ public static Future submit(ExecutorService executor, Runnable task, T result) { Runnable handed = hand(executor, task); + Future future; try { - return executor.submit(handed, result); + future = executor.submit(handed, result); } catch (Throwable t) { dropped(handed, task); throw t; } + return wrapFuture(future, handed, task); } /** Call-site wrapper for {@link ExecutorService#submit(Callable)}. */ public static Future submit(ExecutorService executor, Callable task) { Callable handed = hand(executor, task); + Future future; try { - return executor.submit(handed); + future = executor.submit(handed); } catch (Throwable t) { dropped(handed, task); throw t; } + return wrapFuture(future, handed, task); } /** Call-site wrapper for {@link CompletableFuture#runAsync(Runnable)}. */ public static CompletableFuture runAsync(Runnable task) { Runnable handed = hand(null, task); + CompletableFuture cf; try { - return CompletableFuture.runAsync(handed); + 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)}. */ public static CompletableFuture runAsync(Runnable task, Executor executor) { Runnable handed = hand(executor, task); + CompletableFuture cf; try { - return CompletableFuture.runAsync(handed, executor); + 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)}. */ public static CompletableFuture supplyAsync(Supplier supplier) { Supplier handed = handSupplier(null, supplier); + CompletableFuture cf; try { - return CompletableFuture.supplyAsync(handed); + 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)}. */ public static CompletableFuture supplyAsync(Supplier supplier, Executor executor) { Supplier handed = handSupplier(executor, supplier); + CompletableFuture cf; try { - return CompletableFuture.supplyAsync(handed, executor); + cf = CompletableFuture.supplyAsync(handed, executor); } catch (Throwable t) { dropped(handed, supplier); throw t; } + attachCompletionRelease(cf, handed, supplier); + return cf; + } + + /** + * Call-site wrapper for {@link ThreadPoolExecutor#remove(Runnable)}: finds + * and removes the wrapped {@link Handed} entry if {@code task} was wrapped, + * releasing its pending window permit so END does not wait for it. + */ + public static boolean remove(ThreadPoolExecutor executor, Runnable task) { + if (executor.remove(task)) { + return true; + } + if (task == null) { + 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 drained wrappers and returns the app's + * original tasks so callers casting them never see {@link Handed}. + */ + public static List shutdownNow(ExecutorService executor) { + List pending = executor.shutdownNow(); + 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); + } + } + return unwrapped != null ? unwrapped : pending; + } + + private static Future wrapFuture(Future future, Object handed, Object task) { + if (future != null && handed != task && handed instanceof Hand) { + return new CancelAwareFuture<>(future, (Hand) handed); + } + return future; + } + + private static void attachCompletionRelease(CompletableFuture cf, Object handed, Object task) { + if (cf != null && handed != task && handed instanceof Hand) { + final Hand hand = (Hand) handed; + cf.whenComplete((result, error) -> hand.releaseIfPending()); + } } /** @@ -362,27 +483,43 @@ 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 + // returns or throws, when the executor did not take it, or when it is + // cancelled/timed out/removed/drained while still pending. 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 abstract static class Hand { - private static final AtomicIntegerFieldUpdater RELEASED = - AtomicIntegerFieldUpdater.newUpdater(Hand.class, "released"); + private static final int STATE_PENDING = 0; + private static final int STATE_RUNNING = 1; + private static final int STATE_DONE = 2; + + 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; + private volatile int state; Hand(Window window, String job) { this.window = window; this.job = job; } + // release marks this task done unconditionally (on exit or rejected drop). final void release() { - if (window != null && RELEASED.compareAndSet(this, 0, 1)) { + if (window != null && STATE.getAndSet(this, STATE_DONE) != STATE_DONE) { + done(window); + } + } + + // releaseIfPending marks this task done only if it has not started + // running yet: cancellation/timeout 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 && STATE.compareAndSet(this, STATE_PENDING, STATE_DONE)) { done(window); } } @@ -396,6 +533,7 @@ final Object enter() { if (window == null) { return JobGate.enterAs(job); } + STATE.compareAndSet(this, STATE_PENDING, STATE_RUNNING); Window outer = INSIDE.get(); INSIDE.set(window); return outer; @@ -415,6 +553,47 @@ final void exit(Object outer) { } } + private static final class CancelAwareFuture implements Future { + + private final Future delegate; + private final Hand hand; + + CancelAwareFuture(Future delegate, Hand hand) { + this.delegate = delegate; + this.hand = hand; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + boolean cancelled = delegate.cancel(mayInterruptIfRunning); + if (cancelled) { + hand.releaseIfPending(); + } + return cancelled; + } + + @Override + public boolean isCancelled() { + return delegate.isCancelled(); + } + + @Override + public boolean isDone() { + return delegate.isDone(); + } + + @Override + public T get() throws InterruptedException, ExecutionException { + return delegate.get(); + } + + @Override + public T get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + return delegate.get(timeout, unit); + } + } + private static class Handed extends Hand implements Runnable { final Runnable task; @@ -480,7 +659,7 @@ 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); @@ -505,7 +684,7 @@ public String toString() { private static final class HandedSupplier extends Hand implements Supplier { - private final Supplier task; + final Supplier task; HandedSupplier(Window window, String job, Supplier task) { super(window, job); 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 40417733..1621ea3b 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -50,25 +50,35 @@ * 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 each run of a scheduled job or message listener count in + * {@link JobGate} the same way: Quartz's {@code JobRunShell.run()}, Spring's + * {@code ScheduledMethodRunnable.run()} (each {@code @Scheduled} method), + * Spring Kafka's {@code ListenerConsumer}, and Spring AMQP/JMS's + * {@code AbstractMessageListenerContainer.doInvokeListener} become methods + * that call {@link JobGate#enter(Object, String)}, then their own code, + * renamed {@code keploy$job$}, then {@link JobGate#exit(Object)}, so + * that a test whose window one 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 + * ThreadPoolTaskExecutor, ThreadPoolTaskScheduler, ConcurrentTaskExecutor 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). + * + *

For the application's own indexed classes (strictly allow-listed from + * {@link AppClasses} / {@code CoverageIndex} so third-party libraries such as + * Netty or OkHttp are never touched), it also rewrites standard JDK executor + * and {@code CompletableFuture} call sites ({@code execute}, {@code submit}, + * {@code runAsync}, {@code supplyAsync}, {@code remove}, {@code shutdownNow}) + * to {@link RequestGate}'s identically-stacked static helpers after a fast + * constant-pool pre-check, and preserves those rewrites across retransforms. */ final class ServerEntries implements ClassFileTransformer { @@ -116,8 +126,6 @@ final class ServerEntries implements ClassFileTransformer { // 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("Kafka", "org/springframework/kafka/listener/adapter/MessagingMessageListenerAdapter", - "kafka", "onMessage"); addJob("RabbitMQ", "org/springframework/amqp/rabbit/listener/AbstractMessageListenerContainer", "listener", "doInvokeListener"); addJob("JMS", "org/springframework/jms/listener/AbstractMessageListenerContainer", @@ -150,20 +158,58 @@ final class ServerEntries implements ClassFileTransformer { private static final Set COUNTED = new CopyOnWriteArraySet<>(); private static final Set SEEN_UNCOUNTED = new CopyOnWriteArraySet<>(); + // 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<>(); + + // Constant-pool class owners targeted by wrapExecutorCalls. If none of + // these appear in a class's constant pool, ASM rewriting is skipped. + 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/CompletableFuture"))); // 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) { @@ -189,6 +235,18 @@ static boolean countsNone() { return COUNTED.isEmpty(); } + // Snapshot/restore helpers for unit tests exercising dynamic HELLO flags. + static Set snapshotCounted() { + return new HashSet<>(COUNTED); + } + + static void restoreCounted(Set snapshot) { + COUNTED.clear(); + if (snapshot != null) { + COUNTED.addAll(snapshot); + } + } + // uncounted names the servers whose requests do not count that the app // loaded, as Netty. static List uncounted() { @@ -207,9 +265,13 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (uncounted != null) { SEEN_UNCOUNTED.add(uncounted); } - if (className != null && shouldRewriteExecutorCalls(className) && seesGate(loader)) { + if (shouldRewriteExecutorCalls(className) && seesGate(loader)) { try { - return wrapExecutorCalls(classfileBuffer); + byte[] updated = wrapExecutorCalls(classfileBuffer); + if (updated != null) { + recordRewritten(loader, className); + } + return updated; } catch (Throwable t) { LOGGER.log(Level.FINE, "Keploy dedup skipped executor call-site wrap for " + className, t); } @@ -266,17 +328,47 @@ public byte[] transform(ClassLoader loader, String className, Class classBein } } + 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); + } + } + // 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. + // are. Application classes whose executor call sites were rewritten on + // load also get their call sites re-applied so another agent's + // retransform does not silently undo them. Any other class is left as it + // is: it was loaded unchanged, and the JVM refuses a method added to it. 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; } @@ -308,14 +400,30 @@ 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. + // where END never looks. Cached per loader to avoid repeated Class.forName + // lookups and ClassNotFoundExceptions on startup. 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) { @@ -350,12 +458,28 @@ private static byte[] wrap(byte[] classfile, Entry entry) { return wrap(classfile, entry.methods, entry.job, entry.async); } - // shouldRewriteExecutorCalls filters out JDK, agent, server, and Spring - // executor internals so call-site wrapping targets application and library - // classes that submit async tasks to standard JDK Executor/ExecutorService/ - // CompletableFuture APIs. - static boolean shouldRewriteExecutorCalls(String className) { - return !className.startsWith("java/") + // shouldRewriteExecutorCalls strictly allow-lists indexed application + // classes (or, when external JaCoCo defers index loading, the lightweight + // app package prefix from AppClasses) plus a belt-and-suspenders filter + // against JDK, agent, server, and library internals so third-party + // long-lived threads (Netty event loops, OkHttp TaskRunner, Lettuce, gRPC, + // AWS SDK, etc.) are never rewritten. + boolean shouldRewriteExecutorCalls(String className) { + if (className == null || !isRewriteAllowedPackage(className)) { + return false; + } + if (!appClasses.isEmpty()) { + return appClasses.contains(className); + } + return appPackagePrefix != null && className.startsWith(appPackagePrefix); + } + + // Belt-and-suspenders guard in case KEPLOY_JAVA_CLASS_DIRS includes + // framework/library classes; note org/apache/ is NOT blanket-excluded so + // Apache-hosted applications (e.g. org/apache/fineract/) remain eligible. + static boolean isRewriteAllowedPackage(String className) { + return className != null + && !className.startsWith("java/") && !className.startsWith("javax/") && !className.startsWith("sun/") && !className.startsWith("jdk/") @@ -363,26 +487,66 @@ static boolean shouldRewriteExecutorCalls(String className) { && !className.startsWith("io/keploy/") && !className.startsWith("org/jacoco/") && !className.startsWith("org/newsclub/") - && !className.startsWith("org/springframework/core/task/") - && !className.startsWith("org/springframework/scheduling/concurrent/") - && !className.startsWith("org/springframework/aop/interceptor/") + && !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/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/eclipse/jetty/") && !className.startsWith("io/undertow/") - && !className.startsWith("org/quartz/"); + && !className.startsWith("org/quartz/") + && !className.startsWith("com/zaxxer/"); + } + + // Fast constant-pool scan: every matching invoke instruction references a + // CONSTANT_Class (tag 7) entry for one of TARGET_EXECUTOR_OWNERS. Classes + // with no matching constant-pool class entry skip ASM ClassWriter entirely. + 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; + } + if (reader.readByte(offset - 1) == 7) { + String owner = reader.readUTF8(offset, buf); + if (TARGET_EXECUTOR_OWNERS.contains(owner)) { + return true; + } + } + } + return false; } // wrapExecutorCalls redirects standard JDK executor hand-off call sites - // (Executor.execute, ExecutorService.submit, ThreadPoolExecutor.execute, - // AbstractExecutorService.submit, CompletableFuture.runAsync/supplyAsync) - // to RequestGate's identically-stacked static helpers so async tails count - // in the request's (or job's) window without touching bootstrap JDK classes. - // Returns null when the class contains no matching call sites. + // (Executor/ExecutorService/ScheduledExecutorService.execute, + // ExecutorService/ScheduledExecutorService/AbstractExecutorService/ + // ThreadPoolExecutor/ScheduledThreadPoolExecutor.submit, + // ThreadPoolExecutor/ScheduledThreadPoolExecutor/ForkJoinPool.execute, + // CompletableFuture.runAsync/supplyAsync, ThreadPoolExecutor.remove, and + // ExecutorService.shutdownNow) to RequestGate's identically-stacked static + // helpers so async tails count in the request's (or job's) window without + // touching bootstrap JDK classes. 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) { @@ -397,7 +561,10 @@ public MethodVisitor visitMethod(int access, String name, String descriptor, Str @Override public void visitMethodInsn(int opcode, String owner, String mname, String desc, boolean isInterface) { - if (opcode == Opcodes.INVOKEINTERFACE && "java/util/concurrent/Executor".equals(owner) + 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", @@ -405,7 +572,8 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, return; } if (opcode == Opcodes.INVOKEVIRTUAL - && ("java/util/concurrent/ThreadPoolExecutor".equals(owner) + && ("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)) { @@ -420,8 +588,7 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, || (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)))) { + || "java/util/concurrent/ScheduledThreadPoolExecutor".equals(owner)))) { if ("submit".equals(mname)) { if ("(Ljava/lang/Runnable;)Ljava/util/concurrent/Future;".equals(desc)) { changed[0] = true; @@ -450,6 +617,29 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, } } } + 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) 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 f18c4b78..06318162 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java @@ -108,16 +108,16 @@ public void endWithNoStartNamesTheTestThenAnswersAck() throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); - assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); + 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)); out.flush(); assertEquals("IGNORED test-set-0/test-47", in.readLine()); - assertEquals("ACK test-set-0/test-47", in.readLine()); + assertEquals("ACK", in.readLine()); assertEquals("IGNORED test-set-0/test-48", in.readLine()); - assertEquals("ACK test-set-0/test-48", in.readLine()); + assertEquals("ACK", in.readLine()); } } @@ -131,32 +131,32 @@ public void aStartWhoseResetFailedNamesTheTestThenAnswersAckAndSoDoesItsEnd() th OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); - assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); // JaCoCo goes away for the next reset: the counters still hold // test-1's lines, so test-2 is not measured. jacoco.dropNext.set(1); send(out, "START test-set-0/test-2"); assertEquals("IGNORED test-set-0/test-2", in.readLine()); - assertEquals("ACK test-set-0/test-2", in.readLine()); + assertEquals("ACK", in.readLine()); // test-1 was left when test-2 started, and test-2 never began. send(out, "END test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); send(out, "END test-set-0/test-2"); assertEquals("IGNORED test-set-0/test-2", in.readLine()); - assertEquals("ACK test-set-0/test-2", in.readLine()); + assertEquals("ACK", in.readLine()); // JaCoCo is back: the next test is measured as before. send(out, "START test-set-0/test-3"); - assertEquals("ACK test-set-0/test-3", in.readLine()); + assertEquals("ACK", in.readLine()); send(out, "END test-set-0/test-3"); String cov = in.readLine(); assertTrue("a COV for test-3, got " + cov, cov != null && cov.startsWith("COV ") && cov.contains("test-set-0/test-3")); - assertEquals("ACK test-set-0/test-3", in.readLine()); + assertEquals("ACK", in.readLine()); } } @@ -170,29 +170,29 @@ public void anEndWhoseDumpFailedNamesTheTestThenAnswersAckAndEndsTheTest() throw OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); - assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); // JaCoCo goes away for the dump: test-1's lines never reach the // SDK. Before, it sent an empty COV, as for a test that ran no // line of the app. jacoco.dropNext.set(1); send(out, "END test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); // That END ended test-1. send(out, "END test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); send(out, "START test-set-0/test-2"); - assertEquals("ACK test-set-0/test-2", in.readLine()); + assertEquals("ACK", in.readLine()); send(out, "END test-set-0/test-2"); String cov = in.readLine(); assertTrue("a COV for test-2, got " + cov, cov != null && cov.startsWith("COV ") && cov.contains("test-set-0/test-2")); - assertEquals("ACK test-set-0/test-2", in.readLine()); + assertEquals("ACK", in.readLine()); } } @@ -206,14 +206,14 @@ public void aStartThatThrowsNamesTheTestThenAnswersAckAndTheConnectionGoesOn() t OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); - assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); assertEquals("IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); send(out, "END test-set-0/test-1"); assertEquals("the connection still answers", "IGNORED test-set-0/test-1", in.readLine()); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); } } @@ -236,10 +236,10 @@ public void theManifestWritesAClassIdAs16HexDigitsAndTheCovNamesAClassJacocoSawO OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); - assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); send(out, "END test-set-0/test-1"); assertEquals("COV {\"id\":\"test-set-0/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[0]}," + "\"classMismatch\":[\"com/acme/Shop\"]}", in.readLine()); @@ -247,7 +247,7 @@ public void theManifestWritesAClassIdAs16HexDigitsAndTheCovNamesAClassJacocoSawO assertTrue(classes, classes.startsWith("CLASSES ")); String manifest = new String(Base64.getDecoder().decode(classes.split(" ")[2]), StandardCharsets.UTF_8); assertEquals("{\"com/acme/Shop\":{\"id\":\"0000000000000099\",\"probeCount\":2}}", manifest); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); } } @@ -267,10 +267,10 @@ public void aCutEndSaysSoInItsCovAfterClassMismatch() throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); - assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); + assertHello(in.readLine()); send(out, "START test-set-0/test-1"); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); // The test's request is still running when its END comes, and // past END's wait. Object request = RequestGate.enter(); @@ -278,17 +278,17 @@ public void aCutEndSaysSoInItsCovAfterClassMismatch() throws Exception { send(out, "END test-set-0/test-1"); assertEquals("COV {\"id\":\"test-set-0/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[0]}," + "\"classMismatch\":[\"com/acme/Shop\"],\"windowCut\":true}", in.readLine()); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); } finally { RequestGate.exit(request); } // Its request done, the next test's END is not cut. send(out, "START test-set-0/test-2"); - assertEquals("ACK test-set-0/test-2", in.readLine()); + assertEquals("ACK", in.readLine()); send(out, "END test-set-0/test-2"); String cov = in.readLine(); assertTrue(cov, cov.startsWith("COV ") && !cov.contains("windowCut")); - assertEquals("ACK test-set-0/test-2", in.readLine()); + assertEquals("ACK", in.readLine()); } } @@ -303,18 +303,18 @@ public void anEndIsAnsweredWithoutWaitingForTheCollectorsDelayedAck() throws Exc sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); - assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); + assertHelloLine(readLineRaw(in)); long[] micros = new long[ROUND_TRIPS]; for (int i = 0; i < ROUND_TRIPS; i++) { String id = "test-set-0/test-" + i; send(out, "START " + id); - assertEquals("ACK " + id + "\n", readReply(in)); + assertEquals("ACK\n", readReply(in)); long sent = System.nanoTime(); send(out, "END " + id); String reply = readReply(in); micros[i] = (System.nanoTime() - sent) / 1000; assertTrue(reply, reply.startsWith("COV {\"id\":\"" + id + "\"") - && reply.endsWith("\nACK " + id + "\n")); + && reply.endsWith("\nACK\n")); } long[] sorted = micros.clone(); Arrays.sort(sorted); @@ -333,19 +333,19 @@ public void eachReplyIsReadInOnePiece() throws Exception { sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); - assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); + assertHelloLine(readLineRaw(in)); byte[] buf = new byte[64 * 1024]; for (int i = 0; i < ROUND_TRIPS; i++) { String id = "test-set-0/test-" + i; send(out, "START " + id); - assertEquals("ACK " + id + "\n", readOnce(in, buf)); + assertEquals("ACK\n", readOnce(in, buf)); send(out, "END " + id); String reply = readOnce(in, buf); assertTrue("round " + i + " read " + reply, - reply.startsWith("COV {\"id\":\"" + id + "\"") && reply.endsWith("}\nACK " + id + "\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 " + id); - assertEquals("IGNORED " + id + "\nACK " + id + "\n", readOnce(in, buf)); + assertEquals("IGNORED " + id + "\nACK\n", readOnce(in, buf)); } } } @@ -359,9 +359,9 @@ public void theSocketToKeployHasNagleOff() throws Exception { try (Socket sdk = collector.accept()) { sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); - assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(sdk.getInputStream())); + assertHelloLine(readLineRaw(sdk.getInputStream())); send(out, "END test-set-0/test-1"); - assertEquals("IGNORED test-set-0/test-1\nACK test-set-0/test-1\n", readReply(sdk.getInputStream())); + assertEquals("IGNORED test-set-0/test-1\nACK\n", readReply(sdk.getInputStream())); Field worker = KeployDedupAgent.class.getDeclaredField("coverageWorker"); worker.setAccessible(true); Object client = worker.get(null); @@ -392,9 +392,9 @@ public void aFrameLargerThanTheReplyBufferArrivesWholeAndTheRepliesAfterItStayFa sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); - assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); + assertHelloLine(readLineRaw(in)); send(out, "START test-set-0/test-0"); - assertEquals("ACK test-set-0/test-0\n", readReply(in)); + assertEquals("ACK\n", readReply(in)); probes[0] = true; send(out, "END test-set-0/test-0"); String reply = readReply(in); @@ -408,20 +408,20 @@ public void aFrameLargerThanTheReplyBufferArrivesWholeAndTheRepliesAfterItStayFa assertTrue("the frame is larger than the reply buffer: " + lines[1].length() + " bytes", lines[1].length() > 64 * 1024); assertArrayEquals(classBytes, unzipped(Base64.getDecoder().decode(classes[3]), "com/acme/Big.class")); - assertEquals("ACK test-set-0/test-0", lines[2]); + assertEquals("ACK", lines[2]); assertEquals("", lines[3]); long[] micros = new long[ROUND_TRIPS]; for (int i = 1; i <= ROUND_TRIPS; i++) { String id = "test-set-0/test-" + i; send(out, "START " + id); - assertEquals("ACK " + id + "\n", readReply(in)); + assertEquals("ACK\n", readReply(in)); long sent = System.nanoTime(); send(out, "END " + id); reply = readReply(in); micros[i - 1] = (System.nanoTime() - sent) / 1000; assertTrue(reply, reply.startsWith("COV {\"id\":\"" + id + "\"") - && reply.endsWith("}\nACK " + id + "\n")); + && reply.endsWith("}\nACK\n")); } long[] sorted = micros.clone(); Arrays.sort(sorted); @@ -450,9 +450,9 @@ public void aJobThatStartsWhileEndWaitsForTheRequestsOrReadsTheHitsIsNamed() thr sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); - assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); + assertHelloLine(readLineRaw(in)); send(out, "START test-set-0/test-1"); - assertEquals("ACK test-set-0/test-1\n", readReply(in)); + assertEquals("ACK\n", readReply(in)); jacoco.onDump = () -> JobGate.exit(JobGate.enter(new Object(), "scheduled")); Object request = RequestGate.enter(); try { @@ -470,7 +470,7 @@ public void aJobThatStartsWhileEndWaitsForTheRequestsOrReadsTheHitsIsNamed() thr String reply = readReply(in); assertFalse("END did not reach its bound: " + reply, reply.contains("windowCut")); assertTrue(reply, reply.endsWith( - ",\"contaminated\":[\"quartz:java.lang.Object\",\"scheduled:java.lang.Object\"]}\nACK test-set-0/test-1\n")); + ",\"contaminated\":[\"quartz:java.lang.Object\",\"scheduled:java.lang.Object\"]}\nACK\n")); } } @@ -507,18 +507,18 @@ public void close() { sdk.setSoTimeout(30000); OutputStream out = sdk.getOutputStream(); InputStream in = sdk.getInputStream(); - assertEquals(KeployDedupAgent.HELLO_FRAME + "\n", readLineRaw(in)); + assertHelloLine(readLineRaw(in)); for (int last = test + (connection == 1 ? 2 : 1); test < last; test++) { String id = "test-set-0/test-" + test; System.setProperties(jvm); send(out, "START " + id); - assertEquals("ACK " + id + "\n", readReply(in)); + assertEquals("ACK\n", readReply(in)); System.setProperties(unreadable); int thrown = unreadable.thrown.get(); send(out, "END " + id); String reply = readReply(in); assertTrue(reply, reply.startsWith("COV {\"id\":\"" + id + "\"") - && reply.endsWith("}\nACK " + id + "\n")); + && 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), @@ -552,7 +552,9 @@ public void betweenTestsBackgroundProbesAreEmittedOnTcpOnlyWhenRequested() throw OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); - assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); + 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"); @@ -577,16 +579,18 @@ public void betweenTestsBackgroundProbesAreEmittedOnTcpOnlyWhenRequested() throw 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 before ACK, got: " + bgLine, + 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]")); - assertEquals("ACK test-set-0/test-2", in.readLine()); assertFalse("background probe cleared for test-2", probes[3]); probes[2] = true; @@ -609,10 +613,23 @@ public void betweenTestsBackgroundProbesAreEmittedOnTcpOnlyWhenRequested() throw } probes[3] = true; send(out, "START test-set-0/test-4"); - assertEquals("no BACKGROUND frame after cut END", "ACK test-set-0/test-4", in.readLine()); + 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<>(); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 26659ac3..c89aefad 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -3,50 +3,89 @@ 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 java.io.BufferedReader; +import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; +import java.lang.reflect.Method; 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.Arrays; +import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Set; 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.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +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.AtomicReference; +import java.util.function.Supplier; import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; +import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor; /** - * Covers the v3 honest TCP protocol (HELLO capability declaration, NOP resync), - * JDK executor call-site async-tail tracking (RequestGate + ServerEntries), and - * Kafka/message listener contamination (JobGate + ServerEntries). + * 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"; + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); private ServerSocket collector; private FakeJacoco jacoco; + private ClassLoader savedContextLoader; + private boolean savedTransformerAdded; + private boolean savedExecutorCallSitesEnabled; + private Set savedCounted; + private long savedHandedJobMaxNanos; @Before public void setUp() { + savedTransformerAdded = KeployDedupAgent.transformerAdded; + savedExecutorCallSitesEnabled = KeployDedupAgent.executorCallSitesEnabled; + savedCounted = ServerEntries.snapshotCounted(); + savedHandedJobMaxNanos = JobGate.handedJobMaxNanos; RequestGate.open(); JobGate.close(); } @@ -54,9 +93,20 @@ public void setUp() { @After public void tearDown() throws IOException { KeployDedupAgent.stop(); + if (savedContextLoader != null) { + Thread.currentThread().setContextClassLoader(savedContextLoader); + savedContextLoader = null; + } + KeployDedupAgent.transformerAdded = savedTransformerAdded; + KeployDedupAgent.executorCallSitesEnabled = savedExecutorCallSitesEnabled; + ServerEntries.restoreCounted(savedCounted); + JobGate.handedJobMaxNanos = savedHandedJobMaxNanos; 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); if (collector != null) { collector.close(); collector = null; @@ -70,15 +120,68 @@ public void tearDown() throws IOException { } @Test(timeout = 60000) - public void tcpConnectDeclaresHonestyHelloAndAnswersNopResyncWithoutDisturbingActiveTest() throws Exception { - collector = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + public void helloReportsLiveCapabilitiesAccuratelyAcrossRuntimeConfigurations() throws Exception { + // Case 1: no -javaagent, no in-process JaCoCo -> windowCut/contaminated/background/asyncExecutors/listener false. + KeployDedupAgent.transformerAdded = false; + KeployDedupAgent.executorCallSitesEnabled = false; + ServerEntries.restoreCounted(Collections.emptySet()); + String helloNoAgent = connectAndReadHello(false); + assertEquals(KeployDedupAgent.buildHelloFrame(false, false, true, false, true, true, false, false), + helloNoAgent); + + // Case 2: -javaagent attached, server counted, endWait > 0, in-process JaCoCo scan on, app classes indexed. + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + ServerEntries.restoreCounted(Collections.singleton("Tomcat")); + String helloFull = connectAndReadHello(true); + assertEquals(KeployDedupAgent.buildHelloFrame(true, true, true, true, true, true, true, true), + helloFull); + + // Case 3: endWait == 0 -> windowCut must be false even with agent & counted server. + System.setProperty(END_WAIT_PROPERTY, "0"); + String helloZeroWait = connectAndReadHello(true); + assertEquals(KeployDedupAgent.buildHelloFrame(false, true, true, true, true, true, true, true), + helloZeroWait); + System.clearProperty(END_WAIT_PROPERTY); + + // Case 4: Netty/WebFlux (no counted server) -> windowCut must be false. + ServerEntries.restoreCounted(Collections.emptySet()); + String helloUncountedServer = connectAndReadHello(true); + assertEquals(KeployDedupAgent.buildHelloFrame(false, true, true, true, true, true, true, true), + helloUncountedServer); + + // Case 5: KEPLOY_JAVA_SCAN=off -> background must be false even with in-process JaCoCo. + ServerEntries.restoreCounted(Collections.singleton("Tomcat")); + System.setProperty(SCAN_PROPERTY, "off"); + String helloScanOff = connectAndReadHello(true); + assertEquals(KeployDedupAgent.buildHelloFrame(true, true, true, false, true, true, true, true), + helloScanOff); + System.clearProperty(SCAN_PROPERTY); + + // Case 6: classpath fallback (no app-only index) -> asyncExecutors must be false. + KeployDedupAgent.executorCallSitesEnabled = false; + String helloFallback = connectAndReadHello(true); + assertEquals(KeployDedupAgent.buildHelloFrame(true, true, true, true, true, true, false, true), + helloFallback); + } + + @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); - jacoco = new FakeJacoco(); System.setProperty(ENDPOINT_PROPERTY, "127.0.0.1:" + collector.getLocalPort()); - System.setProperty(JACOCO_PORT_PROPERTY, String.valueOf(jacoco.server.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(); @@ -86,164 +189,957 @@ public void tcpConnectDeclaresHonestyHelloAndAnswersNopResyncWithoutDisturbingAc new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); String hello = in.readLine(); - assertEquals(KeployDedupAgent.HELLO_FRAME, hello); - assertTrue(hello, hello.contains("\"proto\":3")); - assertTrue(hello, hello.contains("\"windowCut\":true")); - assertTrue(hello, hello.contains("\"contaminated\":true")); - assertTrue(hello, hello.contains("\"classMismatch\":true")); + assertTrue(hello, hello != null && hello.startsWith("HELLO {\"proto\":3,")); assertTrue(hello, hello.contains("\"background\":true")); - assertTrue(hello, hello.contains("\"ackId\":true")); - assertTrue(hello, hello.contains("\"nopResync\":true")); - // NOP before any test + // 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()); - // NOP mid-test must not clear activeTestId + // 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 cov = in.readLine(); - assertNotNull(cov); - assertTrue("expected COV for ts/test-1, got " + cov, - cov.startsWith("COV ") && cov.contains("\"id\":\"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" + }) { + 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 jdkExecutorAndCompletableFutureAsyncTailsCountInRequestWindow() throws Exception { - ExecutorService pool = Executors.newSingleThreadExecutor(); + 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 { - // 1. Executor.execute async tail outlives request -> END await returns false (windowCut) - CountDownLatch release = new CountDownLatch(1); - CountDownLatch started = new CountDownLatch(1); + // 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 { - RequestGate.execute(pool, () -> { - started.countDown(); + 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 { - release.await(10, TimeUnit.SECONDS); + runningRelease.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - }); + return "real"; + }, pool); } finally { - RequestGate.exit(req); + RequestGate.exit(req2); } - assertTrue(started.await(10, TimeUnit.SECONDS)); - assertEquals("async tail still counted after request exit", 1, RequestGate.running()); - assertFalse("END cuts window while async tail still runs", - RequestGate.await(TimeUnit.MILLISECONDS.toNanos(40))); - release.countDown(); + 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 tasks (no ClassCastException) and releases permits. + CountDownLatch hold2 = new CountDownLatch(1); + CountDownLatch rel2 = new CountDownLatch(1); + pool.execute(latchTask(hold2, rel2)); + assertTrue(hold2.await(10, TimeUnit.SECONDS)); - // 2. ExecutorService.submit(Callable) and CompletableFuture.supplyAsync RequestGate.open(); - CountDownLatch release2 = new CountDownLatch(1); - CountDownLatch started2 = new CountDownLatch(1); - Object req2 = RequestGate.enter(); - Future submitted; - CompletableFuture supplied; + MyAppTask queuedAppTask = new MyAppTask("queued"); + Object req3 = RequestGate.enter(); try { - submitted = RequestGate.submit(pool, (Callable) () -> { - started2.countDown(); - release2.await(10, TimeUnit.SECONDS); - return "ok"; - }); - supplied = RequestGate.supplyAsync(() -> "done", pool); + RequestGate.execute(pool, queuedAppTask); } finally { - RequestGate.exit(req2); + RequestGate.exit(req3); } - assertTrue(started2.await(10, TimeUnit.SECONDS)); - assertFalse("END cuts while submitted Callable + supplyAsync still run", - RequestGate.await(TimeUnit.MILLISECONDS.toNanos(40))); - release2.countDown(); - assertEquals("ok", submitted.get(10, TimeUnit.SECONDS)); - assertEquals("done", supplied.get(10, TimeUnit.SECONDS)); + assertEquals(1, RequestGate.running()); + List drained = RequestGate.shutdownNow(pool); + rel2.countDown(); + assertEquals(1, 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", 0, RequestGate.running()); } finally { + blockerRelease.countDown(); pool.shutdownNow(); } } @Test(timeout = 60000) - public void rawPriorityThreadPoolExecutorIsNotWrappedByRequestGate() { + 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 subclass overriding beforeExecute that casts Runnable to MyAppTask. + 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); + } + }; + // 4. Exact ScheduledThreadPoolExecutor IS safe (wraps in ScheduledFutureTask). + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); + // 5. ConcurrentTaskExecutor wrapping priority pool vs opaque executor vs normal pool. + 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); + ExecutorService unconfigurable = Executors.unconfigurableExecutorService(priority); + try { - assertTrue("OrderedPools must recognize raw ThreadPoolExecutor with PriorityBlockingQueue", - OrderedPools.orders(priority)); + assertTrue(OrderedPools.orders(priority)); + assertTrue(OrderedPools.orders(discard)); + assertTrue(OrderedPools.orders(discardOldest)); + assertTrue(OrderedPools.orders(customHookPool)); + assertFalse("exact ScheduledThreadPoolExecutor is safe", OrderedPools.orders(stpe)); + 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)); + assertTrue("unconfigurableExecutorService cannot be inspected", + OrderedPools.orders(unconfigurable)); + + // Custom beforeExecute pool receives original MyAppTask without ClassCastException. + RequestGate.open(); + MyAppTask appTask = new MyAppTask("hooked"); + Object req = RequestGate.enter(); + try { + RequestGate.execute(customHookPool, appTask); + } finally { + RequestGate.exit(req); + } + customHookPool.shutdown(); + assertTrue(customHookPool.awaitTermination(10, TimeUnit.SECONDS)); + assertEquals("hooked", hookSaw.get()); + assertTrue(appTask.ran.get()); + + // Pass-through app decorator wrapping a PriorityBlockingQueue pool: + // outer call wraps into Handed; inner RequestGate.execute(priority, handed) unwraps and releases permit! + CountDownLatch ran = new CountDownLatch(1); + Runnable plainTask = ran::countDown; + Executor decorator = r -> RequestGate.execute(priority, r); + RequestGate.open(); + Object req2 = RequestGate.enter(); + try { + RequestGate.execute(decorator, plainTask); + assertEquals("unwrapped by inner priority pool, only request remains counted", + 1, RequestGate.running()); + } finally { + RequestGate.exit(req2); + } + assertEquals(0, RequestGate.running()); + assertTrue(ran.await(10, TimeUnit.SECONDS)); } finally { priority.shutdownNow(); + discard.shutdownNow(); + discardOldest.shutdownNow(); + customHookPool.shutdownNow(); + stpe.shutdownNow(); + normalPool.shutdownNow(); + unconfigurable.shutdownNow(); + } + } + + @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. + JobGate.open(); + assertEquals(1, JobGate.close().size()); + + // Wait past handedJobMaxNanos: JobGate.open() evicts the expired handed-off Run. + Thread.sleep(100); + JobGate.open(); + assertEquals("expired long-lived handed-off task must not poison later tests", + Collections.emptyList(), JobGate.close()); + + checkExpiry.countDown(); + assertTrue(checkedExpiry.await(10, TimeUnit.SECONDS)); + assertNull("worker thread JobGate.running() clears after expiry", runningAfterExpiry.get()); + } finally { + stop.countDown(); + worker.join(10000); } } @Test(timeout = 60000) - public void serverEntriesRewritesAppExecutorCallSitesToRequestGate() throws Exception { - // Generate an app class com/example/AsyncCaller whose fire(Executor, Runnable) - // invokes INVOKEINTERFACE java/util/concurrent/Executor.execute(Runnable)V. - String className = "com/example/AsyncCaller"; + 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:")); + } + } + + 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); - 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(); + 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(); + } - MethodVisitor fire = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "fire", + 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); - fire.visitCode(); - fire.visitVarInsn(Opcodes.ALOAD, 0); - fire.visitVarInsn(Opcodes.ALOAD, 1); - fire.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/Executor", "execute", + 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); - fire.visitInsn(Opcodes.RETURN); - fire.visitMaxs(2, 2); - fire.visitEnd(); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(2, 2); + mv.visitEnd(); cw.visitEnd(); + return cw.toByteArray(); + } - byte[] transformed = new ServerEntries(true).transform( - getClass().getClassLoader(), className, null, null, cw.toByteArray()); - assertNotNull("ServerEntries must rewrite Executor.execute call site", transformed); + // 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); - Class loaded = new ByteLoader(getClass().getClassLoader()).define("com.example.AsyncCaller", transformed); - ExecutorService pool = Executors.newSingleThreadExecutor(); - CountDownLatch started = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - try { - Object req = RequestGate.enter(); - try { - Runnable task = () -> { - started.countDown(); - try { - release.await(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - }; - loaded.getMethod("fire", Executor.class, Runnable.class).invoke(null, pool, task); - } finally { - RequestGate.exit(req); - } - assertTrue(started.await(10, TimeUnit.SECONDS)); - assertEquals("rewritten Executor.execute must keep request window open", 1, RequestGate.running()); - assertFalse("END must detect async tail and report windowCut", - RequestGate.await(TimeUnit.MILLISECONDS.toNanos(40))); - } finally { - release.countDown(); - pool.shutdownNow(); - } + // 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(); } - @Test(timeout = 60000) - public void kafkaListenerInvocationMarksWindowContaminated() throws Exception { - String className = "org/springframework/kafka/listener/KafkaMessageListenerContainer$ListenerConsumer"; + 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); @@ -251,33 +1147,20 @@ public void kafkaListenerInvocationMarksWindowContaminated() throws Exception { init.visitInsn(Opcodes.RETURN); init.visitMaxs(1, 1); init.visitEnd(); + } - MethodVisitor invoke = cw.visitMethod(Opcodes.ACC_PUBLIC, "invokeRecordListener", "()V", null, null); - invoke.visitCode(); - invoke.visitInsn(Opcodes.RETURN); - invoke.visitMaxs(0, 1); - invoke.visitEnd(); - cw.visitEnd(); - - byte[] transformed = new ServerEntries(true).transform( - getClass().getClassLoader(), className, null, null, cw.toByteArray()); - assertNotNull("ServerEntries must wrap Kafka ListenerConsumer.invokeRecordListener", transformed); - - Class loaded = new ByteLoader(getClass().getClassLoader()) - .define(className.replace('/', '.'), transformed); - Object consumer = loaded.getDeclaredConstructor().newInstance(); + private static final class MyAppTask implements Runnable { + final String name; + final AtomicBoolean ran = new AtomicBoolean(false); - JobGate.open(); - loaded.getMethod("invokeRecordListener").invoke(consumer); - List contaminated = JobGate.close(); - assertEquals(1, contaminated.size()); - assertTrue("expected kafka: contamination entry, got " + contaminated, - contaminated.get(0).startsWith("kafka:")); - } + MyAppTask(String name) { + this.name = name; + } - private static void send(OutputStream out, String command) throws IOException { - out.write((command + "\n").getBytes(StandardCharsets.UTF_8)); - out.flush(); + @Override + public void run() { + ran.set(true); + } } private static final class ByteLoader extends ClassLoader { 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 8067b431..84e8e722 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/JobTailTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/JobTailTest.java @@ -316,7 +316,7 @@ private final class App implements AutoCloseable { String test(String id, String... jobs) throws IOException { String fullId = "test-set-0/" + id; send(sdkOut, "START " + fullId); - assertEquals("ACK " + fullId, sdkIn.readLine()); + assertEquals("ACK", sdkIn.readLine()); for (String job : jobs) { command(job); } @@ -324,7 +324,7 @@ String test(String id, String... jobs) throws IOException { String cov = sdkIn.readLine(); assertTrue(cov, cov != null && cov.startsWith("COV ")); String line; - while (!(line = sdkIn.readLine()).equals("ACK " + fullId)) { + while (!(line = sdkIn.readLine()).equals("ACK")) { assertTrue(line, line.startsWith("CLASSES ") || line.startsWith("MANIFEST ")); } cov = cov.substring("COV ".length()); 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 46224811..b416f93f 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java @@ -140,15 +140,17 @@ public void overTcpEachCommandSaysHowLongEachStepTookToo() throws Exception { OutputStream out = sdk.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); - assertEquals(KeployDedupAgent.HELLO_FRAME, in.readLine()); + 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 test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); out.write("END test-set-0/test-1\n".getBytes(StandardCharsets.UTF_8)); out.flush(); String cov = in.readLine(); assertTrue(cov, cov != null && cov.startsWith("COV ") && cov.contains("\"" + SHOP + "\":[0,2]")); - assertEquals("ACK test-set-0/test-1", in.readLine()); + assertEquals("ACK", in.readLine()); } } // Said once the command is answered: waited for. 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 72ecf8cc..00e6d77c 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java @@ -522,7 +522,7 @@ private Result run(Fork fork) throws Exception { for (int test = 1; test <= tests; test++) { String fullId = "test-set-0/test-" + test; send(out, "START " + fullId); - assertEquals("ACK " + fullId, in.readLine()); + assertEquals("ACK", in.readLine()); String query = fork.queries.isEmpty() ? "tail=" + tailMillis : fork.queries.get(test - 1); assertEquals("hello", get(port, "/hello?" + query)); send(out, "END " + fullId); @@ -530,7 +530,7 @@ private Result run(Fork fork) throws Exception { assertTrue(cov, cov != null && cov.startsWith("COV ")); result.covs.add(cov.substring("COV ".length())); String line; - while (!(line = in.readLine()).equals("ACK " + fullId)) { + while (!(line = in.readLine()).equals("ACK")) { assertTrue(line, line.startsWith("CLASSES ") || line.startsWith("MANIFEST ")); } } From 65da5b7dc277c6df460628926ffecb3ae43842d7 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 03:42:47 +0530 Subject: [PATCH 03/26] =?UTF-8?q?fix(dedup):=20address=20r2=20review=20?= =?UTF-8?q?=E2=80=94=20non-latching=20JaCoCo=20lookup,=20live=20HELLO=20re?= =?UTF-8?q?fresh,=20chained=20job=20deadline,=20unwrapped=20Futures,=20com?= =?UTF-8?q?plete=20pool=20guards?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: slayerjain --- .../main/java/io/keploy/dedup/JobGate.java | 50 ++- .../io/keploy/dedup/KeployDedupAgent.java | 124 +++++- .../java/io/keploy/dedup/OrderedPools.java | 42 +- .../java/io/keploy/dedup/RequestGate.java | 406 +++++++++++++----- .../java/io/keploy/dedup/ServerEntries.java | 102 ++++- .../dedup/HonestProtocolAndAsyncTest.java | 291 ++++++++++++- .../java/io/keploy/dedup/ServerTailTest.java | 9 +- 7 files changed, 883 insertions(+), 141 deletions(-) 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 a8310153..07d735fd 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -102,14 +102,24 @@ 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. Bounded by - // handedJobMaxNanos so a long-lived worker loop started from a job cannot - // contaminate every later test forever. Never throws, as enter. - static Object enterAs(String name) { + // enter does, from when the task starts; exit counts it done. Preserves + // the original attribution deadline across chained hand-offs (taking the + // earlier of the carried deadline and now + handedJobMaxNanos) and skips + // entering if already expired, so a self-resubmitting loop started from a + // job cannot contaminate every later test forever. Never throws, as enter. + static Object enterAs(Attribution attribution) { + if (attribution == null) { + return null; + } Run run = null; try { - long expiresAt = System.nanoTime() + handedJobMaxNanos; - run = new Run(name, CURRENT.get(), true, expiresAt); + long now = System.nanoTime(); + if ((now - attribution.expiresAtNanos) >= 0) { + return null; + } + long cap = now + handedJobMaxNanos; + long deadline = (attribution.expiresAtNanos - cap) <= 0 ? attribution.expiresAtNanos : cap; + 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. @@ -132,6 +142,15 @@ private static void begin(Run run) { // running is the name of the job whose run this thread is in (the job's // 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 its carried deadline: + // a direct job run gets a fresh handedJobMaxNanos budget; a handed-off + // task carries its existing deadline unchanged so re-submitting across + // multiple hops can never extend attribution past the original bound. + static Attribution runningAttribution() { Run run = CURRENT.get(); if (run == null) { return null; @@ -140,7 +159,24 @@ static String running() { while (run != null && (run.over || run.isExpired(now))) { run = run.outer; } - return run == null ? null : run.name; + if (run == null) { + return null; + } + long deadline = run.handed ? run.expiresAtNanos : now + handedJobMaxNanos; + return new Attribution(run.name, deadline); + } + + // Attribution carries a job's name and absolute nanoTime expiry across + // async hand-off hops. + static final class Attribution { + + final String name; + final long expiresAtNanos; + + Attribution(String name, long expiresAtNanos) { + this.name = name; + this.expiresAtNanos = expiresAtNanos; + } } /** 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 ef7c6bbf..6e8b88b8 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -1119,6 +1119,11 @@ private static final class CoverageTcpClient implements CoverageWorker { // 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. @@ -1139,6 +1144,14 @@ private String helloFrame() { asyncExecutors, agentAttached); } + 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()) { @@ -1190,6 +1203,7 @@ private void connectAndServe() throws IOException { lastEndedTestId = null; backgroundRequested = false; ackWithId = false; + lastHelloSent = null; backgroundLost = 0; } log(Level.INFO, "Keploy dedup: connected to collector at " + host + ":" + port, null); @@ -1201,9 +1215,12 @@ private void connectAndServe() throws IOException { 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. - writeLine(out, helloFrame()); - out.flush(); + // removal eligibility on this declaration and refresh it if a later + // HELLO arrives after server/JaCoCo initialization completes. + synchronized (testCaseLock) { + maybeSendUpdatedHello(out); + out.flush(); + } String line; while (running.get() && (line = reader.readLine()) != null) { String trimmed = line.trim(); @@ -1286,6 +1303,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // collector has no other sign this test went unmeasured. writeLine(out, IGNORED_REPLY + " " + command.testId); } + maybeSendUpdatedHello(out); ack(out, command.testId); // Emit BACKGROUND after START's ACK (matching the unix path) // so building coverageIndex.report() / JSON never delays the @@ -1337,6 +1355,10 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) log(Level.FINE, "No Java coverage collected for " + command.testId, null); } try { + // Emit updated HELLO if capabilities changed during the test + // (e.g. Jetty/Undertow loaded its request entry on first request, + // or probeScan was dropped). + maybeSendUpdatedHello(out); // Always emit exactly one COV before ACK — even when empty — // so the line-oriented collector stays in lockstep (the unix // transport likewise always publishes). @@ -1533,13 +1555,22 @@ private CoverageCollector(JacocoClient jacocoClient, CoverageIndex coverageIndex 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.lookupRuntimeAgent(); + 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.agent; if (agent != null) { try { probeScan = ProbeScan.locate(agent); @@ -2080,11 +2111,49 @@ 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 { + final Object agent; + final boolean notStartedYet; + + AgentLookup(Object agent, boolean notStartedYet) { + this.agent = agent; + this.notStartedYet = notStartedYet; + } + } + + // lookupRuntimeAgent returns JaCoCo's in-process agent object, or + // notStartedYet=true when RT is present on the classpath but its + // premain has not started the agent yet (avoiding a permanent latch). + private AgentLookup lookupRuntimeAgent() { + if (inProcessUnavailable) { + return new AgentLookup(null, false); + } + InProcessAgent cached = inProcessAgent; + if (cached != null) { + return new AgentLookup(cached.agent, false); + } + synchronized (this) { + if (inProcessUnavailable) { + return new AgentLookup(null, false); + } + if (inProcessAgent != null) { + return new AgentLookup(inProcessAgent.agent, false); + } + try { + inProcessAgent = InProcessAgent.locate(); + return new AgentLookup(inProcessAgent.agent, false); + } catch (AgentNotStartedException e) { + log(Level.FINE, "JaCoCo in-process agent is not started yet; will retry", e); + return new AgentLookup(null, true); + } catch (Throwable t) { + inProcessUnavailable = true; + log(Level.FINE, + "JaCoCo in-process agent unavailable, will use TCP fallback at " + + host + ":" + port, + t); + return new AgentLookup(null, false); + } + } } private InProcessAgent inProcessAgent() { @@ -2104,6 +2173,9 @@ private InProcessAgent inProcessAgent() { } try { inProcessAgent = InProcessAgent.locate(); + } catch (AgentNotStartedException e) { + log(Level.FINE, "JaCoCo in-process agent is not started yet; will retry", e); + return null; } catch (Throwable t) { inProcessUnavailable = true; log(Level.FINE, @@ -2151,6 +2223,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; @@ -2165,11 +2249,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; } @@ -2180,6 +2267,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; @@ -2187,6 +2278,9 @@ static InProcessAgent locate() throws ReflectiveOperationException { } } + if (notStarted != null) { + throw notStarted; + } if (firstFailure != null) { throw firstFailure; } @@ -2203,7 +2297,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; } 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 d626061f..f3ecd417 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -70,6 +70,8 @@ final class OrderedPools { private static final String SPRING_SIMPLE_ASYNC = "org.springframework.core.task.SimpleAsyncTaskExecutor"; 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 = @@ -88,10 +90,12 @@ final class OrderedPools { private static final ClassValue CONCURRENT_EXECUTOR = methodLookup("getConcurrentExecutor"); // Whether a ThreadPoolExecutor subclass overrides beforeExecute, - // afterExecute, or (for ScheduledThreadPoolExecutor) decorateTask, which - // may cast the queued Runnable/Callable to an app-specific subtype. - // Spring 6's ThreadPoolTaskExecutor inner ThreadPoolExecutor subclass only - // tracks Spring lifecycle hooks and never casts the task, so it is allowed. + // 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) { @@ -102,11 +106,18 @@ protected Boolean computeValue(Class type) { if (c == ScheduledThreadPoolExecutor.class) { break; } - if (c.getName().startsWith(SPRING_POOL + "$")) { + 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; @@ -179,6 +190,7 @@ private static boolean read(Object executor, int depth, boolean requireVerified) } String className = executor.getClass().getName(); if (JDK_FINALIZABLE_DELEGATED.equals(className) + || JDK_AUTO_SHUTDOWN_DELEGATED.equals(className) || JDK_DELEGATED_SCHEDULED.equals(className)) { return false; } @@ -259,10 +271,12 @@ private static boolean checkThreadPool(ThreadPoolExecutor pool, Object reportedO } try { RejectedExecutionHandler handler = pool.getRejectedExecutionHandler(); - if (handler instanceof ThreadPoolExecutor.DiscardPolicy - || handler instanceof ThreadPoolExecutor.DiscardOldestPolicy) { + if (handler == null + || (handler.getClass() != ThreadPoolExecutor.AbortPolicy.class + && handler.getClass() != ThreadPoolExecutor.CallerRunsPolicy.class)) { + String handlerName = handler == null ? "null" : handler.getClass().getName(); return uncounted(reportedOwner, "its rejected execution handler, a " - + handler.getClass().getName() + ", may silently discard tasks"); + + handlerName + ", may silently discard or inspect tasks"); } } catch (Throwable e) { if (e instanceof VirtualMachineError) { @@ -270,10 +284,14 @@ private static boolean checkThreadPool(ThreadPoolExecutor pool, Object reportedO } return uncounted(reportedOwner, "its pool's rejected execution handler cannot be read (" + e + ")"); } - if (pool.getClass() == ScheduledThreadPoolExecutor.class) { - // Exact ScheduledThreadPoolExecutor always wraps execute/submit - // tasks in its own ScheduledFutureTask before enqueueing into - // DelayedWorkQueue, so the queue never casts the caller's task. + if (pool.getClass() == ScheduledThreadPoolExecutor.class + || (pool instanceof ScheduledThreadPoolExecutor + && pool.getClass().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; 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 7af176f1..c47f0091 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -1,9 +1,14 @@ package io.keploy.dedup; +import java.lang.ref.WeakReference; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; @@ -40,25 +45,27 @@ * {@link #runAsync}, {@link #supplyAsync}), 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, throws, is rejected, or is - * cancelled/timed out before running. On a thread in a scheduled job's or - * message listener'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 tasks, override task hooks, silently discard tasks, or + * cancelled/timed out/drained before running. On a thread in a scheduled job's + * or message listener's run (JobGate), or in a task such a run handed off, the + * task counts as a run of that job while it runs (bounded by the original + * hand-off deadline), 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 tasks, + * override task/submission hooks, use a non-standard rejection handler, or * delegate opaquely (OrderedPools), is not counted. * - *

Note on pool queue visibility: for {@code submit} and - * {@code CompletableFuture}, the JDK already wraps user tasks in - * {@code FutureTask}/{@code AsyncRun}; for direct {@code execute(Runnable)} - * call sites in rewritten application classes, {@link #remove} and - * {@link #shutdownNow} preserve identity and unwrap queued wrappers, while - * custom {@code ThreadPoolExecutor} subclasses that override - * {@code beforeExecute}/{@code afterExecute} are skipped by - * {@link OrderedPools}. Direct inspection of {@code getQueue()} on a plain - * {@code ThreadPoolExecutor} that casts elements to an app-private subtype - * without {@link Comparable} is the only case where the wrapper could be - * visible. + *

Note on pool queue visibility: {@link #submit} returns the executor's own + * {@link Future} untouched (preserving casts to {@code Runnable}, + * {@code ScheduledFuture}, {@code ListenableFuture}, etc.), tracking pending + * futures separately for cancellation, {@link #remove}, and + * {@link #shutdownNow}. {@link OrderedPools} skips pools with non-standard + * queues, custom rejection handlers, task-hook/{@code newTaskFor}/ + * {@code execute}/{@code submit} overrides, or opaque delegates, and rewritten + * {@link #remove}/{@link #shutdownNow} call sites unwrap queued wrappers. + * Callers that inspect {@code getQueue()} directly on a plain + * {@code ThreadPoolExecutor}, or unrewritten code calling {@code remove}/ + * {@code shutdownNow} on a pool fed by rewritten {@code execute(Runnable)} + * sites, may still observe {@code Handed}. * *

Public only for the server, Spring, and rewritten application classes * ServerEntries changes, which call it from their own packages; not an API. @@ -76,6 +83,21 @@ public final class RequestGate { // runs, counts in; null on any other thread. private static final ThreadLocal INSIDE = new ThreadLocal<>(); + // Weak associations from an executor's returned Future (e.g. FutureTask / + // ScheduledFutureTask) to its Hand, so remove((Runnable) future) releases + // its pending permit without wrapping the returned Future. + private static final Map PENDING_BY_FUTURE = new WeakHashMap<>(); + + // Weak associations from an Executor to its pending Hand instances, so + // shutdownNow() releases every queued task's pending permit regardless of + // whether the pool wrapped it in a FutureTask or ScheduledFutureTask. + private static final Map>> PENDING_BY_EXECUTOR = + new WeakHashMap<>(); + + // 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); + private RequestGate() { } @@ -142,7 +164,7 @@ public static Runnable hand(Object executor, Runnable task) { return task; } Window window = INSIDE.get(); - String job = window == null ? JobGate.running() : null; + JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; if ((window == null && job == null) || OrderedPools.orders(executor)) { return task; } @@ -181,7 +203,7 @@ public static Callable hand(Object executor, Callable task) { return task; } Window window = INSIDE.get(); - String job = window == null ? JobGate.running() : null; + JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; if ((window == null && job == null) || OrderedPools.orders(executor)) { return task; } @@ -215,7 +237,7 @@ public static Supplier handSupplier(Object executor, Supplier supplier return supplier; } Window window = INSIDE.get(); - String job = window == null ? JobGate.running() : null; + JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; if ((window == null && job == null) || OrderedPools.orders(executor)) { return supplier; } @@ -230,9 +252,13 @@ public static Supplier handSupplier(Object executor, Supplier supplier * Call-site wrapper for {@link Executor#execute(Runnable)}: propagates the * current request window (or job run) across standard JDK executors whose * classes live in the bootstrap loader. + * + * @param executor target executor + * @param task runnable to execute */ public static void execute(Executor executor, Runnable task) { Runnable handed = hand(executor, task); + registerForExecutor(executor, handed, task); try { executor.execute(handed); } catch (Throwable t) { @@ -241,9 +267,16 @@ public static void execute(Executor executor, Runnable task) { } } - /** Call-site wrapper for {@link ExecutorService#submit(Runnable)}. */ + /** + * 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) { Runnable handed = hand(executor, task); + registerForExecutor(executor, handed, task); Future future; try { future = executor.submit(handed); @@ -251,12 +284,22 @@ public static Future submit(ExecutorService executor, Runnable task) { dropped(handed, task); throw t; } - return wrapFuture(future, handed, task); + trackSubmitted(future, handed, task); + return future; } - /** Call-site wrapper for {@link ExecutorService#submit(Runnable, Object)}. */ + /** + * 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) { Runnable handed = hand(executor, task); + registerForExecutor(executor, handed, task); Future future; try { future = executor.submit(handed, result); @@ -264,12 +307,21 @@ public static Future submit(ExecutorService executor, Runnable task, T re dropped(handed, task); throw t; } - return wrapFuture(future, handed, task); + trackSubmitted(future, handed, task); + return future; } - /** Call-site wrapper for {@link ExecutorService#submit(Callable)}. */ + /** + * 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) { Callable handed = hand(executor, task); + registerForExecutor(executor, handed, task); Future future; try { future = executor.submit(handed); @@ -277,10 +329,16 @@ public static Future submit(ExecutorService executor, Callable task) { dropped(handed, task); throw t; } - return wrapFuture(future, handed, task); + trackSubmitted(future, handed, task); + return future; } - /** Call-site wrapper for {@link CompletableFuture#runAsync(Runnable)}. */ + /** + * Call-site wrapper for {@link CompletableFuture#runAsync(Runnable)}. + * + * @param task runnable to execute asynchronously + * @return the created CompletableFuture + */ public static CompletableFuture runAsync(Runnable task) { Runnable handed = hand(null, task); CompletableFuture cf; @@ -294,9 +352,16 @@ public static CompletableFuture runAsync(Runnable task) { return cf; } - /** Call-site wrapper for {@link CompletableFuture#runAsync(Runnable, Executor)}. */ + /** + * 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) { Runnable handed = hand(executor, task); + registerForExecutor(executor, handed, task); CompletableFuture cf; try { cf = CompletableFuture.runAsync(handed, executor); @@ -308,7 +373,13 @@ public static CompletableFuture runAsync(Runnable task, Executor executor) return cf; } - /** Call-site wrapper for {@link CompletableFuture#supplyAsync(Supplier)}. */ + /** + * 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) { Supplier handed = handSupplier(null, supplier); CompletableFuture cf; @@ -322,9 +393,17 @@ public static CompletableFuture supplyAsync(Supplier supplier) { return cf; } - /** Call-site wrapper for {@link CompletableFuture#supplyAsync(Supplier, Executor)}. */ + /** + * 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) { Supplier handed = handSupplier(executor, supplier); + registerForExecutor(executor, handed, supplier); CompletableFuture cf; try { cf = CompletableFuture.supplyAsync(handed, executor); @@ -338,11 +417,21 @@ public static CompletableFuture supplyAsync(Supplier supplier, Executo /** * Call-site wrapper for {@link ThreadPoolExecutor#remove(Runnable)}: finds - * and removes the wrapped {@link Handed} entry if {@code task} was wrapped, - * releasing its pending window permit so END does not wait for it. + * 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. + * + * @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) { @@ -362,11 +451,18 @@ public static boolean remove(ThreadPoolExecutor executor, Runnable task) { /** * Call-site wrapper for {@link ExecutorService#shutdownNow()}: releases - * pending window permits for drained wrappers and returns the app's - * original tasks so callers casting them never see {@link Handed}. + * pending window permits for all queued tasks of {@code executor} (both + * direct {@code execute} wrappers and {@code FutureTask}/ + * {@code ScheduledFutureTask}-wrapped submissions) 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; } @@ -380,16 +476,108 @@ public static List shutdownNow(ExecutorService executor) { 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 Future wrapFuture(Future future, Object handed, Object task) { - if (future != null && handed != task && handed instanceof Hand) { - return new CancelAwareFuture<>(future, (Hand) handed); + private static void registerForExecutor(Executor executor, Object handed, Object task) { + if (executor == null || handed == task || !(handed instanceof Hand)) { + return; + } + Hand hand = (Hand) handed; + if (hand.window == null) { + return; + } + try { + ConcurrentLinkedQueue> queue; + synchronized (PENDING_BY_EXECUTOR) { + queue = PENDING_BY_EXECUTOR.get(executor); + if (queue == null) { + queue = new ConcurrentLinkedQueue<>(); + PENDING_BY_EXECUTOR.put(executor, queue); + } + } + // Amortized O(1) prune of finished/collected entries from head. + for (int i = 0; i < 8; i++) { + WeakReference head = queue.peek(); + if (head == null) { + break; + } + Hand h = head.get(); + if (h == null || h.isReleased()) { + queue.poll(); + } else { + break; + } + } + queue.add(new WeakReference<>(hand)); + } catch (Throwable ignored) { + // Never let a broken Executor.hashCode/equals affect app execution. + } + } + + private static void releaseAllPendingForExecutor(Executor executor) { + if (executor == null) { + return; + } + ConcurrentLinkedQueue> queue = null; + try { + synchronized (PENDING_BY_EXECUTOR) { + queue = PENDING_BY_EXECUTOR.remove(executor); + } + } catch (Throwable ignored) { + return; + } + if (queue == null) { + return; + } + for (WeakReference ref; (ref = queue.poll()) != null; ) { + Hand hand = ref.get(); + if (hand != null) { + hand.releaseIfPending(); + } + } + } + + private static void trackSubmitted(Future future, Object handed, Object task) { + if (future == null || handed == task || !(handed instanceof Hand)) { + return; + } + Hand hand = (Hand) handed; + if (hand.window == null) { + return; + } + if (future.isCancelled() || future.isDone()) { + hand.releaseIfPending(); + return; + } + hand.window.track(future, hand); + try { + synchronized (PENDING_BY_FUTURE) { + PENDING_BY_FUTURE.put(future, hand); + } + } catch (Throwable ignored) { + // Never let a custom Future.hashCode/equals affect app execution. + } + } + + private static Hand takeFutureHand(Object key) { + if (key == null) { + return null; + } + try { + synchronized (PENDING_BY_FUTURE) { + return PENDING_BY_FUTURE.remove(key); + } + } catch (Throwable ignored) { + return null; } - return future; } private static void attachCompletionRelease(CompletableFuture cf, Object handed, Object task) { @@ -402,14 +590,15 @@ private static void attachCompletionRelease(CompletableFuture cf, Object hand /** * 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. + * 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).release(); + ((Hand) handed).releaseIfPending(); } } @@ -430,7 +619,9 @@ static void open() { // running is how many requests of the current window are running. static int running() { - return current.running.get(); + Window window = current; + window.sweepCancelledFutures(); + return window.running.get(); } // await closes the current window and waits until none of its requests @@ -441,6 +632,7 @@ static int running() { static boolean await(long timeoutNanos) { Window window = current; current = new Window(); + window.sweepCancelledFutures(); if (window.running.get() <= 0) { return true; } @@ -451,11 +643,18 @@ static boolean await(long timeoutNanos) { try { long deadline = System.nanoTime() + timeoutNanos; while (window.running.get() > 0) { + window.sweepCancelledFutures(); + if (window.running.get() <= 0) { + return true; + } long left = deadline - System.nanoTime(); if (left <= 0 || Thread.currentThread().isInterrupted()) { return false; } - LockSupport.parkNanos(RequestGate.class, left); + long waitNanos = window.hasPendingFutures() + ? Math.min(left, FUTURE_SWEEP_INTERVAL_NANOS) + : left; + LockSupport.parkNanos(RequestGate.class, waitNanos); } return true; } finally { @@ -463,10 +662,60 @@ static boolean await(long timeoutNanos) { } } + private static final class PendingFuture { + + private final WeakReference> future; + private final Hand hand; + + private PendingFuture(Future future, Hand hand) { + this.future = new WeakReference>(future); + this.hand = hand; + } + } + private static final class Window { private final AtomicInteger running = new AtomicInteger(); private volatile Thread waiter; + private volatile ConcurrentLinkedQueue futures; + + private void track(Future future, Hand hand) { + ConcurrentLinkedQueue q = futures; + if (q == null) { + synchronized (this) { + q = futures; + if (q == null) { + q = new ConcurrentLinkedQueue<>(); + futures = q; + } + } + } + q.add(new PendingFuture(future, hand)); + } + + private boolean hasPendingFutures() { + ConcurrentLinkedQueue q = futures; + return q != null && !q.isEmpty(); + } + + private void sweepCancelledFutures() { + ConcurrentLinkedQueue q = futures; + if (q == null || q.isEmpty()) { + return; + } + for (Iterator it = q.iterator(); it.hasNext(); ) { + PendingFuture pf = it.next(); + if (pf.hand.isReleased()) { + it.remove(); + continue; + } + Future f = pf.future.get(); + if (f == null || f.isCancelled() || f.isDone()) { + pf.hand.releaseIfPending(); + it.remove(); + } + } + } } // Nested is the token of a request entered on a thread that already @@ -486,7 +735,8 @@ private Nested(Window window, Window outer) { // returns or throws, when the executor did not take it, or when it is // cancelled/timed out/removed/drained while still pending. 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. + // runs (bounded by its carried deadline), and nothing to count done when + // the executor did not take it. private abstract static class Hand { private static final int STATE_PENDING = 0; @@ -498,16 +748,20 @@ private abstract static class Hand { // 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; + // The job attribution whose run handed it off, when window is null. + final JobGate.Attribution job; private volatile int state; - Hand(Window window, String job) { + Hand(Window window, JobGate.Attribution job) { this.window = window; this.job = job; } - // release marks this task done unconditionally (on exit or rejected drop). + final boolean isReleased() { + return state == STATE_DONE; + } + + // release marks this task done unconditionally (on exit). final void release() { if (window != null && STATE.getAndSet(this, STATE_DONE) != STATE_DONE) { done(window); @@ -515,9 +769,9 @@ final void release() { } // releaseIfPending marks this task done only if it has not started - // running yet: cancellation/timeout of an already-running task waits - // for its finally block's exit() so the window stays open while app - // code is still executing. + // 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 && STATE.compareAndSet(this, STATE_PENDING, STATE_DONE)) { done(window); @@ -527,8 +781,7 @@ final void releaseIfPending() { // 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. + // of the job (preserving the original deadline), and returns its token. final Object enter() { if (window == null) { return JobGate.enterAs(job); @@ -553,52 +806,11 @@ final void exit(Object outer) { } } - private static final class CancelAwareFuture implements Future { - - private final Future delegate; - private final Hand hand; - - CancelAwareFuture(Future delegate, Hand hand) { - this.delegate = delegate; - this.hand = hand; - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - boolean cancelled = delegate.cancel(mayInterruptIfRunning); - if (cancelled) { - hand.releaseIfPending(); - } - return cancelled; - } - - @Override - public boolean isCancelled() { - return delegate.isCancelled(); - } - - @Override - public boolean isDone() { - return delegate.isDone(); - } - - @Override - public T get() throws InterruptedException, ExecutionException { - return delegate.get(); - } - - @Override - public T get(long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - return delegate.get(timeout, unit); - } - } - private static class Handed extends Hand implements Runnable { final Runnable task; - Handed(Window window, String job, Runnable task) { + Handed(Window window, JobGate.Attribution job, Runnable task) { super(window, job); this.task = task; } @@ -621,7 +833,7 @@ public String toString() { private static final class HandedFuture extends Handed implements RunnableFuture { - HandedFuture(Window window, String job, Runnable task) { + HandedFuture(Window window, JobGate.Attribution job, Runnable task) { super(window, job, task); } @@ -661,7 +873,7 @@ private static final class HandedCall extends Hand implements Callable { final Callable task; - HandedCall(Window window, String job, Callable task) { + HandedCall(Window window, JobGate.Attribution job, Callable task) { super(window, job); this.task = task; } @@ -686,7 +898,7 @@ private static final class HandedSupplier extends Hand implements Supplier final Supplier task; - HandedSupplier(Window window, String job, Supplier task) { + HandedSupplier(Window window, JobGate.Attribution job, Supplier task) { super(window, job); this.task = 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 1621ea3b..10e1c721 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,9 @@ package io.keploy.dedup; 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; @@ -161,6 +164,11 @@ final class ServerEntries implements ClassFileTransformer { // 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+, 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. If none of // these appear in a class's constant pool, ASM rewriting is skipped. @@ -265,7 +273,7 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (uncounted != null) { SEEN_UNCOUNTED.add(uncounted); } - if (shouldRewriteExecutorCalls(className) && seesGate(loader)) { + if (shouldRewriteExecutorCalls(className) && canAccessGate(loader, protectionDomain)) { try { byte[] updated = wrapExecutorCalls(classfileBuffer); if (updated != null) { @@ -474,9 +482,83 @@ boolean shouldRewriteExecutorCalls(String className) { return appPackagePrefix != null && className.startsWith(appPackagePrefix); } + // canAccessGate checks both class-loader visibility and (on Java 9+) that + // the class does not live in a named module that cannot read RequestGate's + // unnamed module (which would otherwise throw IllegalAccessError on + // rewritten call sites when KEPLOY_JAVA_CLASS_DIRS overrides indexing). + private 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 { + if (UNREADABLE_MODULE_LOCATIONS.contains(location.toURI())) { + return false; + } + } catch (Throwable ignored) { + } + } + } + return true; + } + + @SuppressWarnings("unchecked") + 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) { + unreadable.add((URI) uri); + } + } + } + } + return unreadable.isEmpty() ? Collections.emptySet() : Collections.unmodifiableSet(unreadable); + } catch (Throwable t) { + // Java 8 (no Module/ModuleLayer) or restricted reflection. + return Collections.emptySet(); + } + } + // Belt-and-suspenders guard in case KEPLOY_JAVA_CLASS_DIRS includes - // framework/library classes; note org/apache/ is NOT blanket-excluded so - // Apache-hosted applications (e.g. org/apache/fineract/) remain eligible. + // framework/library classes or a shaded uber-jar; note org/apache/ is NOT + // blanket-excluded so Apache-hosted applications (e.g. + // org/apache/fineract/) remain eligible. static boolean isRewriteAllowedPackage(String className) { return className != null && !className.startsWith("java/") @@ -502,10 +584,22 @@ static boolean isRewriteAllowedPackage(String className) { && !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("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: every matching invoke instruction references a diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index c89aefad..e47642d8 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -33,11 +33,14 @@ import java.util.concurrent.Future; 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 org.junit.After; @@ -50,6 +53,7 @@ import org.objectweb.asm.MethodVisitor; 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 @@ -165,6 +169,68 @@ public void helloReportsLiveCapabilitiesAccuratelyAcrossRuntimeConfigurations() helloFallback); } + @Test(timeout = 60000) + public void earlyConnectBeforeJacocoAndServerInitDoesNotLatchFailureAndRefreshesHello() 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()); + + // Simulate premain early connect: -javaagent attached, server class NOT loaded yet, + // and external JaCoCo RT is on the classpath but its premain has not run yet + // (RT.getAgent() throws IllegalStateException("JaCoCo agent not started.")). + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + ServerEntries.restoreCounted(Collections.emptySet()); + + 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"); // unreachable TCP port: must use in-process once started + + 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 on early connect honestly reports windowCut:false, background:false. + String initialHello = in.readLine(); + assertEquals(KeployDedupAgent.buildHelloFrame(false, true, true, false, true, true, true, true), + initialHello); + + // Now external JaCoCo's premain finishes and Tomcat's CoyoteAdapter loads. + DeferredRtLoader.agent = realAgent; + ServerEntries.restoreCounted(Collections.singleton("Tomcat")); + + // Next START must succeed via in-process ProbeScan (NOT latched off!) and emit updated HELLO. + send(out, "ACK_ID"); + send(out, "START ts/test-1"); + String updatedHello = in.readLine(); + assertEquals("HELLO must refresh once server and JaCoCo are live", + KeployDedupAgent.buildHelloFrame(true, true, true, true, true, true, true, true), + updatedHello); + assertEquals("ACK ts/test-1", in.readLine()); + + probes[1] = true; + send(out, "END ts/test-1"); + String cov = in.readLine(); + assertEquals("COV {\"id\":\"ts/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}}", cov); + assertEquals("ACK ts/test-1", in.readLine()); + } finally { + DeferredRtLoader.agent = null; + } + } + @Test(timeout = 60000) public void defaultBareAckOptInAckIdBareAndTokenNopAndReconnectStateReset() throws Exception { byte[] shopBytes = new byte[] {7, 8, 9}; @@ -330,7 +396,11 @@ public void appOnlyAllowListExcludesThirdPartyLibrariesAndNonMatchingClassesRetu "software/amazon/awssdk/Client", "com/amazonaws/Client", "org/springframework/core/task/Custom", - "com/zaxxer/hikari/Pool" + "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, @@ -581,7 +651,8 @@ public void cancelledTimedOutRemovedAndShutdownNowTasksNeverLeakRequestWindow() runningRelease.countDown(); assertTrue(RequestGate.await(TimeUnit.SECONDS.toNanos(5))); - // 3. shutdownNow() unwraps queued tasks (no ClassCastException) and releases permits. + // 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)); @@ -590,18 +661,87 @@ public void cancelledTimedOutRemovedAndShutdownNowTasksNeverLeakRequestWindow() 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(1, RequestGate.running()); + assertEquals(3, RequestGate.running()); List drained = RequestGate.shutdownNow(pool); rel2.countDown(); - assertEquals(1, drained.size()); + 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", 0, RequestGate.running()); + 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(); @@ -619,7 +759,8 @@ public void orderedPoolsGuardsDiscardPoliciesTaskHooksConcurrentTaskExecutorAndP new LinkedBlockingQueue(1), new ThreadPoolExecutor.DiscardPolicy()); ThreadPoolExecutor discardOldest = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(1), new ThreadPoolExecutor.DiscardOldestPolicy()); - // 3. ThreadPoolExecutor subclass overriding beforeExecute that casts Runnable to MyAppTask. + // 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()) { @@ -628,14 +769,28 @@ protected void beforeExecute(Thread t, Runnable r) { hookSaw.set(((MyAppTask) r).name); } }; - // 4. Exact ScheduledThreadPoolExecutor IS safe (wraps in ScheduledFutureTask). + 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 */ }); + // 4. Exact ScheduledThreadPoolExecutor & Spring ThreadPoolTaskScheduler ARE safe. ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); - // 5. ConcurrentTaskExecutor wrapping priority pool vs opaque executor vs normal pool. + 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 { @@ -643,22 +798,30 @@ protected void beforeExecute(Thread t, Runnable r) { 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)); 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 pool receives original MyAppTask without ClassCastException. + // 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); } @@ -666,6 +829,9 @@ protected void beforeExecute(Thread t, Runnable r) { 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()); // Pass-through app decorator wrapping a PriorityBlockingQueue pool: // outer call wraps into Handed; inner RequestGate.execute(priority, handed) unwraps and releases permit! @@ -688,12 +854,67 @@ protected void beforeExecute(Thread t, Runnable r) { discard.shutdownNow(); discardOldest.shutdownNow(); customHookPool.shutdownNow(); + customNewTaskForPool.shutdownNow(); + customDropHandlerPool.shutdownNow(); stpe.shutdownNow(); + springScheduler.shutdown(); normalPool.shutdownNow(); + if (cteDefault.getConcurrentExecutor() instanceof ExecutorService) { + ((ExecutorService) cteDefault.getConcurrentExecutor()).shutdownNow(); + } unconfigurable.shutdownNow(); } } + @Test(timeout = 60000) + public void selfResubmittingChainStartedFromJobExpiresAtOriginalDeadline() throws Exception { + JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(80); + ExecutorService pool = Executors.newSingleThreadExecutor(); + AtomicInteger hops = new AtomicInteger(); + AtomicBoolean sawAttributed = new AtomicBoolean(); + CountDownLatch expiredHopSeen = new CountDownLatch(1); + AtomicBoolean keepLooping = new AtomicBoolean(true); + try { + Runnable[] self = new Runnable[1]; + self[0] = () -> { + int hop = hops.incrementAndGet(); + String current = JobGate.running(); + if (current != null) { + sawAttributed.set(true); + } else if (hop > 1) { + expiredHopSeen.countDown(); + keepLooping.set(false); + return; + } + if (keepLooping.get()) { + try { + Thread.sleep(25); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + RequestGate.execute(pool, self[0]); + } + }; + Object job = JobGate.enter(new Object(), "scheduled"); + try { + RequestGate.execute(pool, self[0]); + } finally { + JobGate.exit(job); + } + assertTrue("chained self-resubmitting job task must expire at original deadline, hops=" + hops.get(), + expiredHopSeen.await(10, TimeUnit.SECONDS)); + assertTrue("earlier hops within deadline were attributed", sawAttributed.get()); + assertTrue("multiple hops executed before expiry", hops.get() >= 2); + JobGate.open(); + assertEquals("no contamination after chain deadline expires", + Collections.emptyList(), JobGate.close()); + } finally { + keepLooping.set(false); + pool.shutdownNow(); + } + } + @Test(timeout = 60000) public void longLivedWorkerLoopStartedFromJobDoesNotKeepJobGateOpenForever() throws Exception { JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(60); @@ -1172,4 +1393,56 @@ 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/ServerTailTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java index 00e6d77c..e1d000c3 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java @@ -522,11 +522,18 @@ private Result run(Fork fork) throws Exception { for (int test = 1; test <= tests; test++) { String fullId = "test-set-0/test-" + test; send(out, "START " + fullId); - assertEquals("ACK", in.readLine()); + 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 " + 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; From a8c6177f464bddb48d515f725a008b35e5fed8a2 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 04:02:52 +0530 Subject: [PATCH 04/26] =?UTF-8?q?fix(dedup):=20address=20r3=20review=20?= =?UTF-8?q?=E2=80=94=20bounded=20O(1)=20self-removing=20tracking,=20hop-1?= =?UTF-8?q?=20job=20budget,=20Spring=206=20scheduler=20&=20JPMS=20module?= =?UTF-8?q?=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: slayerjain --- README.md | 4 +- .../main/java/io/keploy/dedup/JobGate.java | 46 ++- .../io/keploy/dedup/KeployDedupAgent.java | 86 ++--- .../java/io/keploy/dedup/OrderedPools.java | 40 ++- .../java/io/keploy/dedup/RequestGate.java | 171 +++++---- .../java/io/keploy/dedup/ServerEntries.java | 60 +++- .../dedup/HonestProtocolAndAsyncTest.java | 332 +++++++++++++++++- .../java/io/keploy/dedup/ServerTailTest.java | 3 +- .../java/org/example/servers/AsyncWork.java | 6 + 9 files changed, 561 insertions(+), 187 deletions(-) diff --git a/README.md b/README.md index 7c766fbb..f7e8343c 100644 --- a/README.md +++ b/README.md @@ -37,9 +37,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. 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, the agent sends a dynamic `HELLO {}` frame on connect (and refreshes it mid-stream if server/JaCoCo capabilities change after an early connect) 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 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 07d735fd..ded203fe 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -102,11 +102,13 @@ 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. Preserves - // the original attribution deadline across chained hand-offs (taking the - // earlier of the carried deadline and now + handedJobMaxNanos) and skips - // entering if already expired, so a self-resubmitting loop started from a - // job cannot contaminate every later test forever. Never throws, as enter. + // 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 and skip entering once expired so a + // self-resubmitting loop cannot contaminate every later test forever. + // Never throws, as enter. static Object enterAs(Attribution attribution) { if (attribution == null) { return null; @@ -114,11 +116,15 @@ static Object enterAs(Attribution attribution) { Run run = null; try { long now = System.nanoTime(); - if ((now - attribution.expiresAtNanos) >= 0) { - return null; + long deadline; + if (attribution.hasDeadline) { + if ((now - attribution.expiresAtNanos) >= 0) { + return null; + } + deadline = attribution.expiresAtNanos; + } else { + deadline = now + handedJobMaxNanos; } - long cap = now + handedJobMaxNanos; - long deadline = (attribution.expiresAtNanos - cap) <= 0 ? attribution.expiresAtNanos : cap; run = new Run(attribution.name, CURRENT.get(), true, deadline); begin(run); } catch (Throwable t) { @@ -146,10 +152,11 @@ static String running() { return attr == null ? null : attr.name; } - // runningAttribution returns the active job name and its carried deadline: - // a direct job run gets a fresh handedJobMaxNanos budget; a handed-off - // task carries its existing deadline unchanged so re-submitting across - // multiple hops can never extend attribution past the original bound. + // 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(); if (run == null) { @@ -162,19 +169,22 @@ static Attribution runningAttribution() { if (run == null) { return null; } - long deadline = run.handed ? run.expiresAtNanos : now + handedJobMaxNanos; - return new Attribution(run.name, deadline); + return run.handed + ? new Attribution(run.name, true, run.expiresAtNanos) + : new Attribution(run.name, false, 0L); } - // Attribution carries a job's name and absolute nanoTime expiry across - // async hand-off hops. + // 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, long expiresAtNanos) { + Attribution(String name, boolean hasDeadline, long expiresAtNanos) { this.name = name; + this.hasDeadline = hasDeadline; this.expiresAtNanos = expiresAtNanos; } } 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 6e8b88b8..97100616 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -1074,13 +1074,15 @@ 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: *
-     *   SDK -> collector (on connect): "HELLO {<dynamic capabilities json>}"
+     *   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 : "ACK [id]" [+ "BACKGROUND <compact-json>"]
+     *   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)
-     *                      "COV <compact-json>" + "ACK [id]" (after an END read the test's hits)
+     *                      ["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
@@ -1235,9 +1237,13 @@ private void connectAndServe() throws IOException {
                     }
                     if (BACKGROUND_COMMAND.equals(trimmed)) {
                         synchronized (testCaseLock) {
-                            if (collector.probeScan() != null) {
-                                backgroundRequested = true;
-                            } else {
+                            // 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.
+                            backgroundRequested = true;
+                            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);
@@ -1553,6 +1559,10 @@ 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) {
                 if (isScanTurnedOff()) {
@@ -1561,7 +1571,7 @@ private synchronized ProbeScan probeScan() {
                             + " and reset, and no BACKGROUND record is sent", null);
                     return null;
                 }
-                JacocoClient.AgentLookup lookup = jacocoClient.lookupRuntimeAgent();
+                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
@@ -1570,7 +1580,7 @@ private synchronized ProbeScan probeScan() {
                     return null;
                 }
                 probeScanLookedUp = true;
-                Object agent = lookup.agent;
+                Object agent = lookup.inProcess == null ? null : lookup.inProcess.agent;
                 if (agent != null) {
                     try {
                         probeScan = ProbeScan.locate(agent);
@@ -2112,79 +2122,55 @@ private byte[] dump(boolean dump, boolean reset) throws IOException {
         }
 
         private static final class AgentLookup {
-            final Object agent;
+            static final AgentLookup UNAVAILABLE = new AgentLookup(null, false);
+            static final AgentLookup NOT_STARTED = new AgentLookup(null, true);
+
+            final InProcessAgent inProcess;
             final boolean notStartedYet;
 
-            AgentLookup(Object agent, boolean notStartedYet) {
-                this.agent = agent;
+            AgentLookup(InProcessAgent inProcess, boolean notStartedYet) {
+                this.inProcess = inProcess;
                 this.notStartedYet = notStartedYet;
             }
         }
 
-        // lookupRuntimeAgent returns JaCoCo's in-process agent object, or
-        // notStartedYet=true when RT is present on the classpath but its
-        // premain has not started the agent yet (avoiding a permanent latch).
-        private AgentLookup lookupRuntimeAgent() {
+        // 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 new AgentLookup(null, false);
+                return AgentLookup.UNAVAILABLE;
             }
             InProcessAgent cached = inProcessAgent;
             if (cached != null) {
-                return new AgentLookup(cached.agent, false);
+                return new AgentLookup(cached, false);
             }
             synchronized (this) {
                 if (inProcessUnavailable) {
-                    return new AgentLookup(null, false);
+                    return AgentLookup.UNAVAILABLE;
                 }
                 if (inProcessAgent != null) {
-                    return new AgentLookup(inProcessAgent.agent, false);
+                    return new AgentLookup(inProcessAgent, false);
                 }
                 try {
                     inProcessAgent = InProcessAgent.locate();
-                    return new AgentLookup(inProcessAgent.agent, false);
+                    return new AgentLookup(inProcessAgent, false);
                 } catch (AgentNotStartedException e) {
                     log(Level.FINE, "JaCoCo in-process agent is not started yet; will retry", e);
-                    return new AgentLookup(null, true);
+                    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 new AgentLookup(null, false);
+                    return AgentLookup.UNAVAILABLE;
                 }
             }
         }
 
         private InProcessAgent inProcessAgent() {
-            if (inProcessUnavailable) {
-                return null;
-            }
-            InProcessAgent cached = inProcessAgent;
-            if (cached != null) {
-                return cached;
-            }
-            synchronized (this) {
-                if (inProcessUnavailable) {
-                    return null;
-                }
-                if (inProcessAgent != null) {
-                    return inProcessAgent;
-                }
-                try {
-                    inProcessAgent = InProcessAgent.locate();
-                } catch (AgentNotStartedException e) {
-                    log(Level.FINE, "JaCoCo in-process agent is not started yet; will retry", e);
-                    return null;
-                } catch (Throwable t) {
-                    inProcessUnavailable = true;
-                    log(Level.FINE,
-                            "JaCoCo in-process agent unavailable, will use TCP fallback at "
-                                    + host + ":" + port,
-                            t);
-                }
-                return inProcessAgent;
-            }
+            return lookupInProcessAgent().inProcess;
         }
 
         private byte[] dumpOverTcp(boolean dump, boolean reset) throws IOException {
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 f3ecd417..eb25dec5 100644
--- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java
+++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java
@@ -31,23 +31,27 @@
  * 

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. A custom ThreadPoolExecutor - * subclass that overrides {@code beforeExecute}/{@code afterExecute} (or - * {@code decorateTask} on ScheduledThreadPoolExecutor) may likewise cast the - * task. A pool configured with {@link ThreadPoolExecutor.DiscardPolicy} or - * {@link ThreadPoolExecutor.DiscardOldestPolicy} can drop a task without - * throwing, which would otherwise leave a request window open until END times - * out. + * subclass that overrides {@code beforeExecute}, {@code afterExecute}, + * {@code newTaskFor}, {@code execute}, {@code submit}, or {@code decorateTask} + * may likewise inspect or cast the task. Only pools with exact + * {@link ThreadPoolExecutor.AbortPolicy} are wrapped: any other rejection + * handler (including {@code DiscardPolicy}, {@code DiscardOldestPolicy}, + * {@code CallerRunsPolicy} which silently drops after shutdown, or custom + * handlers) may silently drop or cast tasks. * - *

Exact {@link ScheduledThreadPoolExecutor} instances are safe for - * immediate {@code execute}/{@code submit} calls (unless configured with a - * discard policy) because they always wrap each task in their own - * {@code ScheduledFutureTask} before enqueueing into {@code DelayedWorkQueue}. - * Spring's {@code ConcurrentTaskExecutor} and {@code ThreadPoolTaskScheduler} - * are inspected through their public delegate accessors; an opaque delegate - * whose queue cannot be verified is left unwrapped. 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. + *

Exact {@link ScheduledThreadPoolExecutor} instances (and Spring's own + * internal {@code ThreadPoolTaskExecutor$} / {@code ThreadPoolTaskScheduler$} + * subclasses) are safe for immediate {@code execute}/{@code submit} calls + * because they wrap each task in their own {@code ScheduledFutureTask} or + * track lifecycle state without casting the caller's task. Spring's + * {@code ConcurrentTaskExecutor} and {@code ThreadPoolTaskScheduler} are + * inspected through their public delegate accessors (recognizing JDK 8-20 + * {@code FinalizableDelegatedExecutorService} and JDK 21+ + * {@code AutoShutdownDelegatedExecutorService}); an opaque delegate whose + * queue cannot be verified is left unwrapped. 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. */ final class OrderedPools { @@ -271,9 +275,7 @@ private static boolean checkThreadPool(ThreadPoolExecutor pool, Object reportedO } try { RejectedExecutionHandler handler = pool.getRejectedExecutionHandler(); - if (handler == null - || (handler.getClass() != ThreadPoolExecutor.AbortPolicy.class - && handler.getClass() != ThreadPoolExecutor.CallerRunsPolicy.class)) { + 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"); 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 c47f0091..304a46e7 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -2,13 +2,13 @@ import java.lang.ref.WeakReference; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; @@ -88,15 +88,19 @@ public final class RequestGate { // its pending permit without wrapping the returned Future. private static final Map PENDING_BY_FUTURE = new WeakHashMap<>(); - // Weak associations from an Executor to its pending Hand instances, so - // shutdownNow() releases every queued task's pending permit regardless of - // whether the pool wrapped it in a FutureTask or ScheduledFutureTask. - private static final Map>> PENDING_BY_EXECUTOR = - new WeakHashMap<>(); + // Weak associations from an Executor to its active Hand instances (stored + // in a ConcurrentHashMap-backed set whose entries self-remove on release), + // so shutdownNow() releases every queued task's pending permit without + // retaining finished tasks behind long-running tasks. + private static final Map> PENDING_BY_EXECUTOR = new WeakHashMap<>(); // 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; private RequestGate() { } @@ -491,32 +495,24 @@ private static void registerForExecutor(Executor executor, Object handed, Object return; } Hand hand = (Hand) handed; - if (hand.window == null) { + if (hand.window == null || hand.isReleased()) { return; } try { - ConcurrentLinkedQueue> queue; + Set set; synchronized (PENDING_BY_EXECUTOR) { - queue = PENDING_BY_EXECUTOR.get(executor); - if (queue == null) { - queue = new ConcurrentLinkedQueue<>(); - PENDING_BY_EXECUTOR.put(executor, queue); + set = PENDING_BY_EXECUTOR.get(executor); + if (set == null) { + set = ConcurrentHashMap.newKeySet(); + PENDING_BY_EXECUTOR.put(executor, set); } } - // Amortized O(1) prune of finished/collected entries from head. - for (int i = 0; i < 8; i++) { - WeakReference head = queue.peek(); - if (head == null) { - break; - } - Hand h = head.get(); - if (h == null || h.isReleased()) { - queue.poll(); - } else { - break; - } + set.add(hand); + hand.executorSet = set; + if (hand.isReleased()) { + hand.executorSet = null; + set.remove(hand); } - queue.add(new WeakReference<>(hand)); } catch (Throwable ignored) { // Never let a broken Executor.hashCode/equals affect app execution. } @@ -526,22 +522,37 @@ private static void releaseAllPendingForExecutor(Executor executor) { if (executor == null) { return; } - ConcurrentLinkedQueue> queue = null; + Set set; try { synchronized (PENDING_BY_EXECUTOR) { - queue = PENDING_BY_EXECUTOR.remove(executor); + set = PENDING_BY_EXECUTOR.remove(executor); } } catch (Throwable ignored) { return; } - if (queue == null) { + if (set == null) { return; } - for (WeakReference ref; (ref = queue.poll()) != null; ) { - Hand hand = ref.get(); - if (hand != null) { - hand.releaseIfPending(); - } + for (Hand hand : set) { + hand.releaseIfPending(); + } + 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); } } @@ -550,14 +561,18 @@ private static void trackSubmitted(Future future, Object handed, Object task) return; } Hand hand = (Hand) handed; - if (hand.window == null) { + if (hand.window == null || hand.isReleased()) { return; } if (future.isCancelled() || future.isDone()) { hand.releaseIfPending(); return; } - hand.window.track(future, hand); + hand.window.track(hand, future); + if (hand.isReleased()) { + hand.window.untrack(hand); + return; + } try { synchronized (PENDING_BY_FUTURE) { PENDING_BY_FUTURE.put(future, hand); @@ -662,57 +677,61 @@ static boolean await(long timeoutNanos) { } } - private static final class PendingFuture { - - private final WeakReference> future; - private final Hand hand; - - private PendingFuture(Future future, Hand hand) { - this.future = new WeakReference>(future); - this.hand = hand; - } - } - private static final class Window { private final AtomicInteger running = new AtomicInteger(); private volatile Thread waiter; - private volatile ConcurrentLinkedQueue futures; - - private void track(Future future, Hand hand) { - ConcurrentLinkedQueue q = futures; - if (q == null) { + // 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). + private volatile ConcurrentHashMap>> futures; + private final AtomicInteger insertsSinceSweep = new AtomicInteger(); + + private void track(Hand hand, Future future) { + ConcurrentHashMap>> map = futures; + if (map == null) { synchronized (this) { - q = futures; - if (q == null) { - q = new ConcurrentLinkedQueue<>(); - futures = q; + map = futures; + if (map == null) { + map = new ConcurrentHashMap<>(); + futures = map; } } } - q.add(new PendingFuture(future, hand)); + map.put(hand, new WeakReference>(future)); + if (insertsSinceSweep.incrementAndGet() >= FUTURE_SWEEP_STRIDE) { + insertsSinceSweep.set(0); + sweepCancelledFutures(); + } + } + + private void untrack(Hand hand) { + ConcurrentHashMap>> map = futures; + if (map != null) { + map.remove(hand); + } } private boolean hasPendingFutures() { - ConcurrentLinkedQueue q = futures; - return q != null && !q.isEmpty(); + ConcurrentHashMap>> map = futures; + return map != null && !map.isEmpty(); } private void sweepCancelledFutures() { - ConcurrentLinkedQueue q = futures; - if (q == null || q.isEmpty()) { + ConcurrentHashMap>> map = futures; + if (map == null || map.isEmpty()) { return; } - for (Iterator it = q.iterator(); it.hasNext(); ) { - PendingFuture pf = it.next(); - if (pf.hand.isReleased()) { - it.remove(); + for (Map.Entry>> entry : map.entrySet()) { + Hand hand = entry.getKey(); + if (hand.isReleased()) { + map.remove(hand, entry.getValue()); continue; } - Future f = pf.future.get(); + Future f = entry.getValue().get(); if (f == null || f.isCancelled() || f.isDone()) { - pf.hand.releaseIfPending(); - it.remove(); + hand.releaseIfPending(); + map.remove(hand, entry.getValue()); } } } @@ -750,6 +769,8 @@ private abstract static class Hand { final Window window; // The job attribution whose run handed it off, when window is null. final JobGate.Attribution job; + // Per-executor tracking set for O(1) self-removal on release. + volatile Set executorSet; private volatile int state; Hand(Window window, JobGate.Attribution job) { @@ -761,10 +782,20 @@ final boolean isReleased() { return state == STATE_DONE; } + private void finishRelease() { + window.untrack(this); + Set set = executorSet; + if (set != null) { + executorSet = null; + set.remove(this); + } + done(window); + } + // release marks this task done unconditionally (on exit). final void release() { if (window != null && STATE.getAndSet(this, STATE_DONE) != STATE_DONE) { - done(window); + finishRelease(); } } @@ -774,7 +805,7 @@ final void release() { // window stays open while app code is still executing. final void releaseIfPending() { if (window != null && STATE.compareAndSet(this, STATE_PENDING, STATE_DONE)) { - done(window); + finishRelease(); } } 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 10e1c721..ec6ae979 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -1,5 +1,6 @@ package io.keploy.dedup; +import java.io.File; import java.lang.instrument.ClassFileTransformer; import java.net.URI; import java.net.URL; @@ -164,11 +165,11 @@ final class ServerEntries implements ClassFileTransformer { // 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+, 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(); + // 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. If none of // these appear in a class's constant pool, ASM rewriting is skipped. @@ -486,7 +487,7 @@ boolean shouldRewriteExecutorCalls(String className) { // the class does not live in a named module that cannot read RequestGate's // unnamed module (which would otherwise throw IllegalAccessError on // rewritten call sites when KEPLOY_JAVA_CLASS_DIRS overrides indexing). - private static boolean canAccessGate(ClassLoader loader, ProtectionDomain protectionDomain) { + static boolean canAccessGate(ClassLoader loader, ProtectionDomain protectionDomain) { if (!seesGate(loader)) { return false; } @@ -495,7 +496,8 @@ private static boolean canAccessGate(ClassLoader loader, ProtectionDomain protec URL location = cs == null ? null : cs.getLocation(); if (location != null) { try { - if (UNREADABLE_MODULE_LOCATIONS.contains(location.toURI())) { + String normalized = normalizeLocation(location.toURI()); + if (normalized != null && UNREADABLE_MODULE_LOCATIONS.contains(normalized)) { return false; } } catch (Throwable ignored) { @@ -505,8 +507,28 @@ private static boolean canAccessGate(ClassLoader loader, ProtectionDomain protec return true; } - @SuppressWarnings("unchecked") - private static Set findUnreadableModuleLocations() { + static Set unreadableModuleLocations() { + return UNREADABLE_MODULE_LOCATIONS; + } + + 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); @@ -522,7 +544,7 @@ private static Set findUnreadableModuleLocations() { 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<>(); + Set unreadable = new HashSet<>(); for (Object mod : modules) { if (!Boolean.TRUE.equals(isNamed.invoke(mod))) { continue; @@ -543,12 +565,15 @@ private static Set findUnreadableModuleLocations() { && Boolean.TRUE.equals(optLoc.getClass().getMethod("isPresent").invoke(optLoc))) { Object uri = optLoc.getClass().getMethod("get").invoke(optLoc); if (uri instanceof URI) { - unreadable.add((URI) uri); + String normalized = normalizeLocation((URI) uri); + if (normalized != null) { + unreadable.add(normalized); + } } } } } - return unreadable.isEmpty() ? Collections.emptySet() : Collections.unmodifiableSet(unreadable); + return unreadable.isEmpty() ? Collections.emptySet() : Collections.unmodifiableSet(unreadable); } catch (Throwable t) { // Java 8 (no Module/ModuleLayer) or restricted reflection. return Collections.emptySet(); @@ -1036,6 +1061,15 @@ 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) { + // Track returned Future / CompletableFuture so cancellation + // before the task starts releases the request window permit. + 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); @@ -1048,7 +1082,7 @@ 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(); } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index e47642d8..960a52fc 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -9,19 +9,27 @@ 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.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.Callable; import java.util.concurrent.CompletableFuture; @@ -31,6 +39,7 @@ 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; @@ -43,7 +52,12 @@ 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; @@ -51,6 +65,7 @@ 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; @@ -208,12 +223,15 @@ public void earlyConnectBeforeJacocoAndServerInitDoesNotLatchFailureAndRefreshes assertEquals(KeployDedupAgent.buildHelloFrame(false, true, true, false, true, true, true, true), initialHello); + // Early BACKGROUND + ACK_ID sent BEFORE JaCoCo starts must still take effect once started. + send(out, "ACK_ID"); + send(out, "BACKGROUND"); + // Now external JaCoCo's premain finishes and Tomcat's CoyoteAdapter loads. DeferredRtLoader.agent = realAgent; ServerEntries.restoreCounted(Collections.singleton("Tomcat")); // Next START must succeed via in-process ProbeScan (NOT latched off!) and emit updated HELLO. - send(out, "ACK_ID"); send(out, "START ts/test-1"); String updatedHello = in.readLine(); assertEquals("HELLO must refresh once server and JaCoCo are live", @@ -226,6 +244,14 @@ public void earlyConnectBeforeJacocoAndServerInitDoesNotLatchFailureAndRefreshes String cov = in.readLine(); assertEquals("COV {\"id\":\"ts/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}}", cov); assertEquals("ACK ts/test-1", in.readLine()); + + // Early BACKGROUND opt-in must emit a BACKGROUND frame on START test-2 after JaCoCo started. + 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]")); } finally { DeferredRtLoader.agent = null; } @@ -780,6 +806,8 @@ protected RunnableFuture newTaskFor(Runnable runnable, T 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(); @@ -800,6 +828,8 @@ protected RunnableFuture newTaskFor(Runnable runnable, T value) { 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", @@ -856,6 +886,7 @@ protected RunnableFuture newTaskFor(Runnable runnable, T value) { customHookPool.shutdownNow(); customNewTaskForPool.shutdownNow(); customDropHandlerPool.shutdownNow(); + callerRunsPool.shutdownNow(); stpe.shutdownNow(); springScheduler.shutdown(); normalPool.shutdownNow(); @@ -867,20 +898,51 @@ protected RunnableFuture newTaskFor(Runnable runnable, T value) { } @Test(timeout = 60000) - public void selfResubmittingChainStartedFromJobExpiresAtOriginalDeadline() throws Exception { - JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(80); + public void firstHopQueueWaitDoesNotEatBudgetWhileChainedSelfResubmissionExpiresAtHop1Deadline() + throws Exception { + JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(120); ExecutorService pool = Executors.newSingleThreadExecutor(); - AtomicInteger hops = new AtomicInteger(); - AtomicBoolean sawAttributed = new AtomicBoolean(); - CountDownLatch expiredHopSeen = new CountDownLatch(1); - AtomicBoolean keepLooping = new AtomicBoolean(true); 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) { - sawAttributed.set(true); + if (hop == 1) { + hop1Attributed.countDown(); + } } else if (hop > 1) { expiredHopSeen.countDown(); keepLooping.set(false); @@ -888,7 +950,7 @@ public void selfResubmittingChainStartedFromJobExpiresAtOriginalDeadline() throw } if (keepLooping.get()) { try { - Thread.sleep(25); + Thread.sleep(40); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; @@ -896,25 +958,191 @@ public void selfResubmittingChainStartedFromJobExpiresAtOriginalDeadline() throw RequestGate.execute(pool, self[0]); } }; - Object job = JobGate.enter(new Object(), "scheduled"); + Object job2 = JobGate.enter(new Object(), "scheduled"); try { RequestGate.execute(pool, self[0]); } finally { - JobGate.exit(job); + JobGate.exit(job2); } - assertTrue("chained self-resubmitting job task must expire at original deadline, hops=" + hops.get(), + 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("earlier hops within deadline were attributed", sawAttributed.get()); assertTrue("multiple hops executed before expiry", hops.get() >= 2); JobGate.open(); assertEquals("no contamination after chain deadline expires", Collections.emptyList(), JobGate.close()); } finally { - keepLooping.set(false); 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 have self-removed immediately even behind the live SSE task. + Field byExecField = RequestGate.class.getDeclaredField("PENDING_BY_EXECUTOR"); + byExecField.setAccessible(true); + @SuppressWarnings("unchecked") + Map> byExec = (Map>) byExecField.get(null); + int execAfterCompleted; + synchronized (byExec) { + Set set = byExec.get(pool); + execAfterCompleted = set == null ? 0 : set.size(); + } + assertEquals("all 400 finished tasks must self-remove immediately behind live SSE task", + 1, execAfterCompleted); + + // 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 byExecField = RequestGate.class.getDeclaredField("PENDING_BY_EXECUTOR"); + byExecField.setAccessible(true); + @SuppressWarnings("unchecked") + Map> byExec = (Map>) byExecField.get(null); + 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 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()); + int execTrackedSize; + synchronized (byExec) { + Set set = byExec.get(pool); + execTrackedSize = set == null ? 0 : set.size(); + } + assertEquals("only the 1 live SSE task remains in PENDING_BY_EXECUTOR", 1, execTrackedSize); + + // 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(); + if (anyBootLocation.startsWith("jrt:") || anyBootLocation.startsWith("file:")) { + ProtectionDomain blockedPd = new ProtectionDomain( + new CodeSource(URI.create(anyBootLocation).toURL(), (Certificate[]) null), null); + assertFalse("canAccessGate must reject unreadable named module location", + 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()); + 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); @@ -1370,6 +1598,82 @@ private static void emitDefaultCtor(ClassWriter cw) { init.visitEnd(); } + public static Future makePendingFuture(Runnable task) { + return new FutureTask(task, null); + } + + 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 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); 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 e1d000c3..036fdbec 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")); 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 0b4d0cc4..c64e7394 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; From b7a53fa81997f8472cba65d912d1de7d77d361da Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 04:16:14 +0530 Subject: [PATCH 05/26] =?UTF-8?q?fix(dedup):=20address=20r4=20review=20?= =?UTF-8?q?=E2=80=94=20weak=20HandRef=20tokens=20with=20ReferenceQueue,=20?= =?UTF-8?q?race-free=20tracking=20test,=20positive=20control=20in=20JPMS?= =?UTF-8?q?=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: slayerjain --- .../java/io/keploy/dedup/RequestGate.java | 80 ++++++++++++++----- .../dedup/HonestProtocolAndAsyncTest.java | 39 ++++++--- 2 files changed, 85 insertions(+), 34 deletions(-) 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 304a46e7..deebf9a3 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -1,5 +1,7 @@ package io.keploy.dedup; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; @@ -88,11 +90,13 @@ public final class RequestGate { // its pending permit without wrapping the returned Future. private static final Map PENDING_BY_FUTURE = new WeakHashMap<>(); - // Weak associations from an Executor to its active Hand instances (stored - // in a ConcurrentHashMap-backed set whose entries self-remove on release), - // so shutdownNow() releases every queued task's pending permit without - // retaining finished tasks behind long-running tasks. - private static final Map> PENDING_BY_EXECUTOR = new WeakHashMap<>(); + // Weak associations from an Executor to weak tokens of its active Hand + // instances (stored in a ConcurrentHashMap-backed set whose tokens + // self-remove in O(1) on release, and dead tokens from cancelled/abandoned + // tasks are drained via DEAD_HANDS), so shutdownNow() releases every queued + // task's pending permit without retaining abandoned tasks or pinning pools. + private static final Map> PENDING_BY_EXECUTOR = new WeakHashMap<>(); + 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. @@ -490,7 +494,15 @@ public static List shutdownNow(ExecutorService executor) { return unwrapped != null ? unwrapped : pending; } + private static void drainDeadHands() { + for (Reference ref; (ref = DEAD_HANDS.poll()) != null; ) { + HandRef hr = (HandRef) ref; + hr.set.remove(hr); + } + } + private static void registerForExecutor(Executor executor, Object handed, Object task) { + drainDeadHands(); if (executor == null || handed == task || !(handed instanceof Hand)) { return; } @@ -499,7 +511,7 @@ private static void registerForExecutor(Executor executor, Object handed, Object return; } try { - Set set; + Set set; synchronized (PENDING_BY_EXECUTOR) { set = PENDING_BY_EXECUTOR.get(executor); if (set == null) { @@ -507,11 +519,12 @@ private static void registerForExecutor(Executor executor, Object handed, Object PENDING_BY_EXECUTOR.put(executor, set); } } - set.add(hand); - hand.executorSet = set; + HandRef ref = new HandRef(hand, DEAD_HANDS, set); + set.add(ref); + hand.executorRef = ref; if (hand.isReleased()) { - hand.executorSet = null; - set.remove(hand); + hand.executorRef = null; + set.remove(ref); } } catch (Throwable ignored) { // Never let a broken Executor.hashCode/equals affect app execution. @@ -519,10 +532,11 @@ private static void registerForExecutor(Executor executor, Object handed, Object } private static void releaseAllPendingForExecutor(Executor executor) { + drainDeadHands(); if (executor == null) { return; } - Set set; + Set set; try { synchronized (PENDING_BY_EXECUTOR) { set = PENDING_BY_EXECUTOR.remove(executor); @@ -533,8 +547,11 @@ private static void releaseAllPendingForExecutor(Executor executor) { if (set == null) { return; } - for (Hand hand : set) { - hand.releaseIfPending(); + for (HandRef ref : set) { + Hand hand = ref.get(); + if (hand != null) { + hand.releaseIfPending(); + } } set.clear(); } @@ -556,6 +573,17 @@ public static void submitted(Object result, Object handed, Object 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) { if (future == null || handed == task || !(handed instanceof Hand)) { return; @@ -564,7 +592,7 @@ private static void trackSubmitted(Future future, Object handed, Object task) if (hand.window == null || hand.isReleased()) { return; } - if (future.isCancelled() || future.isDone()) { + if (isFutureTerminated(future)) { hand.releaseIfPending(); return; } @@ -729,7 +757,7 @@ private void sweepCancelledFutures() { continue; } Future f = entry.getValue().get(); - if (f == null || f.isCancelled() || f.isDone()) { + if (isFutureTerminated(f)) { hand.releaseIfPending(); map.remove(hand, entry.getValue()); } @@ -750,6 +778,16 @@ private Nested(Window window, Window outer) { } } + private static final class HandRef extends WeakReference { + + private final Set set; + + private HandRef(Hand referent, ReferenceQueue queue, Set set) { + super(referent, queue); + this.set = set; + } + } + // Hand is a task counted in a request's window: done once, when it // returns or throws, when the executor did not take it, or when it is // cancelled/timed out/removed/drained while still pending. Or, with no @@ -769,8 +807,8 @@ private abstract static class Hand { final Window window; // The job attribution whose run handed it off, when window is null. final JobGate.Attribution job; - // Per-executor tracking set for O(1) self-removal on release. - volatile Set executorSet; + // Weak token in per-executor tracking set for O(1) self-removal on release. + volatile HandRef executorRef; private volatile int state; Hand(Window window, JobGate.Attribution job) { @@ -784,10 +822,10 @@ final boolean isReleased() { private void finishRelease() { window.untrack(this); - Set set = executorSet; - if (set != null) { - executorSet = null; - set.remove(this); + HandRef ref = executorRef; + if (ref != null) { + executorRef = null; + ref.set.remove(ref); } done(window); } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 960a52fc..794b38d0 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -999,15 +999,23 @@ public void trackingStructuresStayBoundedWithoutEndAndBehindLongRunningTasks() t assertTrue(done.await(10, TimeUnit.SECONDS)); } - // All 400 finished tasks must have self-removed immediately even behind the live SSE task. + // All 400 finished tasks must self-remove promptly even behind the live SSE task. + // Poll briefly because done::countDown runs inside Handed.run() just before finally exit(). Field byExecField = RequestGate.class.getDeclaredField("PENDING_BY_EXECUTOR"); byExecField.setAccessible(true); @SuppressWarnings("unchecked") Map> byExec = (Map>) byExecField.get(null); - int execAfterCompleted; - synchronized (byExec) { - Set set = byExec.get(pool); - execAfterCompleted = set == null ? 0 : set.size(); + int execAfterCompleted = -1; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + synchronized (byExec) { + Set set = byExec.get(pool); + execAfterCompleted = set == null ? 0 : set.size(); + } + if (execAfterCompleted == 1) { + break; + } + Thread.sleep(1); } assertEquals("all 400 finished tasks must self-remove immediately behind live SSE task", 1, execAfterCompleted); @@ -1039,8 +1047,8 @@ public void trackingStructuresStayBoundedWithoutEndAndBehindLongRunningTasks() t futuresField.setAccessible(true); Map futuresMap = (Map) futuresField.get(currentWindow); int beforeSweepSize = futuresMap == null ? 0 : futuresMap.size(); - assertTrue("window futures map must stay bounded without END, was " + beforeSweepSize, - beforeSweepSize < 64); + 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()); @@ -1088,12 +1096,13 @@ public void namedModuleClassViaClassDirsIsSkippedAndDoesNotThrowIllegalAccessErr Set unreadable = ServerEntries.unreadableModuleLocations(); assertFalse("Java 9+ boot layer must have unreadable named module locations", unreadable.isEmpty()); String anyBootLocation = unreadable.iterator().next(); - if (anyBootLocation.startsWith("jrt:") || anyBootLocation.startsWith("file:")) { - ProtectionDomain blockedPd = new ProtectionDomain( - new CodeSource(URI.create(anyBootLocation).toURL(), (Certificate[]) null), null); - assertFalse("canAccessGate must reject unreadable named module location", - ServerEntries.canAccessGate(getClass().getClassLoader(), blockedPd)); - } + 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 @@ -1139,6 +1148,10 @@ public void namedModuleClassViaClassDirsIsSkippedAndDoesNotThrowIllegalAccessErr 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")); } From 0271fed9556ccf6bc230e9f36140832d0249b8ad Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 05:22:56 +0530 Subject: [PATCH 06/26] =?UTF-8?q?fix(dedup):=20address=20plg-87=20audit=20?= =?UTF-8?q?=E2=80=94=20v3=20identity=20HELLO,=20fail-closed=20pools,=20CF?= =?UTF-8?q?=20dependents,=20tail=20contamination,=20lock-free=20gates,=20u?= =?UTF-8?q?narmed=20no-op?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: slayerjain --- README.md | 14 +- .../main/java/io/keploy/dedup/BuildTable.java | 2 +- .../main/java/io/keploy/dedup/JobGate.java | 469 ++++- .../io/keploy/dedup/KeployDedupAgent.java | 471 ++++- .../java/io/keploy/dedup/OrderedPools.java | 213 ++- .../java/io/keploy/dedup/RequestGate.java | 1635 ++++++++++++++--- .../java/io/keploy/dedup/ServerEntries.java | 339 ++-- .../java/io/keploy/dedup/AppIndexTest.java | 6 +- .../java/io/keploy/dedup/AsyncHandTest.java | 4 +- .../io/keploy/dedup/ControlSocketTest.java | 14 +- .../dedup/ForkedAsyncAndHonestyTest.java | 570 ++++++ .../dedup/HonestProtocolAndAsyncTest.java | 701 ++++++- .../io/keploy/dedup/InProcessScanTest.java | 19 +- .../java/io/keploy/dedup/JobGateTest.java | 1 + .../test/java/io/keploy/dedup/PhasesTest.java | 4 +- .../io/keploy/dedup/ServerEntriesTest.java | 1 + .../test/java/io/keploy/dedup/WarmupTest.java | 20 +- .../org/example/servers/AsyncHonestyApp.java | 325 ++++ 18 files changed, 4134 insertions(+), 674 deletions(-) create mode 100644 keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java create mode 100644 keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java diff --git a/README.md b/README.md index f7e8343c..9504205a 100644 --- a/README.md +++ b/README.md @@ -27,9 +27,13 @@ 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). -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` async 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` (`runAsync`, `supplyAsync`, and `*Async` instance methods including synchronous dependent stages registered before completion). `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` (or a new `START` arrives without a preceding `END`), subsequent windows are marked contaminated (`"tail:"`) until the prior lingering work finishes draining. 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 accessors verified through to an allow-listed pool) are wrapped. Any unknown or custom executor (such as Hazelcast `IExecutorService`, Ignite, Redisson, striped/keyed executors, coalescing executors, custom `ThreadPoolExecutor` 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 is marked contaminated (`"untracked-executor:"`). Similarly, untracked async submission sites inside a request (`ScheduledExecutorService.schedule*`, `ExecutorService.invokeAny`, `Thread.start()`) execute untouched and mark the window contaminated (`"untracked-async:"`). 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/`, etc.) and known library packages. + +When Keploy is absent (no collector connected and no control command received), runtime request counting, executor wrapping, and job/listener tracking remain unarmed (no-op); if any traffic ran while unarmed before a collector later connects, the first armed window 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 or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). + +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,7 +41,7 @@ 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, the agent sends a dynamic `HELLO {}` frame on connect (and refreshes it mid-stream if server/JaCoCo capabilities change after an early connect) 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. +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 Unix control socket, accepted commands reply `ACK proto=3 caps=windowCut=,contaminated=,classMismatch=,background=,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` (or `ACK ` when `ACK_ID` is enabled). @@ -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 ac6dfbee..14439718 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 ded203fe..15bbb1c7 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -1,16 +1,20 @@ 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.Iterator; -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; @@ -23,29 +27,15 @@ * 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()}, Spring's - * {@code ScheduledMethodRunnable.run()}, Spring Kafka's - * {@code ListenerConsumer}, and Spring AMQP/JMS's - * {@code AbstractMessageListenerContainer.doInvokeListener} call - * {@link #enter(Object, String)} where a 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 or listener's run hands to a Spring TaskExecutor or a - * rewritten application executor call site 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. Handed-off attribution is bounded by {@link #handedJobMaxNanos} - * so a long-lived worker loop started from a job cannot keep {@code RUNNING} - * open forever. - * - *

Jobs the app runs on plain threads of its own, uninstrumented custom - * executors, a {@code java.util.Timer}, or unhooked messaging clients are not - * seen, nor is 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. @@ -59,35 +49,53 @@ public final class JobGate { // 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 a job open in - // RUNNING before it is evicted as a long-lived worker loop. Not final so - // tests can shorten it. + // 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(); + } + /** * 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", "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()) { + RequestGate.noteUnarmedActivity(); + return null; + } Run run = null; try { run = new Run(name(job, kind), CURRENT.get(), false, 0L); @@ -107,10 +115,10 @@ public static Object enter(Object job, String kind) { // 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 and skip entering once expired so a - // self-resubmitting loop cannot contaminate every later test forever. + // self-resubmitting loop cannot extend attribution forever. // Never throws, as enter. static Object enterAs(Attribution attribution) { - if (attribution == null) { + if (attribution == null || !RequestGate.isArmed()) { return null; } Run run = null; @@ -134,15 +142,16 @@ static Object enterAs(Attribution attribution) { } // begin counts run as going on, in the window open now if any, and as - // the run this thread is in until its exit. + // 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) { - synchronized (LOCK) { - RUNNING.add(run); - if (window != null) { - window.mark(run.name); - } - } + RUNNING.add(run); CURRENT.set(run); + Window active = window; + if (active != null) { + active.mark(run.name); + } } // running is the name of the job whose run this thread is in (the job's @@ -196,11 +205,12 @@ static final class Attribution { * @param token what {@link #enter(Object, String)} returned */ public static void exit(Object token) { + if (token == null) { + 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 @@ -224,34 +234,33 @@ 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. Handed-off tasks that have run past - // handedJobMaxNanos are evicted so a long-lived worker loop started from a - // job cannot mark every later test contaminated forever. + // 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:". static void open() { + RequestGate.arm(); long now = System.nanoTime(); List expired = null; - synchronized (LOCK) { - Window opened = new Window(); - for (Iterator it = RUNNING.iterator(); it.hasNext(); ) { - Run run = it.next(); - if (run.isExpired(now)) { - it.remove(); - if (EXPIRED_LOGGED.add(run.name)) { - if (expired == null) { - expired = new ArrayList<>(); - } - expired.add(run.name); + Window opened = new Window(); + window = opened; + for (Run run : RUNNING) { + if (run.isExpired(now)) { + opened.mark("job-tail:" + run.name); + if (EXPIRED_LOGGED.add(run.name)) { + if (expired == null) { + expired = new ArrayList<>(); } - continue; + expired.add(run.name); } - opened.mark(run.name); + continue; } - window = opened; + opened.mark(run.name); } if (expired != null) { for (String jobName : expired) { - LOGGER.log(Level.INFO, "Keploy dedup stopped attributing a long-lived handed-off task to " - + jobName + " after " + TimeUnit.NANOSECONDS.toMillis(handedJobMaxNanos) - + " ms so it does not mark every later test contaminated"); + 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"); } } } @@ -260,21 +269,20 @@ static void open() { // 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, "kafka:" / "listener:" for a message listener, - // 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 { if ("quartz".equals(kind)) { @@ -290,6 +298,215 @@ static String name(Object job, String kind) { 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 { @@ -321,6 +538,69 @@ 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; @@ -345,31 +625,44 @@ private boolean isExpired(long now) { } // 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 97100616..da41abb0 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; @@ -50,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; @@ -151,8 +154,12 @@ 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 once per JVM startup (never changes on TCP + // reconnect; distinct across JVM restarts) so collectors can detect pod + // identity, restarts, and wrong-JVM routing. + static final String JVM_NONCE = UUID.randomUUID().toString(); + 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 @@ -167,23 +174,217 @@ static String encodeBytecodeFrame(String buildTag, String manifestJson, byte[] z // "NOP" -> "ACK". Does not touch activeTestId, lastEndedTestId, or probes. static final String NOP_COMMAND = "NOP"; // Protocol version declared in the dynamic HELLO frame sent immediately on - // TCP connect. Each capability boolean is computed from live runtime state - // at connect time so collectors never act on false promises. + // TCP connect and on unix ACK proto=3 caps=... replies. static final int TCP_PROTOCOL_VERSION = 3; - static String buildHelloFrame(boolean windowCut, boolean contaminated, boolean classMismatch, + 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 + + ",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 {\"proto\":" + TCP_PROTOCOL_VERSION - + ",\"windowCut\":" + windowCut - + ",\"contaminated\":" + contaminated - + ",\"classMismatch\":" + classMismatch - + ",\"background\":" + background - + ",\"ackId\":" + ackId - + ",\"nopResync\":" + nopResync - + ",\"asyncExecutors\":" + asyncExecutors - + ",\"listenerContamination\":" + 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", ""), + JVM_NONCE, + 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 with endWait > 0 + // (and no uncounted server / hook failure) rather than !countsNone(), + // so Jetty/Undertow cold-start pods honestly declare windowCut=true + // before their first request loads HttpChannel/Connectors. Runtime + // probes with enteredCount==0 still fail closed via "no-server-entry". + boolean serverEntriesInstalled = agentAttached && endWaitActive + && !ServerEntries.hasUncountedServer() + && !ServerEntries.hadServerHookFailure(); + boolean windowCut = serverEntriesInstalled; + boolean contaminated = agentAttached; + boolean classMismatch = true; + boolean background = collector.probeScan() != null; + boolean appOnlyActive = collector.coverageIndex.entries == null + || collector.coverageIndex.appOnly; + boolean asyncExecutors = serverEntriesInstalled + && executorCallSitesEnabled + && !isAsyncCallSitesTurnedOff() + && appOnlyActive + && !ServerEntries.wasJpmsGuardTriggered() + && RequestGate.CF_DEPENDENT_TRACKING_ENABLED; + boolean listenerContamination = agentAttached && !ServerEntries.hadListenerHookFailure(); + 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), JobGate contaminations, and + // no-server-entry, deduplicated in order and capped at JobGate.NAMES with + // "+N" overflow. + static List mergeContaminations(List requestContams, List jobContams, + boolean noServerEntry) { + if ((requestContams == null || requestContams.isEmpty()) + && (jobContams == null || jobContams.isEmpty()) + && !noServerEntry) { + 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 (noServerEntry) { + merged.add("no-server-entry"); + } + 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); @@ -267,6 +468,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); @@ -339,8 +544,15 @@ private static boolean start(CoverageIndex index, Instrumentation instrumentatio 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; } @@ -393,9 +605,17 @@ static void countRequests(Instrumentation instrumentation, boolean jacocoAttache static void countRequests(Instrumentation instrumentation, boolean jacocoAttached, Set appClasses, String appPackagePrefix) { boolean requests = endWaitMillis() != 0; - Set allowed = appClasses == null ? Collections.emptySet() : appClasses; + boolean asyncCallSitesOff = isAsyncCallSitesTurnedOff(); + Set allowed = asyncCallSitesOff || appClasses == null + ? Collections.emptySet() + : appClasses; + String prefix = asyncCallSitesOff ? null : appPackagePrefix; boolean hasCallSiteRewrites = !allowed.isEmpty() - || (appPackagePrefix != null && !appPackagePrefix.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) { @@ -409,7 +629,7 @@ static void countRequests(Instrumentation instrumentation, boolean jacocoAttache + " them. Attach JaCoCo before it, or run keploy-sdk.jar as released", null); } - instrumentation.addTransformer(new ServerEntries(requests, allowed, appPackagePrefix), retransformable); + instrumentation.addTransformer(new ServerEntries(requests, allowed, prefix), retransformable); transformerAdded = true; executorCallSitesEnabled = hasCallSiteRewrites; } catch (RuntimeException e) { @@ -552,6 +772,7 @@ public static void stop() { + " its socket is closed, and it stops once its command ends", null); } } + RequestGate.disarm(); STARTED.set(false); } @@ -826,6 +1047,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 @@ -893,6 +1118,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 @@ -904,6 +1130,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; @@ -920,7 +1149,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); } @@ -952,12 +1181,17 @@ private boolean run(String line) { } } + private String unixReplyTaken() { + return computeCapabilities(collector).toUnixAck(); + } + // 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; lastEndedTestId = null; @@ -966,7 +1200,7 @@ private boolean run(CoverageCommand command, Phases phases) { collector.warmup(); phases.mark("warmup"); List cleared = new ArrayList<>(); - if (!collector.begin(phases, cleared)) { + if (!collector.begin(command.testId, prevActive, phases, cleared)) { return false; } activeTestId = command.testId; @@ -995,10 +1229,16 @@ 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(); + TestCoverage coverage = raw.ended(cut, + mergeContaminations(outcome.contaminations, jobContams, noServerEntry)); if (coverage.probesByClass.isEmpty()) { log(Level.FINE, "No Java coverage collected for " + command.testId, null); } @@ -1138,12 +1378,7 @@ private static final class CoverageTcpClient implements CoverageWorker { } private String helloFrame() { - boolean agentAttached = transformerAdded; - boolean windowCut = agentAttached && collector.endWaitMillis > 0 && !ServerEntries.countsNone(); - boolean background = collector.probeScan() != null; - boolean asyncExecutors = agentAttached && executorCallSitesEnabled; - return buildHelloFrame(windowCut, agentAttached, true, background, true, true, - asyncExecutors, agentAttached); + return computeCapabilities(collector).toHelloFrame(collector.helloBuildId()); } private void maybeSendUpdatedHello(OutputStream out) throws IOException { @@ -1196,6 +1431,8 @@ 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. @@ -1241,8 +1478,11 @@ private void connectAndServe() throws IOException { // 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. + // 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" @@ -1284,6 +1524,7 @@ 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; lastEndedTestId = null; @@ -1294,7 +1535,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // one-time lines aren't charged to the first test. collector.warmup(); phases.mark("warmup"); - reset = collector.begin(phases, cleared); + reset = collector.begin(command.testId, prevActive, phases, cleared); } catch (RuntimeException e) { // Not taken, and the connection goes on: thrown past // here, it ended this thread, and no later command @@ -1346,8 +1587,15 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) TestCoverage coverage; boolean cut; try { - 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; + TestCoverage raw = collector.capture(phases); + List jobContams = JobGate.close(); + boolean noServerEntry = transformerAdded && collector.endWaitMillis > 0 + && !raw.probesByClass.isEmpty() && outcome.enteredCount == 0 + && jobContams.isEmpty(); + coverage = raw.ended(cut, + mergeContaminations(outcome.contaminations, jobContams, noServerEntry)); } 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. @@ -1402,8 +1650,16 @@ private void writeBackgroundFrame(OutputStream out, String after, String before, 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( - collector.coverageIndex.report().build, after, before, + report.build, after, before, collector.backgroundProbes(cleared)); if (backgroundLost > 0) { record.lost = backgroundLost; @@ -1604,21 +1860,87 @@ 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. + 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. + private boolean begin(String testId, String prevActiveTestId, Phases phases, List cleared) { // 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(); // 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. + RequestGate.open(testId, prevActiveTestId); ProbeScan scan = probeScan(); if (scan != null) { try { @@ -1638,27 +1960,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. @@ -2387,6 +2706,50 @@ 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). 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 eb25dec5..772052fb 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; @@ -22,36 +23,41 @@ import java.util.logging.Logger; /** - * OrderedPools says whether an executor's pool may order the tasks it is - * handed by their type, inspect/cast tasks in overridden lifecycle hooks, - * silently discard tasks without throwing, or wrap an opaque delegate whose - * queue cannot be inspected — so that a task handed to it must reach it as it - * is. + * 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. * - *

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. A custom ThreadPoolExecutor - * subclass that overrides {@code beforeExecute}, {@code afterExecute}, - * {@code newTaskFor}, {@code execute}, {@code submit}, or {@code decorateTask} - * may likewise inspect or cast the task. Only pools with exact - * {@link ThreadPoolExecutor.AbortPolicy} are wrapped: any other rejection - * handler (including {@code DiscardPolicy}, {@code DiscardOldestPolicy}, - * {@code CallerRunsPolicy} which silently drops after shutdown, or custom - * handlers) may silently drop or cast tasks. + *

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.
  • + *
* - *

Exact {@link ScheduledThreadPoolExecutor} instances (and Spring's own - * internal {@code ThreadPoolTaskExecutor$} / {@code ThreadPoolTaskScheduler$} - * subclasses) are safe for immediate {@code execute}/{@code submit} calls - * because they wrap each task in their own {@code ScheduledFutureTask} or - * track lifecycle state without casting the caller's task. Spring's - * {@code ConcurrentTaskExecutor} and {@code ThreadPoolTaskScheduler} are - * inspected through their public delegate accessors (recognizing JDK 8-20 - * {@code FinalizableDelegatedExecutorService} and JDK 21+ - * {@code AutoShutdownDelegatedExecutorService}); an opaque delegate whose - * queue cannot be verified is left unwrapped. 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. + *

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 { @@ -72,6 +78,8 @@ final class OrderedPools { 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_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 JDK_FINALIZABLE_DELEGATED = "java.util.concurrent.Executors$FinalizableDelegatedExecutorService"; private static final String JDK_AUTO_SHUTDOWN_DELEGATED = @@ -80,6 +88,14 @@ final class OrderedPools { "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 @@ -92,6 +108,26 @@ final class OrderedPools { 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) { + 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 ThreadPoolExecutor subclass overrides beforeExecute, // afterExecute, newTaskFor, execute, submit, or (for @@ -137,6 +173,17 @@ protected Boolean computeValue(Class type) { private OrderedPools() { } + 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 @@ -164,16 +211,14 @@ private static boolean declares(Class type, String name, Class... params) } } - // orders says whether executor's pool may order its tasks by their - // type (or override task hooks, silently discard tasks, or wrap an opaque - // delegate); 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. + // 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, 0, false); + return read(executor, 0, true); } catch (Throwable e) { return true; } @@ -181,47 +226,94 @@ static boolean orders(Object executor) { private static boolean read(Object executor, int depth, boolean requireVerified) { if (executor == null) { - return requireVerified; + // 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 (executor instanceof ForkJoinPool) { + if (cls == ForkJoinPool.class) { return false; } - String className = executor.getClass().getName(); + String className = cls.getName(); if (JDK_FINALIZABLE_DELEGATED.equals(className) || JDK_AUTO_SHUTDOWN_DELEGATED.equals(className) - || JDK_DELEGATED_SCHEDULED.equals(className)) { + || JDK_THREAD_PER_TASK.equals(className)) { return false; } - if (JDK_DELEGATED.equals(className)) { - return uncounted(executor, "its wrapped ExecutorService cannot be inspected for queue ordering"); + if (JDK_DELEGATED.equals(className) || JDK_DELEGATED_SCHEDULED.equals(className)) { + return readDelegated(executor, depth); } - Object pool = POOL.get(executor.getClass()); + Object pool = POOL.get(cls); if (pool != NONE) { return readViaPoolMethod(executor, pool, SPRING_POOL); } if (SPRING_SIMPLE_ASYNC.equals(className)) { return false; } - Object scheduled = SCHEDULED_POOL.get(executor.getClass()); + Object scheduled = SCHEDULED_POOL.get(cls); if (scheduled != NONE) { return readViaPoolMethod(executor, scheduled, SPRING_SCHEDULER); } - Object concurrent = CONCURRENT_EXECUTOR.get(executor.getClass()); + 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 delegate executor cannot be inspected for queue ordering"); + 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 { + 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 + ")"); @@ -268,9 +360,18 @@ private static boolean readViaConcurrentExecutor(Object executor, Object methodO 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) { - if (Boolean.TRUE.equals(OVERRIDES_TASK_HOOKS.get(pool.getClass()))) { - return uncounted(reportedOwner, "its pool (" + pool.getClass().getName() + 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 { @@ -286,9 +387,9 @@ private static boolean checkThreadPool(ThreadPoolExecutor pool, Object reportedO } return uncounted(reportedOwner, "its pool's rejected execution handler cannot be read (" + e + ")"); } - if (pool.getClass() == ScheduledThreadPoolExecutor.class + if (poolClass == ScheduledThreadPoolExecutor.class || (pool instanceof ScheduledThreadPoolExecutor - && pool.getClass().getName().startsWith(SPRING_SCHEDULER + "$"))) { + && poolClass.getName().startsWith(SPRING_SCHEDULER + "$"))) { // Exact ScheduledThreadPoolExecutor (and Spring's own // ThreadPoolTaskScheduler internal subclass) always wraps // execute/submit tasks in its own ScheduledFutureTask before @@ -305,13 +406,17 @@ private static boolean checkThreadPool(ThreadPoolExecutor pool, Object reportedO } 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; } - if (pool instanceof ScheduledThreadPoolExecutor) { - return uncounted(reportedOwner, "it is a ScheduledThreadPoolExecutor subclass (" - + pool.getClass().getName() + ") whose task handling cannot be assumed safe"); - } 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 deebf9a3..6b7c3d1b 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -3,25 +3,38 @@ 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.List; import java.util.Map; import java.util.Set; -import java.util.WeakHashMap; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; +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.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; /** @@ -29,73 +42,81 @@ * 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. - * - *

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) or to standard JDK executors/CompletableFuture - * from rewritten application classes counts as that request's until it is done: - * ServerEntries passes each task, and the executor it is for, to - * {@link #hand(Object, Runnable)}, {@link #hand(Object, Callable)}, or the - * static call-site helpers ({@link #execute}, {@link #submit}, - * {@link #runAsync}, {@link #supplyAsync}), 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, throws, is rejected, or is - * cancelled/timed out/drained before running. On a thread in a scheduled job's - * or message listener's run (JobGate), or in a task such a run handed off, the - * task counts as a run of that job while it runs (bounded by the original - * hand-off deadline), 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 tasks, - * override task/submission hooks, use a non-standard rejection handler, or - * delegate opaquely (OrderedPools), is not counted. - * - *

Note on pool queue visibility: {@link #submit} returns the executor's own - * {@link Future} untouched (preserving casts to {@code Runnable}, - * {@code ScheduledFuture}, {@code ListenableFuture}, etc.), tracking pending - * futures separately for cancellation, {@link #remove}, and - * {@link #shutdownNow}. {@link OrderedPools} skips pools with non-standard - * queues, custom rejection handlers, task-hook/{@code newTaskFor}/ - * {@code execute}/{@code submit} overrides, or opaque delegates, and rewritten - * {@link #remove}/{@link #shutdownNow} call sites unwrap queued wrappers. - * Callers that inspect {@code getQueue()} directly on a plain - * {@code ThreadPoolExecutor}, or unrewritten code calling {@code remove}/ - * {@code shutdownNow} on a pool fed by rewritten {@code execute(Runnable)} - * sites, may still observe {@code Handed}. + *

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.
  • + *
* *

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 { + /** Feature flag proving CompletableFuture dependent-stage tracking is active. */ + static final boolean CF_DEPENDENT_TRACKING_ENABLED = true; + + // 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); + // 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; // 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<>(); - // Weak associations from an executor's returned Future (e.g. FutureTask / - // ScheduledFutureTask) to its Hand, so remove((Runnable) future) releases - // its pending permit without wrapping the returned Future. - private static final Map PENDING_BY_FUTURE = new WeakHashMap<>(); - - // Weak associations from an Executor to weak tokens of its active Hand - // instances (stored in a ConcurrentHashMap-backed set whose tokens - // self-remove in O(1) on release, and dead tokens from cancelled/abandoned - // tasks are drained via DEAD_HANDS), so shutdownNow() releases every queued - // task's pending permit without retaining abandoned tasks or pinning pools. - private static final Map> PENDING_BY_EXECUTOR = new WeakHashMap<>(); + // 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() @@ -106,15 +127,82 @@ public final class RequestGate { // futures. private static final int FUTURE_SWEEP_STRIDE = 64; + // Reflective handles for Java 12+ CompletableFuture methods so keploy-sdk + // compiles against --release 8 (Java8ApiTest) while rewriting JDK 12+ apps. + private static final Method CF_EXCEPTIONALLY_ASYNC_1 = + findCfMethod("exceptionallyAsync", Function.class); + private static final Method CF_EXCEPTIONALLY_ASYNC_2 = + findCfMethod("exceptionallyAsync", Function.class, Executor.class); + private static final Method CF_EXCEPTIONALLY_COMPOSE_ASYNC_1 = + findCfMethod("exceptionallyComposeAsync", Function.class); + private static final Method CF_EXCEPTIONALLY_COMPOSE_ASYNC_2 = + findCfMethod("exceptionallyComposeAsync", Function.class, Executor.class); + private RequestGate() { } + private static Method findCfMethod(String name, Class... params) { + try { + return CompletableFuture.class.getMethod(name, params); + } catch (Throwable ignored) { + return null; + } + } + + static boolean isArmed() { + return armed; + } + + static void noteUnarmedActivity() { + if (!unarmedEntered) { + unarmedEntered = true; + } + } + + static void arm() { + if (!armed) { + if (unarmedEntered) { + pendingArmedMidFlight = true; + } + armed = true; + } + } + + static void disarm() { + armed = false; + unarmedEntered = false; + pendingArmedMidFlight = false; + ARMED_MID_FLIGHT_CONSUMED.set(false); + 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. + * No-op returning {@code null} when Keploy is unarmed. * * @return the token to pass to {@link #exit(Object)} when it is done */ public static Object enter() { + if (!armed) { + noteUnarmedActivity(); + return null; + } Window window = current; Window outer = INSIDE.get(); // A request in a request (a server's dispatch on the same thread) @@ -123,6 +211,7 @@ public static Object enter() { INSIDE.set(window); // Counted last: whatever failed before it (out of memory) leaves // nothing to undo. + window.enteredCount.incrementAndGet(); window.running.incrementAndGet(); return token; } @@ -134,6 +223,9 @@ public static Object enter() { * @param token what {@link #enter()} returned */ public static void exit(Object token) { + if (token == null) { + return; + } if (token instanceof Window) { INSIDE.remove(); done((Window) token); @@ -148,38 +240,58 @@ 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 (and unwraps an already-wrapped task if the inner executor is - * ordered/unsafe, releasing its pending window permit). + * 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 Comparable) { + return handInternal(executor, task, false); + } + + private static Runnable handInternal(Object executor, Runnable task, boolean deferRelease) { + if (!armed || task == null) { return task; } if (task instanceof Handed) { if (OrderedPools.orders(executor)) { Handed existing = (Handed) task; existing.releaseIfPending(); + if (existing.window != null && executor != null) { + existing.window.contaminate("untracked-executor:" + executor.getClass().getName()); + } return existing.task; } return task; } Window window = INSIDE.get(); JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; - if ((window == null && job == null) || OrderedPools.orders(executor)) { + if (window == null && job == null) { + return task; + } + if (task instanceof Comparable) { + if (window != null) { + window.contaminate("untracked-executor:" + + (executor != null ? executor.getClass().getName() : "comparable")); + } + return task; + } + if (OrderedPools.orders(executor)) { + if (window != null && executor != null) { + window.contaminate("untracked-executor:" + executor.getClass().getName()); + } 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); + Handed handed = task instanceof Future + ? new HandedFuture(window, job, task, deferRelease && window != null) + : new Handed(window, job, task, deferRelease && window != null); // Counted last, as enter() counts: a failed allocation (out of // memory) leaves nothing counted that no task would release. if (window != null) { @@ -198,7 +310,7 @@ 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 Comparable) { + if (!armed || task == null) { return task; } if (task instanceof HandedCall) { @@ -206,13 +318,29 @@ public static Callable hand(Object executor, Callable task) { @SuppressWarnings("unchecked") HandedCall existing = (HandedCall) task; existing.releaseIfPending(); + if (existing.window != null && executor != null) { + existing.window.contaminate("untracked-executor:" + executor.getClass().getName()); + } return existing.task; } return task; } Window window = INSIDE.get(); JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; - if ((window == null && job == null) || OrderedPools.orders(executor)) { + if (window == null && job == null) { + return task; + } + if (task instanceof Comparable) { + if (window != null) { + window.contaminate("untracked-executor:" + + (executor != null ? executor.getClass().getName() : "comparable")); + } + return task; + } + if (OrderedPools.orders(executor)) { + if (window != null && executor != null) { + window.contaminate("untracked-executor:" + executor.getClass().getName()); + } return task; } HandedCall handed = new HandedCall<>(window, job, task); @@ -224,7 +352,8 @@ public static Callable hand(Object executor, Callable task) { /** * Counts a {@link Supplier} handed to {@link CompletableFuture#supplyAsync} - * on a request or job thread until it completes. + * on a request or job thread until it (and its synchronous dependents) + * complete. * * @param executor the executor the supplier is for, or null * @param supplier the supplier handed off @@ -232,7 +361,11 @@ public static Callable hand(Object executor, Callable task) { * @return what runs instead */ public static Supplier handSupplier(Object executor, Supplier supplier) { - if (supplier == null || supplier instanceof Comparable) { + return handSupplierInternal(executor, supplier, true); + } + + private static Supplier handSupplierInternal(Object executor, Supplier supplier, boolean deferRelease) { + if (!armed || supplier == null) { return supplier; } if (supplier instanceof HandedSupplier) { @@ -240,16 +373,32 @@ public static Supplier handSupplier(Object executor, Supplier supplier @SuppressWarnings("unchecked") HandedSupplier existing = (HandedSupplier) supplier; existing.releaseIfPending(); + if (existing.window != null && executor != null) { + existing.window.contaminate("untracked-executor:" + executor.getClass().getName()); + } return existing.task; } return supplier; } Window window = INSIDE.get(); JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; - if ((window == null && job == null) || OrderedPools.orders(executor)) { + if (window == null && job == null) { + return supplier; + } + if (supplier instanceof Comparable) { + if (window != null) { + window.contaminate("untracked-executor:" + + (executor != null ? executor.getClass().getName() : "comparable")); + } return supplier; } - HandedSupplier handed = new HandedSupplier<>(window, job, supplier); + if (OrderedPools.orders(executor)) { + if (window != null && executor != null) { + window.contaminate("untracked-executor:" + executor.getClass().getName()); + } + return supplier; + } + HandedSupplier handed = new HandedSupplier<>(window, job, supplier, deferRelease && window != null); if (window != null) { window.running.incrementAndGet(); } @@ -258,13 +407,16 @@ public static Supplier handSupplier(Object executor, Supplier supplier /** * Call-site wrapper for {@link Executor#execute(Runnable)}: propagates the - * current request window (or job run) across standard JDK executors whose - * classes live in the bootstrap loader. + * 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) { + executor.execute(task); + return; + } Runnable handed = hand(executor, task); registerForExecutor(executor, handed, task); try { @@ -283,6 +435,9 @@ public static void execute(Executor executor, Runnable task) { * @return the executor's own future */ public static Future submit(ExecutorService executor, Runnable task) { + if (!armed) { + return executor.submit(task); + } Runnable handed = hand(executor, task); registerForExecutor(executor, handed, task); Future future; @@ -306,6 +461,9 @@ public static Future submit(ExecutorService executor, Runnable task) { * @return the executor's own future */ public static Future submit(ExecutorService executor, Runnable task, T result) { + if (!armed) { + return executor.submit(task, result); + } Runnable handed = hand(executor, task); registerForExecutor(executor, handed, task); Future future; @@ -328,6 +486,9 @@ public static Future submit(ExecutorService executor, Runnable task, T re * @return the executor's own future */ public static Future submit(ExecutorService executor, Callable task) { + if (!armed) { + return executor.submit(task); + } Callable handed = hand(executor, task); registerForExecutor(executor, handed, task); Future future; @@ -337,90 +498,761 @@ public static Future submit(ExecutorService executor, Callable task) { dropped(handed, task); throw t; } - trackSubmitted(future, handed, task); - return future; + 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) { + 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) { + 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) { + 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) { + 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 *Async instance method call-site wrappers --- + + private static Hand prepareCfStageHand(CompletableFuture receiver, Executor explicitExecutor, boolean hasExecutor) { + if (!armed) { + return null; + } + Window window = INSIDE.get(); + JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; + if (window == null && job == null) { + return null; + } + if (hasExecutor) { + if (explicitExecutor == null) { + return null; + } + if (OrderedPools.orders(explicitExecutor)) { + if (window != null) { + window.contaminate("untracked-executor:" + explicitExecutor.getClass().getName()); + } + return null; + } + } else { + // Default executor: safe only for exact CompletableFuture.class + // (a custom subclass could override defaultExecutor()). + if (receiver != null && receiver.getClass() != CompletableFuture.class) { + if (window != null) { + window.contaminate("untracked-executor:" + receiver.getClass().getName()); + } + return null; + } + } + StageHand hand = new StageHand(window, job, window != null); + if (window != null) { + window.running.incrementAndGet(); + } + if (hasExecutor && explicitExecutor != null) { + registerForExecutor(explicitExecutor, hand, null); + } + return hand; + } + + private static CompletableFuture finishCfStage(CompletableFuture out, Hand hand) { + if (hand != null) { + attachCompletionRelease(out, hand, null); + } + return out; + } + + 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); + } + } + }; + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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 {@link CompletableFuture#runAsync(Runnable)}. - * - * @param task runnable to execute asynchronously - * @return the created CompletableFuture - */ - public static CompletableFuture runAsync(Runnable task) { - Runnable handed = hand(null, task); - CompletableFuture cf; + @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 { - cf = CompletableFuture.runAsync(handed); + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_ASYNC_1, cf, target); } catch (Throwable t) { - dropped(handed, task); - throw t; + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); } - attachCompletionRelease(cf, handed, task); - return cf; + return finishCfStage(out, hand); } - /** - * 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) { - Runnable handed = hand(executor, task); - registerForExecutor(executor, handed, task); - CompletableFuture cf; + @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 { - cf = CompletableFuture.runAsync(handed, executor); + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_ASYNC_2, cf, target, executor); } catch (Throwable t) { - dropped(handed, task); - throw t; + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); } - attachCompletionRelease(cf, handed, task); - return cf; + return finishCfStage(out, hand); } - /** - * 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) { - Supplier handed = handSupplier(null, supplier); - CompletableFuture cf; + @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 { - cf = CompletableFuture.supplyAsync(handed); + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE_ASYNC_1, cf, target); } catch (Throwable t) { - dropped(handed, supplier); - throw t; + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); } - attachCompletionRelease(cf, handed, supplier); - return cf; + return finishCfStage(out, hand); } - /** - * 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) { - Supplier handed = handSupplier(executor, supplier); - registerForExecutor(executor, handed, supplier); - CompletableFuture cf; + @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 { - cf = CompletableFuture.supplyAsync(handed, executor); + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE_ASYNC_2, cf, target, executor); } catch (Throwable t) { - dropped(handed, supplier); - throw t; + if (hand != null) { + hand.releaseIfPending(); + } + throw sneakyThrow(t); } - attachCompletionRelease(cf, handed, supplier); - return cf; + return finishCfStage(out, hand); + } + + private static Object invokeCfReflect(Method method, Object target, Object... args) throws Throwable { + if (method == null) { + throw new NoSuchMethodError("CompletableFuture async 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 --- + + private static void contaminateIfInRequest(String reason) { + if (!armed) { + return; + } + Window window = INSIDE.get(); + if (window != null) { + window.contaminate(reason); + } + } + + public static ScheduledFuture schedule(ScheduledExecutorService executor, Runnable command, + long delay, TimeUnit unit) { + contaminateIfInRequest("untracked-async:schedule"); + return executor.schedule(command, delay, unit); + } + + public static ScheduledFuture schedule(ScheduledExecutorService executor, Callable callable, + long delay, TimeUnit unit) { + contaminateIfInRequest("untracked-async:schedule"); + return executor.schedule(callable, delay, unit); + } + + public static ScheduledFuture scheduleAtFixedRate(ScheduledExecutorService executor, Runnable command, + long initialDelay, long period, TimeUnit unit) { + contaminateIfInRequest("untracked-async:schedule"); + return executor.scheduleAtFixedRate(command, initialDelay, period, unit); + } + + public static ScheduledFuture scheduleWithFixedDelay(ScheduledExecutorService executor, Runnable command, + long initialDelay, long delay, TimeUnit unit) { + contaminateIfInRequest("untracked-async:schedule"); + return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); + } + + public static T invokeAny(ExecutorService executor, Collection> tasks) + throws InterruptedException, ExecutionException { + contaminateIfInRequest("untracked-async:invokeAny"); + return executor.invokeAny(tasks); + } + + public static T invokeAny(ExecutorService executor, Collection> tasks, + long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + contaminateIfInRequest("untracked-async:invokeAny"); + return executor.invokeAny(tasks, timeout, unit); + } + + public static void startThread(Thread thread) { + contaminateIfInRequest("untracked-async:thread-start"); + thread.start(); } /** @@ -428,7 +1260,8 @@ public static CompletableFuture supplyAsync(Supplier supplier, Executo * 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. + * 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 @@ -442,7 +1275,7 @@ public static boolean remove(ThreadPoolExecutor executor, Runnable task) { } return true; } - if (task == null) { + if (task == null || !hasPendingForExecutor(executor)) { return false; } for (Runnable queued : executor.getQueue()) { @@ -459,11 +1292,9 @@ public static boolean remove(ThreadPoolExecutor executor, Runnable task) { /** * Call-site wrapper for {@link ExecutorService#shutdownNow()}: releases - * pending window permits for all queued tasks of {@code executor} (both - * direct {@code execute} wrappers and {@code FutureTask}/ - * {@code ScheduledFutureTask}-wrapped submissions) and unwraps any - * {@link Handed} items in the returned list so callers casting them never - * see {@link Handed}. + * 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 @@ -497,12 +1328,36 @@ public static List shutdownNow(ExecutorService executor) { private static void drainDeadHands() { for (Reference ref; (ref = DEAD_HANDS.poll()) != null; ) { HandRef hr = (HandRef) ref; - hr.set.remove(hr); + 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; } @@ -511,39 +1366,34 @@ private static void registerForExecutor(Executor executor, Object handed, Object return; } try { - Set set; - synchronized (PENDING_BY_EXECUTOR) { - set = PENDING_BY_EXECUTOR.get(executor); - if (set == null) { - set = ConcurrentHashMap.newKeySet(); - PENDING_BY_EXECUTOR.put(executor, set); - } + 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); + 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 let a broken Executor.hashCode/equals affect app execution. + // Never affect app execution. } } private static void releaseAllPendingForExecutor(Executor executor) { drainDeadHands(); + drainDeadExecutorKeys(); if (executor == null) { return; } - Set set; - try { - synchronized (PENDING_BY_EXECUTOR) { - set = PENDING_BY_EXECUTOR.remove(executor); - } - } catch (Throwable ignored) { - return; - } + Set set = PENDING_BY_EXECUTOR.remove(new LookupKey(executor)); if (set == null) { return; } @@ -551,6 +1401,9 @@ private static void releaseAllPendingForExecutor(Executor executor) { Hand hand = ref.get(); if (hand != null) { hand.releaseIfPending(); + } else if (set.remove(ref) && !ref.released) { + ref.released = true; + done(ref.window); } } set.clear(); @@ -585,11 +1438,12 @@ private static boolean isFutureTerminated(Future future) { } 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.isReleased()) { + if (hand.window == null || hand.isStartedOrReleased()) { return; } if (isFutureTerminated(future)) { @@ -597,36 +1451,35 @@ private static void trackSubmitted(Future future, Object handed, Object task) return; } hand.window.track(hand, future); - if (hand.isReleased()) { + if (hand.isStartedOrReleased()) { hand.window.untrack(hand); return; } - try { - synchronized (PENDING_BY_FUTURE) { - PENDING_BY_FUTURE.put(future, hand); - } - } catch (Throwable ignored) { - // Never let a custom Future.hashCode/equals affect app execution. + 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) { - if (key == null) { - return null; - } - try { - synchronized (PENDING_BY_FUTURE) { - return PENDING_BY_FUTURE.remove(key); - } - } catch (Throwable ignored) { + 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; - cf.whenComplete((result, error) -> hand.releaseIfPending()); + try { + cf.whenComplete((result, error) -> hand.onFutureCompleted()); + } catch (Throwable t) { + hand.onFutureCompleted(); + } } } @@ -657,28 +1510,96 @@ private static void done(Window window) { // 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(); + open(null, null); + } + + // open(testId, prevActiveTestId) opens a fresh test window, records + // armed-mid-flight if unarmed traffic occurred prior to arming, and marks + // the new window contaminated ("tail:") if the previous test + // was cut, unclosed, or any prior window still has running > 0. + static void open(String testId, String prevActiveTestId) { + arm(); + drainDeadHands(); + Window prev = current; + Window next = new Window(testId); + if ((pendingArmedMidFlight || unarmedEntered) + && ARMED_MID_FLIGHT_CONSUMED.compareAndSet(false, true)) { + pendingArmedMidFlight = false; + next.contaminate("armed-mid-flight"); + } + if (prev != null) { + prev.sweepCancelledFutures(); + if (prev.running.get() > 0) { + if (prev.testId == null && prevActiveTestId != null && !prevActiveTestId.isEmpty()) { + prev.fallbackId = prevActiveTestId; + } + retainLingering(prev); + } + } + if (prevActiveTestId != null && !prevActiveTestId.isEmpty()) { + next.contaminate("tail:" + prevActiveTestId); + } + for (Window lingering : LINGERING) { + lingering.sweepCancelledFutures(); + boolean stillRunning = lingering.running.get() > 0; + boolean reportCut = lingering.wasCut && !lingering.cutReportedOnce; + if (stillRunning || reportCut) { + next.contaminate("tail:" + lingering.label()); + lingering.cutReportedOnce = true; + } + if (!stillRunning) { + LINGERING.remove(lingering); + } + } + current = next; + } + + private static void retainLingering(Window window) { + if (LINGERING.size() >= MAX_LINGERING) { + for (Window existing : LINGERING) { + existing.sweepCancelledFutures(); + if (existing.running.get() <= 0 && (!existing.wasCut || existing.cutReportedOnce)) { + LINGERING.remove(existing); + } + } + } + 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. 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). + // runs, for at most timeoutNanos, and says whether none runs. static boolean await(long timeoutNanos) { + return awaitWindow(timeoutNanos, true).drained; + } + + // awaitWindow closes the current window, optionally waits up to + // timeoutNanos for its requests/tasks to finish, retains the window in + // LINGERING if cut or still running, and returns its outcome (drained, + // waited, enteredCount, and accumulated contaminations). + static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { + drainDeadHands(); Window window = current; - current = new Window(); + current = new Window(null); window.sweepCancelledFutures(); - if (window.running.get() <= 0) { - return true; + int initialRunning = window.running.get(); + if (!wait) { + if (initialRunning > 0) { + retainLingering(window); + } + return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations()); + } + if (initialRunning <= 0) { + return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations()); } + 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. @@ -686,46 +1607,125 @@ static boolean await(long timeoutNanos) { try { long deadline = System.nanoTime() + timeoutNanos; while (window.running.get() > 0) { + drainDeadHands(); window.sweepCancelledFutures(); if (window.running.get() <= 0) { - return true; + drained = true; + break; } long left = deadline - System.nanoTime(); if (left <= 0 || Thread.currentThread().isInterrupted()) { - return false; + drained = false; + break; } long waitNanos = window.hasPendingFutures() ? Math.min(left, FUTURE_SWEEP_INTERVAL_NANOS) : left; LockSupport.parkNanos(RequestGate.class, waitNanos); } - return true; + if (window.running.get() <= 0) { + drained = true; + } } finally { window.waiter = null; } + if (!drained) { + window.wasCut = true; + retainLingering(window); + } + return new WindowOutcome(drained, true, window.enteredCount.get(), window.contaminations()); + } + + static final class WindowOutcome { + final boolean drained; + final boolean waited; + final int enteredCount; + final List contaminations; + + WindowOutcome(boolean drained, boolean waited, int enteredCount, List contaminations) { + this.drained = drained; + this.waited = waited; + this.enteredCount = enteredCount; + this.contaminations = contaminations; + } } private static final class Window { + private static final AtomicReferenceFieldUpdater FUTURES_UPDATER = + AtomicReferenceFieldUpdater.newUpdater(Window.class, ConcurrentHashMap.class, "futures"); + + private final String testId; + private volatile String fallbackId; private final AtomicInteger running = new AtomicInteger(); + private final AtomicInteger enteredCount = new AtomicInteger(); private volatile Thread waiter; + private volatile boolean wasCut; + private volatile boolean cutReportedOnce; // 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). - private volatile ConcurrentHashMap>> futures; + @SuppressWarnings("rawtypes") + private volatile ConcurrentHashMap futures; 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 void track(Hand hand, Future future) { - ConcurrentHashMap>> map = futures; - if (map == null) { - synchronized (this) { - map = futures; - if (map == null) { - map = new ConcurrentHashMap<>(); - futures = map; - } + 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 contaminate(String reason) { + if (reason == null || reason.isEmpty()) { + return; + } + if (contamCount.get() < JobGate.KEPT && contamSet.add(reason)) { + if (contamCount.incrementAndGet() <= JobGate.KEPT) { + contamOrder.add(reason); + } else { + contamSet.remove(reason); + contamCount.decrementAndGet(); } } + } + + 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); @@ -734,19 +1734,19 @@ private void track(Hand hand, Future future) { } private void untrack(Hand hand) { - ConcurrentHashMap>> map = futures; + ConcurrentHashMap>> map = futuresMap(false); if (map != null) { map.remove(hand); } } private boolean hasPendingFutures() { - ConcurrentHashMap>> map = futures; + ConcurrentHashMap>> map = futuresMap(false); return map != null && !map.isEmpty(); } private void sweepCancelledFutures() { - ConcurrentHashMap>> map = futures; + ConcurrentHashMap>> map = futuresMap(false); if (map == null || map.isEmpty()) { return; } @@ -778,27 +1778,93 @@ private Nested(Window window, Window outer) { } } + 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) { + 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: done once, when it - // returns or throws, when the executor did not take it, or when it is - // cancelled/timed out/removed/drained while still pending. Or, with no - // window, a task a job's run handed off: a run of that job while it - // runs (bounded by its carried deadline), and nothing to count done when - // the executor did not take it. + // 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 int STATE_PENDING = 0; - private static final int STATE_RUNNING = 1; - private static final int STATE_DONE = 2; + 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"); @@ -807,33 +1873,93 @@ private abstract static class Hand { final Window window; // The job attribution whose run handed it off, when window is null. final JobGate.Attribution job; - // Weak token in per-executor tracking set for O(1) self-removal on release. + // 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; private volatile int state; - Hand(Window window, JobGate.Attribution job) { + Hand(Window window, JobGate.Attribution job, boolean deferRelease) { this.window = window; this.job = job; + this.deferRelease = deferRelease; } final boolean isReleased() { - return state == STATE_DONE; + 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() { + clearFutureKey(); window.untrack(this); HandRef ref = executorRef; if (ref != null) { + ref.released = true; executorRef = null; ref.set.remove(ref); } done(window); } - // release marks this task done unconditionally (on exit). + // release marks this task done unconditionally (non-deferred exit). final void release() { - if (window != null && STATE.getAndSet(this, STATE_DONE) != STATE_DONE) { - finishRelease(); + if (window == 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) { + 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; + } } } @@ -842,20 +1968,35 @@ final void release() { // 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 && STATE.compareAndSet(this, STATE_PENDING, STATE_DONE)) { - finishRelease(); + if (window == 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 (preserving the original deadline), and returns its token. final Object enter() { if (window == null) { return JobGate.enterAs(job); } - STATE.compareAndSet(this, STATE_PENDING, STATE_RUNNING); + for (;;) { + int s = state; + if ((s & FLAG_STARTED) != 0) { + break; + } + if (STATE.compareAndSet(this, s, s | FLAG_STARTED)) { + break; + } + } + clearFutureKey(); Window outer = INSIDE.get(); INSIDE.set(window); return outer; @@ -871,7 +2012,33 @@ final void exit(Object outer) { } 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; + } + } + } + } + + private static final class StageHand extends Hand { + StageHand(Window window, JobGate.Attribution job, boolean deferRelease) { + super(window, job, deferRelease); } } @@ -879,8 +2046,8 @@ private static class Handed extends Hand implements Runnable { final Runnable task; - Handed(Window window, JobGate.Attribution job, Runnable task) { - super(window, job); + Handed(Window window, JobGate.Attribution job, Runnable task, boolean deferRelease) { + super(window, job, deferRelease); this.task = task; } @@ -902,8 +2069,8 @@ public String toString() { private static final class HandedFuture extends Handed implements RunnableFuture { - HandedFuture(Window window, JobGate.Attribution job, Runnable task) { - super(window, job, task); + HandedFuture(Window window, JobGate.Attribution job, Runnable task, boolean deferRelease) { + super(window, job, task, deferRelease); } @SuppressWarnings("unchecked") @@ -943,7 +2110,7 @@ private static final class HandedCall extends Hand implements Callable { final Callable task; HandedCall(Window window, JobGate.Attribution job, Callable task) { - super(window, job); + super(window, job, false); this.task = task; } @@ -967,8 +2134,8 @@ private static final class HandedSupplier extends Hand implements Supplier final Supplier task; - HandedSupplier(Window window, JobGate.Attribution job, Supplier task) { - super(window, job); + HandedSupplier(Window window, JobGate.Attribution job, Supplier task, boolean deferRelease) { + super(window, job, deferRelease); this.task = 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 ec6ae979..b97715d9 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -28,61 +28,18 @@ 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 or message listener count in - * {@link JobGate} the same way: Quartz's {@code JobRunShell.run()}, Spring's - * {@code ScheduledMethodRunnable.run()} (each {@code @Scheduled} method), - * Spring Kafka's {@code ListenerConsumer}, and Spring AMQP/JMS's - * {@code AbstractMessageListenerContainer.doInvokeListener} become methods - * that call {@link JobGate#enter(Object, String)}, then their own code, - * renamed {@code keploy$job$}, then {@link JobGate#exit(Object)}, so - * that a test whose window one 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, ThreadPoolTaskScheduler, ConcurrentTaskExecutor 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). - * - *

For the application's own indexed classes (strictly allow-listed from - * {@link AppClasses} / {@code CoverageIndex} so third-party libraries such as - * Netty or OkHttp are never touched), it also rewrites standard JDK executor - * and {@code CompletableFuture} call sites ({@code execute}, {@code submit}, - * {@code runAsync}, {@code supplyAsync}, {@code remove}, {@code shutdownNow}) - * to {@link RequestGate}'s identically-stacked static helpers after a fast - * constant-pool pre-check, and preserves those rewrites across retransforms. + * 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 { @@ -134,14 +91,7 @@ final class ServerEntries implements ClassFileTransformer { "listener", "doInvokeListener"); addJob("JMS", "org/springframework/jms/listener/AbstractMessageListenerContainer", "listener", "doInvokeListener"); - // 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. + // Spring's executors a request hands work to. addAsync("org/springframework/core/task/SimpleAsyncTaskExecutor", "doExecute"); addAsync("org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor", "execute", "submit", "submitListenable"); @@ -152,7 +102,8 @@ final class ServerEntries implements ClassFileTransformer { 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 { @@ -162,6 +113,10 @@ final class ServerEntries implements ClassFileTransformer { private static final Set COUNTED = new CopyOnWriteArraySet<>(); private static final Set SEEN_UNCOUNTED = new CopyOnWriteArraySet<>(); + private static volatile boolean serverHookFailed; + private static volatile boolean listenerHookFailed; + private static volatile boolean jpmsGuardTriggered; + // 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<>(); @@ -181,7 +136,42 @@ final class ServerEntries implements ClassFileTransformer { "java/util/concurrent/ThreadPoolExecutor", "java/util/concurrent/ScheduledThreadPoolExecutor", "java/util/concurrent/ForkJoinPool", - "java/util/concurrent/CompletableFuture"))); + "java/util/concurrent/CompletableFuture", + "java/lang/Thread"))); + + // CompletableFuture *Async instance methods rewritten to RequestGate. + private static final Map> CF_ASYNC_INSTANCE_METHODS = buildCfAsyncMethods(); + + private static Map> buildCfAsyncMethods() { + Map> m = new HashMap<>(); + String cf = "Ljava/util/concurrent/CompletableFuture;"; + 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 + ")" + cf, "(" + fn + ex + ")" + cf)); + m.put("thenAcceptAsync", setOf("(" + cons + ")" + cf, "(" + cons + ex + ")" + cf)); + m.put("thenRunAsync", setOf("(" + run + ")" + cf, "(" + run + ex + ")" + cf)); + m.put("thenComposeAsync", setOf("(" + fn + ")" + cf, "(" + fn + ex + ")" + cf)); + m.put("thenCombineAsync", setOf("(" + cs + bifn + ")" + cf, "(" + cs + bifn + ex + ")" + cf)); + m.put("thenAcceptBothAsync", setOf("(" + cs + bicons + ")" + cf, "(" + cs + bicons + ex + ")" + cf)); + m.put("runAfterBothAsync", setOf("(" + cs + run + ")" + cf, "(" + cs + run + ex + ")" + cf)); + m.put("applyToEitherAsync", setOf("(" + cs + fn + ")" + cf, "(" + cs + fn + ex + ")" + cf)); + m.put("acceptEitherAsync", setOf("(" + cs + cons + ")" + cf, "(" + cs + cons + ex + ")" + cf)); + m.put("runAfterEitherAsync", setOf("(" + cs + run + ")" + cf, "(" + cs + run + ex + ")" + cf)); + m.put("handleAsync", setOf("(" + bifn + ")" + cf, "(" + bifn + ex + ")" + cf)); + m.put("whenCompleteAsync", setOf("(" + bicons + ")" + cf, "(" + bicons + ex + ")" + cf)); + m.put("exceptionallyAsync", setOf("(" + fn + ")" + cf, "(" + fn + ex + ")" + cf)); + m.put("exceptionallyComposeAsync", setOf("(" + fn + ")" + cf, "(" + fn + ex + ")" + cf)); + 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. @@ -244,7 +234,27 @@ static boolean countsNone() { return COUNTED.isEmpty(); } - // Snapshot/restore helpers for unit tests exercising dynamic HELLO flags. + static boolean hasUncountedServer() { + return !SEEN_UNCOUNTED.isEmpty(); + } + + static boolean hadServerHookFailure() { + return serverHookFailed; + } + + static boolean hadListenerHookFailure() { + return listenerHookFailed; + } + + static boolean wasJpmsGuardTriggered() { + return jpmsGuardTriggered; + } + + static void markJpmsGuardTriggered() { + jpmsGuardTriggered = true; + } + + // Snapshot/restore helpers for unit tests exercising dynamic HELLO/caps flags. static Set snapshotCounted() { return new HashSet<>(COUNTED); } @@ -256,6 +266,23 @@ static void restoreCounted(Set 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 void setHookStatusForTests(boolean serverFailed, boolean listenerFailed, boolean jpmsSkipped) { + serverHookFailed = serverFailed; + listenerHookFailed = listenerFailed; + jpmsGuardTriggered = jpmsSkipped; + } + // uncounted names the servers whose requests do not count that the app // loaded, as Netty. static List uncounted() { @@ -274,7 +301,13 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (uncounted != null) { SEEN_UNCOUNTED.add(uncounted); } - if (shouldRewriteExecutorCalls(className) && canAccessGate(loader, protectionDomain)) { + if (shouldRewriteExecutorCalls(className)) { + if (!canAccessGate(loader, protectionDomain)) { + if (seesGate(loader)) { + jpmsGuardTriggered = true; + } + return null; + } try { byte[] updated = wrapExecutorCalls(classfileBuffer); if (updated != null) { @@ -302,6 +335,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; @@ -311,6 +345,7 @@ 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; @@ -331,12 +366,21 @@ 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; } } + 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); @@ -358,16 +402,6 @@ private boolean wasRewritten(ClassLoader loader, String className) { } } - // 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. Application classes whose executor call sites were rewritten on - // load also get their call sites re-applied so another agent's - // retransform does not silently undo them. Any other class is left as it - // is: it was loaded unchanged, and the JVM refuses a method added to it. private byte[] changedAgain(ClassLoader loader, String className, byte[] classfile) { Entry entry = ENTRIES.get(className); if (entry == null) { @@ -406,11 +440,6 @@ 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. Cached per loader to avoid repeated Class.forName - // lookups and ClassNotFoundExceptions on startup. private static boolean seesGate(ClassLoader loader) { // The bootstrap loader (null) does not see keploy-sdk.jar. if (loader == null) { @@ -439,8 +468,6 @@ 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) { @@ -456,9 +483,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); } @@ -467,12 +491,6 @@ private static byte[] wrap(byte[] classfile, Entry entry) { return wrap(classfile, entry.methods, entry.job, entry.async); } - // shouldRewriteExecutorCalls strictly allow-lists indexed application - // classes (or, when external JaCoCo defers index loading, the lightweight - // app package prefix from AppClasses) plus a belt-and-suspenders filter - // against JDK, agent, server, and library internals so third-party - // long-lived threads (Netty event loops, OkHttp TaskRunner, Lettuce, gRPC, - // AWS SDK, etc.) are never rewritten. boolean shouldRewriteExecutorCalls(String className) { if (className == null || !isRewriteAllowedPackage(className)) { return false; @@ -483,10 +501,6 @@ boolean shouldRewriteExecutorCalls(String className) { return appPackagePrefix != null && className.startsWith(appPackagePrefix); } - // canAccessGate checks both class-loader visibility and (on Java 9+) that - // the class does not live in a named module that cannot read RequestGate's - // unnamed module (which would otherwise throw IllegalAccessError on - // rewritten call sites when KEPLOY_JAVA_CLASS_DIRS overrides indexing). static boolean canAccessGate(ClassLoader loader, ProtectionDomain protectionDomain) { if (!seesGate(loader)) { return false; @@ -511,6 +525,22 @@ 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; @@ -580,12 +610,25 @@ private static Set findUnreadableModuleLocations() { } } - // Belt-and-suspenders guard in case KEPLOY_JAVA_CLASS_DIRS includes - // framework/library classes or a shaded uber-jar; note org/apache/ is NOT - // blanket-excluded so Apache-hosted applications (e.g. + static boolean isShadedOrRelocated(String className) { + return className.contains("/shaded/") + || className.contains("/relocated/") + || className.contains("/shadow/") + || className.contains("/repackaged/") + || className.contains("/thirdparty/") + || className.contains("/third_party/") + || className.contains("/vendor/") + || className.startsWith("shaded/") + || className.startsWith("relocated/"); + } + + // Belt-and-suspenders guard in case KEPLOY_JAVA_CLASS_DIRS or + // appPackagePrefix includes framework/library/shaded classes; note + // org/apache/ is NOT blanket-excluded so Apache-hosted applications (e.g. // org/apache/fineract/) remain eligible. static boolean isRewriteAllowedPackage(String className) { return className != null + && !isShadedOrRelocated(className) && !className.startsWith("java/") && !className.startsWith("javax/") && !className.startsWith("sun/") @@ -648,16 +691,11 @@ static boolean hasExecutorReference(ClassReader reader) { return false; } - // wrapExecutorCalls redirects standard JDK executor hand-off call sites - // (Executor/ExecutorService/ScheduledExecutorService.execute, - // ExecutorService/ScheduledExecutorService/AbstractExecutorService/ - // ThreadPoolExecutor/ScheduledThreadPoolExecutor.submit, - // ThreadPoolExecutor/ScheduledThreadPoolExecutor/ForkJoinPool.execute, - // CompletableFuture.runAsync/supplyAsync, ThreadPoolExecutor.remove, and - // ExecutorService.shutdownNow) to RequestGate's identically-stacked static - // helpers so async tails count in the request's (or job's) window without - // touching bootstrap JDK classes. Returns null when the class contains no - // matching call sites. + // wrapExecutorCalls redirects standard JDK executor hand-off call sites, + // CompletableFuture.runAsync/supplyAsync and *Async instance stages, + // remove/shutdownNow, and untracked async sites (schedule*, invokeAny, + // Thread.start) to RequestGate's identically-stacked 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) { @@ -707,7 +745,8 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, || (opcode == Opcodes.INVOKEVIRTUAL && ("java/util/concurrent/AbstractExecutorService".equals(owner) || "java/util/concurrent/ThreadPoolExecutor".equals(owner) - || "java/util/concurrent/ScheduledThreadPoolExecutor".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; @@ -735,6 +774,34 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, 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) @@ -779,6 +846,25 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, return; } } + if (opcode == Opcodes.INVOKEVIRTUAL + && "java/util/concurrent/CompletableFuture".equals(owner)) { + 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; + } + } + 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; + } super.visitMethodInsn(opcode, owner, mname, desc, isInterface); } }; @@ -787,10 +873,6 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, return changed[0] ? writer.toByteArray() : null; } - // 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. static byte[] wrap(byte[] classfile, Set methods, String job, boolean async) { ClassReader reader = new ClassReader(classfile); ClassWriter writer = new ClassWriter(reader, 0); @@ -801,11 +883,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; @@ -816,12 +895,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"; @@ -832,7 +909,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" @@ -842,10 +918,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 @@ -895,9 +967,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++) { @@ -909,8 +978,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); @@ -944,7 +1011,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 { @@ -984,8 +1050,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)) { @@ -995,11 +1059,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; @@ -1062,8 +1121,6 @@ private void handing(Method method) { renamedPrefix + method.name, method.descriptor, false); mv.visitLabel(end); if (returns.getSort() == Type.OBJECT) { - // Track returned Future / CompletableFuture so cancellation - // before the task starts releases the request window permit. mv.visitInsn(Opcodes.DUP); mv.visitVarInsn(Opcodes.ALOAD, handed); mv.visitVarInsn(Opcodes.ALOAD, taskSlot); @@ -1086,12 +1143,10 @@ private void handing(Method method) { 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 3caee801..399e8ff9 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 06fce5fd..a48e02c7 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 " 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 f6bf530e..53cb9d6e 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ControlSocketTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ControlSocketTest.java @@ -65,8 +65,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,asyncExecutors=false,listenerContamination=false\n"; + private static final String IGNORED = "IGNORED proto=3\n"; private String savedControlPath; private String savedDataPath; @@ -114,6 +116,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 +143,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 +214,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 +400,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/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java new file mode 100644 index 00000000..cb613eb0 --- /dev/null +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -0,0 +1,570 @@ +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 proving Ruling #3 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. Reproduce plg-87's exact bug: 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); + app.runHttpTest("ts/drain-after-cf", "/clean"); + + // 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 forkedUnknownSerializableExecutorIsUnwrappedAndContaminatesCov() throws Exception { + try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { + // 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() + "\"]")); + } + } + + @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): probes execute while enteredCount == 0 -> 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 fail closed with no-server-entry: " + cov, + cov.contains("\"contaminated\":[\"no-server-entry\"]")); + } + } + + @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.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; + + 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; + } + + 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 ")) { + 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 index 794b38d0..8a42da6f 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -7,12 +7,16 @@ 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; @@ -31,6 +35,7 @@ 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; @@ -62,6 +67,8 @@ 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; @@ -87,6 +94,10 @@ public class HonestProtocolAndAsyncTest { 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(); @@ -97,14 +108,23 @@ public class HonestProtocolAndAsyncTest { private boolean savedTransformerAdded; private boolean savedExecutorCallSitesEnabled; 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; savedCounted = ServerEntries.snapshotCounted(); + savedUncounted = ServerEntries.snapshotUncounted(); savedHandedJobMaxNanos = JobGate.handedJobMaxNanos; + savedControlSocketPath = KeployDedupAgent.controlSocketPath; + savedDataSocketPath = KeployDedupAgent.dataSocketPath; + ServerEntries.restoreUncounted(Collections.emptySet()); + ServerEntries.setHookStatusForTests(false, false, false); + RequestGate.disarm(); RequestGate.open(); JobGate.close(); } @@ -119,13 +139,21 @@ public void tearDown() throws IOException { KeployDedupAgent.transformerAdded = savedTransformerAdded; KeployDedupAgent.executorCallSitesEnabled = savedExecutorCallSitesEnabled; ServerEntries.restoreCounted(savedCounted); + ServerEntries.restoreUncounted(savedUncounted); + ServerEntries.setHookStatusForTests(false, false, false); JobGate.handedJobMaxNanos = savedHandedJobMaxNanos; + KeployDedupAgent.controlSocketPath = savedControlSocketPath; + KeployDedupAgent.dataSocketPath = savedDataSocketPath; 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; @@ -135,76 +163,127 @@ public void tearDown() throws IOException { jacoco = null; } JobGate.close(); - RequestGate.open(); + 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 helloReportsLiveCapabilitiesAccuratelyAcrossRuntimeConfigurations() throws Exception { + 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()); - String helloNoAgent = connectAndReadHello(false); - assertEquals(KeployDedupAgent.buildHelloFrame(false, false, true, false, true, true, false, false), - helloNoAgent); - - // Case 2: -javaagent attached, server counted, endWait > 0, in-process JaCoCo scan on, app classes indexed. + 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.JVM_NONCE, 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.singleton("Tomcat")); - String helloFull = connectAndReadHello(true); - assertEquals(KeployDedupAgent.buildHelloFrame(true, true, true, true, true, true, true, true), - helloFull); - - // Case 3: endWait == 0 -> windowCut must be false even with agent & counted server. + 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"); - String helloZeroWait = connectAndReadHello(true); - assertEquals(KeployDedupAgent.buildHelloFrame(false, true, true, true, true, true, true, true), - helloZeroWait); + 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 (no counted server) -> windowCut must be false. - ServerEntries.restoreCounted(Collections.emptySet()); - String helloUncountedServer = connectAndReadHello(true); - assertEquals(KeployDedupAgent.buildHelloFrame(false, true, true, true, true, true, true, true), - helloUncountedServer); + // 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. - ServerEntries.restoreCounted(Collections.singleton("Tomcat")); System.setProperty(SCAN_PROPERTY, "off"); - String helloScanOff = connectAndReadHello(true); - assertEquals(KeployDedupAgent.buildHelloFrame(true, true, true, false, true, true, true, true), - helloScanOff); + 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: classpath fallback (no app-only index) -> asyncExecutors must be false. + // 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 -> 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 9: classpath fallback (executorCallSitesEnabled=false) -> asyncExecutors must be false. KeployDedupAgent.executorCallSitesEnabled = false; - String helloFallback = connectAndReadHello(true); - assertEquals(KeployDedupAgent.buildHelloFrame(true, true, true, true, true, true, false, true), - helloFallback); + JsonObject h9 = parseHello(connectAndReadHello(true)); + assertTrue(h9.get("windowCut").getAsBoolean()); + assertFalse(h9.get("asyncExecutors").getAsBoolean()); } @Test(timeout = 60000) - public void earlyConnectBeforeJacocoAndServerInitDoesNotLatchFailureAndRefreshesHello() throws Exception { + 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()); - // Simulate premain early connect: -javaagent attached, server class NOT loaded yet, - // and external JaCoCo RT is on the classpath but its premain has not run yet - // (RT.getAgent() throws IllegalStateException("JaCoCo agent not started.")). 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"); // unreachable TCP port: must use in-process once started + System.setProperty(JACOCO_PORT_PROPERTY, "1"); collector = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); collector.setSoTimeout(30000); @@ -218,40 +297,48 @@ public void earlyConnectBeforeJacocoAndServerInitDoesNotLatchFailureAndRefreshes BufferedReader in = new BufferedReader( new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); - // Initial HELLO on early connect honestly reports windowCut:false, background:false. - String initialHello = in.readLine(); - assertEquals(KeployDedupAgent.buildHelloFrame(false, true, true, false, true, true, true, true), - initialHello); + // 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()); - // Early BACKGROUND + ACK_ID sent BEFORE JaCoCo starts must still take effect once started. send(out, "ACK_ID"); send(out, "BACKGROUND"); - // Now external JaCoCo's premain finishes and Tomcat's CoyoteAdapter loads. + // External JaCoCo premain finishes. DeferredRtLoader.agent = realAgent; - ServerEntries.restoreCounted(Collections.singleton("Tomcat")); - // Next START must succeed via in-process ProbeScan (NOT latched off!) and emit updated HELLO. + // Next START refreshes HELLO with background=true. send(out, "START ts/test-1"); - String updatedHello = in.readLine(); - assertEquals("HELLO must refresh once server and JaCoCo are live", - KeployDedupAgent.buildHelloFrame(true, true, true, true, true, true, true, true), - updatedHello); + 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 cov = in.readLine(); - assertEquals("COV {\"id\":\"ts/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}}", cov); + 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 must emit a BACKGROUND frame on START test-2 after JaCoCo started. + // 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. Netty/WebFlux) -> contaminated: ["no-server-entry"]! + probes[1] = true; + send(out, "END ts/test-2"); + String cov2 = in.readLine(); + assertEquals("COV {\"id\":\"ts/test-2\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}," + + "\"contaminated\":[\"no-server-entry\"]}", cov2); + assertEquals("ACK ts/test-2", in.readLine()); } finally { DeferredRtLoader.agent = null; } @@ -863,21 +950,60 @@ protected RunnableFuture newTaskFor(Runnable runnable, T value) { 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: - // outer call wraps into Handed; inner RequestGate.execute(priority, handed) unwraps and releases permit! + // 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(); + RequestGate.open("t-decorator", null); Object req2 = RequestGate.enter(); try { RequestGate.execute(decorator, plainTask); - assertEquals("unwrapped by inner priority pool, only request remains counted", + assertEquals("fail-closed decorator never wraps, only request remains counted", 1, RequestGate.running()); } finally { RequestGate.exit(req2); } - assertEquals(0, RequestGate.running()); + RequestGate.WindowOutcome decOutcome = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("unknown decorator contaminates window: " + decOutcome.contaminations, + !decOutcome.contaminations.isEmpty() + && decOutcome.contaminations.get(0).startsWith("untracked-executor:")); assertTrue(ran.await(10, TimeUnit.SECONDS)); } finally { priority.shutdownNow(); @@ -1000,18 +1126,10 @@ public void trackingStructuresStayBoundedWithoutEndAndBehindLongRunningTasks() t } // All 400 finished tasks must self-remove promptly even behind the live SSE task. - // Poll briefly because done::countDown runs inside Handed.run() just before finally exit(). - Field byExecField = RequestGate.class.getDeclaredField("PENDING_BY_EXECUTOR"); - byExecField.setAccessible(true); - @SuppressWarnings("unchecked") - Map> byExec = (Map>) byExecField.get(null); int execAfterCompleted = -1; long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (System.nanoTime() < deadline) { - synchronized (byExec) { - Set set = byExec.get(pool); - execAfterCompleted = set == null ? 0 : set.size(); - } + execAfterCompleted = RequestGate.pendingByExecutorSize(pool); if (execAfterCompleted == 1) { break; } @@ -1019,6 +1137,8 @@ public void trackingStructuresStayBoundedWithoutEndAndBehindLongRunningTasks() t } 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); @@ -1036,10 +1156,6 @@ public void trackingStructuresStayBoundedWithoutEndAndBehindLongRunningTasks() t // Inspect current Window's futures map & PENDING_BY_EXECUTOR before END sweep: // periodic sweep (stride 64) must keep both bounded even without END. - Field byExecField = RequestGate.class.getDeclaredField("PENDING_BY_EXECUTOR"); - byExecField.setAccessible(true); - @SuppressWarnings("unchecked") - Map> byExec = (Map>) byExecField.get(null); Field currentField = RequestGate.class.getDeclaredField("current"); currentField.setAccessible(true); Object currentWindow = currentField.get(null); @@ -1053,12 +1169,10 @@ public void trackingStructuresStayBoundedWithoutEndAndBehindLongRunningTasks() t // 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()); - int execTrackedSize; - synchronized (byExec) { - Set set = byExec.get(pool); - execTrackedSize = set == null ? 0 : set.size(); - } - assertEquals("only the 1 live SSE task remains in PENDING_BY_EXECUTOR", 1, execTrackedSize); + 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"; @@ -1191,23 +1305,34 @@ public void longLivedWorkerLoopStartedFromJobDoesNotKeepJobGateOpenForever() thr assertTrue(started.await(10, TimeUnit.SECONDS)); assertNotNull("attributed while fresh", runningWhileFresh.get()); - // Before expiry: window IS marked contaminated. + // Before expiry: window IS marked contaminated with job's name. JobGate.open(); - assertEquals(1, JobGate.close().size()); + List beforeExp = JobGate.close(); + assertEquals(1, beforeExp.size()); + assertFalse(beforeExp.get(0).startsWith("job-tail:")); - // Wait past handedJobMaxNanos: JobGate.open() evicts the expired handed-off Run. + // Wait past handedJobMaxNanos while the worker is STILL EXECUTING: + // Protocol Blocker 3 requires marking overlapping windows with "job-tail:" + // until exit() actually runs! Thread.sleep(100); JobGate.open(); - assertEquals("expired long-lived handed-off task must not poison later tests", - Collections.emptyList(), JobGate.close()); + 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", runningAfterExpiry.get()); + 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) @@ -1257,6 +1382,411 @@ public void kafkaRabbitMqAndJmsListenerHooksMarkWindowContaminatedAndAdapterIsNo } } + @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,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,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. Reproduce plg-87's exact bug: 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; + try { + CountDownLatch gateSupplier = new CountDownLatch(1); + 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(); + } + }); + gateSupplier.countDown(); + } finally { + RequestGate.exit(req); + } + 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()); + try { + 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); + job.future.get(10, TimeUnit.SECONDS); + job = null; + } finally { + 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 { + 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 unarmedKeployAbsentIsNoOpAndFirstArmedWindowMarksArmedMidFlight() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + try { + RequestGate.disarm(); + assertFalse(RequestGate.isArmed()); + + // While unarmed: RequestGate.enter returns null, tasks are NOT wrapped, JobGate does nothing. + Object token = RequestGate.enter(); + assertNull("unarmed RequestGate.enter must be a no-op", token); + Runnable raw = () -> { }; + assertSame("unarmed RequestGate.hand must not wrap", raw, RequestGate.hand(pool, raw)); + Object jobTok = JobGate.enter(new Object(), "quartz"); + assertNull("unarmed JobGate.enter must be a no-op", jobTok); + assertEquals("unarmed JobGate has zero active runs", 0, JobGate.activeRunCount()); + assertEquals("unarmed PENDING_BY_FUTURE stays 0", 0, RequestGate.pendingByFutureSize()); + RequestGate.exit(token); + JobGate.exit(jobTok); + + // Now arm via first START -> first armed window must be contaminated with "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); + + // Second armed window is clean. + RequestGate.open("second-armed", null); + RequestGate.WindowOutcome second = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals(Collections.emptyList(), second.contaminations); + } finally { + 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 shadedAndRelocatedPackagesAreSkippedInPrefixMode() { + ServerEntries prefixed = new ServerEntries(true, Collections.emptySet(), "com/acme/"); + assertTrue(prefixed.shouldRewriteExecutorCalls("com/acme/service/OrderService")); + 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")); + assertFalse(prefixed.shouldRewriteExecutorCalls("com/acme/third_party/Worker")); + } + + @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) { @@ -1615,10 +2145,25 @@ 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(); 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 4f1ed6fe..16f7b5c2 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")); @@ -1208,7 +1210,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 2ff0516d..c46233ac 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/PhasesTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java index b416f93f..728171eb 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,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"; 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 dba62b89..92747b66 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/WarmupTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/WarmupTest.java index 63d1c64c..93375bf2 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 00000000..7cdcbdea --- /dev/null +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -0,0 +1,325 @@ +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.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +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 prove Ruling #3 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(); + + 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)) { + // Reproduces plg-87's exact bug: fast supplier, slow synchronous thenAccept(audit). + 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 ("/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(); + } + } + + /** + * 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 { + @Override + public void execute(Runnable command) { + if (!(command instanceof Serializable)) { + throw new IllegalStateException("Expected Serializable task, got " + command.getClass().getName()); + } + 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(); + } +} From 2e43c970c53b5d3ff0b7e8b9e3edc4942fb9e141 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 06:13:07 +0530 Subject: [PATCH 07/26] fix(dedup): close untracked async tail, B2 async forms, unarmed in-flight, and fail-closed gaps Signed-off-by: slayerjain --- README.md | 8 +- .../main/java/io/keploy/dedup/JobGate.java | 63 +- .../io/keploy/dedup/KeployDedupAgent.java | 64 +- .../java/io/keploy/dedup/OrderedPools.java | 93 +- .../java/io/keploy/dedup/RequestGate.java | 2017 ++++++++++++++++- .../java/io/keploy/dedup/ServerEntries.java | 393 +++- .../java/io/keploy/dedup/AsyncHandTest.java | 10 +- .../io/keploy/dedup/ControlSocketTest.java | 9 +- .../dedup/ForkedAsyncAndHonestyTest.java | 87 +- .../dedup/HonestProtocolAndAsyncTest.java | 265 ++- .../io/keploy/dedup/InProcessScanTest.java | 5 +- .../org/example/servers/AsyncHonestyApp.java | 100 +- 12 files changed, 2867 insertions(+), 247 deletions(-) diff --git a/README.md b/README.md index 9504205a..a3564196 100644 --- a/README.md +++ b/README.md @@ -25,13 +25,13 @@ 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) or to verified standard JDK executors and `CompletableFuture` async 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` (`runAsync`, `supplyAsync`, and `*Async` instance methods including synchronous dependent stages registered before completion). `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` (or a new `START` arrives without a preceding `END`), subsequent windows are marked contaminated (`"tail:"`) until the prior lingering work finishes draining. 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. +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. -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 accessors verified through to an allow-listed pool) are wrapped. Any unknown or custom executor (such as Hazelcast `IExecutorService`, Ignite, Redisson, striped/keyed executors, coalescing executors, custom `ThreadPoolExecutor` 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 is marked contaminated (`"untracked-executor:"`). Similarly, untracked async submission sites inside a request (`ScheduledExecutorService.schedule*`, `ExecutorService.invokeAny`, `Thread.start()`) execute untouched and mark the window contaminated (`"untracked-async:"`). 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/`, etc.) and known library packages. +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. 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*`, `ExecutorService.invokeAny`, `Thread.start()` including subclasses, concrete custom executor `execute`/`submit`, `ForkJoinTask.fork()`, Reactor `Mono`/`Flux` `.subscribe()`, custom `CompletionStage`, and async method references such as `executor::execute`) execute untouched and mark the window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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 are rewritten without shaded-package filtering. -When Keploy is absent (no collector connected and no control command received), runtime request counting, executor wrapping, and job/listener tracking remain unarmed (no-op); if any traffic ran while unarmed before a collector later connects, the first armed window 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 or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). +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 no-op using a static sentinel token); every armed window opened while any unarmed request or job remains in flight (and 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`, or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). 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. 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 15bbb1c7..e357b3d0 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -93,8 +93,7 @@ static int activeRunCount() { */ public static Object enter(Object job, String kind) { if (!RequestGate.isArmed()) { - RequestGate.noteUnarmedActivity(); - return null; + return RequestGate.enterUnarmed(); } Run run = null; try { @@ -114,9 +113,10 @@ public static Object enter(Object job, String kind) { // 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 and skip entering once expired so a - // self-resubmitting loop cannot extend attribution forever. - // Never throws, as enter. + // 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; @@ -124,15 +124,9 @@ static Object enterAs(Attribution attribution) { Run run = null; try { long now = System.nanoTime(); - long deadline; - if (attribution.hasDeadline) { - if ((now - attribution.expiresAtNanos) >= 0) { - return null; - } - deadline = attribution.expiresAtNanos; - } else { - deadline = now + handedJobMaxNanos; - } + long deadline = attribution.hasDeadline + ? attribution.expiresAtNanos + : now + handedJobMaxNanos; run = new Run(attribution.name, CURRENT.get(), true, deadline); begin(run); } catch (Throwable t) { @@ -141,6 +135,41 @@ static Object enterAs(Attribution attribution) { return run; } + // markUntracked records an untracked async hand-off originated by a job's + // run (e.g., an unknown executor) on the currently open window (if any) + // and requests tail contamination on the immediately following window. + static void markUntracked(String reason) { + if (reason == null || reason.isEmpty() || !RequestGate.isArmed()) { + return; + } + Window active = window; + if (active != null) { + active.mark(reason); + } + RequestGate.noteExternalUntrackedTail(reason); + } + + // 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 @@ -150,7 +179,7 @@ private static void begin(Run run) { CURRENT.set(run); Window active = window; if (active != null) { - active.mark(run.name); + active.mark(run.isExpired(System.nanoTime()) ? "job-tail:" + run.name : run.name); } } @@ -208,6 +237,10 @@ 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; RUNNING.remove(run); 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 da41abb0..b13bdb90 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -154,10 +154,18 @@ 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. - // Random UUID generated once per JVM startup (never changes on TCP - // reconnect; distinct across JVM restarts) so collectors can detect pod + // 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. - static final String JVM_NONCE = UUID.randomUUID().toString(); + 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 @@ -287,7 +295,7 @@ String toHelloFrame(String buildId) { 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", ""), - JVM_NONCE, + jvmNonce(), buildId, windowCut, contaminated, classMismatch, background, true, true, asyncExecutors, listenerContamination); @@ -316,8 +324,10 @@ private static Capabilities computeCapabilities(CoverageCollector collector) { && !isAsyncCallSitesTurnedOff() && appOnlyActive && !ServerEntries.wasJpmsGuardTriggered() - && RequestGate.CF_DEPENDENT_TRACKING_ENABLED; - boolean listenerContamination = agentAttached && !ServerEntries.hadListenerHookFailure(); + && !ServerEntries.hadAppRewriteFailure(); + boolean listenerContamination = agentAttached + && !ServerEntries.hadListenerHookFailure() + && !ServerEntries.hasUnhookedConsumer(); return new Capabilities(windowCut, contaminated, classMismatch, background, asyncExecutors, listenerContamination); } @@ -1394,7 +1404,7 @@ public void run() { while (running.get()) { try { connectAndServe(); - } catch (IOException e) { + } catch (IOException | RuntimeException e) { if (running.get()) { Level level = connectFailureLogged ? Level.FINE : Level.INFO; connectFailureLogged = true; @@ -1608,11 +1618,16 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) 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 { - // Emit updated HELLO if capabilities changed during the test - // (e.g. Jetty/Undertow loaded its request entry on first request, - // or probeScan was dropped). maybeSendUpdatedHello(out); + } catch (RuntimeException 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 // transport likewise always publishes). @@ -2753,26 +2768,29 @@ private IndexReport reportForBackground() { // 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; } 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 772052fb..bb105837 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -77,9 +77,12 @@ final class OrderedPools { // 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 = @@ -129,6 +132,51 @@ protected Object computeValue(Class type) { } }; + // 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; + } + // Whether a ThreadPoolExecutor subclass overrides beforeExecute, // afterExecute, newTaskFor, execute, submit, or (for // ScheduledThreadPoolExecutor) decorateTask, which may cast the queued @@ -250,24 +298,33 @@ private static boolean read(Object executor, int depth, boolean requireVerified) if (JDK_DELEGATED.equals(className) || JDK_DELEGATED_SCHEDULED.equals(className)) { return readDelegated(executor, depth); } - Object pool = POOL.get(cls); - 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 (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"); 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 6b7c3d1b..01b3bf31 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -30,6 +30,7 @@ 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; @@ -78,15 +79,27 @@ */ public final class RequestGate { - /** Feature flag proving CompletableFuture dependent-stage tracking is active. */ - static final boolean CF_DEPENDENT_TRACKING_ENABLED = true; - // 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(); + + // 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); + // 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; // 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, @@ -127,23 +140,40 @@ public final class RequestGate { // futures. private static final int FUTURE_SWEEP_STRIDE = 64; - // Reflective handles for Java 12+ CompletableFuture methods so keploy-sdk - // compiles against --release 8 (Java8ApiTest) while rewriting JDK 12+ apps. + // 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 = - findCfMethod("exceptionallyAsync", Function.class); + findMethod(CompletableFuture.class, "exceptionallyAsync", Function.class); private static final Method CF_EXCEPTIONALLY_ASYNC_2 = - findCfMethod("exceptionallyAsync", Function.class, Executor.class); + findMethod(CompletableFuture.class, "exceptionallyAsync", Function.class, Executor.class); private static final Method CF_EXCEPTIONALLY_COMPOSE_ASYNC_1 = - findCfMethod("exceptionallyComposeAsync", Function.class); + findMethod(CompletableFuture.class, "exceptionallyComposeAsync", Function.class); private static final Method CF_EXCEPTIONALLY_COMPOSE_ASYNC_2 = - findCfMethod("exceptionallyComposeAsync", Function.class, Executor.class); + 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 findCfMethod(String name, Class... params) { + private static Method findMethod(Class owner, String name, Class... params) { try { - return CompletableFuture.class.getMethod(name, params); + return owner.getMethod(name, params); } catch (Throwable ignored) { return null; } @@ -159,9 +189,36 @@ static void noteUnarmedActivity() { } } + 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) { + if (!armed) { + return; + } + externalUntrackedTailReason = reason == null || reason.isEmpty() ? "job" : reason; + externalUntrackedTailExpiresAtNanos = System.nanoTime() + untrackedTailWindowNanos; + externalUntrackedTailPending = true; + } + static void arm() { if (!armed) { - if (unarmedEntered) { + if (unarmedEntered || UNARMED_IN_FLIGHT.sum() > 0) { pendingArmedMidFlight = true; } armed = true; @@ -173,6 +230,9 @@ static void disarm() { unarmedEntered = false; pendingArmedMidFlight = false; ARMED_MID_FLIGHT_CONSUMED.set(false); + externalUntrackedTailPending = false; + externalUntrackedTailExpiresAtNanos = 0L; + externalUntrackedTailReason = null; LINGERING.clear(); current = new Window(null); } @@ -194,14 +254,15 @@ static int pendingByExecutorSize(Executor executor) { /** * Counts a request as running, in the window of the test running now. - * No-op returning {@code null} when Keploy is unarmed. + * 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) { - noteUnarmedActivity(); - return null; + return enterUnarmed(); } Window window = current; Window outer = INSIDE.get(); @@ -226,6 +287,10 @@ 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); @@ -254,6 +319,15 @@ public static Runnable hand(Object executor, Runnable task) { return handInternal(executor, task, false); } + 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) { + JobGate.markUntracked(reason); + } + } + private static Runnable handInternal(Object executor, Runnable task, boolean deferRelease) { if (!armed || task == null) { return task; @@ -262,8 +336,8 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def if (OrderedPools.orders(executor)) { Handed existing = (Handed) task; existing.releaseIfPending(); - if (existing.window != null && executor != null) { - existing.window.contaminate("untracked-executor:" + executor.getClass().getName()); + if (executor != null) { + markUntrackedExecutor(existing.window, existing.job, executor, "unknown"); } return existing.task; } @@ -275,23 +349,21 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def return task; } if (task instanceof Comparable) { - if (window != null) { - window.contaminate("untracked-executor:" - + (executor != null ? executor.getClass().getName() : "comparable")); - } + markUntrackedExecutor(window, job, executor, "comparable"); return task; } if (OrderedPools.orders(executor)) { - if (window != null && executor != null) { - window.contaminate("untracked-executor:" + executor.getClass().getName()); + 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. + boolean defer = deferRelease && (window != null || job != null); Handed handed = task instanceof Future - ? new HandedFuture(window, job, task, deferRelease && window != null) - : new Handed(window, job, task, deferRelease && window != null); + ? 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) { @@ -318,8 +390,8 @@ public static Callable hand(Object executor, Callable task) { @SuppressWarnings("unchecked") HandedCall existing = (HandedCall) task; existing.releaseIfPending(); - if (existing.window != null && executor != null) { - existing.window.contaminate("untracked-executor:" + executor.getClass().getName()); + if (executor != null) { + markUntrackedExecutor(existing.window, existing.job, executor, "unknown"); } return existing.task; } @@ -331,15 +403,12 @@ public static Callable hand(Object executor, Callable task) { return task; } if (task instanceof Comparable) { - if (window != null) { - window.contaminate("untracked-executor:" - + (executor != null ? executor.getClass().getName() : "comparable")); - } + markUntrackedExecutor(window, job, executor, "comparable"); return task; } if (OrderedPools.orders(executor)) { - if (window != null && executor != null) { - window.contaminate("untracked-executor:" + executor.getClass().getName()); + if (executor != null) { + markUntrackedExecutor(window, job, executor, "unknown"); } return task; } @@ -373,8 +442,8 @@ private static Supplier handSupplierInternal(Object executor, Supplier @SuppressWarnings("unchecked") HandedSupplier existing = (HandedSupplier) supplier; existing.releaseIfPending(); - if (existing.window != null && executor != null) { - existing.window.contaminate("untracked-executor:" + executor.getClass().getName()); + if (executor != null) { + markUntrackedExecutor(existing.window, existing.job, executor, "unknown"); } return existing.task; } @@ -386,19 +455,17 @@ private static Supplier handSupplierInternal(Object executor, Supplier return supplier; } if (supplier instanceof Comparable) { - if (window != null) { - window.contaminate("untracked-executor:" - + (executor != null ? executor.getClass().getName() : "comparable")); - } + markUntrackedExecutor(window, job, executor, "comparable"); return supplier; } if (OrderedPools.orders(executor)) { - if (window != null && executor != null) { - window.contaminate("untracked-executor:" + executor.getClass().getName()); + if (executor != null) { + markUntrackedExecutor(window, job, executor, "unknown"); } return supplier; } - HandedSupplier handed = new HandedSupplier<>(window, job, supplier, deferRelease && window != null); + boolean defer = deferRelease && (window != null || job != null); + HandedSupplier handed = new HandedSupplier<>(window, job, supplier, defer); if (window != null) { window.running.incrementAndGet(); } @@ -598,7 +665,7 @@ public static CompletableFuture supplyAsync(Supplier supplier, Executo return cf; } - // --- CompletableFuture *Async instance method call-site wrappers --- + // --- CompletableFuture & CompletionStage instance method call-site wrappers --- private static Hand prepareCfStageHand(CompletableFuture receiver, Executor explicitExecutor, boolean hasExecutor) { if (!armed) { @@ -614,22 +681,18 @@ private static Hand prepareCfStageHand(CompletableFuture receiver, Executor e return null; } if (OrderedPools.orders(explicitExecutor)) { - if (window != null) { - window.contaminate("untracked-executor:" + explicitExecutor.getClass().getName()); - } + 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) { - if (window != null) { - window.contaminate("untracked-executor:" + receiver.getClass().getName()); - } + markUntrackedExecutor(window, job, receiver, "unknown"); return null; } } - StageHand hand = new StageHand(window, job, window != null); + StageHand hand = new StageHand(window, job, true); if (window != null) { window.running.incrementAndGet(); } @@ -639,6 +702,36 @@ private static Hand prepareCfStageHand(CompletableFuture receiver, Executor e return hand; } + private static Hand prepareCfSyncHand(CompletableFuture receiver, CompletionStage other, boolean either) { + if (!armed || receiver == null) { + return null; + } + if (other == null) { + if (receiver.isDone()) { + return null; + } + } else { + boolean otherDone = other instanceof CompletableFuture && ((CompletableFuture) other).isDone(); + if (either ? (receiver.isDone() || otherDone) : (receiver.isDone() && otherDone)) { + return null; + } + } + Window window = INSIDE.get(); + JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; + if (window == null && job == null) { + return null; + } + if (receiver.getClass() != CompletableFuture.class) { + markUntrackedExecutor(window, job, receiver, "unknown"); + return null; + } + StageHand hand = new StageHand(window, job, true); + if (window != null) { + window.running.incrementAndGet(); + } + return hand; + } + private static CompletableFuture finishCfStage(CompletableFuture out, Hand hand) { if (hand != null) { attachCompletionRelease(out, hand, null); @@ -646,6 +739,23 @@ private static CompletableFuture finishCfStage(CompletableFuture out, 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; @@ -733,6 +843,66 @@ public void accept(T t, U u) { }; } + /** + * 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); @@ -749,6 +919,16 @@ public static CompletableFuture thenApplyAsync(CompletableFuture cf 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); @@ -765,6 +945,14 @@ public static CompletableFuture thenApplyAsync(CompletableFuture cf 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); @@ -781,6 +969,15 @@ public static CompletableFuture thenAcceptAsync(CompletableFuture c 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); @@ -797,6 +994,14 @@ public static CompletableFuture thenAcceptAsync(CompletableFuture c 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) { @@ -812,6 +1017,15 @@ public static CompletableFuture thenRunAsync(CompletableFuture cf, 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); @@ -828,6 +1042,15 @@ public static CompletableFuture thenRunAsync(CompletableFuture cf, 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); @@ -844,6 +1067,16 @@ public static CompletableFuture thenComposeAsync(CompletableFuture 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); @@ -860,6 +1093,17 @@ public static CompletableFuture thenComposeAsync(CompletableFuture 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); @@ -876,6 +1120,18 @@ public static CompletableFuture thenCombineAsync(CompletableFuture< 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) { @@ -893,6 +1149,16 @@ public static CompletableFuture thenCombineAsync(CompletableFuture< 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); @@ -909,6 +1175,17 @@ public static CompletableFuture thenAcceptBothAsync(CompletableFutu 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); @@ -925,6 +1202,15 @@ public static CompletableFuture thenAcceptBothAsync(CompletableFutu 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); @@ -941,6 +1227,16 @@ public static CompletableFuture runAfterBothAsync(CompletableFuture 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); @@ -957,6 +1253,16 @@ public static CompletableFuture runAfterBothAsync(CompletableFuture 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); @@ -973,6 +1279,17 @@ public static CompletableFuture applyToEitherAsync(CompletableFuture 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); @@ -989,6 +1306,15 @@ public static CompletableFuture applyToEitherAsync(CompletableFuture 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); @@ -1005,6 +1331,16 @@ public static CompletableFuture acceptEitherAsync(CompletableFuture 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); @@ -1021,6 +1357,15 @@ public static CompletableFuture acceptEitherAsync(CompletableFuture 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); @@ -1037,6 +1382,16 @@ public static CompletableFuture runAfterEitherAsync(CompletableFuture< 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); @@ -1053,6 +1408,15 @@ public static CompletableFuture runAfterEitherAsync(CompletableFuture< 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); @@ -1069,6 +1433,16 @@ public static CompletableFuture handleAsync(CompletableFuture cf, 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); @@ -1085,6 +1459,14 @@ public static CompletableFuture handleAsync(CompletableFuture cf, 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); @@ -1101,6 +1483,15 @@ public static CompletableFuture whenCompleteAsync(CompletableFuture cf 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); @@ -1117,6 +1508,14 @@ public static CompletableFuture whenCompleteAsync(CompletableFuture cf 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) { @@ -1134,6 +1533,15 @@ public static CompletableFuture exceptionallyAsync(CompletableFuture c 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) { @@ -1151,6 +1559,14 @@ public static CompletableFuture exceptionallyAsync(CompletableFuture c 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) { @@ -1168,6 +1584,15 @@ public static CompletableFuture exceptionallyComposeAsync(CompletableFutu 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) { @@ -1185,73 +1610,1310 @@ public static CompletableFuture exceptionallyComposeAsync(CompletableFutu return finishCfStage(out, hand); } - private static Object invokeCfReflect(Method method, Object target, Object... args) throws Throwable { - if (method == null) { - throw new NoSuchMethodError("CompletableFuture async method unavailable on this JDK"); + // --- 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 { - return method.invoke(target, args); - } catch (InvocationTargetException e) { - throw e.getCause() != null ? e.getCause() : e; + out = cf.thenApply(wrapFunction(hand, fn)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; } + return finishCfStage(out, hand); } - @SuppressWarnings("unchecked") - private static RuntimeException sneakyThrow(Throwable t) throws E { - throw (E) t; - } - - // --- Untracked async call-site pass-through contamination helpers --- - - private static void contaminateIfInRequest(String reason) { - if (!armed) { - return; + /** + * 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); } - Window window = INSIDE.get(); - if (window != null) { - window.contaminate(reason); + CompletableFuture out; + try { + out = cf.thenAccept(wrapConsumer(hand, action)); + } catch (Throwable t) { + hand.releaseIfPending(); + throw t; } + return finishCfStage(out, hand); } - public static ScheduledFuture schedule(ScheduledExecutorService executor, Runnable command, - long delay, TimeUnit unit) { - contaminateIfInRequest("untracked-async:schedule"); - return executor.schedule(command, delay, unit); + /** + * 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); } - public static ScheduledFuture schedule(ScheduledExecutorService executor, Callable callable, - long delay, TimeUnit unit) { - contaminateIfInRequest("untracked-async:schedule"); - return executor.schedule(callable, delay, unit); - } + /** + * 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) { + if (!armed || reason == null || reason.isEmpty()) { + return; + } + Window window = INSIDE.get(); + if (window != null) { + window.contaminate(reason); + return; + } + if (JobGate.runningAttribution() != null) { + JobGate.markUntracked(reason); + } + } + + /** + * Checks whether {@code target} is a {@link Thread} instance before a + * non-{@code java.lang.Thread} {@code start()} call and flags an untracked + * thread start if so. + * + * @param target receiver of {@code start()} + */ + public static void noteIfThread(Object target) { + if (target instanceof Thread) { + noteUntrackedAsync("untracked-async:thread-start"); + } + } + + /** + * 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) { + noteUntrackedAsync("untracked-async:schedule"); + return executor.schedule(command, delay, unit); + } + + /** + * 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) { + noteUntrackedAsync("untracked-async:schedule"); + return executor.schedule(callable, delay, unit); + } + /** + * 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) { - contaminateIfInRequest("untracked-async:schedule"); + noteUntrackedAsync("untracked-async:schedule"); return executor.scheduleAtFixedRate(command, initialDelay, period, unit); } + /** + * 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) { - contaminateIfInRequest("untracked-async:schedule"); + noteUntrackedAsync("untracked-async:schedule"); return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); } + /** + * 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 { - contaminateIfInRequest("untracked-async:invokeAny"); + 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 { - contaminateIfInRequest("untracked-async:invokeAny"); + 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) { - contaminateIfInRequest("untracked-async:thread-start"); + noteUntrackedAsync("untracked-async:thread-start"); thread.start(); } @@ -1514,54 +3176,98 @@ static void open() { } // open(testId, prevActiveTestId) opens a fresh test window, records - // armed-mid-flight if unarmed traffic occurred prior to arming, and marks - // the new window contaminated ("tail:") if the previous test - // was cut, unclosed, or any prior window still has running > 0. + // 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 an untracked async hand-off, or any prior window still has + // running > 0. static void open(String testId, String prevActiveTestId) { arm(); drainDeadHands(); - Window prev = current; + long now = System.nanoTime(); Window next = new Window(testId); - if ((pendingArmedMidFlight || unarmedEntered) + if (UNARMED_IN_FLIGHT.sum() > 0) { + 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(); - if (prev.running.get() > 0) { + boolean prevRunning = prev.running.get() > 0; + boolean prevUntracked = prev.hadUntrackedAsync; + if (prevRunning || prevUntracked) { if (prev.testId == null && prevActiveTestId != null && !prevActiveTestId.isEmpty()) { prev.fallbackId = prevActiveTestId; } - retainLingering(prev); + if (prevUntracked && prev.untrackedTailExpiresAtNanos == 0L) { + prev.untrackedTailExpiresAtNanos = now + untrackedTailWindowNanos; + } + retainLingering(prev, now); } } if (prevActiveTestId != null && !prevActiveTestId.isEmpty()) { next.contaminate("tail:" + prevActiveTestId); } + if (externalUntrackedTailPending || (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 stillRunning = lingering.running.get() > 0; boolean reportCut = lingering.wasCut && !lingering.cutReportedOnce; - if (stillRunning || reportCut) { + boolean untrackedActive = lingering.hadUntrackedAsync + && (!lingering.untrackedTailReportedOnce + || (now - lingering.untrackedTailExpiresAtNanos) < 0L); + if (stillRunning || reportCut || untrackedActive) { next.contaminate("tail:" + lingering.label()); - lingering.cutReportedOnce = true; + if (reportCut) { + lingering.cutReportedOnce = true; + } + if (lingering.hadUntrackedAsync) { + lingering.untrackedTailReportedOnce = true; + } } - if (!stillRunning) { + boolean cutDone = !lingering.wasCut || lingering.cutReportedOnce; + boolean untrackedDone = !lingering.hadUntrackedAsync + || (lingering.untrackedTailReportedOnce + && (now - lingering.untrackedTailExpiresAtNanos) >= 0L); + if (!stillRunning && cutDone && untrackedDone) { LINGERING.remove(lingering); } } - current = next; } - private static void retainLingering(Window window) { + private static void retainLingering(Window window, long now) { if (LINGERING.size() >= MAX_LINGERING) { for (Window existing : LINGERING) { existing.sweepCancelledFutures(); - if (existing.running.get() <= 0 && (!existing.wasCut || existing.cutReportedOnce)) { + boolean cutDone = !existing.wasCut || existing.cutReportedOnce; + boolean untrackedDone = !existing.hadUntrackedAsync + || (existing.untrackedTailReportedOnce + && (now - existing.untrackedTailExpiresAtNanos) >= 0L); + if (existing.running.get() <= 0 && cutDone && untrackedDone) { LINGERING.remove(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); } @@ -1582,8 +3288,9 @@ static boolean await(long timeoutNanos) { // awaitWindow closes the current window, optionally waits up to // timeoutNanos for its requests/tasks to finish, retains the window in - // LINGERING if cut or still running, and returns its outcome (drained, - // waited, enteredCount, and accumulated contaminations). + // LINGERING if cut, still running, or carrying an untracked async hand-off, + // and returns its outcome (drained, waited, enteredCount, and accumulated + // contaminations). static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { drainDeadHands(); Window window = current; @@ -1591,12 +3298,21 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { window.sweepCancelledFutures(); int initialRunning = window.running.get(); if (!wait) { - if (initialRunning > 0) { - retainLingering(window); + long now = System.nanoTime(); + if (window.hadUntrackedAsync) { + window.untrackedTailExpiresAtNanos = now + untrackedTailWindowNanos; + } + if (initialRunning > 0 || window.hadUntrackedAsync) { + retainLingering(window, now); } return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations()); } if (initialRunning <= 0) { + if (window.hadUntrackedAsync) { + long now = System.nanoTime(); + window.untrackedTailExpiresAtNanos = now + untrackedTailWindowNanos; + retainLingering(window, now); + } return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations()); } boolean drained = false; @@ -1629,9 +3345,15 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { } finally { window.waiter = null; } - if (!drained) { - window.wasCut = true; - retainLingering(window); + if (!drained || window.hadUntrackedAsync) { + long now = System.nanoTime(); + if (!drained) { + window.wasCut = true; + } + if (window.hadUntrackedAsync) { + window.untrackedTailExpiresAtNanos = now + untrackedTailWindowNanos; + } + retainLingering(window, now); } return new WindowOutcome(drained, true, window.enteredCount.get(), window.contaminations()); } @@ -1662,6 +3384,9 @@ private static final class Window { private volatile Thread waiter; private volatile boolean wasCut; private volatile boolean cutReportedOnce; + private volatile boolean hadUntrackedAsync; + private volatile long untrackedTailExpiresAtNanos; + private volatile boolean untrackedTailReportedOnce; // 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). @@ -1689,6 +3414,9 @@ private void contaminate(String reason) { if (reason == null || reason.isEmpty()) { return; } + if (reason.startsWith("untracked-")) { + hadUntrackedAsync = true; + } if (contamCount.get() < JobGate.KEPT && contamSet.add(reason)) { if (contamCount.incrementAndGet() <= JobGate.KEPT) { contamOrder.add(reason); @@ -1880,6 +3608,9 @@ private abstract static class Hand { 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, JobGate.Attribution job, boolean deferRelease) { @@ -1905,20 +3636,28 @@ final void clearFutureKey() { } private void finishRelease() { - clearFutureKey(); - window.untrack(this); - HandRef ref = executorRef; - if (ref != null) { - ref.released = true; - executorRef = null; - ref.set.remove(ref); + 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); + } } - done(window); } // release marks this task done unconditionally (non-deferred exit). final void release() { - if (window == null) { + if (window == null && job == null) { return; } for (;;) { @@ -1937,7 +3676,7 @@ final void release() { // callback (registered immediately before returning the CF, so LIFO // postComplete pops caller-registered synchronous dependents first). final void onFutureCompleted() { - if (window == null) { + if (window == null && job == null) { return; } if (!deferRelease) { @@ -1968,7 +3707,7 @@ final void onFutureCompleted() { // 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) { + if (window == null && job == null) { return; } for (;;) { @@ -1985,14 +3724,36 @@ final void releaseIfPending() { 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 (STATE.compareAndSet(this, s, s | FLAG_STARTED)) { + 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; } } @@ -2004,8 +3765,28 @@ 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; + } + } } if (outer == null) { INSIDE.remove(); 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 b97715d9..76e45abd 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -22,6 +22,7 @@ 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; @@ -109,13 +110,34 @@ final class ServerEntries implements ClassFileTransformer { 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"); } 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 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. @@ -126,8 +148,7 @@ final class ServerEntries implements ClassFileTransformer { // 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. If none of - // these appear in a class's constant pool, ASM rewriting is skipped. + // 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", @@ -136,15 +157,47 @@ final class ServerEntries implements ClassFileTransformer { "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/lang/Thread"))); + "java/util/concurrent/CompletionStage", + "java/lang/Thread", + "reactor/core/publisher/Mono", + "reactor/core/publisher/Flux", + "reactor/core/publisher/ParallelFlux"))); + + // Constant-pool method names (CONSTANT_NameAndType, tag 12) targeted by + // wrapExecutorCalls, so custom executor subtypes, Thread subclasses, + // CompletionStage, Reactor subscribe, method references, and raw consumer + // polling are never skipped by the fast pre-scan. + private static final Set TARGET_ASYNC_METHOD_NAMES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "execute", "submit", "schedule", "scheduleAtFixedRate", "scheduleWithFixedDelay", + "invokeAny", "remove", "shutdownNow", "runAsync", "supplyAsync", "completeAsync", + "fork", "subscribe", "start", "poll", "basicConsume", "receive", + "thenApplyAsync", "thenAcceptAsync", "thenRunAsync", "thenComposeAsync", + "thenCombineAsync", "thenAcceptBothAsync", "runAfterBothAsync", + "applyToEitherAsync", "acceptEitherAsync", "runAfterEitherAsync", + "handleAsync", "whenCompleteAsync", "exceptionallyAsync", "exceptionallyComposeAsync", + "thenApply", "thenAccept", "thenRun", "thenCompose", + "thenCombine", "thenAcceptBoth", "runAfterBoth", + "applyToEither", "acceptEither", "runAfterEither", + "handle", "whenComplete", "exceptionally", "exceptionallyCompose"))); // CompletableFuture *Async instance methods rewritten to RequestGate. - private static final Map> CF_ASYNC_INSTANCE_METHODS = buildCfAsyncMethods(); - - private static Map> buildCfAsyncMethods() { + 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 cf = "Ljava/util/concurrent/CompletableFuture;"; String cs = "Ljava/util/concurrent/CompletionStage;"; String ex = "Ljava/util/concurrent/Executor;"; String fn = "Ljava/util/function/Function;"; @@ -152,20 +205,45 @@ private static Map> buildCfAsyncMethods() { String run = "Ljava/lang/Runnable;"; String bifn = "Ljava/util/function/BiFunction;"; String bicons = "Ljava/util/function/BiConsumer;"; - m.put("thenApplyAsync", setOf("(" + fn + ")" + cf, "(" + fn + ex + ")" + cf)); - m.put("thenAcceptAsync", setOf("(" + cons + ")" + cf, "(" + cons + ex + ")" + cf)); - m.put("thenRunAsync", setOf("(" + run + ")" + cf, "(" + run + ex + ")" + cf)); - m.put("thenComposeAsync", setOf("(" + fn + ")" + cf, "(" + fn + ex + ")" + cf)); - m.put("thenCombineAsync", setOf("(" + cs + bifn + ")" + cf, "(" + cs + bifn + ex + ")" + cf)); - m.put("thenAcceptBothAsync", setOf("(" + cs + bicons + ")" + cf, "(" + cs + bicons + ex + ")" + cf)); - m.put("runAfterBothAsync", setOf("(" + cs + run + ")" + cf, "(" + cs + run + ex + ")" + cf)); - m.put("applyToEitherAsync", setOf("(" + cs + fn + ")" + cf, "(" + cs + fn + ex + ")" + cf)); - m.put("acceptEitherAsync", setOf("(" + cs + cons + ")" + cf, "(" + cs + cons + ex + ")" + cf)); - m.put("runAfterEitherAsync", setOf("(" + cs + run + ")" + cf, "(" + cs + run + ex + ")" + cf)); - m.put("handleAsync", setOf("(" + bifn + ")" + cf, "(" + bifn + ex + ")" + cf)); - m.put("whenCompleteAsync", setOf("(" + bicons + ")" + cf, "(" + bicons + ex + ")" + cf)); - m.put("exceptionallyAsync", setOf("(" + fn + ")" + cf, "(" + fn + ex + ")" + cf)); - m.put("exceptionallyComposeAsync", setOf("(" + fn + ")" + cf, "(" + fn + ex + ")" + cf)); + 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); } @@ -238,6 +316,10 @@ static boolean hasUncountedServer() { return !SEEN_UNCOUNTED.isEmpty(); } + static boolean hasUnhookedConsumer() { + return !SEEN_UNHOOKED_CONSUMERS.isEmpty(); + } + static boolean hadServerHookFailure() { return serverHookFailed; } @@ -250,6 +332,10 @@ static boolean wasJpmsGuardTriggered() { return jpmsGuardTriggered; } + static boolean hadAppRewriteFailure() { + return appRewriteFailed; + } + static void markJpmsGuardTriggered() { jpmsGuardTriggered = true; } @@ -277,10 +363,28 @@ static void restoreUncounted(Set 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 @@ -301,10 +405,16 @@ 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; } return null; } @@ -315,6 +425,7 @@ public byte[] transform(ClassLoader loader, String className, Class classBein } return updated; } catch (Throwable t) { + appRewriteFailed = true; LOGGER.log(Level.FINE, "Keploy dedup skipped executor call-site wrap for " + className, t); } } @@ -498,7 +609,9 @@ boolean shouldRewriteExecutorCalls(String className) { if (!appClasses.isEmpty()) { return appClasses.contains(className); } - return appPackagePrefix != null && className.startsWith(appPackagePrefix); + return appPackagePrefix != null + && className.startsWith(appPackagePrefix) + && !isShadedOrRelocated(className); } static boolean canAccessGate(ClassLoader loader, ProtectionDomain protectionDomain) { @@ -613,22 +726,18 @@ private static Set findUnreadableModuleLocations() { static boolean isShadedOrRelocated(String className) { return className.contains("/shaded/") || className.contains("/relocated/") - || className.contains("/shadow/") || className.contains("/repackaged/") - || className.contains("/thirdparty/") - || className.contains("/third_party/") - || className.contains("/vendor/") || className.startsWith("shaded/") || className.startsWith("relocated/"); } // Belt-and-suspenders guard in case KEPLOY_JAVA_CLASS_DIRS or - // appPackagePrefix includes framework/library/shaded classes; note + // appPackagePrefix includes framework/library classes; note // org/apache/ is NOT blanket-excluded so Apache-hosted applications (e.g. - // org/apache/fineract/) remain eligible. + // 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 - && !isShadedOrRelocated(className) && !className.startsWith("java/") && !className.startsWith("javax/") && !className.startsWith("sun/") @@ -670,9 +779,11 @@ static boolean isRewriteAllowedPackage(String className) { && !className.startsWith("redis/clients/"); } - // Fast constant-pool scan: every matching invoke instruction references a - // CONSTANT_Class (tag 7) entry for one of TARGET_EXECUTOR_OWNERS. Classes - // with no matching constant-pool class entry skip ASM ClassWriter entirely. + // 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()]; @@ -681,20 +792,139 @@ static boolean hasExecutorReference(ClassReader reader) { if (offset == 0) { continue; } - if (reader.readByte(offset - 1) == 7) { + 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 boolean isHookedSpringExecutorOwner(String owner) { + return "org/springframework/core/task/TaskExecutor".equals(owner) + || "org/springframework/core/task/AsyncTaskExecutor".equals(owner) + || "org/springframework/core/task/AsyncListenableTaskExecutor".equals(owner) + || "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 isUntrackedExecuteOrSubmit(String owner, String mname, String desc) { + if (isHookedSpringExecutorOwner(owner)) { + return false; + } + if ("execute".equals(mname) && "(Ljava/lang/Runnable;)V".equals(desc)) { + return true; + } + if ("submit".equals(mname) + && (desc.startsWith("(Ljava/lang/Runnable;)") + || desc.startsWith("(Ljava/lang/Runnable;Ljava/lang/Object;)") + || desc.startsWith("(Ljava/util/concurrent/Callable;)"))) { + return true; + } + return false; + } + + private static boolean isUntrackedScheduleOrInvokeAny(String mname, String desc) { + if ("schedule".equals(mname) + && (desc.startsWith("(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)") + || desc.startsWith("(Ljava/util/concurrent/Callable;JLjava/util/concurrent/TimeUnit;)"))) { + return true; + } + if (("scheduleAtFixedRate".equals(mname) || "scheduleWithFixedDelay".equals(mname)) + && desc.startsWith("(Ljava/lang/Runnable;JJLjava/util/concurrent/TimeUnit;)")) { + 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 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) + && ("javax/jms/MessageConsumer".equals(owner) + || "jakarta/jms/MessageConsumer".equals(owner))) { + return true; + } + return false; + } + + private static boolean isAsyncMethodRefTarget(Handle h) { + String owner = h.getOwner(); + String mname = h.getName(); + String desc = h.getDesc(); + if (isUntrackedExecuteOrSubmit(owner, mname, desc) || isUntrackedScheduleOrInvokeAny(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)) { + 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 and *Async instance stages, + // 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) to RequestGate's identically-stacked static helpers. + // 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); @@ -715,9 +945,40 @@ public MethodVisitor visitMethod(int access, String name, String descriptor, Str return null; } return new MethodVisitor(Opcodes.ASM9, mv) { + private boolean addedStack; + + private void emitUntrackedFlag(String reason) { + changed[0] = true; + addedStack = true; + 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; + if (isAsyncMethodRefTarget(h)) { + emitUntrackedFlag("untracked-async:method-ref:" + + h.getOwner().replace('/', '.') + "." + h.getName()); + 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) @@ -848,6 +1109,16 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, } 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; @@ -855,6 +1126,30 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, "(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/lang/Thread".equals(owner) @@ -865,8 +1160,36 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, "(Ljava/lang/Thread;)V", false); return; } + // Flag-only async submission sites (task untouched, 100% app-safe). + if (opcode == Opcodes.INVOKEVIRTUAL || opcode == Opcodes.INVOKEINTERFACE) { + if (isUntrackedExecuteOrSubmit(owner, mname, desc)) { + emitUntrackedFlag("untracked-executor:" + owner.replace('/', '.')); + } else if (isUntrackedScheduleOrInvokeAny(mname, desc)) { + 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; + addedStack = true; + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfThread", + "(Ljava/lang/Object;)V", false); + } + } super.visitMethodInsn(opcode, owner, mname, desc, isInterface); } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + super.visitMaxs(addedStack ? maxStack + 1 : maxStack, maxLocals); + } }; } }, 0); 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 a48e02c7..397e77ff 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/AsyncHandTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/AsyncHandTest.java @@ -775,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 53cb9d6e..467df7a2 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=...,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. diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index cb613eb0..013bf78a 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -101,7 +101,9 @@ public void forkedExternalJacocoPrefixModeTracksCompletableFutureDependentsAndCh // Wait for audit to finish, then verify tail contamination was observed and drains. Thread.sleep(500); - app.runHttpTest("ts/drain-after-cf", "/clean"); + 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"); @@ -120,14 +122,77 @@ public void forkedExternalJacocoPrefixModeTracksCompletableFutureDependentsAndCh } @Test(timeout = 120000) - public void forkedUnknownSerializableExecutorIsUnwrappedAndContaminatesCov() throws Exception { + public void forkedUnknownSerializableExecutorIsUnwrappedAndContaminatesCurrentAndNextWindow() throws Exception { try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { - // SerializableOnlyExecutor throws IllegalStateException if task is wrapped! + // 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. B1: 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)) { + // B2: 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\"")); + + // B2: 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-async:method-ref:")); } } @@ -204,7 +269,9 @@ public void forkedJettyColdStartDeclaresWindowCutTrueAndUncountedServerMarksNoSe assertFalse("Jetty request is counted, no no-server-entry: " + cov, cov.contains("no-server-entry")); } - // 2. Uncounted HTTP server (JDK HttpServer): probes execute while enteredCount == 0 -> 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", @@ -212,6 +279,12 @@ public void forkedJettyColdStartDeclaresWindowCutTrueAndUncountedServerMarksNoSe String cov = uncounted.runHttpTest("ts/uncounted-1", "/clean"); assertTrue("uncounted server recording probes must fail closed with no-server-entry: " + cov, cov.contains("\"contaminated\":[\"no-server-entry\"]")); + 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()); } } @@ -238,7 +311,8 @@ private ForkedApp startFork(String mode, String endWait, boolean externalJacocoP File classes = tmp.newFolder(); for (Class cls : new Class[] { AsyncHonestyApp.class, AsyncHonestyApp.AsyncServlet.class, - AsyncHonestyApp.SerializableOnlyExecutor.class, AsyncHonestyApp.OrdersListenerBean.class, + AsyncHonestyApp.SerializableOnlyExecutor.class, AsyncHonestyApp.ConcreteCustomPool.class, + AsyncHonestyApp.MyWorkerThread.class, AsyncHonestyApp.OrdersListenerBean.class, AsyncHonestyApp.FakeKafkaProps.class, AsyncTail.class, Tail.class }) { String key = cls.getName().replace('.', '/') + ".class"; @@ -495,6 +569,7 @@ private static final class ForkedApp implements AutoCloseable { 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) { @@ -506,6 +581,7 @@ private static final class ForkedApp implements AutoCloseable { this.out = out; this.port = port; this.initialHello = initialHello; + this.lastHello = initialHello; } String runHttpTest(String testId, String path) throws IOException { @@ -547,6 +623,7 @@ String runKafkaTest(String testId) throws IOException { private String nextNonHello() throws IOException { String line = in.readLine(); while (line != null && line.startsWith("HELLO ")) { + lastHello = line; line = in.readLine(); } return line; diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 8a42da6f..d730b114 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -188,7 +188,7 @@ public void helloReportsLiveCapabilitiesAndIdentityAccuratelyAcrossRuntimeConfig assertEquals("uid-1234", h1.get("podUid").getAsString()); assertEquals("orders-pod-0", h1.get("podName").getAsString()); assertEquals("sess-abc", h1.get("sessionId").getAsString()); - assertEquals(KeployDedupAgent.JVM_NONCE, h1.get("jvmNonce").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()); @@ -249,13 +249,44 @@ public void helloReportsLiveCapabilitiesAndIdentityAccuratelyAcrossRuntimeConfig JsonObject h7 = parseHello(connectAndReadHello(true)); assertFalse("JPMS skipped must declare asyncExecutors=false", h7.get("asyncExecutors").getAsBoolean()); - // Case 8: Listener hook failure -> listenerContamination must be false. + // 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 (S4): 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 (S5): 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 (Nit): 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)); @@ -1001,9 +1032,10 @@ public void execute(Runnable command) { 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.isEmpty() - && decOutcome.contaminations.get(0).startsWith("untracked-executor:")); + decOutcome.contaminations.stream().anyMatch(s -> s.startsWith("untracked-executor:"))); assertTrue(ran.await(10, TimeUnit.SECONDS)); } finally { priority.shutdownNow(); @@ -1094,8 +1126,13 @@ public void firstHopQueueWaitDoesNotEatBudgetWhileChainedSelfResubmissionExpires 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 chain deadline expires", + assertEquals("no contamination after expired chain hop exits", Collections.emptyList(), JobGate.close()); } finally { pool.shutdownNow(); @@ -1544,7 +1581,13 @@ public void completableFutureDependentStagesAndAsyncInstanceMethodsAreTrackedAnd 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; @@ -1552,9 +1595,13 @@ public void pendingByFutureDoesNotLeakSelfReferencingCancellableJob() throws Exc 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))); @@ -1568,6 +1615,7 @@ public void pendingByFutureDoesNotLeakSelfReferencingCancellableJob() throws Exc assertNull("self-referencing job.future = exec.submit(job) must be GC'd with no leak", weakJob.get()); } finally { + blockRel.countDown(); pool.shutdownNow(); } } @@ -1607,35 +1655,43 @@ public void referenceQueueReleasesAbandonedHandPermitOnGc() throws Exception { } @Test(timeout = 60000) - public void unarmedKeployAbsentIsNoOpAndFirstArmedWindowMarksArmedMidFlight() throws Exception { + public void unarmedKeployAbsentIsNoOpAndMarksArmedMidFlightWhileUnarmedWorkRemainsInFlight() throws Exception { ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); try { RequestGate.disarm(); assertFalse(RequestGate.isArmed()); - // While unarmed: RequestGate.enter returns null, tasks are NOT wrapped, JobGate does nothing. - Object token = RequestGate.enter(); - assertNull("unarmed RequestGate.enter must be a no-op", token); + // 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"); - assertNull("unarmed JobGate.enter must be a no-op", jobTok); + 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(token); - JobGate.exit(jobTok); + RequestGate.exit(reqTok); - // Now arm via first START -> first armed window must be contaminated with "armed-mid-flight". + // B3: 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); - // Second armed window is clean. - RequestGate.open("second-armed", null); + RequestGate.open("second-armed-still-in-flight", null); RequestGate.WindowOutcome second = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - assertEquals(Collections.emptyList(), second.contaminations); + 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, Test 3 is clean. + JobGate.exit(jobTok); + assertEquals(0L, RequestGate.unarmedInFlight()); + RequestGate.open("third-armed-after-exit", null); + RequestGate.WindowOutcome third = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals(Collections.emptyList(), third.contaminations); } finally { pool.shutdownNow(); } @@ -1662,14 +1718,187 @@ public void listenerAttributionExtractsTopicsQueuesDestinationAndCachesPerInstan } @Test(timeout = 60000) - public void shadedAndRelocatedPackagesAreSkippedInPrefixMode() { + 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 (S6)", + prefixed.shouldRewriteExecutorCalls("com/acme/vendor/VendorService")); + assertTrue("app package /shadow/ must NOT be skipped (S6)", + 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")); - assertFalse(prefixed.shouldRewriteExecutorCalls("com/acme/third_party/Worker")); + + // S6: 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 untrackedTailsJobDeferredCfSpringSubclassFailClosedAndB2BytecodeForms() throws Exception { + ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + long savedTailWindow = RequestGate.untrackedTailWindowNanos; + try { + // B1: Untracked async hand-off marks current window AND immediately following window + // "tail:" until untrackedTailWindowNanos elapses. + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(120); + RequestGate.open("b1-untracked", 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("b1-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:b1-untracked"), out2.contaminations); + + Thread.sleep(160); + RequestGate.open("b1-after-expiry", null); + RequestGate.WindowOutcome out3 = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertEquals("clean after untracked tail window expires", + Collections.emptyList(), out3.contaminations); + + // S1: 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("s1-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()); + + // S1b: 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("s1-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")); + + // S3: 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 (S3)", + 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 (S3)", + OrderedPools.orders(nonSpringWithPoolMethod)); + + // B2: Non-Thread start() must NOT false-positive, while Thread subclass start() DOES flag. + RequestGate.disarm(); + RequestGate.open("b2-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); + + // B2 + S4: 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 (S4)", + ServerEntries.hasUnhookedConsumer()); + ServerEntries.setHookStatusForTests(false, false, false, false); + } finally { + RequestGate.untrackedTailWindowNanos = savedTailWindow; + pool.shutdownNow(); + } } @Test(timeout = 60000) 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 16f7b5c2..ade6d560 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/InProcessScanTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/InProcessScanTest.java @@ -1072,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()); } } diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index 7cdcbdea..ecf23571 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -18,9 +18,14 @@ 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; @@ -53,7 +58,27 @@ public final class AsyncHonestyApp { t.setDaemon(true); return t; }); - private static final ExecutorService SERIALIZABLE_ONLY_POOL = new SerializableOnlyExecutor(); + 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(); + // 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() { } @@ -170,6 +195,49 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO 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 ("/untracked-schedule".equals(path)) { SCHED.schedule(() -> AsyncTail.ran(), 1, TimeUnit.MILLISECONDS); } else if ("/untracked-thread".equals(path)) { @@ -187,17 +255,45 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } } + 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; + }); + } + } + + 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()); } - command.run(); + if (async) { + Thread t = new Thread(command, "serializable-async"); + t.setDaemon(true); + t.start(); + } else { + command.run(); + } } @Override From 95b625e0b3432d66aee66566291799f4f806d60d Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 06:45:57 +0530 Subject: [PATCH 08/26] fix(dedup): guard MinimalStage isDone, track MinimalFuture & GC permits, runtime Spring receiver check, delay-aware schedule tail, and S2/S4/S6 fixes Signed-off-by: slayerjain --- README.md | 4 +- .../main/java/io/keploy/dedup/JobGate.java | 35 +- .../io/keploy/dedup/KeployDedupAgent.java | 18 +- .../java/io/keploy/dedup/OrderedPools.java | 32 ++ .../java/io/keploy/dedup/RequestGate.java | 312 ++++++++++++++++-- .../java/io/keploy/dedup/ServerEntries.java | 243 +++++++++++--- .../dedup/HonestProtocolAndAsyncTest.java | 306 ++++++++++++++++- 7 files changed, 857 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index a3564196..56003f87 100644 --- a/README.md +++ b/README.md @@ -29,9 +29,9 @@ A server sends a response before it is done with the request: a filter's code af 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. -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. 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*`, `ExecutorService.invokeAny`, `Thread.start()` including subclasses, concrete custom executor `execute`/`submit`, `ForkJoinTask.fork()`, Reactor `Mono`/`Flux` `.subscribe()`, custom `CompletionStage`, and async method references such as `executor::execute`) execute untouched and mark the window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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 are rewritten without shaded-package filtering. +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. 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*` with delay-aware tail extension, Spring `TaskScheduler.schedule*`, `java.util.Timer.schedule*`, `ExecutorService.invokeAny`, `Thread.start()` including subclasses via runtime `instanceof Thread` check, 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`) execute untouched and mark the window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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 stuck lingering windows). 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 no-op using a static sentinel token); every armed window opened while any unarmed request or job remains in flight (and 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`, or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). +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`, or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). 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. 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 e357b3d0..1220bfa2 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -136,9 +136,14 @@ static Object enterAs(Attribution attribution) { } // markUntracked records an untracked async hand-off originated by a job's - // run (e.g., an unknown executor) on the currently open window (if any) - // and requests tail contamination on the immediately following window. + // 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; } @@ -146,7 +151,26 @@ static void markUntracked(String reason) { if (active != null) { active.mark(reason); } - RequestGate.noteExternalUntrackedTail(reason); + RequestGate.noteExternalUntrackedTail(reason, extraTailNanos); + } + + // expiredRunningName returns the job name if this thread is currently + // executing an expired handed-off job Run (whose runningAttribution() + // returns null so chained wrapping stops, while fan-out work from it is + // still flagged via job-tail:). + static String expiredRunningName() { + Run run = CURRENT.get(); + if (run == null) { + return null; + } + long now = System.nanoTime(); + while (run != null) { + if (!run.over && run.isExpired(now)) { + return run.name; + } + run = run.outer; + } + return null; } // detachThread restores CURRENT without removing the Run from RUNNING, so @@ -642,8 +666,9 @@ private static final class Run { // True for tasks handed off via enterAs (bounded by expiresAtNanos). private final boolean handed; private final long expiresAtNanos; - // Whether its exit came; only its own thread reads or sets it. - private boolean over; + // 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, boolean handed, long expiresAtNanos) { this.name = name; 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 b13bdb90..4a97cbb2 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -1192,7 +1192,12 @@ private boolean run(String line) { } private String unixReplyTaken() { - return computeCapabilities(collector).toUnixAck(); + 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. @@ -1404,7 +1409,7 @@ public void run() { while (running.get()) { try { connectAndServe(); - } catch (IOException | RuntimeException e) { + } catch (IOException | RuntimeException | LinkageError e) { if (running.get()) { Level level = connectFailureLogged ? Level.FINE : Level.INFO; connectFailureLogged = true; @@ -1560,7 +1565,11 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // collector has no other sign this test went unmeasured. writeLine(out, IGNORED_REPLY + " " + command.testId); } - maybeSendUpdatedHello(out); + try { + maybeSendUpdatedHello(out); + } catch (RuntimeException 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 @@ -1881,7 +1890,8 @@ private synchronized void dropProbeScan(Throwable cause) { // 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. + // 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) { 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 bb105837..1b6d910f 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -177,6 +177,38 @@ private static boolean isSpringExecutorHierarchy(Class cls) { 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 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 01b3bf31..80e0d30c 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -90,11 +90,18 @@ 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(); + // 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; @@ -112,6 +119,58 @@ public final class RequestGate { 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<>(); @@ -208,17 +267,27 @@ static long unarmedInFlight() { } 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; - externalUntrackedTailExpiresAtNanos = System.nanoTime() + untrackedTailWindowNanos; + 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) { + if (unarmedEntered || UNARMED_IN_FLIGHT.sum() > 0 || lastUnarmedHandOffNanos != 0L) { pendingArmedMidFlight = true; } armed = true; @@ -229,6 +298,7 @@ static void disarm() { armed = false; unarmedEntered = false; pendingArmedMidFlight = false; + lastUnarmedHandOffNanos = 0L; ARMED_MID_FLIGHT_CONSUMED.set(false); externalUntrackedTailPending = false; externalUntrackedTailExpiresAtNanos = 0L; @@ -328,10 +398,23 @@ private static void markUntrackedExecutor(Window window, JobGate.Attribution job } } + private static void noteExpiredJobFanOut() { + String expiredJob = JobGate.expiredRunningName(); + if (expiredJob != null) { + JobGate.markUntracked("job-tail:" + expiredJob); + } + } + private static Runnable handInternal(Object executor, Runnable task, boolean deferRelease) { - if (!armed || task == null) { + if (!armed) { + if (task != null && UNARMED_IN_FLIGHT.sum() > 0) { + lastUnarmedHandOffNanos = System.nanoTime(); + } return task; } + if (task == null) { + return null; + } if (task instanceof Handed) { if (OrderedPools.orders(executor)) { Handed existing = (Handed) task; @@ -346,6 +429,7 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def Window window = INSIDE.get(); JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; if (window == null && job == null) { + noteExpiredJobFanOut(); return task; } if (task instanceof Comparable) { @@ -382,9 +466,15 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def * @return what the executor runs instead */ public static Callable hand(Object executor, Callable task) { - if (!armed || task == null) { + if (!armed) { + if (task != null && UNARMED_IN_FLIGHT.sum() > 0) { + lastUnarmedHandOffNanos = System.nanoTime(); + } return task; } + if (task == null) { + return null; + } if (task instanceof HandedCall) { if (OrderedPools.orders(executor)) { @SuppressWarnings("unchecked") @@ -400,6 +490,7 @@ public static Callable hand(Object executor, Callable task) { Window window = INSIDE.get(); JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; if (window == null && job == null) { + noteExpiredJobFanOut(); return task; } if (task instanceof Comparable) { @@ -434,9 +525,15 @@ public static Supplier handSupplier(Object executor, Supplier supplier } private static Supplier handSupplierInternal(Object executor, Supplier supplier, boolean deferRelease) { - if (!armed || supplier == null) { + if (!armed) { + if (supplier != null && UNARMED_IN_FLIGHT.sum() > 0) { + lastUnarmedHandOffNanos = System.nanoTime(); + } return supplier; } + if (supplier == null) { + return null; + } if (supplier instanceof HandedSupplier) { if (OrderedPools.orders(executor)) { @SuppressWarnings("unchecked") @@ -452,6 +549,7 @@ private static Supplier handSupplierInternal(Object executor, Supplier Window window = INSIDE.get(); JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; if (window == null && job == null) { + noteExpiredJobFanOut(); return supplier; } if (supplier instanceof Comparable) { @@ -472,6 +570,12 @@ private static Supplier handSupplierInternal(Object executor, Supplier return handed; } + private static void noteUnarmedHandOffIfInFlight() { + if (UNARMED_IN_FLIGHT.sum() > 0) { + lastUnarmedHandOffNanos = System.nanoTime(); + } + } + /** * Call-site wrapper for {@link Executor#execute(Runnable)}: propagates the * current request window (or job run) across verified JDK executors. @@ -481,6 +585,7 @@ private static Supplier handSupplierInternal(Object executor, Supplier */ public static void execute(Executor executor, Runnable task) { if (!armed) { + noteUnarmedHandOffIfInFlight(); executor.execute(task); return; } @@ -503,6 +608,7 @@ public static void execute(Executor executor, Runnable task) { */ public static Future submit(ExecutorService executor, Runnable task) { if (!armed) { + noteUnarmedHandOffIfInFlight(); return executor.submit(task); } Runnable handed = hand(executor, task); @@ -529,6 +635,7 @@ public static Future submit(ExecutorService executor, Runnable task) { */ public static Future submit(ExecutorService executor, Runnable task, T result) { if (!armed) { + noteUnarmedHandOffIfInFlight(); return executor.submit(task, result); } Runnable handed = hand(executor, task); @@ -554,6 +661,7 @@ public static Future submit(ExecutorService executor, Runnable task, T re */ public static Future submit(ExecutorService executor, Callable task) { if (!armed) { + noteUnarmedHandOffIfInFlight(); return executor.submit(task); } Callable handed = hand(executor, task); @@ -579,6 +687,7 @@ public static Future submit(ExecutorService executor, Callable task) { */ public static CompletableFuture runAsync(Runnable task) { if (!armed) { + noteUnarmedHandOffIfInFlight(); return CompletableFuture.runAsync(task); } Runnable handed = handInternal(null, task, true); @@ -602,6 +711,7 @@ public static CompletableFuture runAsync(Runnable task) { */ public static CompletableFuture runAsync(Runnable task, Executor executor) { if (!armed) { + noteUnarmedHandOffIfInFlight(); return CompletableFuture.runAsync(task, executor); } Runnable handed = handInternal(executor, task, true); @@ -626,6 +736,7 @@ public static CompletableFuture runAsync(Runnable task, Executor executor) */ public static CompletableFuture supplyAsync(Supplier supplier) { if (!armed) { + noteUnarmedHandOffIfInFlight(); return CompletableFuture.supplyAsync(supplier); } Supplier handed = handSupplierInternal(null, supplier, true); @@ -650,6 +761,7 @@ public static CompletableFuture supplyAsync(Supplier supplier) { */ public static CompletableFuture supplyAsync(Supplier supplier, Executor executor) { if (!armed) { + noteUnarmedHandOffIfInFlight(); return CompletableFuture.supplyAsync(supplier, executor); } Supplier handed = handSupplierInternal(executor, supplier, true); @@ -669,11 +781,15 @@ public static CompletableFuture supplyAsync(Supplier supplier, Executo private static Hand prepareCfStageHand(CompletableFuture receiver, Executor explicitExecutor, boolean hasExecutor) { if (!armed) { + if (UNARMED_IN_FLIGHT.sum() > 0) { + lastUnarmedHandOffNanos = System.nanoTime(); + } return null; } Window window = INSIDE.get(); JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; if (window == null && job == null) { + noteExpiredJobFanOut(); return null; } if (hasExecutor) { @@ -698,40 +814,93 @@ private static Hand prepareCfStageHand(CompletableFuture receiver, Executor e } 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 || receiver == null) { return null; } + Window window = INSIDE.get(); + JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; + if (window == null && job == null) { + noteExpiredJobFanOut(); + return null; + } if (other == null) { - if (receiver.isDone()) { + if (safeIsDone(receiver)) { return null; } } else { - boolean otherDone = other instanceof CompletableFuture && ((CompletableFuture) other).isDone(); - if (either ? (receiver.isDone() || otherDone) : (receiver.isDone() && otherDone)) { + boolean receiverDone = safeIsDone(receiver); + boolean otherDone = safeIsDone(other); + if (either ? (receiverDone || otherDone) : (receiverDone && otherDone)) { return null; } } - Window window = INSIDE.get(); - JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; - if (window == null && job == null) { - return null; - } - if (receiver.getClass() != CompletableFuture.class) { + // 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); @@ -2779,19 +2948,63 @@ private static RuntimeException sneakyThrow(Throwable t) t * @param reason contamination reason label */ public static void noteUntrackedAsync(String reason) { - if (!armed || reason == null || reason.isEmpty()) { + noteUntrackedAsync(reason, 0L); + } + + private static void noteUntrackedAsync(String reason, long extraTailNanos) { + if (!armed) { + if (UNARMED_IN_FLIGHT.sum() > 0) { + lastUnarmedHandOffNanos = System.nanoTime(); + } + return; + } + if (reason == null || reason.isEmpty()) { return; } Window window = INSIDE.get(); if (window != null) { - window.contaminate(reason); + window.contaminate(reason, extraTailNanos); + if (window != current) { + retainLingering(window, System.nanoTime()); + } return; } if (JobGate.runningAttribution() != null) { - JobGate.markUntracked(reason); + JobGate.markUntracked(reason, extraTailNanos); + return; + } + String expiredJob = JobGate.expiredRunningName(); + if (expiredJob != null) { + JobGate.markUntracked("job-tail:" + expiredJob, extraTailNanos); } } + /** + * Checks at runtime whether an executor receiver is a hooked and verified + * Spring executor before a non-JDK {@code execute}/{@code submit} call, + * flagging {@code untracked-executor:} only when it is not. + * + * @param receiver target executor receiver + */ + public static void noteIfUntrackedExecutor(Object receiver) { + if (!armed) { + if (receiver != null && UNARMED_IN_FLIGHT.sum() > 0) { + lastUnarmedHandOffNanos = System.nanoTime(); + } + return; + } + if (receiver == null) { + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + return; + } + if (OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + return; + } + noteUntrackedAsync("untracked-executor:" + receiver.getClass().getName(), 0L); + } + /** * Checks whether {@code target} is a {@link Thread} instance before a * non-{@code java.lang.Thread} {@code start()} call and flags an untracked @@ -2801,8 +3014,16 @@ public static void noteUntrackedAsync(String reason) { */ public static void noteIfThread(Object target) { if (target instanceof Thread) { - noteUntrackedAsync("untracked-async:thread-start"); + noteUntrackedAsync("untracked-async:thread-start", 0L); + } + } + + private static long boundedDelayNanos(long delay, TimeUnit unit) { + if (delay <= 0L || unit == null) { + return 0L; } + long nanos = unit.toNanos(delay); + return nanos <= 0L ? 0L : Math.min(nanos, maxLingeringNanos); } /** @@ -2816,7 +3037,7 @@ public static void noteIfThread(Object target) { */ public static ScheduledFuture schedule(ScheduledExecutorService executor, Runnable command, long delay, TimeUnit unit) { - noteUntrackedAsync("untracked-async:schedule"); + noteUntrackedAsync("untracked-async:schedule", boundedDelayNanos(delay, unit)); return executor.schedule(command, delay, unit); } @@ -2832,7 +3053,7 @@ public static ScheduledFuture schedule(ScheduledExecutorService executor, Run */ public static ScheduledFuture schedule(ScheduledExecutorService executor, Callable callable, long delay, TimeUnit unit) { - noteUntrackedAsync("untracked-async:schedule"); + noteUntrackedAsync("untracked-async:schedule", boundedDelayNanos(delay, unit)); return executor.schedule(callable, delay, unit); } @@ -2849,7 +3070,8 @@ public static ScheduledFuture schedule(ScheduledExecutorService executor, */ public static ScheduledFuture scheduleAtFixedRate(ScheduledExecutorService executor, Runnable command, long initialDelay, long period, TimeUnit unit) { - noteUntrackedAsync("untracked-async:schedule"); + long extra = boundedDelayNanos(initialDelay, unit) + boundedDelayNanos(period, unit); + noteUntrackedAsync("untracked-async:schedule", Math.min(extra, maxLingeringNanos)); return executor.scheduleAtFixedRate(command, initialDelay, period, unit); } @@ -2866,7 +3088,8 @@ public static ScheduledFuture scheduleAtFixedRate(ScheduledExecutorService ex */ public static ScheduledFuture scheduleWithFixedDelay(ScheduledExecutorService executor, Runnable command, long initialDelay, long delay, TimeUnit unit) { - noteUntrackedAsync("untracked-async:schedule"); + long extra = boundedDelayNanos(initialDelay, unit) + boundedDelayNanos(delay, unit); + noteUntrackedAsync("untracked-async:schedule", Math.min(extra, maxLingeringNanos)); return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); } @@ -3137,6 +3360,7 @@ private static Hand takeFutureHand(Object key) { 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) { @@ -3190,6 +3414,10 @@ static void open(String testId, String prevActiveTestId) { 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; @@ -3208,7 +3436,7 @@ static void open(String testId, String prevActiveTestId) { prev.fallbackId = prevActiveTestId; } if (prevUntracked && prev.untrackedTailExpiresAtNanos == 0L) { - prev.untrackedTailExpiresAtNanos = now + untrackedTailWindowNanos; + prev.extendUntrackedTail(now, 0L); } retainLingering(prev, now); } @@ -3227,7 +3455,9 @@ static void open(String testId, String prevActiveTestId) { } for (Window lingering : LINGERING) { lingering.sweepCancelledFutures(); - boolean stillRunning = lingering.running.get() > 0; + boolean lingeringExpired = lingering.lingeringSinceNanos != 0L + && (now - lingering.lingeringSinceNanos) >= maxLingeringNanos; + boolean stillRunning = !lingeringExpired && lingering.running.get() > 0; boolean reportCut = lingering.wasCut && !lingering.cutReportedOnce; boolean untrackedActive = lingering.hadUntrackedAsync && (!lingering.untrackedTailReportedOnce @@ -3252,14 +3482,19 @@ static void open(String testId, String prevActiveTestId) { } private static void retainLingering(Window window, long now) { + if (window.lingeringSinceNanos == 0L) { + window.lingeringSinceNanos = now; + } if (LINGERING.size() >= MAX_LINGERING) { for (Window existing : LINGERING) { existing.sweepCancelledFutures(); + boolean lingeringExpired = existing.lingeringSinceNanos != 0L + && (now - existing.lingeringSinceNanos) >= maxLingeringNanos; boolean cutDone = !existing.wasCut || existing.cutReportedOnce; boolean untrackedDone = !existing.hadUntrackedAsync || (existing.untrackedTailReportedOnce && (now - existing.untrackedTailExpiresAtNanos) >= 0L); - if (existing.running.get() <= 0 && cutDone && untrackedDone) { + if ((lingeringExpired || existing.running.get() <= 0) && cutDone && untrackedDone) { LINGERING.remove(existing); } } @@ -3300,7 +3535,7 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { if (!wait) { long now = System.nanoTime(); if (window.hadUntrackedAsync) { - window.untrackedTailExpiresAtNanos = now + untrackedTailWindowNanos; + window.extendUntrackedTail(now, 0L); } if (initialRunning > 0 || window.hadUntrackedAsync) { retainLingering(window, now); @@ -3310,7 +3545,7 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { if (initialRunning <= 0) { if (window.hadUntrackedAsync) { long now = System.nanoTime(); - window.untrackedTailExpiresAtNanos = now + untrackedTailWindowNanos; + window.extendUntrackedTail(now, 0L); retainLingering(window, now); } return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations()); @@ -3351,7 +3586,7 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { window.wasCut = true; } if (window.hadUntrackedAsync) { - window.untrackedTailExpiresAtNanos = now + untrackedTailWindowNanos; + window.extendUntrackedTail(now, 0L); } retainLingering(window, now); } @@ -3387,6 +3622,7 @@ private static final class Window { private volatile boolean hadUntrackedAsync; 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). @@ -3410,12 +3646,26 @@ private String label() { 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; + extendUntrackedTail(System.nanoTime(), extraTailNanos); } if (contamCount.get() < JobGate.KEPT && contamSet.add(reason)) { if (contamCount.incrementAndGet() <= JobGate.KEPT) { @@ -3748,9 +3998,13 @@ final Object enter() { 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. + // window permit and re-retain the window if closed so exit() + // releases it cleanly when done. if (STATE.compareAndSet(this, s, (s & ~FLAG_RELEASED) | FLAG_STARTED)) { window.running.incrementAndGet(); + if (window != current) { + retainLingering(window, System.nanoTime()); + } break; } } else if (STATE.compareAndSet(this, s, s | FLAG_STARTED)) { 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 76e45abd..6adf6f93 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -93,13 +93,13 @@ final class ServerEntries implements ClassFileTransformer { addJob("JMS", "org/springframework/jms/listener/AbstractMessageListenerContainer", "listener", "doInvokeListener"); // Spring's executors a request hands work to. - addAsync("org/springframework/core/task/SimpleAsyncTaskExecutor", "doExecute"); + 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"); + "submitListenable", "submitCompletable"); addAsync("org/springframework/scheduling/concurrent/ConcurrentTaskExecutor", "execute", "submit", - "submitListenable"); + "submitListenable", "submitCompletable"); addAsync("org/springframework/aop/interceptor/AsyncExecutionAspectSupport", "doSubmit"); } @@ -129,11 +129,25 @@ final class ServerEntries implements ClassFileTransformer { 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; @@ -162,26 +176,26 @@ final class ServerEntries implements ClassFileTransformer { "java/util/concurrent/CompletableFuture", "java/util/concurrent/CompletionStage", "java/lang/Thread", + "java/util/Timer", + "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, so custom executor subtypes, Thread subclasses, - // CompletionStage, Reactor subscribe, method references, and raw consumer - // polling are never skipped by the fast pre-scan. + // 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", "schedule", "scheduleAtFixedRate", "scheduleWithFixedDelay", - "invokeAny", "remove", "shutdownNow", "runAsync", "supplyAsync", "completeAsync", - "fork", "subscribe", "start", "poll", "basicConsume", "receive", - "thenApplyAsync", "thenAcceptAsync", "thenRunAsync", "thenComposeAsync", - "thenCombineAsync", "thenAcceptBothAsync", "runAfterBothAsync", - "applyToEitherAsync", "acceptEitherAsync", "runAfterEitherAsync", - "handleAsync", "whenCompleteAsync", "exceptionallyAsync", "exceptionallyComposeAsync", - "thenApply", "thenAccept", "thenRun", "thenCompose", - "thenCombine", "thenAcceptBoth", "runAfterBoth", - "applyToEither", "acceptEither", "runAfterEither", - "handle", "whenComplete", "exceptionally", "exceptionallyCompose"))); + "execute", "submit", "submitListenable", "submitCompletable", + "schedule", "scheduleAtFixedRate", "scheduleWithFixedDelay", + "invokeAny", "fork", "subscribe", "start", + "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 = @@ -320,6 +334,14 @@ 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 boolean hadServerHookFailure() { return serverHookFailed; } @@ -416,6 +438,7 @@ public byte[] transform(ClassLoader loader, String className, Class classBein } else { appRewriteFailed = true; } + scanRawConsumerCalls(classfileBuffer); return null; } try { @@ -428,6 +451,12 @@ public byte[] transform(ClassLoader loader, String className, Class classBein appRewriteFailed = true; LOGGER.log(Level.FINE, "Keploy dedup skipped executor call-site wrap for " + className, t); } + } else if (className != null && isRewriteAllowedPackage(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. + scanRawConsumerCalls(classfileBuffer); } return null; } @@ -463,6 +492,8 @@ public byte[] transform(ClassLoader loader, String className, Class classBein } 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); @@ -607,6 +638,10 @@ boolean shouldRewriteExecutorCalls(String 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 @@ -614,6 +649,17 @@ boolean shouldRewriteExecutorCalls(String className) { && !isShadedOrRelocated(className); } + 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; @@ -738,14 +784,7 @@ static boolean isShadedOrRelocated(String className) { // applied only in prefix mode (not exact appClasses index mode). static boolean isRewriteAllowedPackage(String className) { return className != null - && !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/") + && !isInternalOrAgentClass(className) && !className.startsWith("io/netty/") && !className.startsWith("reactor/") && !className.startsWith("okhttp3/") @@ -754,7 +793,8 @@ static boolean isRewriteAllowedPackage(String className) { && !className.startsWith("io/grpc/") && !className.startsWith("software/amazon/") && !className.startsWith("com/amazonaws/") - && !className.startsWith("org/springframework/") + && (!className.startsWith("org/springframework/") + || className.startsWith("org/springframework/samples/")) && !className.startsWith("org/apache/catalina/") && !className.startsWith("org/apache/coyote/") && !className.startsWith("org/apache/tomcat/") @@ -808,40 +848,79 @@ static boolean hasExecutorReference(ClassReader reader) { return false; } - private static boolean isHookedSpringExecutorOwner(String owner) { - return "org/springframework/core/task/TaskExecutor".equals(owner) - || "org/springframework/core/task/AsyncTaskExecutor".equals(owner) - || "org/springframework/core/task/AsyncListenableTaskExecutor".equals(owner) - || "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 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 isUntrackedExecuteOrSubmit(String owner, String mname, String desc) { - if (isHookedSpringExecutorOwner(owner)) { - return false; - } + private static boolean isSingleArgExecutorSubmitOrExecute(String mname, String desc) { if ("execute".equals(mname) && "(Ljava/lang/Runnable;)V".equals(desc)) { return true; } - if ("submit".equals(mname) + if (("submit".equals(mname) || "submitListenable".equals(mname) || "submitCompletable".equals(mname)) && (desc.startsWith("(Ljava/lang/Runnable;)") - || desc.startsWith("(Ljava/lang/Runnable;Ljava/lang/Object;)") || desc.startsWith("(Ljava/util/concurrent/Callable;)"))) { return true; } return false; } + 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;JLjava/util/concurrent/TimeUnit;)") - || desc.startsWith("(Ljava/util/concurrent/Callable;JLjava/util/concurrent/TimeUnit;)"))) { + && (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;JJLjava/util/concurrent/TimeUnit;)")) { + && desc.startsWith("(Ljava/lang/Runnable;")) { return true; } if ("invokeAny".equals(mname) @@ -852,6 +931,30 @@ private static boolean isUntrackedScheduleOrInvokeAny(String mname, String desc) 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) @@ -868,7 +971,7 @@ private static boolean isDirectRawConsumerCall(String owner, String mname) { if ("basicConsume".equals(mname) && "com/rabbitmq/client/Channel".equals(owner)) { return true; } - if ("receive".equals(mname) + if (("receive".equals(mname) || "setMessageListener".equals(mname)) && ("javax/jms/MessageConsumer".equals(owner) || "jakarta/jms/MessageConsumer".equals(owner))) { return true; @@ -876,11 +979,24 @@ private static boolean isDirectRawConsumerCall(String owner, String mname) { 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 isAsyncMethodRefTarget(Handle h) { String owner = h.getOwner(); String mname = h.getName(); String desc = h.getDesc(); - if (isUntrackedExecuteOrSubmit(owner, mname, desc) || isUntrackedScheduleOrInvokeAny(mname, desc)) { + if (!isHookedSpringMethodRefOwner(owner) + && (isSingleArgExecutorSubmitOrExecute(mname, desc) || isTwoArgExecutorSubmit(mname, desc))) { + return true; + } + if (isUntrackedScheduleOrInvokeAny(mname, desc) + || isTimerSchedule(owner, mname, desc) + || isForkJoinTaskSubmission(owner, mname, desc)) { return true; } if ("java/util/concurrent/CompletableFuture".equals(owner)) { @@ -945,11 +1061,17 @@ public MethodVisitor visitMethod(int access, String name, String descriptor, Str return null; } return new MethodVisitor(Opcodes.ASM9, mv) { - private boolean addedStack; + private int extraStack; + + private void ensureExtraStack(int needed) { + if (extraStack < needed) { + extraStack = needed; + } + } private void emitUntrackedFlag(String reason) { changed[0] = true; - addedStack = true; + ensureExtraStack(1); super.visitLdcInsn(reason); super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteUntrackedAsync", "(Ljava/lang/String;)V", false); @@ -1161,9 +1283,26 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, return; } // Flag-only async submission sites (task untouched, 100% app-safe). - if (opcode == Opcodes.INVOKEVIRTUAL || opcode == Opcodes.INVOKEINTERFACE) { - if (isUntrackedExecuteOrSubmit(owner, mname, desc)) { + if (isGuavaAsyncCall(opcode, owner, mname, desc)) { + emitUntrackedFlag("untracked-async:guava-future"); + } else if (opcode == Opcodes.INVOKEVIRTUAL || opcode == Opcodes.INVOKEINTERFACE) { + if (isSingleArgExecutorSubmitOrExecute(mname, desc)) { + // Decide at runtime by actual receiver so Spring interfaces + // (TaskExecutor/AsyncTaskExecutor) and subclasses have zero + // false positives when hooked+verified AND zero false negatives + // when backed by VirtualThreadTaskExecutor/custom pools. + 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 (isTwoArgExecutorSubmit(mname, desc)) { emitUntrackedFlag("untracked-executor:" + owner.replace('/', '.')); + } 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)) { emitUntrackedFlag("untracked-async:" + ("invokeAny".equals(mname) ? "invokeAny" : "schedule")); @@ -1177,7 +1316,7 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, // Only flag if runtime receiver is a Thread subclass (zero false // positives on non-Thread start() methods). changed[0] = true; - addedStack = true; + ensureExtraStack(1); super.visitInsn(Opcodes.DUP); super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfThread", "(Ljava/lang/Object;)V", false); @@ -1188,7 +1327,7 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, @Override public void visitMaxs(int maxStack, int maxLocals) { - super.visitMaxs(addedStack ? maxStack + 1 : maxStack, maxLocals); + super.visitMaxs(maxStack + extraStack, maxLocals); } }; } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index d730b114..21f90cd8 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -1658,7 +1658,9 @@ public void referenceQueueReleasesAbandonedHandPermitOnGc() throws Exception { 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()); @@ -1686,13 +1688,15 @@ public void unarmedKeployAbsentIsNoOpAndMarksArmedMidFlightWhileUnarmedWorkRemai 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, Test 3 is clean. + // 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(); } } @@ -1901,6 +1905,306 @@ public ThreadPoolExecutor getThreadPoolExecutor() { } } + @Test(timeout = 60000) + public void minimalStageNoUoeMinimalFutureTrackedAbandonedStageGcAndR3Regressions() 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 { + // NB1: 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("nb1-minimal-stage", 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 nb1Out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("MinimalStage dependents must drain cleanly", nb1Out.drained); + assertEquals("MinimalStage must not spuriously contaminate: " + nb1Out.contaminations, + Collections.emptyList(), nb1Out.contaminations); + } catch (NoSuchMethodException java8Skip) { + // Java 8 has no completedStage/minimalCompletionStage. + } + + // SF3: 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("sf3-minimal-future", null); + Object reqSf3 = 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(reqSf3); + } + assertEquals("window still waits for MinimalFuture-like dependent", 1, RequestGate.running()); + httpCf.complete("200"); + assertTrue(auditRan.get()); + RequestGate.WindowOutcome sf3Out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue(sf3Out.drained); + assertEquals("MinimalFuture-like dependent must NOT contaminate", + Collections.emptyList(), sf3Out.contaminations); + + RequestGate.open("sf3-override-cf", null); + Object reqSf3b = RequestGate.enter(); + try { + RequestGate.thenAccept(new OverridingCf(), v -> { }); + } finally { + RequestGate.exit(reqSf3b); + } + RequestGate.WindowOutcome sf3bOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("CF subclass overriding thenAccept must fail closed: " + sf3bOut.contaminations, + sf3bOut.contaminations.stream().anyMatch(s -> s.startsWith("untracked-executor:"))); + + // SF1: 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("sf1-gc", null); + Object reqSf1 = RequestGate.enter(); + try { + CompletableFuture abandoned = new CompletableFuture<>(); + RequestGate.thenAccept(abandoned, v -> { }); + assertEquals(2, RequestGate.running()); + abandoned = null; + } finally { + RequestGate.exit(reqSf1); + } + 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 (SF1)", + 0, RequestGate.running()); + + RequestGate.maxLingeringNanos = TimeUnit.MILLISECONDS.toNanos(100); + CompletableFuture neverCompletes = new CompletableFuture<>(); + RequestGate.open("sf1-stuck", 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("sf1-while-stuck", null); + assertEquals(Collections.singletonList("tail:sf1-stuck"), + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(50), true).contaminations); + Thread.sleep(140); + RequestGate.open("sf1-after-bound", null); + assertEquals("stuck lingering window must stop poisoning after maxLingeringNanos (SF1)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(50), true).contaminations); + RequestGate.maxLingeringNanos = savedMaxLingering; + + // SF2: 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("sf2-spring-ok", null); + Object reqSp = RequestGate.enter(); + try { + RequestGate.noteIfUntrackedExecutor(springExec); + } finally { + RequestGate.exit(reqSp); + } + assertEquals("hooked & verified Spring executor must NOT false-positive (SF2)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + RequestGate.open("sf2-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 (SF2): " + + customOut.contaminations, + customOut.contaminations.contains("untracked-executor:" + customTe.getClass().getName())); + } finally { + springExec.shutdown(); + } + + // SF4: schedule(r, delay, unit) extends untracked tail window by delay! + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(50); + RequestGate.open("sf4-sched", 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("sf4-during-delay", null); + assertEquals("scheduled delay must keep next window contaminated past base tail (SF4)", + Collections.singletonList("tail:sf4-sched"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.untrackedTailWindowNanos = savedTailWindow; + + // SF5: Expired job hop that fans out to an executor flags job-tail on active & next window! + RequestGate.disarm(); + JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(40); + RequestGate.open("sf5-arm", null); + CountDownLatch fanoutDone = new CountDownLatch(1); + 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.execute(pool, fanoutDone::countDown); + }); + } finally { + JobGate.exit(jTok); + } + hop1.run(); + assertTrue(fanoutDone.await(5, TimeUnit.SECONDS)); + List sf5JobContams = JobGate.close(); + assertTrue("expired hop fan-out must mark JobGate window job-tail (SF5): " + sf5JobContams, + sf5JobContams.stream().anyMatch(s -> s.startsWith("job-tail:"))); + RequestGate.open("sf5-next", null); + RequestGate.WindowOutcome sf5Next = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("expired hop fan-out must mark next RequestGate window tail:job-tail (SF5): " + + sf5Next.contaminations, + sf5Next.contaminations.stream().anyMatch(s -> s.startsWith("tail:job-tail:"))); + + // SF6: 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("sf6-w1", null); + assertEquals(Collections.singletonList("armed-mid-flight"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.open("sf6-w2", null); + assertEquals("unarmed hand-off keeps marking armed-mid-flight within tail window (SF6)", + Collections.singletonList("armed-mid-flight"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.untrackedTailWindowNanos = savedTailWindow; + + // SF7: 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 (SF7)", + 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 (SF7)", + ServerEntries.hasUnhookedConsumer()); + ServerEntries.setHookStatusForTests(false, false, false, false); + + // SF8: 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 (SF8)", + 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 concurrentRequestExecutorAndJobGateContentionStaysBoundedAndLeakFree() throws Exception { ThreadPoolExecutor pool = new ThreadPoolExecutor(4, 4, 0L, TimeUnit.MILLISECONDS, From db2174c7e2a14ad49811b286f1d861ba5b034b0f Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 07:13:34 +0530 Subject: [PATCH 09/26] fix(dedup): track executing work past lingering cap, live Thread/ScheduledFuture handles, multi-hop expired jobs, JDK 21 virtual threads, and flag-site tests Signed-off-by: slayerjain --- README.md | 2 +- .../main/java/io/keploy/dedup/JobGate.java | 20 +- .../java/io/keploy/dedup/RequestGate.java | 276 ++++++++++--- .../java/io/keploy/dedup/ServerEntries.java | 53 ++- .../dedup/ForkedAsyncAndHonestyTest.java | 35 +- .../dedup/HonestProtocolAndAsyncTest.java | 380 +++++++++++++++++- .../org/example/servers/AsyncHonestyApp.java | 88 ++++ 7 files changed, 790 insertions(+), 64 deletions(-) diff --git a/README.md b/README.md index 56003f87..a652e502 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ A server sends a response before it is done with the request: a filter's code af 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. -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. 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*` with delay-aware tail extension, Spring `TaskScheduler.schedule*`, `java.util.Timer.schedule*`, `ExecutorService.invokeAny`, `Thread.start()` including subclasses via runtime `instanceof Thread` check, 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`) execute untouched and mark the window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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 stuck lingering windows). 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`. +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. 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, `java.util.Timer.schedule*` with a 2 s tail bound because `Timer.schedule` returns `void`, `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`) execute untouched and mark the window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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). Limits: 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`, or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). 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 1220bfa2..34d438ba 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -154,11 +154,12 @@ static void markUntracked(String reason, long extraTailNanos) { RequestGate.noteExternalUntrackedTail(reason, extraTailNanos); } - // expiredRunningName returns the job name if this thread is currently - // executing an expired handed-off job Run (whose runningAttribution() - // returns null so chained wrapping stops, while fan-out work from it is - // still flagged via job-tail:). - static String expiredRunningName() { + // 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; @@ -166,13 +167,20 @@ static String expiredRunningName() { long now = System.nanoTime(); while (run != null) { if (!run.over && run.isExpired(now)) { - return run.name; + 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). 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 80e0d30c..6b1fb351 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -107,6 +107,12 @@ public final class RequestGate { 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); // 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, @@ -303,6 +309,7 @@ static void disarm() { externalUntrackedTailPending = false; externalUntrackedTailExpiresAtNanos = 0L; externalUntrackedTailReason = null; + EXTERNAL_UNTRACKED_HANDLES.clear(); LINGERING.clear(); current = new Window(null); } @@ -343,6 +350,7 @@ public static Object enter() { // Counted last: whatever failed before it (out of memory) leaves // nothing to undo. window.enteredCount.incrementAndGet(); + window.executing.incrementAndGet(); window.running.incrementAndGet(); return token; } @@ -363,10 +371,13 @@ public static void exit(Object token) { } 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); } } @@ -389,26 +400,28 @@ public static Runnable hand(Object executor, Runnable task) { 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) { - JobGate.markUntracked(reason); - } - } - - private static void noteExpiredJobFanOut() { - String expiredJob = JobGate.expiredRunningName(); - if (expiredJob != null) { - JobGate.markUntracked("job-tail:" + expiredJob); + 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 && UNARMED_IN_FLIGHT.sum() > 0) { - lastUnarmedHandOffNanos = System.nanoTime(); + if (task != null) { + noteUnarmedHandOffIfInFlight(); } return task; } @@ -427,9 +440,8 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def return task; } Window window = INSIDE.get(); - JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; + JobGate.Attribution job = currentOrExpiredJob(window); if (window == null && job == null) { - noteExpiredJobFanOut(); return task; } if (task instanceof Comparable) { @@ -467,8 +479,8 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def */ public static Callable hand(Object executor, Callable task) { if (!armed) { - if (task != null && UNARMED_IN_FLIGHT.sum() > 0) { - lastUnarmedHandOffNanos = System.nanoTime(); + if (task != null) { + noteUnarmedHandOffIfInFlight(); } return task; } @@ -488,9 +500,8 @@ public static Callable hand(Object executor, Callable task) { return task; } Window window = INSIDE.get(); - JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; + JobGate.Attribution job = currentOrExpiredJob(window); if (window == null && job == null) { - noteExpiredJobFanOut(); return task; } if (task instanceof Comparable) { @@ -526,8 +537,8 @@ public static Supplier handSupplier(Object executor, Supplier supplier private static Supplier handSupplierInternal(Object executor, Supplier supplier, boolean deferRelease) { if (!armed) { - if (supplier != null && UNARMED_IN_FLIGHT.sum() > 0) { - lastUnarmedHandOffNanos = System.nanoTime(); + if (supplier != null) { + noteUnarmedHandOffIfInFlight(); } return supplier; } @@ -547,9 +558,8 @@ private static Supplier handSupplierInternal(Object executor, Supplier return supplier; } Window window = INSIDE.get(); - JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; + JobGate.Attribution job = currentOrExpiredJob(window); if (window == null && job == null) { - noteExpiredJobFanOut(); return supplier; } if (supplier instanceof Comparable) { @@ -572,7 +582,11 @@ private static Supplier handSupplierInternal(Object executor, Supplier private static void noteUnarmedHandOffIfInFlight() { if (UNARMED_IN_FLIGHT.sum() > 0) { - lastUnarmedHandOffNanos = System.nanoTime(); + long now = System.nanoTime(); + long prev = lastUnarmedHandOffNanos; + if (prev == 0L || (now - prev) >= UNARMED_HANDOFF_THROTTLE_NANOS) { + lastUnarmedHandOffNanos = now; + } } } @@ -781,15 +795,12 @@ public static CompletableFuture supplyAsync(Supplier supplier, Executo private static Hand prepareCfStageHand(CompletableFuture receiver, Executor explicitExecutor, boolean hasExecutor) { if (!armed) { - if (UNARMED_IN_FLIGHT.sum() > 0) { - lastUnarmedHandOffNanos = System.nanoTime(); - } + noteUnarmedHandOffIfInFlight(); return null; } Window window = INSIDE.get(); - JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; + JobGate.Attribution job = currentOrExpiredJob(window); if (window == null && job == null) { - noteExpiredJobFanOut(); return null; } if (hasExecutor) { @@ -841,13 +852,18 @@ private static boolean safeIsDone(Object stage) { } private static Hand prepareCfSyncHand(CompletableFuture receiver, CompletionStage other, boolean either) { - if (!armed || receiver == null) { + if (!armed) { + if (receiver != null) { + noteUnarmedHandOffIfInFlight(); + } + return null; + } + if (receiver == null) { return null; } Window window = INSIDE.get(); - JobGate.Attribution job = window == null ? JobGate.runningAttribution() : null; + JobGate.Attribution job = currentOrExpiredJob(window); if (window == null && job == null) { - noteExpiredJobFanOut(); return null; } if (other == null) { @@ -3007,17 +3023,90 @@ public static void noteIfUntrackedExecutor(Object receiver) { /** * Checks whether {@code target} is a {@link Thread} instance before a - * non-{@code java.lang.Thread} {@code start()} call and flags an untracked - * thread start if so. + * 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 while the thread remains alive. * * @param target receiver of {@code start()} */ public static void noteIfThread(Object target) { if (target instanceof Thread) { noteUntrackedAsync("untracked-async:thread-start", 0L); + trackUntrackedHandleForCurrent(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) { + if (thread instanceof Thread) { + trackUntrackedHandleForCurrent(thread, true); } } + /** + * 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) { + if (future instanceof Future) { + trackUntrackedHandleForCurrent(future, true); + } + } + + private static void trackUntrackedHandleForCurrent(Object handle, boolean alreadyStarted) { + if (!armed || handle == null) { + return; + } + Window window = INSIDE.get(); + if (window != null) { + window.addUntrackedHandle(handle, alreadyStarted); + if (window != current) { + retainLingering(window, System.nanoTime()); + } + return; + } + if (JobGate.runningAttribution() != null || JobGate.expiredAttribution() != null) { + addHandleToQueue(EXTERNAL_UNTRACKED_HANDLES, handle, alreadyStarted); + } + } + + private static void addHandleToQueue(ConcurrentLinkedQueue queue, Object handle, + boolean alreadyStarted) { + long now = System.nanoTime(); + if (queue.size() >= MAX_UNTRACKED_HANDLES) { + sweepUntrackedHandles(queue, now); + if (queue.size() >= MAX_UNTRACKED_HANDLES) { + return; + } + } + queue.add(new UntrackedHandle(handle, alreadyStarted, now)); + } + + 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 long boundedDelayNanos(long delay, TimeUnit unit) { if (delay <= 0L || unit == null) { return 0L; @@ -3038,7 +3127,9 @@ private static long boundedDelayNanos(long delay, TimeUnit unit) { public static ScheduledFuture schedule(ScheduledExecutorService executor, Runnable command, long delay, TimeUnit unit) { noteUntrackedAsync("untracked-async:schedule", boundedDelayNanos(delay, unit)); - return executor.schedule(command, delay, unit); + ScheduledFuture sf = executor.schedule(command, delay, unit); + trackUntrackedHandleForCurrent(sf, true); + return sf; } /** @@ -3054,7 +3145,9 @@ public static ScheduledFuture schedule(ScheduledExecutorService executor, Run public static ScheduledFuture schedule(ScheduledExecutorService executor, Callable callable, long delay, TimeUnit unit) { noteUntrackedAsync("untracked-async:schedule", boundedDelayNanos(delay, unit)); - return executor.schedule(callable, delay, unit); + ScheduledFuture sf = executor.schedule(callable, delay, unit); + trackUntrackedHandleForCurrent(sf, true); + return sf; } /** @@ -3072,7 +3165,9 @@ public static ScheduledFuture scheduleAtFixedRate(ScheduledExecutorService ex long initialDelay, long period, TimeUnit unit) { long extra = boundedDelayNanos(initialDelay, unit) + boundedDelayNanos(period, unit); noteUntrackedAsync("untracked-async:schedule", Math.min(extra, maxLingeringNanos)); - return executor.scheduleAtFixedRate(command, initialDelay, period, unit); + ScheduledFuture sf = executor.scheduleAtFixedRate(command, initialDelay, period, unit); + trackUntrackedHandleForCurrent(sf, true); + return sf; } /** @@ -3090,7 +3185,9 @@ public static ScheduledFuture scheduleWithFixedDelay(ScheduledExecutorService long initialDelay, long delay, TimeUnit unit) { long extra = boundedDelayNanos(initialDelay, unit) + boundedDelayNanos(delay, unit); noteUntrackedAsync("untracked-async:schedule", Math.min(extra, maxLingeringNanos)); - return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); + ScheduledFuture sf = executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); + trackUntrackedHandleForCurrent(sf, true); + return sf; } /** @@ -3138,6 +3235,7 @@ public static T invokeAny(ExecutorService executor, Collection= maxLingeringNanos; - boolean stillRunning = !lingeringExpired && lingering.running.get() > 0; + boolean aliveHandles = lingering.hasAliveUntrackedHandles(now); + // Actively executing work (executing > 0) and live untracked + // threads/futures NEVER expire under maxLingeringNanos; only idle + // uncompleted permits (running > 0 && executing == 0) are bounded + // by maxLingeringNanos. + boolean stillRunning = lingering.executing.get() > 0 + || aliveHandles + || (!lingeringExpired && lingering.running.get() > 0); boolean reportCut = lingering.wasCut && !lingering.cutReportedOnce; boolean untrackedActive = lingering.hadUntrackedAsync && (!lingering.untrackedTailReportedOnce @@ -3490,11 +3597,15 @@ private static void retainLingering(Window window, long now) { 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); boolean cutDone = !existing.wasCut || existing.cutReportedOnce; boolean untrackedDone = !existing.hadUntrackedAsync || (existing.untrackedTailReportedOnce && (now - existing.untrackedTailExpiresAtNanos) >= 0L); - if ((lingeringExpired || existing.running.get() <= 0) && cutDone && untrackedDone) { + if (!stillRunning && cutDone && untrackedDone) { LINGERING.remove(existing); } } @@ -3607,14 +3718,58 @@ static final class WindowOutcome { } } + private static final class UntrackedHandle { + + private final WeakReference ref; + private final boolean alreadyStarted; + private final long registeredAtNanos; + private volatile boolean observedAlive; + + private UntrackedHandle(Object target, boolean alreadyStarted, long registeredAtNanos) { + this.ref = new WeakReference(target); + this.alreadyStarted = alreadyStarted; + this.registeredAtNanos = registeredAtNanos; + } + + 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) { + return false; + } + // Registered immediately before subThread.start(): keep active + // briefly in case the OS thread hasn't transitioned to alive yet. + return (now - registeredAtNanos) < untrackedTailWindowNanos; + } + if (target instanceof Future) { + return !isFutureTerminated((Future) target); + } + 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; @@ -3628,6 +3783,10 @@ private static final class Window { // windows without an END cannot grow unboundedly). @SuppressWarnings("rawtypes") private volatile ConcurrentHashMap futures; + // Weak handles to live untracked Threads and ScheduledFutures started + // in this window so tail contamination persists while they stay alive. + @SuppressWarnings("rawtypes") + private volatile ConcurrentLinkedQueue untrackedHandles; private final AtomicInteger insertsSinceSweep = new AtomicInteger(); // Lock-free contamination reasons collected during this window. private final Set contamSet = ConcurrentHashMap.newKeySet(); @@ -3741,6 +3900,29 @@ private void sweepCancelledFutures() { } } } + + @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(Object target, boolean alreadyStarted) { + hadUntrackedAsync = true; + addHandleToQueue(untrackedHandlesQueue(true), target, alreadyStarted); + } + + private boolean hasAliveUntrackedHandles(long now) { + return sweepUntrackedHandles(untrackedHandlesQueue(false), now); + } } // Nested is the token of a request entered on a thread that already @@ -3998,19 +4180,22 @@ final Object enter() { 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 and re-retain the window if closed so exit() - // releases it cleanly when done. + // window permit so exit() releases it cleanly when done. if (STATE.compareAndSet(this, s, (s & ~FLAG_RELEASED) | FLAG_STARTED)) { window.running.incrementAndGet(); - if (window != current) { - retainLingering(window, System.nanoTime()); - } break; } } else if (STATE.compareAndSet(this, s, s | FLAG_STARTED)) { break; } } + window.executing.incrementAndGet(); + if (window != current) { + // Re-retain closed windows when a queued/late task actually + // begins executing so executing > 0 keeps flagging tail: + // until it finishes, even past maxLingeringNanos. + retainLingering(window, System.nanoTime()); + } clearFutureKey(); Window outer = INSIDE.get(); INSIDE.set(window); @@ -4042,6 +4227,7 @@ final void exit(Object outer) { } } } + window.executing.decrementAndGet(); if (outer == null) { INSIDE.remove(); } else { 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 6adf6f93..4d3afbbf 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -176,6 +176,9 @@ final class ServerEntries implements ClassFileTransformer { "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", "org/springframework/scheduling/TaskScheduler", "com/google/common/util/concurrent/Futures", @@ -193,7 +196,7 @@ final class ServerEntries implements ClassFileTransformer { 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", + "invokeAny", "fork", "subscribe", "start", "startVirtualThread", "addListener", "addCallback", "transform", "transformAsync", "catching", "catchingAsync", "poll", "basicConsume", "receive", "setMessageListener"))); @@ -451,11 +454,13 @@ public byte[] transform(ClassLoader loader, String className, Class classBein appRewriteFailed = true; LOGGER.log(Level.FINE, "Keploy dedup skipped executor call-site wrap for " + className, t); } - } else if (className != null && isRewriteAllowedPackage(className)) { + } 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. + // stays honest without modifying any bytecode (skipping known + // JMS/RabbitMQ pooling/recovery wrappers used by Spring Boot). scanRawConsumerCalls(classfileBuffer); } return null; @@ -649,6 +654,12 @@ boolean shouldRewriteExecutorCalls(String className) { && !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/") @@ -1025,7 +1036,13 @@ private static boolean isAsyncMethodRefTarget(Handle h) { if ("fork".equals(mname) && "()Ljava/util/concurrent/ForkJoinTask;".equals(desc)) { return true; } - if ("java/lang/Thread".equals(owner) && "start".equals(mname) && "()V".equals(desc)) { + 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); @@ -1282,6 +1299,27 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, "(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)) { + emitUntrackedFlag("untracked-async:virtual-thread"); + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "trackUntrackedThread", + "(Ljava/lang/Object;)V", false); + return; + } + if ((opcode == Opcodes.INVOKEINTERFACE || opcode == Opcodes.INVOKEVIRTUAL) + && "start".equals(mname) + && "(Ljava/lang/Runnable;)Ljava/lang/Thread;".equals(desc)) { + emitUntrackedFlag("untracked-async:thread-builder"); + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "trackUntrackedThread", + "(Ljava/lang/Object;)V", false); + return; + } // Flag-only async submission sites (task untouched, 100% app-safe). if (isGuavaAsyncCall(opcode, owner, mname, desc)) { emitUntrackedFlag("untracked-async:guava-future"); @@ -1306,6 +1344,13 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, } else if (isUntrackedScheduleOrInvokeAny(mname, desc)) { emitUntrackedFlag("untracked-async:" + ("invokeAny".equals(mname) ? "invokeAny" : "schedule")); + if (desc.endsWith(")Ljava/util/concurrent/ScheduledFuture;")) { + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "trackUntrackedFuture", + "(Ljava/lang/Object;)V", false); + return; + } } else if ("fork".equals(mname) && "()Ljava/util/concurrent/ForkJoinTask;".equals(desc)) { emitUntrackedFlag("untracked-async:fork"); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index 013bf78a..72799d59 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -288,6 +288,36 @@ public void forkedJettyColdStartDeclaresWindowCutTrueAndUncountedServerMarksNoSe } } + @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! + try (ForkedApp app = startFork("tomcat", "2000", true, false, null, null)) { + String covDirect = app.runHttpTest("ts/vthread-1", "/virtual-thread?ms=350"); + assertTrue("Thread.startVirtualThread must contaminate COV (SF-D): " + covDirect, + covDirect.contains("\"untracked-async:virtual-thread\"")); + + String covAfterDirect = app.runHttpTest("ts/vthread-next", "/clean"); + assertTrue("next window while virtual thread is alive must carry tail (SF-B/SF-D): " + covAfterDirect, + covAfterDirect.contains("\"tail:ts/vthread-1\"")); + Thread.sleep(450); + + String covBuilder = app.runHttpTest("ts/vbuilder-1", "/virtual-builder?ms=350"); + assertTrue("Thread.ofVirtual().start() must contaminate COV (SF-D): " + covBuilder, + covBuilder.contains("\"untracked-async:thread-builder\"")); + + String covAfterBuilder = app.runHttpTest("ts/vbuilder-next", "/clean"); + assertTrue("next window while builder virtual thread is alive must carry tail (SF-B/SF-D): " + + covAfterBuilder, + covAfterBuilder.contains("\"tail:ts/vbuilder-1\"")); + Thread.sleep(450); + } + } + @Test(timeout = 120000) public void forkedKafkaListenerHookEmitsTopicAndBeanAttributionInTcpCov() throws Exception { try (ForkedApp kafka = startFork("kafka", "2000", false, false, null, null)) { @@ -312,8 +342,9 @@ private ForkedApp startFork(String mode, String endWait, boolean externalJacocoP for (Class cls : new Class[] { AsyncHonestyApp.class, AsyncHonestyApp.AsyncServlet.class, AsyncHonestyApp.SerializableOnlyExecutor.class, AsyncHonestyApp.ConcreteCustomPool.class, - AsyncHonestyApp.MyWorkerThread.class, AsyncHonestyApp.OrdersListenerBean.class, - AsyncHonestyApp.FakeKafkaProps.class, AsyncTail.class, Tail.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); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 21f90cd8..fe9cdfd5 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -2103,11 +2103,12 @@ public CompletableFuture thenAccept(java.util.function.Consumer RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); RequestGate.untrackedTailWindowNanos = savedTailWindow; - // SF5: Expired job hop that fans out to an executor flags job-tail on active & next window! + // SF5: 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("sf5-arm", null); - CountDownLatch fanoutDone = new CountDownLatch(1); + Object unknownExecSf5 = new Object(); Runnable hop1; Object jTok = JobGate.enter(new Object(), "scheduled"); try { @@ -2120,19 +2121,18 @@ public CompletableFuture thenAccept(java.util.function.Consumer assertNull("hop1 expired so running() is null", JobGate.running()); assertNotNull("hop1 expiredRunningName() still knows job", JobGate.expiredRunningName()); JobGate.open(); - RequestGate.execute(pool, fanoutDone::countDown); + RequestGate.hand(unknownExecSf5, () -> { }); }); } finally { JobGate.exit(jTok); } hop1.run(); - assertTrue(fanoutDone.await(5, TimeUnit.SECONDS)); List sf5JobContams = JobGate.close(); - assertTrue("expired hop fan-out must mark JobGate window job-tail (SF5): " + sf5JobContams, + assertTrue("expired hop unverified fan-out must mark JobGate window job-tail (SF5): " + sf5JobContams, sf5JobContams.stream().anyMatch(s -> s.startsWith("job-tail:"))); RequestGate.open("sf5-next", null); RequestGate.WindowOutcome sf5Next = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - assertTrue("expired hop fan-out must mark next RequestGate window tail:job-tail (SF5): " + assertTrue("expired hop unverified fan-out must mark next RequestGate window tail:job-tail (SF5): " + sf5Next.contaminations, sf5Next.contaminations.stream().anyMatch(s -> s.startsWith("tail:job-tail:"))); @@ -2205,6 +2205,374 @@ public CompletableFuture thenAccept(java.util.function.Consumer } } + @Test(timeout = 60000) + public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopExpiredJobAndBytecodeFlagSites() + 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 { + // SF-A: 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("sfa-active", null); + Object reqSfa = RequestGate.enter(); + try { + RequestGate.execute(pool, latchTask(taskStarted, taskRelease)); + } finally { + RequestGate.exit(reqSfa); + } + 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("sfa-past-cap", null); + assertEquals("actively executing task past maxLingeringNanos must STILL flag tail (SF-A)", + Collections.singletonList("tail:sfa-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("sfa-after-exit", null); + assertEquals("clean after actively executing task finishes", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(50), true).contaminations); + RequestGate.maxLingeringNanos = savedMaxLingering; + + // SF-B: 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), "sfb-live-thread"); + rawThread.setDaemon(true); + RequestGate.open("sfb-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); + Thread.sleep(80); // Past 30ms base tail while rawThread.isAlive() is STILL true! + RequestGate.open("sfb-thread-still-alive", null); + assertEquals("live raw thread must keep marking tail past base window (SF-B)", + Collections.singletonList("tail:sfb-thread"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + rawRelease.countDown(); + rawThread.join(5000); + RequestGate.open("sfb-thread-dead", null); + assertEquals("clean once raw thread terminates", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // SF-B periodic ScheduledFuture: + RequestGate.disarm(); + RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(30); + RequestGate.open("sfb-periodic", 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); + Thread.sleep(100); + RequestGate.open("sfb-periodic-alive", null); + assertEquals("uncancelled periodic ScheduledFuture keeps marking tail (SF-B)", + Collections.singletonList("tail:sfb-periodic"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + periodic.cancel(false); + RequestGate.open("sfb-periodic-cancelled", null); + assertEquals("clean once periodic ScheduledFuture is cancelled", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.untrackedTailWindowNanos = savedTailWindow; + + // SF-C: 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("sfc-arm", null); + CountDownLatch gen3Entered = new CountDownLatch(1); + CountDownLatch gen3Release = new CountDownLatch(1); + CountDownLatch gen1Exited = new CountDownLatch(1); + CountDownLatch gen2Exited = new CountDownLatch(1); + 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(); + } + assertNull("gen 1 expired", JobGate.running()); + RequestGate.execute(pool, () -> { + try { + gen1Exited.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + RequestGate.execute(pool, () -> { + try { + gen2Exited.await(5, TimeUnit.SECONDS); + 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)); + JobGate.open(); + List gen3Contams = JobGate.close(); + gen3Release.countDown(); + assertTrue("gen 3 of expired self-resubmitting loop must STILL carry job-tail (SF-C): " + 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); + } + + // SF-E: Real bytecode-rewritten call sites via ServerEntries.wrapExecutorCalls for + // TaskExecutor interface, TaskScheduler.schedule, Timer.schedule, + // ForkJoinPool.execute/submit(ForkJoinTask), and Guava addListener/Futures.addCallback! + byte[] sfEBytes = ServerEntries.wrapExecutorCalls(generateSfEBytecodeClass("com/acme/SfECallSites")); + assertNotNull("SfECallSites must be rewritten by ServerEntries.wrapExecutorCalls", sfEBytes); + Class sfEClass = new ByteLoader(getClass().getClassLoader()).define("com.acme.SfECallSites", sfEBytes); + + // SF-E.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("sfe-spring-te", null); + Object r1 = RequestGate.enter(); + CountDownLatch teRan = new CountDownLatch(1); + try { + sfEClass.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 (SF-E)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + RequestGate.disarm(); + RequestGate.open("sfe-custom-te", null); + Object r2 = RequestGate.enter(); + org.springframework.core.task.TaskExecutor customTe = r -> r.run(); + try { + sfEClass.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 (SF-E): " + customTeContams, + customTeContams.contains("untracked-executor:" + customTe.getClass().getName())); + } finally { + springTe.shutdown(); + } + + // SF-E.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("sfe-task-scheduler", null); + Object rTs = RequestGate.enter(); + ScheduledFuture tsFut; + try { + tsFut = (ScheduledFuture) sfEClass.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 (SF-E): " + tsContams, + tsContams.contains("untracked-async:schedule")); + Thread.sleep(60); // Past 30ms base tail while ScheduledFuture is still pending! + RequestGate.open("sfe-ts-alive", null); + assertEquals("TaskScheduler ScheduledFuture keeps tail active until cancelled (SF-B/SF-E)", + Collections.singletonList("tail:sfe-task-scheduler"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + tsFut.cancel(false); + } finally { + springTs.shutdown(); + RequestGate.untrackedTailWindowNanos = savedTailWindow; + } + + // SF-E.3: Timer.schedule(TimerTask, long) flags untracked-async:timer! + RequestGate.disarm(); + RequestGate.open("sfe-timer", null); + Object rTimer = RequestGate.enter(); + CountDownLatch timerRan = new CountDownLatch(1); + try { + sfEClass.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 (SF-E)", + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations + .contains("untracked-async:timer")); + + // SF-E.4: ForkJoinPool.execute(ForkJoinTask) flags untracked-async:forkjoin-task! + RequestGate.disarm(); + RequestGate.open("sfe-fjp", null); + Object rFjp = RequestGate.enter(); + CountDownLatch fjpRan = new CountDownLatch(1); + try { + sfEClass.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 (SF-E)", + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations + .contains("untracked-async:forkjoin-task")); + + // SF-E.5: Guava ListenableFuture.addListener(Runnable, Executor) flags untracked-async:guava-future! + RequestGate.disarm(); + RequestGate.open("sfe-guava", null); + Object rGuava = RequestGate.enter(); + try { + sfEClass.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 (SF-E)", + 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[] generateSfEBytecodeClass(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 concurrentRequestExecutorAndJobGateContentionStaysBoundedAndLeakFree() throws Exception { ThreadPoolExecutor pool = new ThreadPoolExecutor(4, 4, 0L, TimeUnit.MILLISECONDS, diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index ecf23571..ee34b485 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -238,6 +238,18 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO }); } else if ("/method-ref".equals(path)) { Collections.singletonList(() -> AsyncTail.ran()).forEach(PLAIN_POOL::execute); + } else if ("/virtual-thread".equals(path)) { + final long delay = ms; + VirtualThreadLauncher.launchDirect(() -> { + sleepQuietly(delay); + AsyncTail.ran(); + }); + } else if ("/virtual-builder".equals(path)) { + final long delay = ms; + VirtualThreadLauncher.launchBuilder(() -> { + sleepQuietly(delay); + AsyncTail.ran(); + }); } else if ("/untracked-schedule".equals(path)) { SCHED.schedule(() -> AsyncTail.ran(), 1, TimeUnit.MILLISECONDS); } else if ("/untracked-thread".equals(path)) { @@ -265,6 +277,82 @@ public ConcreteCustomPool() { } } + /** + * 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"); From a6cc514f277602bc73306903ed75c36672ead377 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 07:50:50 +0530 Subject: [PATCH 10/26] =?UTF-8?q?fix(dedup):=20close=20R5=20review=20gaps?= =?UTF-8?q?=20=E2=80=94=20late-start=20current-window=20contamination=20&?= =?UTF-8?q?=20Dekker=20LINGERING=20check,=20Timer=20delay/periodic=20track?= =?UTF-8?q?ing,=20ScheduledThreadPoolExecutor=20multi-hop=20context,=20and?= =?UTF-8?q?=20JDK=2021=20virtual-thread=20liveness=20proof?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: slayerjain --- README.md | 2 +- .../java/io/keploy/dedup/RequestGate.java | 312 ++++++++++++++++-- .../java/io/keploy/dedup/ServerEntries.java | 24 ++ .../dedup/ForkedAsyncAndHonestyTest.java | 27 +- .../dedup/HonestProtocolAndAsyncTest.java | 279 +++++++++++++++- 5 files changed, 613 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index a652e502..f3c43fc9 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ A server sends a response before it is done with the request: a filter's code af 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. -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. 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, `java.util.Timer.schedule*` with a 2 s tail bound because `Timer.schedule` returns `void`, `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`) execute untouched and mark the window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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). Limits: 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`. +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. 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 delay-aware tail for one-shot tasks and weak `TimerTask` liveness tracking for periodic tasks, `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 window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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: 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`, or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). 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 6b1fb351..f7df5e23 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -8,9 +8,12 @@ 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.CompletionStage; @@ -352,6 +355,13 @@ public static Object enter() { window.enteredCount.incrementAndGet(); window.executing.incrementAndGet(); window.running.incrementAndGet(); + Window cur = current; + if (window != cur) { + retainLingering(window, System.nanoTime()); + if (cur != null) { + cur.contaminate("tail:" + window.label()); + } + } return token; } @@ -2969,9 +2979,7 @@ public static void noteUntrackedAsync(String reason) { private static void noteUntrackedAsync(String reason, long extraTailNanos) { if (!armed) { - if (UNARMED_IN_FLIGHT.sum() > 0) { - lastUnarmedHandOffNanos = System.nanoTime(); - } + noteUnarmedHandOffIfInFlight(); return; } if (reason == null || reason.isEmpty()) { @@ -3004,8 +3012,8 @@ private static void noteUntrackedAsync(String reason, long extraTailNanos) { */ public static void noteIfUntrackedExecutor(Object receiver) { if (!armed) { - if (receiver != null && UNARMED_IN_FLIGHT.sum() > 0) { - lastUnarmedHandOffNanos = System.nanoTime(); + if (receiver != null) { + noteUnarmedHandOffIfInFlight(); } return; } @@ -3076,20 +3084,23 @@ private static void trackUntrackedHandleForCurrent(Object handle, boolean alread return; } if (JobGate.runningAttribution() != null || JobGate.expiredAttribution() != null) { - addHandleToQueue(EXTERNAL_UNTRACKED_HANDLES, handle, alreadyStarted); + if (!addHandleToQueue(EXTERNAL_UNTRACKED_HANDLES, handle, alreadyStarted)) { + noteExternalUntrackedTail("job", maxLingeringNanos); + } } } - private static void addHandleToQueue(ConcurrentLinkedQueue queue, Object handle, + private static boolean addHandleToQueue(ConcurrentLinkedQueue queue, Object handle, boolean alreadyStarted) { long now = System.nanoTime(); if (queue.size() >= MAX_UNTRACKED_HANDLES) { sweepUntrackedHandles(queue, now); if (queue.size() >= MAX_UNTRACKED_HANDLES) { - return; + return false; } } queue.add(new UntrackedHandle(handle, alreadyStarted, now)); + return true; } private static boolean sweepUntrackedHandles(ConcurrentLinkedQueue queue, long now) { @@ -3115,6 +3126,37 @@ private static long boundedDelayNanos(long delay, TimeUnit unit) { return nanos <= 0L ? 0L : Math.min(nanos, maxLingeringNanos); } + 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)}. * @@ -3127,7 +3169,7 @@ private static long boundedDelayNanos(long delay, TimeUnit unit) { public static ScheduledFuture schedule(ScheduledExecutorService executor, Runnable command, long delay, TimeUnit unit) { noteUntrackedAsync("untracked-async:schedule", boundedDelayNanos(delay, unit)); - ScheduledFuture sf = executor.schedule(command, delay, unit); + ScheduledFuture sf = executor.schedule(wrapScheduledContext(executor, command), delay, unit); trackUntrackedHandleForCurrent(sf, true); return sf; } @@ -3145,7 +3187,7 @@ public static ScheduledFuture schedule(ScheduledExecutorService executor, Run public static ScheduledFuture schedule(ScheduledExecutorService executor, Callable callable, long delay, TimeUnit unit) { noteUntrackedAsync("untracked-async:schedule", boundedDelayNanos(delay, unit)); - ScheduledFuture sf = executor.schedule(callable, delay, unit); + ScheduledFuture sf = executor.schedule(wrapScheduledContext(executor, callable), delay, unit); trackUntrackedHandleForCurrent(sf, true); return sf; } @@ -3165,7 +3207,8 @@ public static ScheduledFuture scheduleAtFixedRate(ScheduledExecutorService ex long initialDelay, long period, TimeUnit unit) { long extra = boundedDelayNanos(initialDelay, unit) + boundedDelayNanos(period, unit); noteUntrackedAsync("untracked-async:schedule", Math.min(extra, maxLingeringNanos)); - ScheduledFuture sf = executor.scheduleAtFixedRate(command, initialDelay, period, unit); + ScheduledFuture sf = executor.scheduleAtFixedRate( + wrapScheduledContext(executor, command), initialDelay, period, unit); trackUntrackedHandleForCurrent(sf, true); return sf; } @@ -3185,11 +3228,108 @@ public static ScheduledFuture scheduleWithFixedDelay(ScheduledExecutorService long initialDelay, long delay, TimeUnit unit) { long extra = boundedDelayNanos(initialDelay, unit) + boundedDelayNanos(delay, unit); noteUntrackedAsync("untracked-async:schedule", Math.min(extra, maxLingeringNanos)); - ScheduledFuture sf = executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); + ScheduledFuture sf = executor.scheduleWithFixedDelay( + wrapScheduledContext(executor, command), initialDelay, delay, unit); trackUntrackedHandleForCurrent(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) { + noteUntrackedAsync("untracked-async:timer", boundedDelayNanos(delay, TimeUnit.MILLISECONDS)); + timer.schedule(task, delay); + } + + /** + * 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) { + noteUntrackedAsync("untracked-async:timer", boundedDelayNanos(dateDelayMillis(time), TimeUnit.MILLISECONDS)); + timer.schedule(task, time); + } + + /** + * 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) { + long extra = boundedDelayNanos(delay, TimeUnit.MILLISECONDS) + + boundedDelayNanos(period, TimeUnit.MILLISECONDS); + noteUntrackedAsync("untracked-async:timer", Math.min(extra, maxLingeringNanos)); + timer.schedule(task, delay, period); + trackUntrackedHandleForCurrent(task, 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) { + long extra = boundedDelayNanos(dateDelayMillis(firstTime), TimeUnit.MILLISECONDS) + + boundedDelayNanos(period, TimeUnit.MILLISECONDS); + noteUntrackedAsync("untracked-async:timer", Math.min(extra, maxLingeringNanos)); + timer.schedule(task, firstTime, period); + trackUntrackedHandleForCurrent(task, 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) { + long extra = boundedDelayNanos(delay, TimeUnit.MILLISECONDS) + + boundedDelayNanos(period, TimeUnit.MILLISECONDS); + noteUntrackedAsync("untracked-async:timer", Math.min(extra, maxLingeringNanos)); + timer.scheduleAtFixedRate(task, delay, period); + trackUntrackedHandleForCurrent(task, 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) { + long extra = boundedDelayNanos(dateDelayMillis(firstTime), TimeUnit.MILLISECONDS) + + boundedDelayNanos(period, TimeUnit.MILLISECONDS); + noteUntrackedAsync("untracked-async:timer", Math.min(extra, maxLingeringNanos)); + timer.scheduleAtFixedRate(task, firstTime, period); + trackUntrackedHandleForCurrent(task, true); + } + /** * Pass-through call-site wrapper for {@link ExecutorService#invokeAny(Collection)}. * @@ -3559,12 +3699,12 @@ static void open(String testId, String prevActiveTestId) { && (now - lingering.lingeringSinceNanos) >= maxLingeringNanos; boolean aliveHandles = lingering.hasAliveUntrackedHandles(now); // Actively executing work (executing > 0) and live untracked - // threads/futures NEVER expire under maxLingeringNanos; only idle - // uncompleted permits (running > 0 && executing == 0) are bounded - // by maxLingeringNanos. + // 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); + || (!lingeringExpired && (lingering.running.get() > 0 || lingering.untrackedHandlesOverflowed)); boolean reportCut = lingering.wasCut && !lingering.cutReportedOnce; boolean untrackedActive = lingering.hadUntrackedAsync && (!lingering.untrackedTailReportedOnce @@ -3584,6 +3724,14 @@ static void open(String testId, String prevActiveTestId) { && (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.hadUntrackedAsync + && (now - lingering.untrackedTailExpiresAtNanos) < 0L)) { + LINGERING.add(lingering); + } } } } @@ -3592,6 +3740,9 @@ 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(); @@ -3600,13 +3751,19 @@ private static void retainLingering(Window window, long now) { boolean aliveHandles = existing.hasAliveUntrackedHandles(now); boolean stillRunning = existing.executing.get() > 0 || aliveHandles - || (!lingeringExpired && existing.running.get() > 0); + || (!lingeringExpired && (existing.running.get() > 0 || existing.untrackedHandlesOverflowed)); boolean cutDone = !existing.wasCut || existing.cutReportedOnce; boolean untrackedDone = !existing.hadUntrackedAsync || (existing.untrackedTailReportedOnce && (now - existing.untrackedTailExpiresAtNanos) >= 0L); if (!stillRunning && cutDone && untrackedDone) { LINGERING.remove(existing); + if (existing.executing.get() > 0 + || existing.hasAliveUntrackedHandles(now) + || (existing.hadUntrackedAsync + && (now - existing.untrackedTailExpiresAtNanos) < 0L)) { + LINGERING.add(existing); + } } } // Strictly bound memory if 64+ windows are already stuck lingering; @@ -3752,6 +3909,11 @@ private boolean isActive(long now) { if (target instanceof Future) { return !isFutureTerminated((Future) target); } + if (target instanceof TimerTask) { + // Timer's internal TaskQueue holds periodic TimerTasks strongly + // while scheduled, so weak reachability errs toward flagging. + return true; + } return false; } } @@ -3783,10 +3945,12 @@ private static final class Window { // windows without an END cannot grow unboundedly). @SuppressWarnings("rawtypes") private volatile ConcurrentHashMap futures; - // Weak handles to live untracked Threads and ScheduledFutures started - // in this window so tail contamination persists while they stay alive. + // Weak handles to live untracked Threads, ScheduledFutures, and + // periodic TimerTasks started in this window so tail contamination + // persists 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(); @@ -3917,7 +4081,9 @@ private ConcurrentLinkedQueue untrackedHandlesQueue(boolean cre private void addUntrackedHandle(Object target, boolean alreadyStarted) { hadUntrackedAsync = true; - addHandleToQueue(untrackedHandlesQueue(true), target, alreadyStarted); + if (!addHandleToQueue(untrackedHandlesQueue(true), target, alreadyStarted)) { + untrackedHandlesOverflowed = true; + } } private boolean hasAliveUntrackedHandles(long now) { @@ -4191,10 +4357,15 @@ final Object enter() { } window.executing.incrementAndGet(); if (window != current) { - // Re-retain closed windows when a queued/late task actually - // begins executing so executing > 0 keeps flagging tail: - // until it finishes, even past maxLingeringNanos. + // 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(); @@ -4257,6 +4428,101 @@ final void exit(Object outer) { } } + // 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); + } + } + } + + 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); + } + } + } + private static final class StageHand extends Hand { StageHand(Window window, JobGate.Attribution job, boolean deferRelease) { super(window, job, deferRelease); 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 4d3afbbf..57a38e8b 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -345,6 +345,10 @@ 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; } @@ -1290,6 +1294,26 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, 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 (opcode == Opcodes.INVOKEVIRTUAL && "java/lang/Thread".equals(owner) && "start".equals(mname) diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index 72799d59..60ac8036 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -296,25 +296,40 @@ public void forkedVirtualThreadStartAndBuilderFlagAndTrackLiveness() throws Exce // External-JaCoCo prefix mode ("org/example/servers/") automatically rewrites // the dynamically defined org/example/servers/VirtualThreadHelper on load! + // Run each virtual thread for 2700ms and sleep 2200ms BEFORE /clean so the + // check occurs strictly PAST the default 2000ms untrackedTailWindowNanos, + // proving the post-call DUP + trackUntrackedThread liveness tracking end-to-end + // (and proving the window returns clean after the virtual thread exits). try (ForkedApp app = startFork("tomcat", "2000", true, false, null, null)) { - String covDirect = app.runHttpTest("ts/vthread-1", "/virtual-thread?ms=350"); + String covDirect = app.runHttpTest("ts/vthread-1", "/virtual-thread?ms=2700"); assertTrue("Thread.startVirtualThread must contaminate COV (SF-D): " + covDirect, covDirect.contains("\"untracked-async:virtual-thread\"")); + Thread.sleep(2200); // Past default 2000ms base tail while virtual thread is still alive (~500ms left)! String covAfterDirect = app.runHttpTest("ts/vthread-next", "/clean"); - assertTrue("next window while virtual thread is alive must carry tail (SF-B/SF-D): " + covAfterDirect, + assertTrue("next window past 2s base tail while virtual thread is alive must carry tail (SF-D/SF-4): " + + covAfterDirect, covAfterDirect.contains("\"tail:ts/vthread-1\"")); - Thread.sleep(450); - String covBuilder = app.runHttpTest("ts/vbuilder-1", "/virtual-builder?ms=350"); + Thread.sleep(800); // Virtual thread has now exited! + String covDirectDone = app.runHttpTest("ts/vthread-done", "/clean"); + assertFalse("window after virtual thread exits must be clean (SF-4): " + covDirectDone, + covDirectDone.contains("\"tail:ts/vthread-1\"")); + + String covBuilder = app.runHttpTest("ts/vbuilder-1", "/virtual-builder?ms=2700"); assertTrue("Thread.ofVirtual().start() must contaminate COV (SF-D): " + covBuilder, covBuilder.contains("\"untracked-async:thread-builder\"")); + Thread.sleep(2200); // Past default 2000ms base tail while builder virtual thread is still alive! String covAfterBuilder = app.runHttpTest("ts/vbuilder-next", "/clean"); - assertTrue("next window while builder virtual thread is alive must carry tail (SF-B/SF-D): " + assertTrue("next window past 2s base tail while builder virtual thread is alive must carry tail (SF-4): " + covAfterBuilder, covAfterBuilder.contains("\"tail:ts/vbuilder-1\"")); - Thread.sleep(450); + + Thread.sleep(800); // Builder virtual thread has now exited! + String covBuilderDone = app.runHttpTest("ts/vbuilder-done", "/clean"); + assertFalse("window after builder virtual thread exits must be clean (SF-4): " + covBuilderDone, + covBuilderDone.contains("\"tail:ts/vbuilder-1\"")); } } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index fe9cdfd5..4b1fc3a6 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -2326,9 +2326,11 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + assertNull("gen 2 expired", JobGate.running()); RequestGate.execute(pool, () -> { try { gen2Exited.await(5, TimeUnit.SECONDS); + assertNull("gen 3 expired", JobGate.running()); gen3Entered.countDown(); gen3Release.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { @@ -2343,6 +2345,11 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx JobGate.exit(jTokC); } assertTrue("gen 3 entered after gen 1 and gen 2 exited", gen3Entered.await(10, TimeUnit.SECONDS)); + 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(); @@ -2355,7 +2362,7 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx // SF-E: Real bytecode-rewritten call sites via ServerEntries.wrapExecutorCalls for // TaskExecutor interface, TaskScheduler.schedule, Timer.schedule, - // ForkJoinPool.execute/submit(ForkJoinTask), and Guava addListener/Futures.addCallback! + // ForkJoinPool.execute(ForkJoinTask), and ListenableFuture.addListener! byte[] sfEBytes = ServerEntries.wrapExecutorCalls(generateSfEBytecodeClass("com/acme/SfECallSites")); assertNotNull("SfECallSites must be rewritten by ServerEntries.wrapExecutorCalls", sfEBytes); Class sfEClass = new ByteLoader(getClass().getClassLoader()).define("com.acme.SfECallSites", sfEBytes); @@ -2398,6 +2405,7 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx assertTrue("rewritten TaskExecutor.execute on unhooked impl must flag (SF-E): " + customTeContams, customTeContams.contains("untracked-executor:" + customTe.getClass().getName())); } finally { + ServerEntries.unmarkSpringExecutorHookedForTests(springTe.getClass().getName()); springTe.shutdown(); } @@ -2573,6 +2581,275 @@ private static byte[] generateSfEBytecodeClass(String className) { return cw.toByteArray(); } + @Test(timeout = 60000) + public void r5RegressionsLateStartContaminatesCurrentWindowTimerDelayAndPeriodicMultiHopScheduledRetryAndBranchyFrames() + 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 { + // SF-1: 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("sf1-late", 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("sf1-dropper", null); + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(20), true); + + // Open window M: A is already gone from LINGERING so M opens clean! + RequestGate.open("sf1-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:sf1-late (SF-1): " + mContams, + mContams.contains("tail:sf1-late")); + RequestGate.maxLingeringNanos = savedMaxLingering; + + // SF-2: 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); + + // SF-2a: 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("sf2-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")); + Thread.sleep(75); // Past 30ms base tail, well before 180ms + 30ms extended tail! + RequestGate.open("sf2-timer-oneshot-next", null); + assertEquals("one-shot Timer delay must extend tail past base window (SF-2)", + Collections.singletonList("tail:sf2-timer-oneshot"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + assertTrue(oneShotRan.await(5, TimeUnit.SECONDS)); + + // SF-2b: 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("sf2-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")); + Thread.sleep(100); // Past 30ms + 5ms + 25ms tail while TimerTask is still in Timer's queue! + RequestGate.open("sf2-timer-periodic-alive", null); + assertEquals("periodic TimerTask held by Timer queue keeps tail active (SF-2)", + Collections.singletonList("tail:sf2-timer-periodic"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + periodicTimer.cancel(); + + // SF-3: 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("sf3-retry", null); + Object reqS3 = 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(reqS3); + } + RequestGate.WindowOutcome sf3Out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("END must not block on delayed scheduled task (SF-3)", sf3Out.drained); + assertTrue("SF-3 flags untracked-async:schedule", sf3Out.contaminations.contains("untracked-async:schedule")); + assertTrue("gen 1 completed", gen1Done.await(5, TimeUnit.SECONDS)); + Thread.sleep(50); // Past gen 1 completion + 30ms base tail while gen 2 is still pending! + RequestGate.open("sf3-while-gen2-pending", null); + assertEquals("gen 2 ScheduledFuture tracked via propagated context keeps tail active (SF-3)", + Collections.singletonList("tail:sf3-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("sf3-while-downstream-running", null); + assertEquals("downstream workerPool task launched by gen 2 keeps tail:sf3-retry (SF-3)", + Collections.singletonList("tail:sf3-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("sf5-branchy", 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(); + } + } + + 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, From e24bf0a6f67ca5fddec499f8c07c2e852485ed72 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 08:10:06 +0530 Subject: [PATCH 11/26] test(dedup): consume one-time untracked tail report before asserting handle liveness and delay extension across unit and forked JDK 21 tests Signed-off-by: slayerjain --- README.md | 2 +- .../java/io/keploy/dedup/RequestGate.java | 16 +++++-- .../dedup/ForkedAsyncAndHonestyTest.java | 41 ++++++++++------- .../dedup/HonestProtocolAndAsyncTest.java | 32 +++++++++++-- .../org/example/servers/AsyncHonestyApp.java | 46 +++++++++++++++++++ 5 files changed, 113 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index f3c43fc9..7a4f5c7f 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ A server sends a response before it is done with the request: a filter's code af 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. -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. 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 delay-aware tail for one-shot tasks and weak `TimerTask` liveness tracking for periodic tasks, `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 window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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: 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`. +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. 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 delay-aware tail (up to 30 s) for one-shot tasks and weak `TimerTask` liveness tracking for periodic tasks, `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 window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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: custom `ScheduledExecutorService` implementations (and `Executors.newSingleThreadScheduledExecutor()` on JDK 9+ without `--add-opens java.base/java.util.concurrent`), 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`, or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). 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 f7df5e23..155a50d1 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -355,10 +355,10 @@ public static Object enter() { window.enteredCount.incrementAndGet(); window.executing.incrementAndGet(); window.running.incrementAndGet(); - Window cur = current; - if (window != cur) { + if (window != current) { retainLingering(window, System.nanoTime()); - if (cur != null) { + Window cur = current; + if (cur != null && cur != window) { cur.contaminate("tail:" + window.label()); } } @@ -4476,6 +4476,11 @@ public void run() { JobGate.exit(jt); } } + + @Override + public String toString() { + return task.toString(); + } } private static final class ScheduledContextCallable implements Callable { @@ -4521,6 +4526,11 @@ public V call() throws Exception { JobGate.exit(jt); } } + + @Override + public String toString() { + return task.toString(); + } } private static final class StageHand extends Hand { diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index 60ac8036..612cde39 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -296,37 +296,46 @@ public void forkedVirtualThreadStartAndBuilderFlagAndTrackLiveness() throws Exce // External-JaCoCo prefix mode ("org/example/servers/") automatically rewrites // the dynamically defined org/example/servers/VirtualThreadHelper on load! - // Run each virtual thread for 2700ms and sleep 2200ms BEFORE /clean so the - // check occurs strictly PAST the default 2000ms untrackedTailWindowNanos, - // proving the post-call DUP + trackUntrackedThread liveness tracking end-to-end - // (and proving the window returns clean after the virtual thread exits). + // 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?ms=2700"); + String covDirect = app.runHttpTest("ts/vthread-1", "/virtual-thread-latch"); assertTrue("Thread.startVirtualThread must contaminate COV (SF-D): " + covDirect, covDirect.contains("\"untracked-async:virtual-thread\"")); - Thread.sleep(2200); // Past default 2000ms base tail while virtual thread is still alive (~500ms left)! - String covAfterDirect = app.runHttpTest("ts/vthread-next", "/clean"); - assertTrue("next window past 2s base tail while virtual thread is alive must carry tail (SF-D/SF-4): " - + covAfterDirect, + // 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 (SF-D/SF-4): " + covAfterDirect, covAfterDirect.contains("\"tail:ts/vthread-1\"")); - Thread.sleep(800); // Virtual thread has now exited! + app.runHttpTest("ts/vthread-release", "/release-virtual"); String covDirectDone = app.runHttpTest("ts/vthread-done", "/clean"); assertFalse("window after virtual thread exits must be clean (SF-4): " + covDirectDone, covDirectDone.contains("\"tail:ts/vthread-1\"")); - String covBuilder = app.runHttpTest("ts/vbuilder-1", "/virtual-builder?ms=2700"); + String covBuilder = app.runHttpTest("ts/vbuilder-1", "/virtual-builder-latch"); assertTrue("Thread.ofVirtual().start() must contaminate COV (SF-D): " + covBuilder, covBuilder.contains("\"untracked-async:thread-builder\"")); - Thread.sleep(2200); // Past default 2000ms base tail while builder virtual thread is still alive! - String covAfterBuilder = app.runHttpTest("ts/vbuilder-next", "/clean"); - assertTrue("next window past 2s base tail while builder virtual thread is alive must carry tail (SF-4): " - + covAfterBuilder, + // 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 (SF-4): " + covAfterBuilder, covAfterBuilder.contains("\"tail:ts/vbuilder-1\"")); - Thread.sleep(800); // Builder virtual thread has now exited! + 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 (SF-4): " + covBuilderDone, covBuilderDone.contains("\"tail:ts/vbuilder-1\"")); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 4b1fc3a6..991056bd 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -2266,6 +2266,9 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx } 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("sfb-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("sfb-thread-still-alive", null); assertEquals("live raw thread must keep marking tail past base window (SF-B)", @@ -2290,7 +2293,10 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx RequestGate.exit(reqP); } RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - Thread.sleep(100); + // Consume one-time report first so the next window depends strictly on !ScheduledFuture.isDone(). + RequestGate.open("sfb-periodic-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("sfb-periodic-alive", null); assertEquals("uncancelled periodic ScheduledFuture keeps marking tail (SF-B)", Collections.singletonList("tail:sfb-periodic"), @@ -2311,6 +2317,9 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx 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, () -> { @@ -2319,18 +2328,18 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - assertNull("gen 1 expired", JobGate.running()); + gen1Running.set(JobGate.running()); RequestGate.execute(pool, () -> { try { gen1Exited.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - assertNull("gen 2 expired", JobGate.running()); + gen2Running.set(JobGate.running()); RequestGate.execute(pool, () -> { try { gen2Exited.await(5, TimeUnit.SECONDS); - assertNull("gen 3 expired", JobGate.running()); + gen3Running.set(JobGate.running()); gen3Entered.countDown(); gen3Release.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { @@ -2345,6 +2354,9 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx 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); @@ -2430,6 +2442,9 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx List tsContams = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations; assertTrue("rewritten TaskScheduler.schedule must flag (SF-E): " + tsContams, tsContams.contains("untracked-async:schedule")); + // Consume one-time report first so the next window depends strictly on !ScheduledFuture.isDone(). + RequestGate.open("sfe-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("sfe-ts-alive", null); assertEquals("TaskScheduler ScheduledFuture keeps tail active until cancelled (SF-B/SF-E)", @@ -2658,6 +2673,9 @@ public void run() { 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("sf2-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("sf2-timer-oneshot-next", null); assertEquals("one-shot Timer delay must extend tail past base window (SF-2)", @@ -2680,6 +2698,9 @@ public void run() { 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("sf2-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("sf2-timer-periodic-alive", null); assertEquals("periodic TimerTask held by Timer queue keeps tail active (SF-2)", @@ -2720,6 +2741,9 @@ public void run() { assertTrue("END must not block on delayed scheduled task (SF-3)", sf3Out.drained); assertTrue("SF-3 flags untracked-async:schedule", sf3Out.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("sf3-gen2-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("sf3-while-gen2-pending", null); assertEquals("gen 2 ScheduledFuture tracked via propagated context keeps tail active (SF-3)", diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index ee34b485..cd39c234 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -61,6 +61,8 @@ public final class AsyncHonestyApp { 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 java.util.concurrent.CountDownLatch VIRTUAL_DONE_LATCH; // 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<>(); @@ -250,6 +252,50 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO sleepQuietly(delay); AsyncTail.ran(); }); + } else if ("/virtual-thread-latch".equals(path)) { + final java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); + final java.util.concurrent.CountDownLatch done = new java.util.concurrent.CountDownLatch(1); + VIRTUAL_RELEASE_LATCH = release; + VIRTUAL_DONE_LATCH = done; + VirtualThreadLauncher.launchDirect(() -> { + try { + release.await(30, TimeUnit.SECONDS); + AsyncTail.ran(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + done.countDown(); + } + }); + } else if ("/virtual-builder-latch".equals(path)) { + final java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); + final java.util.concurrent.CountDownLatch done = new java.util.concurrent.CountDownLatch(1); + VIRTUAL_RELEASE_LATCH = release; + VIRTUAL_DONE_LATCH = done; + VirtualThreadLauncher.launchBuilder(() -> { + try { + release.await(30, TimeUnit.SECONDS); + AsyncTail.ran(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + done.countDown(); + } + }); + } else if ("/release-virtual".equals(path)) { + java.util.concurrent.CountDownLatch release = VIRTUAL_RELEASE_LATCH; + java.util.concurrent.CountDownLatch done = VIRTUAL_DONE_LATCH; + if (release != null) { + release.countDown(); + } + if (done != null) { + try { + done.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + sleepQuietly(30); } else if ("/untracked-schedule".equals(path)) { SCHED.schedule(() -> AsyncTail.ran(), 1, TimeUnit.MILLISECONDS); } else if ("/untracked-thread".equals(path)) { From 5650f4fadf312840d246d2a4b8c84c16100761ee Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 08:25:45 +0530 Subject: [PATCH 12/26] test(dedup): fix supplier countdown race before RequestGate.exit and use deterministic Thread.join in forked virtual-thread release Signed-off-by: slayerjain --- README.md | 2 +- .../dedup/HonestProtocolAndAsyncTest.java | 8 +++-- .../org/example/servers/AsyncHonestyApp.java | 33 ++++--------------- 3 files changed, 12 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 7a4f5c7f..62235b18 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ A server sends a response before it is done with the request: a filter's code af 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. -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. 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 delay-aware tail (up to 30 s) for one-shot tasks and weak `TimerTask` liveness tracking for periodic tasks, `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 window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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: custom `ScheduledExecutorService` implementations (and `Executors.newSingleThreadScheduledExecutor()` on JDK 9+ without `--add-opens java.base/java.util.concurrent`), 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`. +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. 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 delay-aware tail (up to 30 s) for one-shot tasks and weak `TimerTask` liveness tracking for periodic tasks, `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 window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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: custom `ScheduledExecutorService` implementations (and `Executors.newSingleThreadExecutor()` / `Executors.newSingleThreadScheduledExecutor()` on JDK 16+ without `--add-opens java.base/java.util.concurrent`), 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`, or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 991056bd..d9fc073b 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -1467,8 +1467,8 @@ public void completableFutureDependentStagesAndAsyncInstanceMethodsAreTrackedAnd RequestGate.open("cf-dep", null); Object req = RequestGate.enter(); CompletableFuture chain; + CountDownLatch gateSupplier = new CountDownLatch(1); try { - CountDownLatch gateSupplier = new CountDownLatch(1); CompletableFuture base = RequestGate.supplyAsync(() -> { try { gateSupplier.await(10, TimeUnit.SECONDS); @@ -1487,10 +1487,12 @@ public void completableFutureDependentStagesAndAsyncInstanceMethodsAreTrackedAnd Thread.currentThread().interrupt(); } }); - gateSupplier.countDown(); } 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", @@ -2746,7 +2748,7 @@ public void run() { 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("sf3-while-gen2-pending", null); - assertEquals("gen 2 ScheduledFuture tracked via propagated context keeps tail active (SF-3)", + assertEquals("gen 2 scheduled via propagated context keeps tail active past gen 1 base tail (SF-3)", Collections.singletonList("tail:sf3-retry"), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); assertTrue("gen 2 started", gen2Started.await(5, TimeUnit.SECONDS)); diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index cd39c234..e966f4aa 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -62,7 +62,7 @@ public final class AsyncHonestyApp { 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 java.util.concurrent.CountDownLatch VIRTUAL_DONE_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<>(); @@ -240,62 +240,41 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO }); } else if ("/method-ref".equals(path)) { Collections.singletonList(() -> AsyncTail.ran()).forEach(PLAIN_POOL::execute); - } else if ("/virtual-thread".equals(path)) { - final long delay = ms; - VirtualThreadLauncher.launchDirect(() -> { - sleepQuietly(delay); - AsyncTail.ran(); - }); - } else if ("/virtual-builder".equals(path)) { - final long delay = ms; - VirtualThreadLauncher.launchBuilder(() -> { - sleepQuietly(delay); - AsyncTail.ran(); - }); } else if ("/virtual-thread-latch".equals(path)) { final java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); - final java.util.concurrent.CountDownLatch done = new java.util.concurrent.CountDownLatch(1); VIRTUAL_RELEASE_LATCH = release; - VIRTUAL_DONE_LATCH = done; - VirtualThreadLauncher.launchDirect(() -> { + VIRTUAL_THREAD = VirtualThreadLauncher.launchDirect(() -> { try { release.await(30, TimeUnit.SECONDS); AsyncTail.ran(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - } finally { - done.countDown(); } }); } else if ("/virtual-builder-latch".equals(path)) { final java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); - final java.util.concurrent.CountDownLatch done = new java.util.concurrent.CountDownLatch(1); VIRTUAL_RELEASE_LATCH = release; - VIRTUAL_DONE_LATCH = done; - VirtualThreadLauncher.launchBuilder(() -> { + VIRTUAL_THREAD = VirtualThreadLauncher.launchBuilder(() -> { try { release.await(30, TimeUnit.SECONDS); AsyncTail.ran(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - } finally { - done.countDown(); } }); } else if ("/release-virtual".equals(path)) { java.util.concurrent.CountDownLatch release = VIRTUAL_RELEASE_LATCH; - java.util.concurrent.CountDownLatch done = VIRTUAL_DONE_LATCH; + Thread vt = VIRTUAL_THREAD; if (release != null) { release.countDown(); } - if (done != null) { + if (vt != null) { try { - done.await(5, TimeUnit.SECONDS); + vt.join(5000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } - sleepQuietly(30); } else if ("/untracked-schedule".equals(path)) { SCHED.schedule(() -> AsyncTail.ran(), 1, TimeUnit.MILLISECONDS); } else if ("/untracked-thread".equals(path)) { From b582be16ad7caa82c043853ec107cae0a4be6f1b Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 09:17:24 +0530 Subject: [PATCH 13/26] =?UTF-8?q?fix(dedup):=20address=20R1=20review=20?= =?UTF-8?q?=E2=80=94=20unverified=20no-server-entry,=20Executor=20runtime?= =?UTF-8?q?=20guard,=20handle-driven=20tail=20&=20TimerTask=20cancel,=20BA?= =?UTF-8?q?CKGROUND=20tail=20suppression,=20inline=20executors,=20HELLO=20?= =?UTF-8?q?connect=20guard,=20and=20unix=20ackId=3Dtrue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: slayerjain --- README.md | 6 +- .../main/java/io/keploy/dedup/JobGate.java | 20 +- .../io/keploy/dedup/KeployDedupAgent.java | 127 +++- .../java/io/keploy/dedup/OrderedPools.java | 47 ++ .../java/io/keploy/dedup/RequestGate.java | 569 ++++++++++++++---- .../java/io/keploy/dedup/ServerEntries.java | 86 ++- .../io/keploy/dedup/ControlSocketTest.java | 4 +- .../io/keploy/dedup/DedupWireFormatTest.java | 21 + .../dedup/ForkedAsyncAndHonestyTest.java | 6 +- .../dedup/HonestProtocolAndAsyncTest.java | 512 +++++++++++++++- .../test/java/io/keploy/dedup/PhasesTest.java | 2 +- 11 files changed, 1227 insertions(+), 173 deletions(-) diff --git a/README.md b/README.md index 62235b18..fe97e0fa 100644 --- a/README.md +++ b/README.md @@ -29,9 +29,9 @@ A server sends a response before it is done with the request: a filter's code af 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. -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. 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 delay-aware tail (up to 30 s) for one-shot tasks and weak `TimerTask` liveness tracking for periodic tasks, `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 window contaminated (`"untracked-async:"` / `"untracked-executor:"`). 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: custom `ScheduledExecutorService` implementations (and `Executors.newSingleThreadExecutor()` / `Executors.newSingleThreadScheduledExecutor()` on JDK 16+ without `--add-opens java.base/java.util.concurrent`), 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`. +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`, or a server loaded before the agent), the window is marked contaminated (`"no-server-entry"`). +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. @@ -41,7 +41,7 @@ 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 Unix control socket, accepted commands reply `ACK proto=3 caps=windowCut=,contaminated=,classMismatch=,background=,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. +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 (the previous window had an untracked async hand-off, 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 so a test's async tail probes are never calibrated 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 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` (or `ACK ` when `ACK_ID` is enabled). 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 34d438ba..f8db2fe8 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -154,6 +154,18 @@ static void markUntracked(String reason, long extraTailNanos) { 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 @@ -301,15 +313,18 @@ public static void exit(Object token) { // 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:". - static void open() { + // 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) { @@ -328,6 +343,7 @@ static void open() { + " ms; marking overlapping windows with job-tail:" + jobName + " until it finishes"); } } + return hasJobTail; } // close ends the window, after its END read the test's hits, and names 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 4a97cbb2..8b15f064 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -96,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 @@ -192,6 +198,7 @@ static String buildUnixCapsReply(boolean windowCut, boolean contaminated, boolea + ",contaminated=" + contaminated + ",classMismatch=" + classMismatch + ",background=" + background + + ",ackId=true" + ",asyncExecutors=" + asyncExecutors + ",listenerContamination=" + listenerContamination; } @@ -338,14 +345,14 @@ static boolean isAsyncCallSitesTurnedOff() { } // Merges RequestGate contaminations (tail, untracked-executor, - // untracked-async, armed-mid-flight), JobGate contaminations, and - // no-server-entry, deduplicated in order and capped at JobGate.NAMES with - // "+N" overflow. - static List mergeContaminations(List requestContams, List jobContams, - boolean noServerEntry) { + // 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()) - && !noServerEntry) { + && (jobContams == null || jobContams.isEmpty())) { return Collections.emptyList(); } LinkedHashSet merged = new LinkedHashSet<>(); @@ -360,9 +367,6 @@ static List mergeContaminations(List requestContams, List(merged); } @@ -1026,6 +1030,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 lastEndedHadUntrackedAsync; // 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 @@ -1209,22 +1214,31 @@ private boolean run(CoverageCommand command, Phases phases) { String prevActive = activeTestId; activeTestId = ""; String after = lastEndedTestId; + boolean prevUntracked = lastEndedHadUntrackedAsync; lastEndedTestId = null; + lastEndedHadUntrackedAsync = 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(command.testId, prevActive, 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 never calibrated as + // background. if (after != null && !cleared.isEmpty() && publisher.backgroundAsked()) { - pendingBackground = new BackgroundWindow(after, command.testId, cleared); + if (prevUntracked || suppressBackground[0]) { + publisher.noteBackgroundLost(); + } else { + pendingBackground = new BackgroundWindow(after, command.testId, cleared); + } } return true; } @@ -1233,6 +1247,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; + lastEndedHadUntrackedAsync = false; if (!command.testId.equals(activeTestId)) { log(Level.SEVERE, "Ignoring mismatched END command. expected=" + activeTestId + ", actual=" @@ -1252,8 +1267,11 @@ private boolean run(CoverageCommand command, Phases phases) { List jobContams = JobGate.close(); boolean noServerEntry = transformerAdded && collector.endWaitMillis > 0 && !raw.probesByClass.isEmpty() && outcome.enteredCount == 0 && jobContams.isEmpty(); + List unverified = noServerEntry + ? Collections.singletonList("no-server-entry") + : Collections.emptyList(); TestCoverage coverage = raw.ended(cut, - mergeContaminations(outcome.contaminations, jobContams, noServerEntry)); + mergeContaminations(outcome.contaminations, jobContams), unverified); if (coverage.probesByClass.isEmpty()) { log(Level.FINE, "No Java coverage collected for " + command.testId, null); } @@ -1262,6 +1280,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; + lastEndedHadUntrackedAsync = !cut && outcome.hadUntrackedAsync; return true; } catch (Exception e) { // Not ACK for the same reason: nothing reached Keploy. @@ -1370,6 +1389,7 @@ private static final class CoverageTcpClient implements CoverageWorker { // 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 lastEndedHadUntrackedAsync; // Opt-in per TCP connection via "BACKGROUND" command so older collectors // never receive unexpected BACKGROUND frames. private boolean backgroundRequested; @@ -1455,6 +1475,7 @@ private void connectAndServe() throws IOException { synchronized (testCaseLock) { activeTestId = ""; lastEndedTestId = null; + lastEndedHadUntrackedAsync = false; backgroundRequested = false; ackWithId = false; lastHelloSent = null; @@ -1472,7 +1493,15 @@ private void connectAndServe() throws IOException { // removal eligibility on this declaration and refresh it if a later // HELLO arrives after server/JaCoCo initialization completes. synchronized (testCaseLock) { - maybeSendUpdatedHello(out); + try { + maybeSendUpdatedHello(out); + } catch (RuntimeException 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; @@ -1542,15 +1571,18 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) String prevActive = activeTestId; activeTestId = ""; String after = lastEndedTestId; + boolean prevUntracked = lastEndedHadUntrackedAsync; lastEndedTestId = null; + lastEndedHadUntrackedAsync = 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(command.testId, prevActive, phases, cleared); + 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 @@ -1573,9 +1605,14 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) 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. + // 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) { - writeBackgroundFrame(out, after, command.testId, cleared); + if (prevUntracked || suppressBackground[0]) { + backgroundLost++; + } else { + writeBackgroundFrame(out, after, command.testId, cleared); + } } return; } @@ -1585,6 +1622,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // after an END not taken or cut, what the next START clears // may hold this test's own hits. lastEndedTestId = null; + lastEndedHadUntrackedAsync = false; if (!command.testId.equals(activeTestId)) { log(Level.SEVERE, "Ignoring mismatched END command. expected=" + activeTestId + ", actual=" @@ -1605,16 +1643,21 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // exception would shift the collector onto the next test's frames. TestCoverage coverage; boolean cut; + boolean hadUntrackedAsync; try { RequestGate.WindowOutcome outcome = collector.awaitRequests(command.testId, phases); cut = !outcome.drained; + hadUntrackedAsync = outcome.hadUntrackedAsync; TestCoverage raw = collector.capture(phases); List jobContams = JobGate.close(); boolean noServerEntry = transformerAdded && collector.endWaitMillis > 0 && !raw.probesByClass.isEmpty() && outcome.enteredCount == 0 && jobContams.isEmpty(); + List unverified = noServerEntry + ? Collections.singletonList("no-server-entry") + : Collections.emptyList(); coverage = raw.ended(cut, - mergeContaminations(outcome.contaminations, jobContams, noServerEntry)); + 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. @@ -1649,6 +1692,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // at the ACK. writeLine(out, cov); lastEndedTestId = cut ? null : command.testId; + lastEndedHadUntrackedAsync = !cut && hadUntrackedAsync; // 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 @@ -1956,16 +2000,21 @@ private static void updateDigest(MessageDigest md, String s) { // 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. - private boolean begin(String testId, String prevActiveTestId, 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. Any cut/lingering prior window marks this window // contaminated ("tail:") until drained. - RequestGate.open(testId, prevActiveTestId); + boolean reqTail = RequestGate.open(testId, prevActiveTestId); + if (suppressBackground != null && suppressBackground.length > 0) { + suppressBackground[0] = jobTail || reqTail; + } ProbeScan scan = probeScan(); if (scan != null) { try { @@ -3197,6 +3246,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. @@ -3286,6 +3345,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; @@ -3293,13 +3353,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(), @@ -3309,24 +3371,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 1b6d910f..2101343d 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -73,6 +73,50 @@ final class OrderedPools { // What lookup caches hold for a class with no matching public method. private static final Object NONE = new Object(); + // 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"))); + + 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 isSpringAsyncTaskExecutor(Object receiver) { + return receiver instanceof java.util.concurrent.Executor + && Boolean.TRUE.equals(IS_SPRING_ASYNC_TASK_EXECUTOR.get(receiver.getClass())); + } + // 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"; @@ -327,6 +371,9 @@ private static boolean read(Object executor, int depth, boolean requireVerified) || JDK_THREAD_PER_TASK.equals(className)) { return false; } + if (depth > 0 && INLINE_EXECUTORS.contains(className)) { + return false; + } if (JDK_DELEGATED.equals(className) || JDK_DELEGATED_SCHEDULED.equals(className)) { return readDelegated(executor, depth); } 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 155a50d1..67ca08c2 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -3,6 +3,7 @@ import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; +import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; @@ -16,6 +17,7 @@ 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; @@ -116,6 +118,31 @@ public final class RequestGate { 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 for one-shot TimerTasks when TimerTask.state + // cannot be read reflectively (JDK 16+ without --add-opens java.base/java.util). + private static final long HANDLE_START_GRACE_NANOS = TimeUnit.MILLISECONDS.toNanos(50); + private static final long HANDLE_TIMER_ONESHOT_GRACE_NANOS = TimeUnit.MILLISECONDS.toNanos(50); + // Weakly-keyed sets of cancelled TimerTasks and Timers populated by rewritten + // TimerTask.cancel() / Timer.cancel() call sites so cancelled timers stop + // contaminating immediately even on JDK 16+ without --add-opens. + 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 Field TIMER_TASK_STATE_FIELD = findTimerTaskStateField(); + + private static Field findTimerTaskStateField() { + try { + Field f = TimerTask.class.getDeclaredField("state"); + f.setAccessible(true); + return f; + } catch (Throwable ignored) { + return null; + } + } // 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, @@ -313,6 +340,8 @@ static void disarm() { externalUntrackedTailExpiresAtNanos = 0L; externalUntrackedTailReason = null; EXTERNAL_UNTRACKED_HANDLES.clear(); + CANCELLED_TIMER_TASKS.clear(); + CANCELLED_TIMERS.clear(); LINGERING.clear(); current = new Window(null); } @@ -439,6 +468,9 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def return null; } if (task instanceof Handed) { + if (OrderedPools.isInlineExecutor(executor)) { + return task; + } if (OrderedPools.orders(executor)) { Handed existing = (Handed) task; existing.releaseIfPending(); @@ -454,6 +486,9 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def if (window == null && job == null) { return task; } + if (OrderedPools.isInlineExecutor(executor)) { + return task; + } if (task instanceof Comparable) { markUntrackedExecutor(window, job, executor, "comparable"); return task; @@ -498,6 +533,9 @@ public static Callable hand(Object executor, Callable task) { return null; } if (task instanceof HandedCall) { + if (OrderedPools.isInlineExecutor(executor)) { + return task; + } if (OrderedPools.orders(executor)) { @SuppressWarnings("unchecked") HandedCall existing = (HandedCall) task; @@ -514,6 +552,9 @@ public static Callable hand(Object executor, Callable task) { if (window == null && job == null) { return task; } + if (OrderedPools.isInlineExecutor(executor)) { + return task; + } if (task instanceof Comparable) { markUntrackedExecutor(window, job, executor, "comparable"); return task; @@ -556,6 +597,9 @@ private static Supplier handSupplierInternal(Object executor, Supplier return null; } if (supplier instanceof HandedSupplier) { + if (OrderedPools.isInlineExecutor(executor)) { + return supplier; + } if (OrderedPools.orders(executor)) { @SuppressWarnings("unchecked") HandedSupplier existing = (HandedSupplier) supplier; @@ -572,6 +616,9 @@ private static Supplier handSupplierInternal(Object executor, Supplier if (window == null && job == null) { return supplier; } + if (OrderedPools.isInlineExecutor(executor)) { + return supplier; + } if (supplier instanceof Comparable) { markUntrackedExecutor(window, job, executor, "comparable"); return supplier; @@ -817,7 +864,7 @@ private static Hand prepareCfStageHand(CompletableFuture receiver, Executor e if (explicitExecutor == null) { return null; } - if (OrderedPools.orders(explicitExecutor)) { + if (!OrderedPools.isInlineExecutor(explicitExecutor) && OrderedPools.orders(explicitExecutor)) { markUntrackedExecutor(window, job, explicitExecutor, "unknown"); return null; } @@ -3004,44 +3051,154 @@ private static void noteUntrackedAsync(String reason, long extraTailNanos) { } /** - * Checks at runtime whether an executor receiver is a hooked and verified - * Spring executor before a non-JDK {@code execute}/{@code submit} call, - * flagging {@code untracked-executor:} only when it is not. + * 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 executor receiver + * @param receiver target receiver of {@code execute(Runnable)} */ public static void noteIfUntrackedExecutor(Object receiver) { + if (!(receiver instanceof Executor)) { + return; + } if (!armed) { - if (receiver != null) { - noteUnarmedHandOffIfInFlight(); - } + noteUnarmedHandOffIfInFlight(); return; } - if (receiver == null) { + 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.isHookedAndVerifiedSpringExecutor(receiver)) { + if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { return; } noteUntrackedAsync("untracked-executor:" + receiver.getClass().getName(), 0L); } + /** + * Records cancellation of a {@link Timer} so tracked {@link TimerTask} + * handles scheduled on it stop driving tail contamination immediately. + * + * @param timer cancelled timer + */ + public static void noteTimerCancelled(Timer timer) { + if (timer == null || !armed) { + return; + } + drainDeadTimerKeys(); + CANCELLED_TIMERS.put(new WeakIdentityKey(timer, DEAD_TIMER_KEYS), Boolean.TRUE); + } + + /** + * Records cancellation when {@code target} is a {@link TimerTask} so its + * tracked handle stops driving tail contamination immediately even on + * JDK 16+ without {@code --add-opens java.base/java.util}. + * + * @param target receiver of {@code cancel()} + */ + public static void noteIfTimerTaskCancelled(Object target) { + if (!(target instanceof TimerTask) || !armed) { + return; + } + drainDeadTimerTaskKeys(); + CANCELLED_TIMER_TASKS.put(new WeakIdentityKey(target, DEAD_TIMER_TASK_KEYS), Boolean.TRUE); + } + + 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 boolean isTimerTaskCancelled(TimerTask task) { + if (task == null || CANCELLED_TIMER_TASKS.isEmpty()) { + return false; + } + drainDeadTimerTaskKeys(); + return CANCELLED_TIMER_TASKS.containsKey(new LookupKey(task)); + } + + private static boolean isTimerCancelled(Timer timer) { + if (timer == null || CANCELLED_TIMERS.isEmpty()) { + return false; + } + drainDeadTimerKeys(); + return CANCELLED_TIMERS.containsKey(new LookupKey(timer)); + } + + private static int readTimerTaskState(TimerTask task) { + Field f = TIMER_TASK_STATE_FIELD; + if (f == null || task == null) { + return -1; + } + try { + return f.getInt(task); + } catch (Throwable ignored) { + return -1; + } + } + + 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 while the thread remains alive. + * contamination persists only while the thread remains alive. * * @param target receiver of {@code start()} */ public static void noteIfThread(Object target) { - if (target instanceof Thread) { - noteUntrackedAsync("untracked-async:thread-start", 0L); - trackUntrackedHandleForCurrent(target, false); + if (!(target instanceof Thread)) { + return; } + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return; + } + noteTrackedUntrackedAsync("untracked-async:thread-start", target, false); } /** @@ -3053,8 +3210,28 @@ public static void noteIfThread(Object target) { * @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) { - trackUntrackedHandleForCurrent(thread, true); + noteTrackedUntrackedAsync(reason, thread, true); + } else if (reason != null && !reason.isEmpty()) { + noteUntrackedAsync(reason, 0L); } } @@ -3066,40 +3243,104 @@ public static void trackUntrackedThread(Object thread) { * @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) { - trackUntrackedHandleForCurrent(future, true); + noteTrackedUntrackedAsync(reason, future, true); + } else if (reason != null && !reason.isEmpty()) { + noteUntrackedAsync(reason, 0L); } } - private static void trackUntrackedHandleForCurrent(Object handle, boolean alreadyStarted) { - if (!armed || handle == null) { + 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) { - window.addUntrackedHandle(handle, alreadyStarted); + if (reason != null && !reason.isEmpty()) { + window.contaminateTracked(reason); + } + window.addUntrackedHandle(handle, now); if (window != current) { - retainLingering(window, System.nanoTime()); + retainLingering(window, now); } return; } - if (JobGate.runningAttribution() != null || JobGate.expiredAttribution() != null) { - if (!addHandleToQueue(EXTERNAL_UNTRACKED_HANDLES, handle, alreadyStarted)) { - noteExternalUntrackedTail("job", maxLingeringNanos); + 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, Object handle, - boolean alreadyStarted) { - long now = System.nanoTime(); + 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(new UntrackedHandle(handle, alreadyStarted, now)); + queue.add(handle); return true; } @@ -3118,14 +3359,6 @@ private static boolean sweepUntrackedHandles(ConcurrentLinkedQueue Callable wrapScheduledContext(ScheduledExecutorService exe */ public static ScheduledFuture schedule(ScheduledExecutorService executor, Runnable command, long delay, TimeUnit unit) { - noteUntrackedAsync("untracked-async:schedule", boundedDelayNanos(delay, unit)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.schedule(command, delay, unit); + } ScheduledFuture sf = executor.schedule(wrapScheduledContext(executor, command), delay, unit); - trackUntrackedHandleForCurrent(sf, true); + noteTrackedUntrackedAsync("untracked-async:schedule", sf, true); return sf; } @@ -3186,9 +3422,12 @@ public static ScheduledFuture schedule(ScheduledExecutorService executor, Run */ public static ScheduledFuture schedule(ScheduledExecutorService executor, Callable callable, long delay, TimeUnit unit) { - noteUntrackedAsync("untracked-async:schedule", boundedDelayNanos(delay, unit)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.schedule(callable, delay, unit); + } ScheduledFuture sf = executor.schedule(wrapScheduledContext(executor, callable), delay, unit); - trackUntrackedHandleForCurrent(sf, true); + noteTrackedUntrackedAsync("untracked-async:schedule", sf, true); return sf; } @@ -3205,11 +3444,13 @@ public static ScheduledFuture schedule(ScheduledExecutorService executor, */ public static ScheduledFuture scheduleAtFixedRate(ScheduledExecutorService executor, Runnable command, long initialDelay, long period, TimeUnit unit) { - long extra = boundedDelayNanos(initialDelay, unit) + boundedDelayNanos(period, unit); - noteUntrackedAsync("untracked-async:schedule", Math.min(extra, maxLingeringNanos)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.scheduleAtFixedRate(command, initialDelay, period, unit); + } ScheduledFuture sf = executor.scheduleAtFixedRate( wrapScheduledContext(executor, command), initialDelay, period, unit); - trackUntrackedHandleForCurrent(sf, true); + noteTrackedUntrackedAsync("untracked-async:schedule", sf, true); return sf; } @@ -3226,11 +3467,13 @@ public static ScheduledFuture scheduleAtFixedRate(ScheduledExecutorService ex */ public static ScheduledFuture scheduleWithFixedDelay(ScheduledExecutorService executor, Runnable command, long initialDelay, long delay, TimeUnit unit) { - long extra = boundedDelayNanos(initialDelay, unit) + boundedDelayNanos(delay, unit); - noteUntrackedAsync("untracked-async:schedule", Math.min(extra, maxLingeringNanos)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); + } ScheduledFuture sf = executor.scheduleWithFixedDelay( wrapScheduledContext(executor, command), initialDelay, delay, unit); - trackUntrackedHandleForCurrent(sf, true); + noteTrackedUntrackedAsync("untracked-async:schedule", sf, true); return sf; } @@ -3250,8 +3493,13 @@ private static long dateDelayMillis(Date time) { * @param delay execution delay in milliseconds */ public static void timerSchedule(Timer timer, TimerTask task, long delay) { - noteUntrackedAsync("untracked-async:timer", boundedDelayNanos(delay, TimeUnit.MILLISECONDS)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.schedule(task, delay); + return; + } timer.schedule(task, delay); + noteTrackedTimerTask(timer, task, delay, 0L, false); } /** @@ -3262,8 +3510,14 @@ public static void timerSchedule(Timer timer, TimerTask task, long delay) { * @param time execution time */ public static void timerSchedule(Timer timer, TimerTask task, Date time) { - noteUntrackedAsync("untracked-async:timer", boundedDelayNanos(dateDelayMillis(time), TimeUnit.MILLISECONDS)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.schedule(task, time); + return; + } + long delay = dateDelayMillis(time); timer.schedule(task, time); + noteTrackedTimerTask(timer, task, delay, 0L, false); } /** @@ -3275,11 +3529,13 @@ public static void timerSchedule(Timer timer, TimerTask task, Date time) { * @param period period in milliseconds */ public static void timerSchedule(Timer timer, TimerTask task, long delay, long period) { - long extra = boundedDelayNanos(delay, TimeUnit.MILLISECONDS) - + boundedDelayNanos(period, TimeUnit.MILLISECONDS); - noteUntrackedAsync("untracked-async:timer", Math.min(extra, maxLingeringNanos)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.schedule(task, delay, period); + return; + } timer.schedule(task, delay, period); - trackUntrackedHandleForCurrent(task, true); + noteTrackedTimerTask(timer, task, delay, period, true); } /** @@ -3291,11 +3547,14 @@ public static void timerSchedule(Timer timer, TimerTask task, long delay, long p * @param period period in milliseconds */ public static void timerSchedule(Timer timer, TimerTask task, Date firstTime, long period) { - long extra = boundedDelayNanos(dateDelayMillis(firstTime), TimeUnit.MILLISECONDS) - + boundedDelayNanos(period, TimeUnit.MILLISECONDS); - noteUntrackedAsync("untracked-async:timer", Math.min(extra, maxLingeringNanos)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.schedule(task, firstTime, period); + return; + } + long delay = dateDelayMillis(firstTime); timer.schedule(task, firstTime, period); - trackUntrackedHandleForCurrent(task, true); + noteTrackedTimerTask(timer, task, delay, period, true); } /** @@ -3307,11 +3566,13 @@ public static void timerSchedule(Timer timer, TimerTask task, Date firstTime, lo * @param period period in milliseconds */ public static void timerScheduleAtFixedRate(Timer timer, TimerTask task, long delay, long period) { - long extra = boundedDelayNanos(delay, TimeUnit.MILLISECONDS) - + boundedDelayNanos(period, TimeUnit.MILLISECONDS); - noteUntrackedAsync("untracked-async:timer", Math.min(extra, maxLingeringNanos)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.scheduleAtFixedRate(task, delay, period); + return; + } timer.scheduleAtFixedRate(task, delay, period); - trackUntrackedHandleForCurrent(task, true); + noteTrackedTimerTask(timer, task, delay, period, true); } /** @@ -3323,11 +3584,14 @@ public static void timerScheduleAtFixedRate(Timer timer, TimerTask task, long de * @param period period in milliseconds */ public static void timerScheduleAtFixedRate(Timer timer, TimerTask task, Date firstTime, long period) { - long extra = boundedDelayNanos(dateDelayMillis(firstTime), TimeUnit.MILLISECONDS) - + boundedDelayNanos(period, TimeUnit.MILLISECONDS); - noteUntrackedAsync("untracked-async:timer", Math.min(extra, maxLingeringNanos)); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + timer.scheduleAtFixedRate(task, firstTime, period); + return; + } + long delay = dateDelayMillis(firstTime); timer.scheduleAtFixedRate(task, firstTime, period); - trackUntrackedHandleForCurrent(task, true); + noteTrackedTimerTask(timer, task, delay, period, true); } /** @@ -3373,9 +3637,13 @@ public static T invokeAny(ExecutorService executor, Collection") if the previous test was cut, - // unclosed, had an untracked async hand-off, or any prior window still has - // running > 0. - static void open(String testId, String prevActiveTestId) { + // 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(); @@ -3668,12 +3937,13 @@ static void open(String testId, String prevActiveTestId) { if (prev != null) { prev.sweepCancelledFutures(); boolean prevRunning = prev.running.get() > 0; - boolean prevUntracked = prev.hadUntrackedAsync; - if (prevRunning || prevUntracked) { + 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 (prevUntracked && prev.untrackedTailExpiresAtNanos == 0L) { + if (prevBlindUntracked && prev.untrackedTailExpiresAtNanos == 0L) { prev.extendUntrackedTail(now, 0L); } retainLingering(prev, now); @@ -3706,7 +3976,7 @@ static void open(String testId, String prevActiveTestId) { || aliveHandles || (!lingeringExpired && (lingering.running.get() > 0 || lingering.untrackedHandlesOverflowed)); boolean reportCut = lingering.wasCut && !lingering.cutReportedOnce; - boolean untrackedActive = lingering.hadUntrackedAsync + boolean untrackedActive = lingering.hasBlindUntrackedAsync && (!lingering.untrackedTailReportedOnce || (now - lingering.untrackedTailExpiresAtNanos) < 0L); if (stillRunning || reportCut || untrackedActive) { @@ -3714,12 +3984,12 @@ static void open(String testId, String prevActiveTestId) { if (reportCut) { lingering.cutReportedOnce = true; } - if (lingering.hadUntrackedAsync) { + if (lingering.hasBlindUntrackedAsync) { lingering.untrackedTailReportedOnce = true; } } boolean cutDone = !lingering.wasCut || lingering.cutReportedOnce; - boolean untrackedDone = !lingering.hadUntrackedAsync + boolean untrackedDone = !lingering.hasBlindUntrackedAsync || (lingering.untrackedTailReportedOnce && (now - lingering.untrackedTailExpiresAtNanos) >= 0L); if (!stillRunning && cutDone && untrackedDone) { @@ -3728,12 +3998,13 @@ static void open(String testId, String prevActiveTestId) { // concurrent Hand.enter / addUntrackedHandle / noteUntrackedAsync. if (lingering.executing.get() > 0 || lingering.hasAliveUntrackedHandles(now) - || (lingering.hadUntrackedAsync + || (lingering.hasBlindUntrackedAsync && (now - lingering.untrackedTailExpiresAtNanos) < 0L)) { LINGERING.add(lingering); } } } + return next.hasOpeningTail(); } private static void retainLingering(Window window, long now) { @@ -3753,14 +4024,14 @@ private static void retainLingering(Window window, long now) { || aliveHandles || (!lingeringExpired && (existing.running.get() > 0 || existing.untrackedHandlesOverflowed)); boolean cutDone = !existing.wasCut || existing.cutReportedOnce; - boolean untrackedDone = !existing.hadUntrackedAsync + 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.hadUntrackedAsync + || (existing.hasBlindUntrackedAsync && (now - existing.untrackedTailExpiresAtNanos) < 0L)) { LINGERING.add(existing); } @@ -3791,9 +4062,8 @@ static boolean await(long timeoutNanos) { // 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, or carrying an untracked async hand-off, - // and returns its outcome (drained, waited, enteredCount, and accumulated - // contaminations). + // 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; @@ -3802,21 +4072,27 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { int initialRunning = window.running.get(); if (!wait) { long now = System.nanoTime(); - if (window.hadUntrackedAsync) { + if (window.hasBlindUntrackedAsync) { window.extendUntrackedTail(now, 0L); } - if (initialRunning > 0 || window.hadUntrackedAsync) { + if (initialRunning > 0 || window.hasBlindUntrackedAsync + || window.hasAliveUntrackedHandles(now) || window.untrackedHandlesOverflowed) { retainLingering(window, now); } - return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations()); + return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations(), + window.hadUntrackedAsync); } if (initialRunning <= 0) { - if (window.hadUntrackedAsync) { - long now = System.nanoTime(); + 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()); + return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations(), + window.hadUntrackedAsync); } boolean drained = false; // Set before the count is read again: an exit that takes the count @@ -3848,17 +4124,20 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { } finally { window.waiter = null; } - if (!drained || window.hadUntrackedAsync) { - long now = System.nanoTime(); + long now = System.nanoTime(); + boolean needsRetain = !drained || window.hasBlindUntrackedAsync + || window.hasAliveUntrackedHandles(now) || window.untrackedHandlesOverflowed; + if (needsRetain) { if (!drained) { window.wasCut = true; } - if (window.hadUntrackedAsync) { + if (window.hasBlindUntrackedAsync) { window.extendUntrackedTail(now, 0L); } retainLingering(window, now); } - return new WindowOutcome(drained, true, window.enteredCount.get(), window.contaminations()); + return new WindowOutcome(drained, true, window.enteredCount.get(), window.contaminations(), + window.hadUntrackedAsync); } static final class WindowOutcome { @@ -3866,26 +4145,54 @@ static final class WindowOutcome { final boolean waited; final int enteredCount; final List contaminations; + final boolean hadUntrackedAsync; - WindowOutcome(boolean drained, boolean waited, int enteredCount, List contaminations) { + WindowOutcome(boolean drained, boolean waited, int enteredCount, List contaminations, + boolean hadUntrackedAsync) { this.drained = drained; this.waited = waited; this.enteredCount = enteredCount; this.contaminations = contaminations; + this.hadUntrackedAsync = hadUntrackedAsync; } } 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 volatile boolean observedAlive; private UntrackedHandle(Object target, boolean alreadyStarted, long registeredAtNanos) { + this(target, null, alreadyStarted, registeredAtNanos, false, 0L, 0L); + } + + private UntrackedHandle(Object target, Timer timer, boolean alreadyStarted, long registeredAtNanos, + boolean timerPeriodic, long timerExpectedFireAtNanos, long timerPeriodMillis) { 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; + } + + 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; + return new UntrackedHandle(task, timer, true, now, periodic, expectedFire, safePeriodMs); } private boolean isActive(long now) { @@ -3899,20 +4206,45 @@ private boolean isActive(long now) { observedAlive = true; return true; } - if (alreadyStarted || observedAlive) { + if (alreadyStarted || observedAlive || t.getState() == Thread.State.TERMINATED) { return false; } - // Registered immediately before subThread.start(): keep active - // briefly in case the OS thread hasn't transitioned to alive yet. - return (now - registeredAtNanos) < untrackedTailWindowNanos; + // 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) { - // Timer's internal TaskQueue holds periodic TimerTasks strongly - // while scheduled, so weak reachability errs toward flagging. - return true; + TimerTask task = (TimerTask) target; + if (isTimerTaskCancelled(task)) { + return false; + } + Timer t = timerRef == null ? null : timerRef.get(); + if (t != null && isTimerCancelled(t)) { + return false; + } + int state = readTimerTaskState(task); + if (state >= 0) { + // java.util.TimerTask states: VIRGIN=0, SCHEDULED=1, EXECUTED=2, CANCELLED=3 + return state == 1; + } + // Fallback when TimerTask.state cannot be read reflectively (JDK 16+ without --add-opens): + if (!timerPeriodic) { + long grace = Math.min(HANDLE_TIMER_ONESHOT_GRACE_NANOS, untrackedTailWindowNanos); + return (now - timerExpectedFireAtNanos) < grace; + } + if ((now - timerExpectedFireAtNanos) < 0L) { + return true; + } + long execMillis = safeScheduledExecutionTime(task); + if (execMillis <= 0L) { + return (now - registeredAtNanos) < maxLingeringNanos; + } + long slackMillis = Math.max(timerPeriodMillis * 2L, 150L); + return System.currentTimeMillis() <= execMillis + timerPeriodMillis + slackMillis; } return false; } @@ -3936,7 +4268,11 @@ private static final class Window { 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; @@ -3946,8 +4282,8 @@ private static final class Window { @SuppressWarnings("rawtypes") private volatile ConcurrentHashMap futures; // Weak handles to live untracked Threads, ScheduledFutures, and - // periodic TimerTasks started in this window so tail contamination - // persists while they stay alive. + // TimerTasks started in this window so tail contamination persists + // strictly while they stay alive. @SuppressWarnings("rawtypes") private volatile ConcurrentLinkedQueue untrackedHandles; private volatile boolean untrackedHandlesOverflowed; @@ -3988,8 +4324,23 @@ private void contaminate(String reason, long extraTailNanos) { } 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); @@ -4000,6 +4351,16 @@ private void contaminate(String reason, long extraTailNanos) { } } + 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(); @@ -4079,9 +4440,9 @@ private ConcurrentLinkedQueue untrackedHandlesQueue(boolean cre return (ConcurrentLinkedQueue) untrackedHandles; } - private void addUntrackedHandle(Object target, boolean alreadyStarted) { + private void addUntrackedHandle(UntrackedHandle handle, long now) { hadUntrackedAsync = true; - if (!addHandleToQueue(untrackedHandlesQueue(true), target, alreadyStarted)) { + if (!addHandleToQueue(untrackedHandlesQueue(true), handle, now)) { untrackedHandlesOverflowed = true; } } 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 57a38e8b..3a1ab9c2 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -180,6 +180,7 @@ final class ServerEntries implements ClassFileTransformer { "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", @@ -196,7 +197,7 @@ final class ServerEntries implements ClassFileTransformer { 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", + "invokeAny", "fork", "subscribe", "start", "startVirtualThread", "cancel", "addListener", "addCallback", "transform", "transformAsync", "catching", "catchingAsync", "poll", "basicConsume", "receive", "setMessageListener"))); @@ -903,20 +904,23 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, } } - private static boolean isSingleArgExecutorSubmitOrExecute(String mname, String desc) { - if ("execute".equals(mname) && "(Ljava/lang/Runnable;)V".equals(desc)) { - return true; - } - if (("submit".equals(mname) || "submitListenable".equals(mname) || "submitCompletable".equals(mname)) + 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;)"))) { - return true; - } - return false; + || desc.startsWith("(Ljava/util/concurrent/Callable;)")); + } + + private static boolean isSingleArgExecutorSubmitOrExecute(String mname, String desc) { + return isSingleArgExecutorExecute(mname, desc) || isSingleArgExecutorSubmit(mname, desc); } private static boolean isTwoArgExecutorSubmit(String mname, String desc) { - return "submit".equals(mname) && desc.startsWith("(Ljava/lang/Runnable;Ljava/lang/Object;)"); + return "submit".equals(mname) + && "(Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Future;".equals(desc); } private static boolean isForkJoinTaskSubmission(String owner, String mname, String desc) { @@ -1313,6 +1317,15 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, "(Ljava/util/Timer;" + desc.substring(1), false); return; } + if ("cancel".equals(mname) && "()V".equals(desc)) { + changed[0] = true; + ensureExtraStack(1); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteTimerCancelled", + "(Ljava/util/Timer;)V", false); + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + return; + } } if (opcode == Opcodes.INVOKEVIRTUAL && "java/lang/Thread".equals(owner) @@ -1327,38 +1340,49 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, && "java/lang/Thread".equals(owner) && "startVirtualThread".equals(mname) && "(Ljava/lang/Runnable;)Ljava/lang/Thread;".equals(desc)) { - emitUntrackedFlag("untracked-async:virtual-thread"); + 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;)V", false); + "(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)) { - emitUntrackedFlag("untracked-async:thread-builder"); + 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;)V", false); + "(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 (isSingleArgExecutorSubmitOrExecute(mname, desc)) { - // Decide at runtime by actual receiver so Spring interfaces - // (TaskExecutor/AsyncTaskExecutor) and subclasses have zero - // false positives when hooked+verified AND zero false negatives - // when backed by VirtualThreadTaskExecutor/custom pools. + 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)) { emitUntrackedFlag("untracked-executor:" + owner.replace('/', '.')); } else if (isForkJoinTaskSubmission(owner, mname, desc)) { @@ -1366,15 +1390,19 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, } else if (isTimerSchedule(owner, mname, desc)) { emitUntrackedFlag("untracked-async:timer"); } else if (isUntrackedScheduleOrInvokeAny(mname, desc)) { - emitUntrackedFlag("untracked-async:" + ("invokeAny".equals(mname) - ? "invokeAny" : "schedule")); - if (desc.endsWith(")Ljava/util/concurrent/ScheduledFuture;")) { + 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;)V", false); + "(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"); @@ -1389,6 +1417,16 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, 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() calls so cancelled TimerTasks stop + // driving tail contamination immediately even on JDK 16+ without + // --add-opens java.base/java.util. + changed[0] = true; + ensureExtraStack(1); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfTimerTaskCancelled", + "(Ljava/lang/Object;)V", false); } } super.visitMethodInsn(opcode, owner, mname, desc, isInterface); 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 467df7a2..3f012134 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ControlSocketTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ControlSocketTest.java @@ -52,7 +52,7 @@ * 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=3 caps=windowCut=...,contaminated=...,classMismatch=...,background=...,asyncExecutors=...,listenerContamination=..." + * "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. @@ -68,7 +68,7 @@ public class ControlSocketTest { private static final String END_WAIT_PROPERTY = "keploy.java.end.wait.ms"; private static final String TAKEN = "ACK proto=3 caps=windowCut=false,contaminated=false,classMismatch=true," - + "background=false,asyncExecutors=false,listenerContamination=false\n"; + + "background=false,ackId=true,asyncExecutors=false,listenerContamination=false\n"; private static final String IGNORED = "IGNORED proto=3\n"; private String savedControlPath; 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 0cd90e25..0e6ad442 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 index 612cde39..93938e48 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -277,8 +277,10 @@ public void forkedJettyColdStartDeclaresWindowCutTrueAndUncountedServerMarksNoSe 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 fail closed with no-server-entry: " + cov, - cov.contains("\"contaminated\":[\"no-server-entry\"]")); + 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, diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index d9fc073b..ab52308d 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -363,12 +363,15 @@ public void earlyConnectBeforeJacocoAndServerInitDoesNotLatchFailureRefreshesHel 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. Netty/WebFlux) -> contaminated: ["no-server-entry"]! + // Uncounted server (probes > 0 while enteredCount == 0, e.g. Netty/WebFlux) -> + // unverified: ["no-server-entry"] with NO "contaminated" field (old enterprise compat)! probes[1] = true; send(out, "END ts/test-2"); String cov2 = in.readLine(); assertEquals("COV {\"id\":\"ts/test-2\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}," - + "\"contaminated\":[\"no-server-entry\"]}", cov2); + + "\"unverified\":[\"no-server-entry\"]}", cov2); + assertFalse("no contaminated field for old enterprise notMeasuredBy compat", + cov2.contains("\"contaminated\"")); assertEquals("ACK ts/test-2", in.readLine()); } finally { DeferredRtLoader.agent = null; @@ -1437,7 +1440,7 @@ public void unixControlSocketDeclaresProto3CapsMatchingLiveState() throws Except String reply1 = sendUnix(KeployDedupAgent.controlSocketPath, "START ts/u1"); assertEquals("ACK proto=3 caps=windowCut=true,contaminated=true,classMismatch=true," - + "background=false,asyncExecutors=true,listenerContamination=true\n", reply1); + + "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(" ")); @@ -1446,7 +1449,7 @@ public void unixControlSocketDeclaresProto3CapsMatchingLiveState() throws Except 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,asyncExecutors=false,listenerContamination=true\n", reply2); + + "background=false,ackId=true,asyncExecutors=false,listenerContamination=true\n", reply2); System.clearProperty(ASYNC_CALLSITES_PROPERTY); } @@ -2800,6 +2803,507 @@ public void run() { } } + public static final class PlainSyncTxHelper { + public void execute(Runnable action) { + action.run(); + } + + public Object submit(Runnable action) { + action.run(); + return "ok"; + } + } + + public static final class CustomWorkerThread extends Thread { + public CustomWorkerThread(Runnable r) { + super(r, "r9-custom-thread"); + setDaemon(true); + } + } + + @Test(timeout = 60000) + public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineExecutorsAndBackgroundSuppression() + throws Exception { + ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); + java.util.Timer timer = new java.util.Timer(true); + long savedTailWindow = RequestGate.untrackedTailWindowNanos; + try { + // Blocker 2: 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/R9DeltaCaller"); + byte[] callerRewritten = ServerEntries.wrapExecutorCalls(callerRaw); + assertNotNull("R9DeltaCaller must be rewritten by ServerEntries.wrapExecutorCalls", callerRewritten); + Class caller = new ByteLoader(getClass().getClassLoader()) + .define("com.acme.R9DeltaCaller", callerRewritten); + + RequestGate.disarm(); + RequestGate.open("b2-sync-helper", null); + Object reqB2 = 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(reqB2); + } + assertTrue("TxHelper.execute ran", execRan.get()); + assertTrue("TxHelper.submit ran", submitRan.get()); + assertEquals("non-Executor TxHelper.execute/submit must NOT contaminate current window (B2)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.open("b2-next-window", null); + assertEquals("non-Executor TxHelper.execute/submit must NOT taint subsequent window (B2)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Positive control for B2: a real custom Executor/ExecutorService still gets flagged! + RequestGate.open("b2-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())); + + // Should-Fix 1(a): Request schedules a 30s timeout and cancels it before returning -> + // next request MUST be CLEAN (no 32s tail: taint)! + RequestGate.disarm(); + RequestGate.open("sf1a-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 sf1aOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("originating window still notes schedule", + sf1aOut.contaminations.contains("untracked-async:schedule")); + RequestGate.open("sf1a-next-clean", null); + assertEquals("cancelled 30s timeout must NOT taint subsequent window (SF1a)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Should-Fix 1(b): Thread.start() + join() before response -> next request MUST be CLEAN! + RequestGate.disarm(); + RequestGate.open("sf1b-thread-join", null); + Object reqJoin = RequestGate.enter(); + try { + Thread t = new Thread(() -> { }, "sf1b-joined"); + 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("sf1b-next-clean", null); + assertEquals("joined Thread.start() must NOT leave 2s tail taint on next window (SF1b)", + 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("sf1b-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("sf1b-subthread-next-clean", null); + assertEquals("joined Thread subclass must NOT taint next window (SF1b)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Should-Fix 1(c): Periodic TimerTask cancelled and retained strongly in a field -> + // next request MUST be CLEAN! + RequestGate.disarm(); + java.util.TimerTask retainedTask = new NoopTimerTask(); + RequestGate.open("sf1c-timer-cancel", 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 sf1cOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("originating window notes untracked-async:timer", + sf1cOut.contaminations.contains("untracked-async:timer")); + RequestGate.open("sf1c-next-clean", null); + assertEquals("cancelled periodic TimerTask retained in a field must NOT taint next window (SF1c)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + assertNotNull("keep strong reference alive past assertion", retainedTask); + + // Also verify one-shot TimerTask with 30s delay cancelled before returning -> CLEAN! + RequestGate.disarm(); + java.util.TimerTask retainedOneShot = new NoopTimerTask(); + RequestGate.open("sf1c-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("sf1c-oneshot-next-clean", null); + assertEquals("cancelled one-shot 30s TimerTask must NOT taint next window (SF1c)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + assertNotNull("keep strong reference alive", retainedOneShot); + + // Should-Fix 3: Known same-thread inline executors (Spring SyncTaskExecutor, + // ConcurrentTaskExecutor(SyncTaskExecutor), and Guava DirectExecutor) are + // NEITHER wrapped NOR flagged untracked-executor! + 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(); + + RequestGate.open("sf3-inline", null); + Object reqInline = RequestGate.enter(); + AtomicBoolean inlineRan1 = new AtomicBoolean(false); + AtomicBoolean inlineRan2 = new AtomicBoolean(false); + try { + Runnable raw1 = () -> inlineRan1.set(true); + Runnable raw2 = () -> inlineRan2.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)); + RequestGate.execute(syncExec, raw1); + RequestGate.execute(guavaDirect, raw2); + RequestGate.noteIfUntrackedExecutor(syncExec); + RequestGate.noteIfUntrackedExecutor(guavaDirect); + assertFalse("ConcurrentTaskExecutor(SyncTaskExecutor) must be allow-listed", + OrderedPools.orders(concurrentDefault)); + } finally { + RequestGate.exit(reqInline); + } + assertTrue("SyncTaskExecutor task executed", inlineRan1.get()); + assertTrue("Guava DirectExecutor task executed", inlineRan2.get()); + assertEquals("known inline executors must NOT contaminate current window (SF3)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + RequestGate.open("sf3-inline-next", null); + assertEquals("known inline executors must NOT taint next window (SF3)", + Collections.emptyList(), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + + // Should-Fix 4: Minimal connect-time fallback HELLO format is valid JSON with empty identity. + String minimalHello = KeployDedupAgent.buildHelloFrame("", "", "", "", "", "", + false, false, false, false, true, true, false, false); + JsonObject minObj = parseHello(minimalHello); + 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()); + } 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")); + } finally { + KeployDedupAgent.stop(); + collector.close(); + collector = null; + } + + // 2. Unix transport: verify the exact same suppression + lost:1 counter! + System.clearProperty(ENDPOINT_PROPERTY); + 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")); + Object req2 = RequestGate.enter(); + try { + probes[1] = true; + } finally { + RequestGate.exit(req2); + } + assertTrue(sendUnixControl("END ts/u2").startsWith("ACK proto=3")); + + probes[3] = true; + assertTrue(sendUnixControl("START ts/u3").startsWith("ACK proto=3")); + + // Drain data records and verify no BACKGROUND for u1->u2 and BACKGROUND for u2->u3 has lost:1! + String bgU2U3 = null; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + 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\"")); + if (rec.contains("\"kind\":\"background\"") && rec.contains("\"after\":\"ts/u2\"")) { + bgU2U3 = rec; + break; + } + } + assertNotNull("expected BACKGROUND for clean gap u2->u3", bgU2U3); + assertTrue("Unix BACKGROUND must carry lost:1 for suppressed u1->u2 gap: " + bgU2U3, + bgU2U3.contains("\"lost\":1")); + } finally { + KeployDedupAgent.stop(); + dataServer.close(); + } + } + + 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[] 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.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(); + + 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(5L); + m3.visitLdcInsn(25L); + 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(); + + 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; 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 728171eb..9d6c9148 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/PhasesTest.java @@ -51,7 +51,7 @@ public class PhasesTest { "keploy.build.tag"}; private static final String TAKEN = "ACK proto=3 caps=windowCut=false,contaminated=false,classMismatch=true," - + "background=false,asyncExecutors=false,listenerContamination=false\n"; + + "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"; From cf6e0c93edbb10fa9dec35d52583041b18c59e91 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 09:49:25 +0530 Subject: [PATCH 14/26] =?UTF-8?q?fix(dedup):=20close=20R9=20review=20findi?= =?UTF-8?q?ngs=20=E2=80=94=20TimerTask=20running-body=20&=20cancel-return?= =?UTF-8?q?=20tracking=20(no=20JDK-internal=20reflection),=202-arg=20submi?= =?UTF-8?q?t=20runtime=20check,=20active-lingering=20BACKGROUND=20suppress?= =?UTF-8?q?ion,=20and=20full=20Unix/TCP/inline/HELLO=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: slayerjain --- README.md | 2 +- .../main/java/io/keploy/dedup/JobGate.java | 13 + .../io/keploy/dedup/KeployDedupAgent.java | 48 +- .../java/io/keploy/dedup/OrderedPools.java | 3 +- .../java/io/keploy/dedup/RequestGate.java | 179 +++--- .../java/io/keploy/dedup/ServerEntries.java | 31 +- .../dedup/HonestProtocolAndAsyncTest.java | 510 +++++++++++++++++- 7 files changed, 662 insertions(+), 124 deletions(-) diff --git a/README.md b/README.md index fe97e0fa..56b2eb87 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ 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. Likewise, when a gap may hold a test's tail (the previous window had an untracked async hand-off, 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 so a test's async tail probes are never calibrated 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 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. +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` (or `ACK ` when `ACK_ID` is enabled). 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 f8db2fe8..d5720b1c 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -82,6 +82,19 @@ 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. 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 8b15f064..58904e3d 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -187,6 +187,9 @@ static String jvmNonce() { // 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; @@ -1030,7 +1033,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 lastEndedHadUntrackedAsync; + 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 @@ -1214,9 +1217,9 @@ private boolean run(CoverageCommand command, Phases phases) { String prevActive = activeTestId; activeTestId = ""; String after = lastEndedTestId; - boolean prevUntracked = lastEndedHadUntrackedAsync; + boolean prevMayEmitTail = lastEndedMayEmitTail; lastEndedTestId = null; - lastEndedHadUntrackedAsync = false; + 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(); @@ -1231,10 +1234,10 @@ private boolean run(CoverageCommand command, Phases phases) { // 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. Also suppress gaps that may hold a previous test's - // async/cut/job tail so those probes are never calibrated as + // async/cut/job tail so those probes are not emitted as // background. if (after != null && !cleared.isEmpty() && publisher.backgroundAsked()) { - if (prevUntracked || suppressBackground[0]) { + if (prevMayEmitTail || suppressBackground[0]) { publisher.noteBackgroundLost(); } else { pendingBackground = new BackgroundWindow(after, command.testId, cleared); @@ -1247,7 +1250,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; - lastEndedHadUntrackedAsync = false; + lastEndedMayEmitTail = false; if (!command.testId.equals(activeTestId)) { log(Level.SEVERE, "Ignoring mismatched END command. expected=" + activeTestId + ", actual=" @@ -1280,7 +1283,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; - lastEndedHadUntrackedAsync = !cut && outcome.hadUntrackedAsync; + lastEndedMayEmitTail = !cut && (outcome.tailActiveAtEnd || JobGate.hasExpiredRunning()); return true; } catch (Exception e) { // Not ACK for the same reason: nothing reached Keploy. @@ -1389,7 +1392,7 @@ private static final class CoverageTcpClient implements CoverageWorker { // 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 lastEndedHadUntrackedAsync; + private boolean lastEndedMayEmitTail; // Opt-in per TCP connection via "BACKGROUND" command so older collectors // never receive unexpected BACKGROUND frames. private boolean backgroundRequested; @@ -1413,6 +1416,10 @@ private static final class CoverageTcpClient implements CoverageWorker { } private String helloFrame() { + RuntimeException injected = testHelloFailure; + if (injected != null) { + throw injected; + } return computeCapabilities(collector).toHelloFrame(collector.helloBuildId()); } @@ -1475,7 +1482,7 @@ private void connectAndServe() throws IOException { synchronized (testCaseLock) { activeTestId = ""; lastEndedTestId = null; - lastEndedHadUntrackedAsync = false; + lastEndedMayEmitTail = false; backgroundRequested = false; ackWithId = false; lastHelloSent = null; @@ -1495,7 +1502,7 @@ private void connectAndServe() throws IOException { synchronized (testCaseLock) { try { maybeSendUpdatedHello(out); - } catch (RuntimeException e) { + } 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); @@ -1571,9 +1578,9 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) String prevActive = activeTestId; activeTestId = ""; String after = lastEndedTestId; - boolean prevUntracked = lastEndedHadUntrackedAsync; + boolean prevMayEmitTail = lastEndedMayEmitTail; lastEndedTestId = null; - lastEndedHadUntrackedAsync = false; + lastEndedMayEmitTail = false; boolean reset; List cleared = new ArrayList<>(); boolean[] suppressBackground = {false}; @@ -1599,7 +1606,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) } try { maybeSendUpdatedHello(out); - } catch (RuntimeException e) { + } catch (RuntimeException | LinkageError e) { log(Level.FINE, "Failed to refresh HELLO before START ACK for " + command.testId, e); } ack(out, command.testId); @@ -1608,7 +1615,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // 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 (prevUntracked || suppressBackground[0]) { + if (prevMayEmitTail || suppressBackground[0]) { backgroundLost++; } else { writeBackgroundFrame(out, after, command.testId, cleared); @@ -1622,7 +1629,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // after an END not taken or cut, what the next START clears // may hold this test's own hits. lastEndedTestId = null; - lastEndedHadUntrackedAsync = false; + lastEndedMayEmitTail = false; if (!command.testId.equals(activeTestId)) { log(Level.SEVERE, "Ignoring mismatched END command. expected=" + activeTestId + ", actual=" @@ -1643,13 +1650,16 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // exception would shift the collector onto the next test's frames. TestCoverage coverage; boolean cut; - boolean hadUntrackedAsync; + boolean tailActiveAtEnd; try { RequestGate.WindowOutcome outcome = collector.awaitRequests(command.testId, phases); cut = !outcome.drained; - hadUntrackedAsync = outcome.hadUntrackedAsync; + 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(); @@ -1676,7 +1686,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // runtime error computing HELLO can never suppress COV before ACK. try { maybeSendUpdatedHello(out); - } catch (RuntimeException e) { + } catch (RuntimeException | LinkageError e) { log(Level.FINE, "Failed to refresh HELLO before COV for " + command.testId, e); } try { @@ -1692,7 +1702,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // at the ACK. writeLine(out, cov); lastEndedTestId = cut ? null : command.testId; - lastEndedHadUntrackedAsync = !cut && hadUntrackedAsync; + 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 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 2101343d..c20f649e 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -79,7 +79,8 @@ final class OrderedPools { "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.DirectExecutorService", + "com.google.common.util.concurrent.MoreExecutors$DirectExecutorService"))); private static final String SPRING_ASYNC_TASK_EXECUTOR = "org.springframework.core.task.AsyncTaskExecutor"; 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 67ca08c2..e157c2a9 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -3,7 +3,6 @@ import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; -import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; @@ -119,28 +118,25 @@ public final class RequestGate { 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 for one-shot TimerTasks when TimerTask.state - // cannot be read reflectively (JDK 16+ without --add-opens java.base/java.util). + // still in Thread.State.NEW. private static final long HANDLE_START_GRACE_NANOS = TimeUnit.MILLISECONDS.toNanos(50); - private static final long HANDLE_TIMER_ONESHOT_GRACE_NANOS = TimeUnit.MILLISECONDS.toNanos(50); - // Weakly-keyed sets of cancelled TimerTasks and Timers populated by rewritten - // TimerTask.cancel() / Timer.cancel() call sites so cancelled timers stop - // contaminating immediately even on JDK 16+ without --add-opens. - private static final ConcurrentHashMap CANCELLED_TIMER_TASKS = + // 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 = + private static final ConcurrentHashMap CANCELLED_TIMERS = new ConcurrentHashMap<>(); private static final ReferenceQueue DEAD_TIMER_KEYS = new ReferenceQueue<>(); - private static final Field TIMER_TASK_STATE_FIELD = findTimerTaskStateField(); - private static Field findTimerTaskStateField() { - try { - Field f = TimerTask.class.getDeclaredField("state"); - f.setAccessible(true); - return f; - } catch (Throwable ignored) { - return null; + private static final class TimerCancelInfo { + final boolean cancelledBeforeRun; + final long cancelledAtNanos; + + TimerCancelInfo(boolean cancelledBeforeRun, long cancelledAtNanos) { + this.cancelledBeforeRun = cancelledBeforeRun; + this.cancelledAtNanos = cancelledAtNanos; } } @@ -3103,8 +3099,9 @@ public static void noteIfUntrackedSubmit(Object receiver) { } /** - * Records cancellation of a {@link Timer} so tracked {@link TimerTask} - * handles scheduled on it stop driving tail contamination immediately. + * 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 */ @@ -3113,22 +3110,26 @@ public static void noteTimerCancelled(Timer timer) { return; } drainDeadTimerKeys(); - CANCELLED_TIMERS.put(new WeakIdentityKey(timer, DEAD_TIMER_KEYS), Boolean.TRUE); + CANCELLED_TIMERS.putIfAbsent(new WeakIdentityKey(timer, DEAD_TIMER_KEYS), Long.valueOf(System.nanoTime())); } /** - * Records cancellation when {@code target} is a {@link TimerTask} so its - * tracked handle stops driving tail contamination immediately even on - * JDK 16+ without {@code --add-opens java.base/java.util}. + * 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 noteIfTimerTaskCancelled(Object target) { + public static void noteTimerTaskCancelResult(Object target, boolean cancelled) { if (!(target instanceof TimerTask) || !armed) { return; } drainDeadTimerTaskKeys(); - CANCELLED_TIMER_TASKS.put(new WeakIdentityKey(target, DEAD_TIMER_TASK_KEYS), Boolean.TRUE); + CANCELLED_TIMER_TASKS.putIfAbsent(new WeakIdentityKey(target, DEAD_TIMER_TASK_KEYS), + new TimerCancelInfo(cancelled, System.nanoTime())); } private static void drainDeadTimerTaskKeys() { @@ -3143,32 +3144,20 @@ private static void drainDeadTimerKeys() { } } - private static boolean isTimerTaskCancelled(TimerTask task) { + private static TimerCancelInfo timerTaskCancelInfo(TimerTask task) { if (task == null || CANCELLED_TIMER_TASKS.isEmpty()) { - return false; + return null; } drainDeadTimerTaskKeys(); - return CANCELLED_TIMER_TASKS.containsKey(new LookupKey(task)); + return CANCELLED_TIMER_TASKS.get(new LookupKey(task)); } - private static boolean isTimerCancelled(Timer timer) { + private static Long timerCancelledAtNanos(Timer timer) { if (timer == null || CANCELLED_TIMERS.isEmpty()) { - return false; + return null; } drainDeadTimerKeys(); - return CANCELLED_TIMERS.containsKey(new LookupKey(timer)); - } - - private static int readTimerTaskState(TimerTask task) { - Field f = TIMER_TASK_STATE_FIELD; - if (f == null || task == null) { - return -1; - } - try { - return f.getInt(task); - } catch (Throwable ignored) { - return -1; - } + return CANCELLED_TIMERS.get(new LookupKey(timer)); } private static long safeScheduledExecutionTime(TimerTask task) { @@ -4060,6 +4049,37 @@ 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 @@ -4080,7 +4100,7 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { retainLingering(window, now); } return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations(), - window.hadUntrackedAsync); + hasActiveLingering(now)); } if (initialRunning <= 0) { long now = System.nanoTime(); @@ -4092,7 +4112,7 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { retainLingering(window, now); } return new WindowOutcome(true, false, window.enteredCount.get(), window.contaminations(), - window.hadUntrackedAsync); + hasActiveLingering(now)); } boolean drained = false; // Set before the count is read again: an exit that takes the count @@ -4137,7 +4157,7 @@ static WindowOutcome awaitWindow(long timeoutNanos, boolean wait) { retainLingering(window, now); } return new WindowOutcome(drained, true, window.enteredCount.get(), window.contaminations(), - window.hadUntrackedAsync); + hasActiveLingering(now)); } static final class WindowOutcome { @@ -4145,15 +4165,19 @@ static final class WindowOutcome { final boolean waited; final int enteredCount; final List contaminations; - final boolean hadUntrackedAsync; + // 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 hadUntrackedAsync) { + boolean tailActiveAtEnd) { this.drained = drained; this.waited = waited; this.enteredCount = enteredCount; this.contaminations = contaminations; - this.hadUntrackedAsync = hadUntrackedAsync; + this.tailActiveAtEnd = tailActiveAtEnd; } } @@ -4166,14 +4190,16 @@ private static final class UntrackedHandle { 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); + 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) { + boolean timerPeriodic, long timerExpectedFireAtNanos, long timerPeriodMillis, + long timerInitialScheduledExecMillis) { this.ref = new WeakReference(target); this.timerRef = timer == null ? null : new WeakReference(timer); this.alreadyStarted = alreadyStarted; @@ -4181,6 +4207,7 @@ private UntrackedHandle(Object target, Timer timer, boolean alreadyStarted, long this.timerPeriodic = timerPeriodic; this.timerExpectedFireAtNanos = timerExpectedFireAtNanos; this.timerPeriodMillis = timerPeriodMillis; + this.timerInitialScheduledExecMillis = timerInitialScheduledExecMillis; } private static UntrackedHandle forTimerTask(Timer timer, TimerTask task, long delayMillis, @@ -4192,7 +4219,8 @@ private static UntrackedHandle forTimerTask(Timer timer, TimerTask task, long de } long expectedFire = now + delayNanos; long safePeriodMs = periodMillis > 0L ? periodMillis : 1L; - return new UntrackedHandle(task, timer, true, now, periodic, expectedFire, safePeriodMs); + long initialExec = safeScheduledExecutionTime(task); + return new UntrackedHandle(task, timer, true, now, periodic, expectedFire, safePeriodMs, initialExec); } private boolean isActive(long now) { @@ -4219,22 +4247,42 @@ private boolean isActive(long now) { } if (target instanceof TimerTask) { TimerTask task = (TimerTask) target; - if (isTimerTaskCancelled(task)) { - return false; + 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(); - if (t != null && isTimerCancelled(t)) { - return false; - } - int state = readTimerTaskState(task); - if (state >= 0) { - // java.util.TimerTask states: VIRGIN=0, SCHEDULED=1, EXECUTED=2, CANCELLED=3 - return state == 1; + Long timerCancelledAt = t == null ? null : timerCancelledAtNanos(t); + if (timerCancelledAt != null) { + boolean cancelledBeforeFirstFire = (timerCancelledAt.longValue() - timerExpectedFireAtNanos) < 0L + && (!timerPeriodic || safeScheduledExecutionTime(task) == timerInitialScheduledExecMillis); + if (cancelledBeforeFirstFire) { + return false; + } + return (now - timerCancelledAt.longValue()) < untrackedTailWindowNanos; } - // Fallback when TimerTask.state cannot be read reflectively (JDK 16+ without --add-opens): if (!timerPeriodic) { - long grace = Math.min(HANDLE_TIMER_ONESHOT_GRACE_NANOS, untrackedTailWindowNanos); - return (now - timerExpectedFireAtNanos) < grace; + // 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; @@ -4243,7 +4291,8 @@ private boolean isActive(long now) { if (execMillis <= 0L) { return (now - registeredAtNanos) < maxLingeringNanos; } - long slackMillis = Math.max(timerPeriodMillis * 2L, 150L); + long tailWindowMs = TimeUnit.NANOSECONDS.toMillis(untrackedTailWindowNanos); + long slackMillis = Math.max(timerPeriodMillis * 2L, tailWindowMs); return System.currentTimeMillis() <= execMillis + timerPeriodMillis + slackMillis; } return false; 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 3a1ab9c2..f26c90ee 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -919,8 +919,7 @@ private static boolean isSingleArgExecutorSubmitOrExecute(String mname, String d } private static boolean isTwoArgExecutorSubmit(String mname, String desc) { - return "submit".equals(mname) - && "(Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Future;".equals(desc); + return "submit".equals(mname) && desc.startsWith("(Ljava/lang/Runnable;Ljava/lang/Object;)"); } private static boolean isForkJoinTaskSubmission(String owner, String mname, String desc) { @@ -1384,7 +1383,17 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfUntrackedSubmit", "(Ljava/lang/Object;)V", false); } else if (isTwoArgExecutorSubmit(mname, desc)) { - emitUntrackedFlag("untracked-executor:" + owner.replace('/', '.')); + // 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)) { @@ -1419,14 +1428,18 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, "(Ljava/lang/Object;)V", false); } else if (opcode == Opcodes.INVOKEVIRTUAL && "cancel".equals(mname) && "()Z".equals(desc)) { - // Track TimerTask.cancel() calls so cancelled TimerTasks stop - // driving tail contamination immediately even on JDK 16+ without - // --add-opens java.base/java.util. + // 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(1); + ensureExtraStack(2); super.visitInsn(Opcodes.DUP); - super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfTimerTaskCancelled", - "(Ljava/lang/Object;)V", false); + 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); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index ab52308d..f58e22c6 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -144,6 +144,7 @@ public void tearDown() throws IOException { 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); @@ -2812,6 +2813,85 @@ 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 { @@ -2929,8 +3009,8 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx Collections.emptyList(), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); - // Should-Fix 1(c): Periodic TimerTask cancelled and retained strongly in a field -> - // next request MUST be CLEAN! + // Should-Fix 1(c) + B1: + // (i) Periodic TimerTask cancelled BEFORE first fire (retained strongly in a field) -> CLEAN immediately! RequestGate.disarm(); java.util.TimerTask retainedTask = new NoopTimerTask(); RequestGate.open("sf1c-timer-cancel", null); @@ -2950,7 +3030,78 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); assertNotNull("keep strong reference alive past assertion", retainedTask); - // Also verify one-shot TimerTask with 30s delay cancelled before returning -> CLEAN! + // (ii) B1 regression: 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("b1-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("b1-during-slow-body", null); + assertEquals("running one-shot TimerTask body MUST contaminate t2 (B1)", + Collections.singletonList("tail:b1-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("b1-after-cancel-while-running", null); + assertEquals("cancel() while body is running MUST NOT drop tail immediately (B1)", + Collections.singletonList("tail:b1-slow-oneshot"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); + releaseBody.countDown(); + + // (iii) B1/SF1c: 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("b1-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); + Thread.sleep(120); // Past 80ms untrackedTailWindowNanos after cancel! + RequestGate.open("b1-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; + + // (iv) One-shot TimerTask with 30s delay cancelled before returning -> immediately CLEAN! RequestGate.disarm(); java.util.TimerTask retainedOneShot = new NoopTimerTask(); RequestGate.open("sf1c-oneshot-cancel", null); @@ -2968,9 +3119,27 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); assertNotNull("keep strong reference alive", retainedOneShot); - // Should-Fix 3: Known same-thread inline executors (Spring SyncTaskExecutor, - // ConcurrentTaskExecutor(SyncTaskExecutor), and Guava DirectExecutor) are - // NEITHER wrapped NOR flagged untracked-executor! + // S1: 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("s1-listenable-submit2", null); + Object reqS1 = 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(reqS1); + } + RequestGate.WindowOutcome s1Out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("two-arg ListenableFuture submit must flag untracked-executor (S1): " + s1Out.contaminations, + s1Out.contaminations.contains("untracked-executor:" + listenableExec.getClass().getName())); + + // Should-Fix 3 + S4: 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(); @@ -2980,27 +3149,46 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx "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(); RequestGate.open("sf3-inline", 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)); RequestGate.execute(syncExec, raw1); RequestGate.execute(guavaDirect, raw2); + RequestGate.submit(guavaDirectSvc, raw3); RequestGate.noteIfUntrackedExecutor(syncExec); RequestGate.noteIfUntrackedExecutor(guavaDirect); + RequestGate.noteIfUntrackedSubmit(guavaDirectSvc); 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 (S4)", + 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 (SF3)", Collections.emptyList(), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); @@ -3009,17 +3197,41 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx Collections.emptyList(), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); - // Should-Fix 4: Minimal connect-time fallback HELLO format is valid JSON with empty identity. - String minimalHello = KeployDedupAgent.buildHelloFrame("", "", "", "", "", "", - false, false, false, false, true, true, false, false); - JsonObject minObj = parseHello(minimalHello); - 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()); + // Should-Fix 4 (S4): 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(); @@ -3114,14 +3326,136 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO bgLine.contains("\"after\":\"ts/test-2\"")); assertTrue("BACKGROUND reports lost:1 from suppressed gap: " + bgLine, bgLine.contains("\"lost\":1")); + + // S2 (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 (S2)", + "ACK check-no-bg-bc", in.readLine()); + + // S2 (opposite): 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 (S2): " + bg56, + bg56 != null && bg56.startsWith("BACKGROUND ") + && bg56.contains("\"after\":\"ts/test-5\"") + && bg56.contains("\"lost\":1")); + + // S2 (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 (S2)", + "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 (S2): " + bg78, + bg78 != null && bg78.startsWith("BACKGROUND ") && bg78.contains("\"lost\":1")); } finally { KeployDedupAgent.stop(); collector.close(); collector = null; } - // 2. Unix transport: verify the exact same suppression + lost:1 counter! + // 2. Unix transport: verify BOTH (a) BACKGROUND suppression + lost:1 AND + // (b) Blocker 1 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(); @@ -3175,32 +3509,40 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO assertTrue(auditDone.await(5, TimeUnit.SECONDS)); assertTrue(sendUnixControl("START ts/u2").startsWith("ACK proto=3")); - Object req2 = RequestGate.enter(); - try { - probes[1] = true; - } finally { - RequestGate.exit(req2); - } + // Uncounted server on Unix (probes > 0 while enteredCount == 0): + // MUST emit "unverified":["no-server-entry"] with NO "contaminated" field (Blocker 1 / S4)! + probes[1] = true; assertTrue(sendUnixControl("END ts/u2").startsWith("ACK proto=3")); probes[3] = true; assertTrue(sendUnixControl("START ts/u3").startsWith("ACK proto=3")); - // Drain data records and verify no BACKGROUND for u1->u2 and BACKGROUND for u2->u3 has lost:1! + // Drain data records and verify: + // - u2 carries "unverified":["no-server-entry"] and NO "contaminated" + // - no BACKGROUND for u1->u2 + // - BACKGROUND for u2->u3 has lost:1 + String recU2 = null; String bgU2U3 = null; long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); - while (System.nanoTime() < deadline) { + while (System.nanoTime() < deadline && (recU2 == null || bgU2U3 == 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\"")); + if (rec.contains("\"id\":\"ts/u2\"")) { + recU2 = rec; + } if (rec.contains("\"kind\":\"background\"") && rec.contains("\"after\":\"ts/u2\"")) { bgU2U3 = rec; - break; } } + assertNotNull("expected Unix record for ts/u2", recU2); + assertTrue("Unix uncounted-server record must carry unverified no-server-entry (S4): " + recU2, + recU2.contains("\"unverified\":[\"no-server-entry\"]")); + assertFalse("Unix uncounted-server record must NOT carry contaminated (B1/S4): " + recU2, + recU2.contains("\"contaminated\"")); assertNotNull("expected BACKGROUND for clean gap u2->u3", bgU2U3); assertTrue("Unix BACKGROUND must carry lost:1 for suppressed u1->u2 gap: " + bgU2U3, bgU2U3.contains("\"lost\":1")); @@ -3238,6 +3580,61 @@ private static byte[] generateInlineExecutorClass(String className) { 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); @@ -3255,6 +3652,12 @@ private static byte[] generateTxHelperAndTimerCancelCaller(String className) { 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(); @@ -3269,13 +3672,14 @@ private static byte[] generateTxHelperAndTimerCancelCaller(String className) { 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(5L); - m3.visitLdcInsn(25L); + 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); @@ -3300,6 +3704,54 @@ private static byte[] generateTxHelperAndTimerCancelCaller(String className) { 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(); + + 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(); } From 53304dead6fbbe785566fa4cabd87b4774f53587 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 10:19:42 +0530 Subject: [PATCH 15/26] fix(dedup): suppress BACKGROUND after no-server-entry, add Timer.cancel() post-call margin, and complete B1/Timer.cancel/DirectExecutorService test coverage Signed-off-by: slayerjain --- .../io/keploy/dedup/KeployDedupAgent.java | 5 +- .../java/io/keploy/dedup/RequestGate.java | 8 +- .../java/io/keploy/dedup/ServerEntries.java | 4 +- .../dedup/HonestProtocolAndAsyncTest.java | 138 ++++++++++++++++-- 4 files changed, 136 insertions(+), 19 deletions(-) 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 58904e3d..e304f4aa 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -1283,7 +1283,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 || JobGate.hasExpiredRunning()); + lastEndedMayEmitTail = !cut && (outcome.tailActiveAtEnd || noServerEntry || JobGate.hasExpiredRunning()); return true; } catch (Exception e) { // Not ACK for the same reason: nothing reached Keploy. @@ -1663,6 +1663,9 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) boolean noServerEntry = transformerAdded && collector.endWaitMillis > 0 && !raw.probesByClass.isEmpty() && outcome.enteredCount == 0 && jobContams.isEmpty(); + if (noServerEntry) { + tailActiveAtEnd = true; + } List unverified = noServerEntry ? Collections.singletonList("no-server-entry") : Collections.emptyList(); 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 e157c2a9..4fbb8831 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -118,8 +118,11 @@ public final class RequestGate { 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. + // still in Thread.State.NEW, and safety margin for Timer.cancel() wall-clock + // vs nanoTime() rounding (~1ms) 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(5); // 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). @@ -4271,7 +4274,8 @@ private boolean isActive(long now) { Timer t = timerRef == null ? null : timerRef.get(); Long timerCancelledAt = t == null ? null : timerCancelledAtNanos(t); if (timerCancelledAt != null) { - boolean cancelledBeforeFirstFire = (timerCancelledAt.longValue() - timerExpectedFireAtNanos) < 0L + boolean cancelledBeforeFirstFire = + (timerCancelledAt.longValue() - timerExpectedFireAtNanos) < -TIMER_CANCEL_MARGIN_NANOS && (!timerPeriodic || safeScheduledExecutionTime(task) == timerInitialScheduledExecMillis); if (cancelledBeforeFirstFire) { return false; 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 f26c90ee..42c25e1b 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -1317,12 +1317,14 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, 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); - super.visitMethodInsn(opcode, owner, mname, desc, isInterface); return; } } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index f58e22c6..4e5c6617 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -3093,6 +3093,13 @@ public void run() { 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("b1-periodic-right-after-cancel", null); + assertEquals("periodic TimerTask cancelled after ticking MUST keep tail active during tail window", + Collections.singletonList("tail:b1-periodic-ran-then-cancel"), + RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); Thread.sleep(120); // Past 80ms untrackedTailWindowNanos after cancel! RequestGate.open("b1-periodic-clean-after-tail", null); assertEquals("cancelled periodic TimerTask retained in field must become clean after tail window", @@ -3101,6 +3108,57 @@ public void run() { 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("b1-timer-cancel-before-fire", 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("b1-timer-cancel-before-fire-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("b1-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("b1-timer-cancel-running-next", null); + assertEquals("Timer.cancel() while body is running MUST keep tail active", + Collections.singletonList("tail:b1-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(); @@ -3153,6 +3211,12 @@ public void run() { "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("sf3-inline", null); Object reqInline = RequestGate.enter(); @@ -3169,12 +3233,15 @@ public void run() { 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); @@ -3509,43 +3576,75 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO assertTrue(auditDone.await(5, TimeUnit.SECONDS)); assertTrue(sendUnixControl("START ts/u2").startsWith("ACK proto=3")); - // Uncounted server on Unix (probes > 0 while enteredCount == 0): - // MUST emit "unverified":["no-server-entry"] with NO "contaminated" field (Blocker 1 / S4)! - probes[1] = true; + // 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; assertTrue(sendUnixControl("START ts/u3").startsWith("ACK proto=3")); + // Uncounted server on Unix (probes > 0 while enteredCount == 0): + // MUST emit "unverified":["no-server-entry"] with NO "contaminated" field (Blocker 1 / S4) + // AND MUST suppress BACKGROUND(u3->u4) because an uncounted request's tail may run in the gap! + probes[1] = true; + assertTrue(sendUnixControl("END ts/u3").startsWith("ACK proto=3")); + + probes[3] = true; // gap after uncounted u3: MUST be suppressed (lost increments to 1)! + assertTrue(sendUnixControl("START ts/u4").startsWith("ACK proto=3")); + Object reqU4 = RequestGate.enter(); + try { + probes[0] = true; + } finally { + RequestGate.exit(reqU4); + } + assertTrue(sendUnixControl("END ts/u4").startsWith("ACK proto=3")); + + 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: - // - u2 carries "unverified":["no-server-entry"] and NO "contaminated" - // - no BACKGROUND for u1->u2 + // - no BACKGROUND for u1->u2 or u3->u4 // - BACKGROUND for u2->u3 has lost:1 - String recU2 = null; + // - 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 && (recU2 == null || bgU2U3 == null)) { + 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\"")); - if (rec.contains("\"id\":\"ts/u2\"")) { - recU2 = rec; + 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/u2", recU2); - assertTrue("Unix uncounted-server record must carry unverified no-server-entry (S4): " + recU2, - recU2.contains("\"unverified\":[\"no-server-entry\"]")); - assertFalse("Unix uncounted-server record must NOT carry contaminated (B1/S4): " + recU2, - recU2.contains("\"contaminated\"")); + assertNotNull("expected Unix record for ts/u3", recU3); + assertTrue("Unix uncounted-server record must carry unverified no-server-entry (S4): " + recU3, + recU3.contains("\"unverified\":[\"no-server-entry\"]")); + assertFalse("Unix uncounted-server record must NOT carry contaminated (B1/S4): " + recU3, + recU3.contains("\"contaminated\"")); assertNotNull("expected BACKGROUND for clean gap u2->u3", bgU2U3); - assertTrue("Unix BACKGROUND must carry lost:1 for suppressed u1->u2 gap: " + 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(); @@ -3738,6 +3837,15 @@ private static byte[] generateTxHelperAndTimerCancelCaller(String className) { 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", From 6576c18c01359f5f1a23c9b76261a6b938340f48 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 10:23:46 +0530 Subject: [PATCH 16/26] test(dedup): add TCP no-server-entry BACKGROUND suppression test and raise Timer.cancel() margin to 20ms Signed-off-by: slayerjain --- .../java/io/keploy/dedup/RequestGate.java | 6 ++-- .../dedup/HonestProtocolAndAsyncTest.java | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) 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 4fbb8831..8258069e 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -119,10 +119,10 @@ public final class RequestGate { 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 (~1ms) so an already-firing one-shot task is never - // misclassified as cancelled-before-fire. + // 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(5); + 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). diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 4e5c6617..7ee73343 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -374,6 +374,35 @@ public void earlyConnectBeforeJacocoAndServerInitDoesNotLatchFailureRefreshesHel 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; } From 88567de277bb24876c9493e97d4c76aae1bd0b6d Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 11:12:28 +0530 Subject: [PATCH 17/26] fix(dedup): runtime-check executor method refs, latch windowCut=false on noServerEntry, and test open-time BACKGROUND suppression Signed-off-by: slayerjain --- .../io/keploy/dedup/KeployDedupAgent.java | 21 +- .../java/io/keploy/dedup/OrderedPools.java | 10 + .../java/io/keploy/dedup/RequestGate.java | 53 ++ .../java/io/keploy/dedup/ServerEntries.java | 62 +- .../dedup/ForkedAsyncAndHonestyTest.java | 2 +- .../dedup/HonestProtocolAndAsyncTest.java | 691 +++++++++++++++++- 6 files changed, 822 insertions(+), 17 deletions(-) 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 e304f4aa..e6783e66 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -146,6 +146,20 @@ static String encodeBytecodeFrame(String buildTag, String manifestJson, byte[] z // 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; + + private static void noteObservedNoServerEntry(String testId) { + if (!observedNoServerEntry) { + observedNoServerEntry = true; + log(Level.INFO, "Keploy dedup: " + testId + " recorded coverage probes with no counted server request" + + " entry; latching windowCut=false for this JVM", 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 @@ -322,7 +336,8 @@ private static Capabilities computeCapabilities(CoverageCollector collector) { // probes with enteredCount==0 still fail closed via "no-server-entry". boolean serverEntriesInstalled = agentAttached && endWaitActive && !ServerEntries.hasUncountedServer() - && !ServerEntries.hadServerHookFailure(); + && !ServerEntries.hadServerHookFailure() + && !observedNoServerEntry; boolean windowCut = serverEntriesInstalled; boolean contaminated = agentAttached; boolean classMismatch = true; @@ -1270,6 +1285,9 @@ private boolean run(CoverageCommand command, Phases 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(); @@ -1664,6 +1682,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) && !raw.probesByClass.isEmpty() && outcome.enteredCount == 0 && jobContams.isEmpty(); if (noServerEntry) { + noteObservedNoServerEntry(command.testId); tailActiveAtEnd = true; } List unverified = noServerEntry 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 c20f649e..12b9032f 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -113,11 +113,21 @@ 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"; 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 8258069e..a3647e3c 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -3101,6 +3101,59 @@ public static void noteIfUntrackedSubmit(Object receiver) { noteUntrackedAsync("untracked-executor:" + receiver.getClass().getName(), 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. + * + * @param owner declaring owner class of the method reference + */ + public static void noteIfUntrackedExecutorClass(Class owner) { + if (owner == null || !Executor.class.isAssignableFrom(owner)) { + return; + } + if (!armed) { + noteUnarmedHandOffIfInFlight(); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + return; + } + if (OrderedPools.isInlineExecutorClass(owner)) { + return; + } + noteUntrackedAsync("untracked-executor:" + owner.getName(), 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. + * + * @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 (!armed) { + noteUnarmedHandOffIfInFlight(); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + return; + } + if (OrderedPools.isInlineExecutorClass(owner)) { + return; + } + noteUntrackedAsync("untracked-executor:" + owner.getName(), 0L); + } + /** * Records cancellation of a {@link Timer} with timestamp so tasks that had * not started stop driving tail contamination immediately, while any 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 42c25e1b..eadedf42 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -914,10 +914,6 @@ private static boolean isSingleArgExecutorSubmit(String mname, String desc) { || desc.startsWith("(Ljava/util/concurrent/Callable;)")); } - private static boolean isSingleArgExecutorSubmitOrExecute(String mname, String desc) { - return isSingleArgExecutorExecute(mname, desc) || isSingleArgExecutorSubmit(mname, desc); - } - private static boolean isTwoArgExecutorSubmit(String mname, String desc) { return "submit".equals(mname) && desc.startsWith("(Ljava/lang/Runnable;Ljava/lang/Object;)"); } @@ -1004,14 +1000,30 @@ private static boolean isHookedSpringMethodRefOwner(String 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 (!isHookedSpringMethodRefOwner(owner) - && (isSingleArgExecutorSubmitOrExecute(mname, desc) || isTwoArgExecutorSubmit(mname, desc))) { - return true; - } if (isUntrackedScheduleOrInvokeAny(mname, desc) || isTimerSchedule(owner, mname, desc) || isForkJoinTaskSubmission(owner, mname, desc)) { @@ -1108,6 +1120,40 @@ public void visitInvokeDynamicInsn(String indyName, String indyDesc, Handle bsm, 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. + changed[0] = true; + ensureExtraStack(1); + super.visitInsn(Opcodes.DUP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, + execRef ? "noteIfUntrackedExecutor" : "noteIfUntrackedSubmit", + "(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)) { emitUntrackedFlag("untracked-async:method-ref:" + h.getOwner().replace('/', '.') + "." + h.getName()); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index 93938e48..f8ca8aaf 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -192,7 +192,7 @@ public void forkedExternalCfDependentAndConcreteAsyncFormsAreTrackedOrFlagged() String covMethodRef = app.runHttpTest("ts/method-ref", "/method-ref"); assertTrue("executor::execute method ref must contaminate: " + covMethodRef, - covMethodRef.contains("untracked-async:method-ref:")); + covMethodRef.contains("untracked-executor:java.util.concurrent.ThreadPoolExecutor")); } } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 7ee73343..8081837d 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -107,6 +107,7 @@ public class HonestProtocolAndAsyncTest { private ClassLoader savedContextLoader; private boolean savedTransformerAdded; private boolean savedExecutorCallSitesEnabled; + private boolean savedObservedNoServerEntry; private Set savedCounted; private Set savedUncounted; private long savedHandedJobMaxNanos; @@ -117,11 +118,13 @@ public class HonestProtocolAndAsyncTest { public void setUp() { savedTransformerAdded = KeployDedupAgent.transformerAdded; savedExecutorCallSitesEnabled = KeployDedupAgent.executorCallSitesEnabled; + savedObservedNoServerEntry = KeployDedupAgent.observedNoServerEntry; savedCounted = ServerEntries.snapshotCounted(); savedUncounted = ServerEntries.snapshotUncounted(); savedHandedJobMaxNanos = JobGate.handedJobMaxNanos; savedControlSocketPath = KeployDedupAgent.controlSocketPath; savedDataSocketPath = KeployDedupAgent.dataSocketPath; + KeployDedupAgent.observedNoServerEntry = false; ServerEntries.restoreUncounted(Collections.emptySet()); ServerEntries.setHookStatusForTests(false, false, false); RequestGate.disarm(); @@ -138,6 +141,7 @@ public void tearDown() throws IOException { } KeployDedupAgent.transformerAdded = savedTransformerAdded; KeployDedupAgent.executorCallSitesEnabled = savedExecutorCallSitesEnabled; + KeployDedupAgent.observedNoServerEntry = savedObservedNoServerEntry; ServerEntries.restoreCounted(savedCounted); ServerEntries.restoreUncounted(savedUncounted); ServerEntries.setHookStatusForTests(false, false, false); @@ -364,10 +368,16 @@ public void earlyConnectBeforeJacocoAndServerInitDoesNotLatchFailureRefreshesHel 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. Netty/WebFlux) -> - // unverified: ["no-server-entry"] with NO "contaminated" field (old enterprise compat)! + // 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); @@ -3615,22 +3625,32 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO assertTrue(sendUnixControl("END ts/u2").startsWith("ACK proto=3")); probes[3] = true; - assertTrue(sendUnixControl("START ts/u3").startsWith("ACK proto=3")); + 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 (Blocker 1 / S4) + // 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; - assertTrue(sendUnixControl("END ts/u3").startsWith("ACK proto=3")); + 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)! - assertTrue(sendUnixControl("START ts/u4").startsWith("ACK proto=3")); + 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); } - assertTrue(sendUnixControl("END ts/u4").startsWith("ACK proto=3")); + 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")); @@ -3680,6 +3700,663 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO } } + 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())); + } + + @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))); From 56f289a4debd25d7e83b2ee66e89caf7adc61944 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 12:39:43 +0530 Subject: [PATCH 18/26] fix(dedup): latch asyncExecutors=false on pre-captured executor method refs and polish logs/comments Signed-off-by: slayerjain --- .../io/keploy/dedup/KeployDedupAgent.java | 40 +- .../java/io/keploy/dedup/RequestGate.java | 114 ++- .../java/io/keploy/dedup/ServerEntries.java | 15 +- .../dedup/ForkedAsyncAndHonestyTest.java | 22 +- .../dedup/HonestProtocolAndAsyncTest.java | 955 ++++++++++++------ .../org/example/servers/AsyncHonestyApp.java | 4 +- 6 files changed, 832 insertions(+), 318 deletions(-) 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 e6783e66..51eca2a9 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -152,12 +152,27 @@ static String encodeBytecodeFrame(String buildTag, String manifestJson, byte[] z // 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 + " recorded coverage probes with no counted server request" - + " entry; latching windowCut=false for this JVM", null); + 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 @@ -329,11 +344,14 @@ String toHelloFrame(String buildId) { private static Capabilities computeCapabilities(CoverageCollector collector) { boolean agentAttached = transformerAdded; boolean endWaitActive = collector.endWaitMillis > 0; - // Base windowCut on ServerEntries being installed with endWait > 0 - // (and no uncounted server / hook failure) rather than !countsNone(), - // so Jetty/Undertow cold-start pods honestly declare windowCut=true - // before their first request loads HttpChannel/Connectors. Runtime - // probes with enteredCount==0 still fail closed via "no-server-entry". + // 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() @@ -344,12 +362,18 @@ private static Capabilities computeCapabilities(CoverageCollector collector) { 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(); + && !ServerEntries.hadAppRewriteFailure() + && !observedPreCapturedUntrackedExecutor; boolean listenerContamination = agentAttached && !ServerEntries.hadListenerHookFailure() && !ServerEntries.hasUnhookedConsumer(); 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 a3647e3c..f6cb458b 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -3101,11 +3101,77 @@ public static void noteIfUntrackedSubmit(Object receiver) { 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. + * 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 */ @@ -3113,24 +3179,29 @@ 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; } - if (OrderedPools.isInlineExecutorClass(owner)) { - return; - } - noteUntrackedAsync("untracked-executor:" + owner.getName(), 0L); + 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. + * 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 */ @@ -3141,17 +3212,44 @@ public static void noteIfUntrackedSubmitClass(Class 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; } - if (OrderedPools.isInlineExecutorClass(owner)) { + 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; } - noteUntrackedAsync("untracked-executor:" + owner.getName(), 0L); + if (!armed) { + noteUnarmedHandOffIfInFlight(); + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(reason); + return; + } + if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { + KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(reason); + return; + } + noteUntrackedAsync(reason, 0L); } /** 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 eadedf42..901fe59a 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -83,7 +83,7 @@ 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"); - // Message listeners (F10 listener contamination): an inbound message + // 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", @@ -1132,12 +1132,14 @@ public void visitInvokeDynamicInsn(String indyName, String indyDesc, Handle bsm, // 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. + // 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 ? "noteIfUntrackedExecutor" : "noteIfUntrackedSubmit", + execRef ? "noteIfUntrackedExecutorMethodRef" + : "noteIfUntrackedSubmitMethodRef", "(Ljava/lang/Object;)V", false); } else { // Unbound method ref (e.g. TxHelper::execute as BiConsumer) @@ -1155,8 +1157,13 @@ public void visitInvokeDynamicInsn(String indyName, String indyDesc, Handle bsm, break; } if (isAsyncMethodRefTarget(h)) { - emitUntrackedFlag("untracked-async:method-ref:" + 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; } } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index f8ca8aaf..a593631a 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -38,7 +38,7 @@ import org.junit.rules.TemporaryFolder; /** - * End-to-end forked {@code -javaagent} JVM tests proving Ruling #3 across both + * 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}, @@ -93,7 +93,7 @@ public void forkedExternalJacocoPrefixModeTracksCompletableFutureDependentsAndCh assertTrue("k8s external-JaCoCo prefix mode must declare asyncExecutors=true", hello.get("asyncExecutors").getAsBoolean()); - // 1. Reproduce plg-87's exact bug: supplyAsync(20ms, pool).thenAccept(350ms audit) + // 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, @@ -131,7 +131,7 @@ public void forkedUnknownSerializableExecutorIsUnwrappedAndContaminatesCurrentAn cov.contains("\"contaminated\":[\"untracked-executor:" + AsyncHonestyApp.SerializableOnlyExecutor.class.getName() + "\"]")); - // 2. B1: Async 350ms task on unknown SerializableOnlyExecutor -> Test 1 gets + // 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, @@ -147,7 +147,7 @@ public void forkedUnknownSerializableExecutorIsUnwrappedAndContaminatesCurrentAn @Test(timeout = 120000) public void forkedExternalCfDependentAndConcreteAsyncFormsAreTrackedOrFlagged() throws Exception { try (ForkedApp app = startFork("tomcat", "80", false, false, null, null)) { - // B2: External library CompletableFuture.thenAccept(350ms audit) with endWait=80ms -> windowCut:true! + // 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")); @@ -156,7 +156,7 @@ public void forkedExternalCfDependentAndConcreteAsyncFormsAreTrackedOrFlagged() assertTrue("window after cut external CF must carry tail:ts/ext-cf-cut: " + covAfterExt, covAfterExt.contains("\"tail:ts/ext-cf-cut\"")); - // B2: CompletionStage-typed thenApplyAsync(350ms) with endWait=80ms -> windowCut:true! + // 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")); @@ -309,7 +309,7 @@ public void forkedVirtualThreadStartAndBuilderFlagAndTrackLiveness() throws Exce // 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 (SF-D): " + covDirect, + 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(). @@ -317,16 +317,16 @@ public void forkedVirtualThreadStartAndBuilderFlagAndTrackLiveness() throws Exce 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 (SF-D/SF-4): " + covAfterDirect, + + "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 (SF-4): " + covDirectDone, + 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 (SF-D): " + covBuilder, + 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(). @@ -334,12 +334,12 @@ public void forkedVirtualThreadStartAndBuilderFlagAndTrackLiveness() throws Exce 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 (SF-4): " + covAfterBuilder, + + "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 (SF-4): " + covBuilderDone, + assertFalse("window after builder virtual thread exits must be clean: " + covBuilderDone, covBuilderDone.contains("\"tail:ts/vbuilder-1\"")); } } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 8081837d..3fb61f4e 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -108,6 +108,7 @@ public class HonestProtocolAndAsyncTest { private boolean savedTransformerAdded; private boolean savedExecutorCallSitesEnabled; private boolean savedObservedNoServerEntry; + private boolean savedObservedPreCapturedUntrackedExecutor; private Set savedCounted; private Set savedUncounted; private long savedHandedJobMaxNanos; @@ -119,12 +120,14 @@ 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(); @@ -142,6 +145,7 @@ public void tearDown() throws IOException { KeployDedupAgent.transformerAdded = savedTransformerAdded; KeployDedupAgent.executorCallSitesEnabled = savedExecutorCallSitesEnabled; KeployDedupAgent.observedNoServerEntry = savedObservedNoServerEntry; + KeployDedupAgent.observedPreCapturedUntrackedExecutor = savedObservedPreCapturedUntrackedExecutor; ServerEntries.restoreCounted(savedCounted); ServerEntries.restoreUncounted(savedUncounted); ServerEntries.setHookStatusForTests(false, false, false); @@ -261,7 +265,7 @@ public void helloReportsLiveCapabilitiesAndIdentityAccuratelyAcrossRuntimeConfig h8.get("listenerContamination").getAsBoolean()); ServerEntries.setHookStatusForTests(false, false, false); - // Case 8b (S4): Unhooked consumer (e.g. KafkaStreams) -> listenerContamination must be 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")); @@ -270,7 +274,7 @@ public void helloReportsLiveCapabilitiesAndIdentityAccuratelyAcrossRuntimeConfig h8b.get("listenerContamination").getAsBoolean()); ServerEntries.setHookStatusForTests(false, false, false); - // Case 8c (S5): Uncounted servers (gRPC, Vert.x, Micronaut, JDK HttpServer) -> windowCut & asyncExecutors 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", @@ -285,7 +289,7 @@ public void helloReportsLiveCapabilitiesAndIdentityAccuratelyAcrossRuntimeConfig } ServerEntries.restoreUncounted(Collections.emptySet()); - // Case 8d (Nit): App rewrite failure -> asyncExecutors must be false. + // 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", @@ -1392,7 +1396,7 @@ public void longLivedWorkerLoopStartedFromJobDoesNotKeepJobGateOpenForever() thr assertFalse(beforeExp.get(0).startsWith("job-tail:")); // Wait past handedJobMaxNanos while the worker is STILL EXECUTING: - // Protocol Blocker 3 requires marking overlapping windows with "job-tail:" + // overlapping windows must be marked with "job-tail:" // until exit() actually runs! Thread.sleep(100); JobGate.open(); @@ -1500,7 +1504,7 @@ public void completableFutureDependentStagesAndAsyncInstanceMethodsAreTrackedAnd new LinkedBlockingQueue()); ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); try { - // 1. Reproduce plg-87's exact bug: supplyAsync(fast, pool).thenAccept(slowAudit) + // 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); @@ -1721,7 +1725,7 @@ public void unarmedKeployAbsentIsNoOpAndMarksArmedMidFlightWhileUnarmedWorkRemai assertEquals("unarmed PENDING_BY_FUTURE stays 0", 0, RequestGate.pendingByFutureSize()); RequestGate.exit(reqTok); - // B3: Long-running job started BEFORE arming stays in flight across Tests 1 AND 2 -> + // 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()); @@ -1770,16 +1774,16 @@ public void listenerAttributionExtractsTopicsQueuesDestinationAndCachesPerInstan 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 (S6)", + assertTrue("app package /vendor/ must NOT be skipped", prefixed.shouldRewriteExecutorCalls("com/acme/vendor/VendorService")); - assertTrue("app package /shadow/ must NOT be skipped (S6)", + 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")); - // S6: In exact appClasses index mode, shaded filter does NOT drop indexed app classes. + // 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")); @@ -1787,15 +1791,15 @@ public void shadedAndRelocatedPackagesAreSkippedOnlyInPrefixModeAndVendorIsNotSk } @Test(timeout = 60000) - public void untrackedTailsJobDeferredCfSpringSubclassFailClosedAndB2BytecodeForms() throws Exception { + public void untrackedTailsJobDeferredCfSpringSubclassFailClosedAndBytecodeForms() throws Exception { ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); long savedTailWindow = RequestGate.untrackedTailWindowNanos; try { - // B1: Untracked async hand-off marks current window AND immediately following window - // "tail:" until untrackedTailWindowNanos elapses. + // Untracked async hand-off marks current window AND immediately following window + // "tail:" until untrackedTailWindowNanos elapses. RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(120); - RequestGate.open("b1-untracked", null); + RequestGate.open("untracked-tail-1", null); Object req1 = RequestGate.enter(); try { RequestGate.noteUntrackedAsync("untracked-executor:com.acme.CustomPool"); @@ -1805,23 +1809,23 @@ public void untrackedTailsJobDeferredCfSpringSubclassFailClosedAndB2BytecodeForm RequestGate.WindowOutcome out1 = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); assertEquals(Collections.singletonList("untracked-executor:com.acme.CustomPool"), out1.contaminations); - RequestGate.open("b1-next", null); + 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:b1-untracked"), out2.contaminations); + Collections.singletonList("tail:untracked-tail-1"), out2.contaminations); Thread.sleep(160); - RequestGate.open("b1-after-expiry", null); + 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); - // S1: Job-originated CompletableFuture.supplyAsync().thenAccept(audit) keeps JobGate run - // active until audit finishes, and job-originated unknown executor flags contamination! + // 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("s1-arm", null); + RequestGate.open("job-cf-arm", null); JobGate.open(); Object jt = JobGate.enter(new Object(), "scheduled"); CompletableFuture jobChain; @@ -1861,7 +1865,7 @@ public void untrackedTailsJobDeferredCfSpringSubclassFailClosedAndB2BytecodeForm } assertEquals("JobGate run exits once job CF dependent completes", 0, JobGate.activeRunCount()); - // S1b: Job-originated unknown executor flags active JobGate window AND next RequestGate window! + // 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"); @@ -1874,14 +1878,14 @@ public void untrackedTailsJobDeferredCfSpringSubclassFailClosedAndB2BytecodeForm List jobContams = JobGate.close(); assertTrue("job window must contain untracked-executor: " + jobContams, jobContams.contains("untracked-executor:java.lang.Object")); - RequestGate.open("s1-after-job-unknown", null); + 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")); - // S3: App subclass of ThreadPoolTaskExecutor overriding execute() MUST fail closed, - // and arbitrary non-Spring class with getThreadPoolExecutor() MUST fail closed! + // 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; @@ -1893,7 +1897,7 @@ public void execute(Runnable task) { }; overridingSpring.initialize(); try { - assertTrue("Spring subclass overriding execute() must fail closed (S3)", + assertTrue("Spring subclass overriding execute() must fail closed", OrderedPools.orders(overridingSpring)); } finally { overridingSpring.shutdown(); @@ -1904,12 +1908,12 @@ public ThreadPoolExecutor getThreadPoolExecutor() { return pool; } }; - assertTrue("non-Spring class with getThreadPoolExecutor() must fail closed (S3)", + assertTrue("non-Spring class with getThreadPoolExecutor() must fail closed", OrderedPools.orders(nonSpringWithPoolMethod)); - // B2: Non-Thread start() must NOT false-positive, while Thread subclass start() DOES flag. + // Non-Thread start() must NOT false-positive, while Thread subclass start() DOES flag. RequestGate.disarm(); - RequestGate.open("b2-start-check", null); + RequestGate.open("non-thread-start-check", null); Object reqStart = RequestGate.enter(); try { RequestGate.noteIfThread(new Object()); @@ -1921,7 +1925,7 @@ public ThreadPoolExecutor getThreadPoolExecutor() { Collections.emptyList(), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); - // B2 + S4: Direct raw KafkaConsumer.poll in an app class flips hasUnhookedConsumer()! + // 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); @@ -1941,7 +1945,7 @@ public ThreadPoolExecutor getThreadPoolExecutor() { pollMv.visitEnd(); kafkaApp.visitEnd(); ServerEntries.wrapExecutorCalls(kafkaApp.toByteArray()); - assertTrue("direct KafkaConsumer.poll in app class must flag unhooked consumer (S4)", + assertTrue("direct KafkaConsumer.poll in app class must flag unhooked consumer", ServerEntries.hasUnhookedConsumer()); ServerEntries.setHookStatusForTests(false, false, false, false); } finally { @@ -1951,7 +1955,7 @@ public ThreadPoolExecutor getThreadPoolExecutor() { } @Test(timeout = 60000) - public void minimalStageNoUoeMinimalFutureTrackedAbandonedStageGcAndR3Regressions() throws Exception { + public void minimalStageNoUoeMinimalFutureTrackedAbandonedStageGcAndConsumerScanChecks() throws Exception { ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); @@ -1959,10 +1963,10 @@ public void minimalStageNoUoeMinimalFutureTrackedAbandonedStageGcAndR3Regression long savedMaxLingering = RequestGate.maxLingeringNanos; long savedJobMax = JobGate.handedJobMaxNanos; try { - // NB1: 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("nb1-minimal-stage", null); + // 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); @@ -2003,16 +2007,16 @@ public void minimalStageNoUoeMinimalFutureTrackedAbandonedStageGcAndR3Regression } finally { RequestGate.exit(req); } - RequestGate.WindowOutcome nb1Out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - assertTrue("MinimalStage dependents must drain cleanly", nb1Out.drained); - assertEquals("MinimalStage must not spuriously contaminate: " + nb1Out.contaminations, - Collections.emptyList(), nb1Out.contaminations); + 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. } - // SF3: CompletableFuture subclass inheriting thenAccept/whenComplete (like JDK HttpClient's - // MinimalFuture) IS tracked instead of flagged; subclass overriding thenAccept fails closed! + // 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() { @@ -2025,59 +2029,59 @@ public CompletableFuture thenAccept(java.util.function.Consumer return super.thenAccept(action); } } - RequestGate.open("sf3-minimal-future", null); - Object reqSf3 = RequestGate.enter(); + 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(reqSf3); + RequestGate.exit(reqMinimal); } assertEquals("window still waits for MinimalFuture-like dependent", 1, RequestGate.running()); httpCf.complete("200"); assertTrue(auditRan.get()); - RequestGate.WindowOutcome sf3Out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - assertTrue(sf3Out.drained); + RequestGate.WindowOutcome minimalOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue(minimalOut.drained); assertEquals("MinimalFuture-like dependent must NOT contaminate", - Collections.emptyList(), sf3Out.contaminations); + Collections.emptyList(), minimalOut.contaminations); - RequestGate.open("sf3-override-cf", null); - Object reqSf3b = RequestGate.enter(); + RequestGate.open("override-cf-sub", null); + Object reqOverride = RequestGate.enter(); try { RequestGate.thenAccept(new OverridingCf(), v -> { }); } finally { - RequestGate.exit(reqSf3b); + RequestGate.exit(reqOverride); } - RequestGate.WindowOutcome sf3bOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - assertTrue("CF subclass overriding thenAccept must fail closed: " + sf3bOut.contaminations, - sf3bOut.contaminations.stream().anyMatch(s -> s.startsWith("untracked-executor:"))); + 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:"))); - // SF1: 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. + // 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("sf1-gc", null); - Object reqSf1 = RequestGate.enter(); + 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(reqSf1); + 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 (SF1)", + 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("sf1-stuck", null); + RequestGate.open("stuck-cf", null); Object reqStuck = RequestGate.enter(); try { RequestGate.thenAccept(neverCompletes, v -> { }); @@ -2085,36 +2089,36 @@ public CompletableFuture thenAccept(java.util.function.Consumer RequestGate.exit(reqStuck); } assertFalse("stuck future cuts window", RequestGate.await(TimeUnit.MILLISECONDS.toNanos(30))); - RequestGate.open("sf1-while-stuck", null); - assertEquals(Collections.singletonList("tail:sf1-stuck"), + RequestGate.open("while-stuck", null); + assertEquals(Collections.singletonList("tail:stuck-cf"), RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(50), true).contaminations); Thread.sleep(140); - RequestGate.open("sf1-after-bound", null); - assertEquals("stuck lingering window must stop poisoning after maxLingeringNanos (SF1)", + 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; - // SF2: Runtime receiver check for hooked Spring executor vs custom TaskExecutor + - // TaskScheduler.schedule / Timer.schedule / ForkJoinPool.execute(ForkJoinTask) / Guava. + // 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("sf2-spring-ok", null); + 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 (SF2)", + assertEquals("hooked & verified Spring executor must NOT false-positive", Collections.emptyList(), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); - RequestGate.open("sf2-custom-task-exec", null); + RequestGate.open("custom-task-exec", null); Object reqCustom = RequestGate.enter(); org.springframework.core.task.TaskExecutor customTe = r -> r.run(); try { @@ -2123,17 +2127,17 @@ public CompletableFuture thenAccept(java.util.function.Consumer RequestGate.exit(reqCustom); } RequestGate.WindowOutcome customOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - assertTrue("unhooked TaskExecutor impl must be flagged by runtime class (SF2): " + assertTrue("unhooked TaskExecutor impl must be flagged by runtime class: " + customOut.contaminations, customOut.contaminations.contains("untracked-executor:" + customTe.getClass().getName())); } finally { springExec.shutdown(); } - // SF4: schedule(r, delay, unit) extends untracked tail window by delay! + // schedule(r, delay, unit) extends untracked tail window by delay! RequestGate.disarm(); RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(50); - RequestGate.open("sf4-sched", null); + RequestGate.open("sched-delay-check", null); Object reqSched = RequestGate.enter(); try { RequestGate.schedule(stpe, () -> { }, 300, TimeUnit.MILLISECONDS); @@ -2142,18 +2146,18 @@ public CompletableFuture thenAccept(java.util.function.Consumer } RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); Thread.sleep(100); // past 50ms base window, still inside 350ms delay-extended tail! - RequestGate.open("sf4-during-delay", null); - assertEquals("scheduled delay must keep next window contaminated past base tail (SF4)", - Collections.singletonList("tail:sf4-sched"), + 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; - // SF5: 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! + // 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("sf5-arm", null); - Object unknownExecSf5 = new Object(); + RequestGate.open("expired-hop-arm", null); + Object unknownExecHop = new Object(); Runnable hop1; Object jTok = JobGate.enter(new Object(), "scheduled"); try { @@ -2166,22 +2170,22 @@ public CompletableFuture thenAccept(java.util.function.Consumer assertNull("hop1 expired so running() is null", JobGate.running()); assertNotNull("hop1 expiredRunningName() still knows job", JobGate.expiredRunningName()); JobGate.open(); - RequestGate.hand(unknownExecSf5, () -> { }); + RequestGate.hand(unknownExecHop, () -> { }); }); } finally { JobGate.exit(jTok); } hop1.run(); - List sf5JobContams = JobGate.close(); - assertTrue("expired hop unverified fan-out must mark JobGate window job-tail (SF5): " + sf5JobContams, - sf5JobContams.stream().anyMatch(s -> s.startsWith("job-tail:"))); - RequestGate.open("sf5-next", null); - RequestGate.WindowOutcome sf5Next = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - assertTrue("expired hop unverified fan-out must mark next RequestGate window tail:job-tail (SF5): " - + sf5Next.contaminations, - sf5Next.contaminations.stream().anyMatch(s -> s.startsWith("tail:job-tail:"))); - - // SF6: Unarmed hand-off made while unarmed keeps marking armed-mid-flight within tail window! + 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(); @@ -2189,16 +2193,16 @@ public CompletableFuture thenAccept(java.util.function.Consumer RequestGate.execute(pool, unarmedDone::countDown); RequestGate.exit(unarmedReq); assertTrue(unarmedDone.await(5, TimeUnit.SECONDS)); - RequestGate.open("sf6-w1", null); + RequestGate.open("unarmed-tail-w1", null); assertEquals(Collections.singletonList("armed-mid-flight"), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); - RequestGate.open("sf6-w2", null); - assertEquals("unarmed hand-off keeps marking armed-mid-flight within tail window (SF6)", + 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; - // SF7: Expanded unhooked consumers + read-only scan works even with empty appClasses! + // 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", @@ -2208,7 +2212,7 @@ public CompletableFuture thenAccept(java.util.function.Consumer ServerEntries.setHookStatusForTests(false, false, false, false); new ServerEntries(true).transform(getClass().getClassLoader(), consumerCls, null, null, generatePlainClass(consumerCls)); - assertTrue(consumerCls + " must flip hasUnhookedConsumer (SF7)", + assertTrue(consumerCls + " must flip hasUnhookedConsumer", ServerEntries.hasUnhookedConsumer()); } // Read-only raw JMS setMessageListener scan with NO appClasses / callsites off: @@ -2231,14 +2235,14 @@ public CompletableFuture thenAccept(java.util.function.Consumer 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 (SF7)", + assertTrue("raw JMS setMessageListener must be detected even with callsites off", ServerEntries.hasUnhookedConsumer()); ServerEntries.setHookStatusForTests(false, false, false, false); - // SF8: Exact indexed app classes under org/springframework/samples/... must NOT be dropped! + // 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 (SF8)", + assertTrue("indexed PetClinic class under org/springframework/samples must be rewritten", petclinic.shouldRewriteExecutorCalls( "org/springframework/samples/petclinic/owner/OwnerController")); } finally { @@ -2251,7 +2255,7 @@ public CompletableFuture thenAccept(java.util.function.Consumer } @Test(timeout = 60000) - public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopExpiredJobAndBytecodeFlagSites() + public void executingPastMaxLingeringLiveUntrackedHandlesMultiHopExpiredJobAndBytecodeFlagSites() throws Exception { ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); @@ -2262,25 +2266,25 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx long savedMaxLingering = RequestGate.maxLingeringNanos; long savedJobMax = JobGate.handedJobMaxNanos; try { - // SF-A: Actively executing task running PAST maxLingeringNanos MUST keep marking tail: - // until it actually exits, then clear cleanly! + // 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("sfa-active", null); - Object reqSfa = RequestGate.enter(); + RequestGate.open("exec-active", null); + Object reqActive = RequestGate.enter(); try { RequestGate.execute(pool, latchTask(taskStarted, taskRelease)); } finally { - RequestGate.exit(reqSfa); + 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("sfa-past-cap", null); - assertEquals("actively executing task past maxLingeringNanos must STILL flag tail (SF-A)", - Collections.singletonList("tail:sfa-active"), + 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); @@ -2288,21 +2292,21 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx Thread.sleep(5); } Thread.sleep(20); - RequestGate.open("sfa-after-exit", null); + 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; - // SF-B: Untracked Thread.start() and periodic ScheduledFuture stay flagged past base tail - // for as long as Thread.isAlive() / !ScheduledFuture.isDone()! + // 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), "sfb-live-thread"); + Thread rawThread = new Thread(latchTask(rawStarted, rawRelease), "live-raw-thread"); rawThread.setDaemon(true); - RequestGate.open("sfb-thread", null); + RequestGate.open("live-thread", null); Object reqT = RequestGate.enter(); try { RequestGate.startThread(rawThread); @@ -2312,24 +2316,24 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx 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("sfb-thread-consume-once", null); + 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("sfb-thread-still-alive", null); - assertEquals("live raw thread must keep marking tail past base window (SF-B)", - Collections.singletonList("tail:sfb-thread"), + 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("sfb-thread-dead", null); + RequestGate.open("live-thread-dead", null); assertEquals("clean once raw thread terminates", Collections.emptyList(), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); - // SF-B periodic ScheduledFuture: + // Periodic ScheduledFuture: RequestGate.disarm(); RequestGate.untrackedTailWindowNanos = TimeUnit.MILLISECONDS.toNanos(30); - RequestGate.open("sfb-periodic", null); + RequestGate.open("periodic-sched", null); Object reqP = RequestGate.enter(); ScheduledFuture periodic; try { @@ -2339,25 +2343,25 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx } RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); // Consume one-time report first so the next window depends strictly on !ScheduledFuture.isDone(). - RequestGate.open("sfb-periodic-consume-once", null); + 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("sfb-periodic-alive", null); - assertEquals("uncancelled periodic ScheduledFuture keeps marking tail (SF-B)", - Collections.singletonList("tail:sfb-periodic"), + 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("sfb-periodic-cancelled", null); + 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; - // SF-C: 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! + // 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("sfc-arm", null); + RequestGate.open("multihop-arm", null); CountDownLatch gen3Entered = new CountDownLatch(1); CountDownLatch gen3Release = new CountDownLatch(1); CountDownLatch gen1Exited = new CountDownLatch(1); @@ -2410,74 +2414,76 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx JobGate.open(); List gen3Contams = JobGate.close(); gen3Release.countDown(); - assertTrue("gen 3 of expired self-resubmitting loop must STILL carry job-tail (SF-C): " + gen3Contams, + 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); } - // SF-E: Real bytecode-rewritten call sites via ServerEntries.wrapExecutorCalls for - // TaskExecutor interface, TaskScheduler.schedule, Timer.schedule, - // ForkJoinPool.execute(ForkJoinTask), and ListenableFuture.addListener! - byte[] sfEBytes = ServerEntries.wrapExecutorCalls(generateSfEBytecodeClass("com/acme/SfECallSites")); - assertNotNull("SfECallSites must be rewritten by ServerEntries.wrapExecutorCalls", sfEBytes); - Class sfEClass = new ByteLoader(getClass().getClassLoader()).define("com.acme.SfECallSites", sfEBytes); - - // SF-E.1: TaskExecutor interface with hooked+verified ThreadPoolTaskExecutor (CLEAN) - // vs unhooked custom TaskExecutor (FLAGGED). + // 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("sfe-spring-te", null); + RequestGate.open("spring-te-check", null); Object r1 = RequestGate.enter(); CountDownLatch teRan = new CountDownLatch(1); try { - sfEClass.getMethod("callTaskExecutor", + 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 (SF-E)", + 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("sfe-custom-te", null); + RequestGate.open("custom-te-check", null); Object r2 = RequestGate.enter(); org.springframework.core.task.TaskExecutor customTe = r -> r.run(); try { - sfEClass.getMethod("callTaskExecutor", + 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 (SF-E): " + customTeContams, + 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(); } - // SF-E.2: Spring TaskScheduler.schedule(Runnable, Date) flags AND tracks returned ScheduledFuture! + // 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("sfe-task-scheduler", null); + RequestGate.open("task-scheduler-check", null); Object rTs = RequestGate.enter(); ScheduledFuture tsFut; try { - tsFut = (ScheduledFuture) sfEClass.getMethod("callTaskScheduler", + 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)); @@ -2485,15 +2491,15 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx RequestGate.exit(rTs); } List tsContams = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations; - assertTrue("rewritten TaskScheduler.schedule must flag (SF-E): " + tsContams, + 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("sfe-ts-consume-once", null); + 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("sfe-ts-alive", null); - assertEquals("TaskScheduler ScheduledFuture keeps tail active until cancelled (SF-B/SF-E)", - Collections.singletonList("tail:sfe-task-scheduler"), + 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 { @@ -2501,13 +2507,13 @@ public void r4RegressionsExecutingPastMaxLingeringLiveUntrackedHandlesMultiHopEx RequestGate.untrackedTailWindowNanos = savedTailWindow; } - // SF-E.3: Timer.schedule(TimerTask, long) flags untracked-async:timer! + // 3. Timer.schedule(TimerTask, long) flags untracked-async:timer! RequestGate.disarm(); - RequestGate.open("sfe-timer", null); + RequestGate.open("timer-flag-check", null); Object rTimer = RequestGate.enter(); CountDownLatch timerRan = new CountDownLatch(1); try { - sfEClass.getMethod("callTimer", java.util.Timer.class, java.util.TimerTask.class, long.class) + asyncSiteClass.getMethod("callTimer", java.util.Timer.class, java.util.TimerTask.class, long.class) .invoke(null, timer, new java.util.TimerTask() { @Override public void run() { @@ -2518,38 +2524,38 @@ public void run() { RequestGate.exit(rTimer); } assertTrue(timerRan.await(5, TimeUnit.SECONDS)); - assertTrue("rewritten Timer.schedule must flag untracked-async:timer (SF-E)", + assertTrue("rewritten Timer.schedule must flag untracked-async:timer", RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations .contains("untracked-async:timer")); - // SF-E.4: ForkJoinPool.execute(ForkJoinTask) flags untracked-async:forkjoin-task! + // 4. ForkJoinPool.execute(ForkJoinTask) flags untracked-async:forkjoin-task! RequestGate.disarm(); - RequestGate.open("sfe-fjp", null); + RequestGate.open("fjp-flag-check", null); Object rFjp = RequestGate.enter(); CountDownLatch fjpRan = new CountDownLatch(1); try { - sfEClass.getMethod("callFjpTask", java.util.concurrent.ForkJoinPool.class, + 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 (SF-E)", + assertTrue("rewritten ForkJoinPool.execute(ForkJoinTask) must flag", RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations .contains("untracked-async:forkjoin-task")); - // SF-E.5: Guava ListenableFuture.addListener(Runnable, Executor) flags untracked-async:guava-future! + // 5. Guava ListenableFuture.addListener(Runnable, Executor) flags untracked-async:guava-future! RequestGate.disarm(); - RequestGate.open("sfe-guava", null); + RequestGate.open("guava-flag-check", null); Object rGuava = RequestGate.enter(); try { - sfEClass.getMethod("callGuavaListener", FakeListenableFuture.class, Runnable.class, Executor.class) + 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 (SF-E)", + 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 { @@ -2567,7 +2573,7 @@ public interface FakeListenableFuture { void addListener(Runnable listener, Executor executor); } - private static byte[] generateSfEBytecodeClass(String className) { + 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); @@ -2642,7 +2648,7 @@ private static byte[] generateSfEBytecodeClass(String className) { } @Test(timeout = 60000) - public void r5RegressionsLateStartContaminatesCurrentWindowTimerDelayAndPeriodicMultiHopScheduledRetryAndBranchyFrames() + public void lateStartContaminatesCurrentWindowTimerDelayAndPeriodicMultiHopScheduledRetryAndBranchyFrames() throws Exception { ThreadPoolExecutor singlePool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); @@ -2654,10 +2660,10 @@ public void r5RegressionsLateStartContaminatesCurrentWindowTimerDelayAndPeriodic long savedTailWindow = RequestGate.untrackedTailWindowNanos; long savedMaxLingering = RequestGate.maxLingeringNanos; try { - // SF-1: 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)! + // 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); @@ -2667,7 +2673,7 @@ public void r5RegressionsLateStartContaminatesCurrentWindowTimerDelayAndPeriodic assertTrue(blockerRunning.await(5, TimeUnit.SECONDS)); CountDownLatch lateTaskDone = new CountDownLatch(1); - RequestGate.open("sf1-late", null); + RequestGate.open("late-start-orig", null); Object reqA = RequestGate.enter(); try { RequestGate.execute(singlePool, lateTaskDone::countDown); @@ -2677,32 +2683,32 @@ public void r5RegressionsLateStartContaminatesCurrentWindowTimerDelayAndPeriodic 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("sf1-dropper", null); + 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("sf1-target-m", null); + 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:sf1-late (SF-1): " + mContams, - mContams.contains("tail:sf1-late")); + 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; - // SF-2: Rewritten java.util.Timer one-shot (delay-aware tail) and - // periodic scheduleAtFixedRate (weak TimerTask liveness). + // 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); - // SF-2a: One-shot Timer.schedule(TimerTask, long delay) past 30ms base tail - // remains flagged through delay + base tail! + // 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("sf2-timer-oneshot", null); + RequestGate.open("timer-oneshot", null); Object reqT1 = RequestGate.enter(); try { timerClass.getMethod("scheduleOneShot", java.util.Timer.class, java.util.TimerTask.class, long.class) @@ -2719,20 +2725,20 @@ public void run() { 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("sf2-timer-oneshot-consume-once", null); + 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("sf2-timer-oneshot-next", null); - assertEquals("one-shot Timer delay must extend tail past base window (SF-2)", - Collections.singletonList("tail:sf2-timer-oneshot"), + 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)); - // SF-2b: Periodic Timer.scheduleAtFixedRate(TimerTask, long, long) stays - // flagged past base tail + delay + period while scheduled! + // 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("sf2-timer-periodic", null); + RequestGate.open("timer-periodic", null); Object reqT2 = RequestGate.enter(); try { timerClass.getMethod("schedulePeriodic", java.util.Timer.class, long.class, long.class) @@ -2744,18 +2750,18 @@ public void run() { 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("sf2-timer-periodic-consume-once", null); + 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("sf2-timer-periodic-alive", null); - assertEquals("periodic TimerTask held by Timer queue keeps tail active (SF-2)", - Collections.singletonList("tail:sf2-timer-periodic"), + 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(); - // SF-3: 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! + // 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); @@ -2763,8 +2769,8 @@ public void run() { CountDownLatch gen2Release = new CountDownLatch(1); CountDownLatch downstreamStarted = new CountDownLatch(1); CountDownLatch downstreamRelease = new CountDownLatch(1); - RequestGate.open("sf3-retry", null); - Object reqS3 = RequestGate.enter(); + 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. @@ -2780,27 +2786,27 @@ public void run() { gen1Done.countDown(); }, 10, TimeUnit.MILLISECONDS); } finally { - RequestGate.exit(reqS3); + RequestGate.exit(reqSchedRetry); } - RequestGate.WindowOutcome sf3Out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - assertTrue("END must not block on delayed scheduled task (SF-3)", sf3Out.drained); - assertTrue("SF-3 flags untracked-async:schedule", sf3Out.contaminations.contains("untracked-async:schedule")); + 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("sf3-gen2-consume-once", null); + 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("sf3-while-gen2-pending", null); - assertEquals("gen 2 scheduled via propagated context keeps tail active past gen 1 base tail (SF-3)", - Collections.singletonList("tail:sf3-retry"), + 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("sf3-while-downstream-running", null); - assertEquals("downstream workerPool task launched by gen 2 keeps tail:sf3-retry (SF-3)", - Collections.singletonList("tail:sf3-retry"), + 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(); @@ -2812,7 +2818,7 @@ public void run() { springTs.initialize(); try { RequestGate.disarm(); - RequestGate.open("sf5-branchy", null); + RequestGate.open("branchy-schedule", null); Object reqBr = RequestGate.enter(); ScheduledFuture brFut; try { @@ -2935,30 +2941,30 @@ public T get(long timeout, TimeUnit unit) public static final class CustomWorkerThread extends Thread { public CustomWorkerThread(Runnable r) { - super(r, "r9-custom-thread"); + super(r, "custom-worker-thread"); setDaemon(true); } } @Test(timeout = 60000) - public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineExecutorsAndBackgroundSuppression() + public void nonExecutorSyncHelperTrackedHandleLivenessInlineExecutorsAndBackgroundSuppression() throws Exception { ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); java.util.Timer timer = new java.util.Timer(true); long savedTailWindow = RequestGate.untrackedTailWindowNanos; try { - // Blocker 2: Bytecode-rewritten plain synchronous helper TxHelper.execute(Runnable) + // 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/R9DeltaCaller"); + byte[] callerRaw = generateTxHelperAndTimerCancelCaller("com/acme/SyncHelperAndTimerCaller"); byte[] callerRewritten = ServerEntries.wrapExecutorCalls(callerRaw); - assertNotNull("R9DeltaCaller must be rewritten by ServerEntries.wrapExecutorCalls", callerRewritten); + assertNotNull("SyncHelperAndTimerCaller must be rewritten by ServerEntries.wrapExecutorCalls", callerRewritten); Class caller = new ByteLoader(getClass().getClassLoader()) - .define("com.acme.R9DeltaCaller", callerRewritten); + .define("com.acme.SyncHelperAndTimerCaller", callerRewritten); RequestGate.disarm(); - RequestGate.open("b2-sync-helper", null); - Object reqB2 = RequestGate.enter(); + RequestGate.open("sync-helper", null); + Object reqSync = RequestGate.enter(); AtomicBoolean execRan = new AtomicBoolean(false); AtomicBoolean submitRan = new AtomicBoolean(false); try { @@ -2968,20 +2974,20 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx (Runnable) () -> execRan.set(true), (Runnable) () -> submitRan.set(true)); } finally { - RequestGate.exit(reqB2); + 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 (B2)", + assertEquals("non-Executor TxHelper.execute/submit must NOT contaminate current window", Collections.emptyList(), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); - RequestGate.open("b2-next-window", null); - assertEquals("non-Executor TxHelper.execute/submit must NOT taint subsequent window (B2)", + 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 for B2: a real custom Executor/ExecutorService still gets flagged! - RequestGate.open("b2-real-custom-exec", null); + // 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 { @@ -2993,10 +2999,10 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx assertTrue("real custom Executor must still be flagged: " + customExecOut.contaminations, customExecOut.contaminations.contains("untracked-executor:" + customExec.getClass().getName())); - // Should-Fix 1(a): Request schedules a 30s timeout and cancels it before returning -> + // Request schedules a 30s timeout and cancels it before returning -> // next request MUST be CLEAN (no 32s tail: taint)! RequestGate.disarm(); - RequestGate.open("sf1a-timeout", null); + RequestGate.open("cancelled-timeout", null); Object reqTimeout = RequestGate.enter(); try { ScheduledFuture timeout = RequestGate.schedule(stpe, () -> { }, 30, TimeUnit.SECONDS); @@ -3004,20 +3010,20 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx } finally { RequestGate.exit(reqTimeout); } - RequestGate.WindowOutcome sf1aOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + RequestGate.WindowOutcome timeoutOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); assertTrue("originating window still notes schedule", - sf1aOut.contaminations.contains("untracked-async:schedule")); - RequestGate.open("sf1a-next-clean", null); - assertEquals("cancelled 30s timeout must NOT taint subsequent window (SF1a)", + 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); - // Should-Fix 1(b): Thread.start() + join() before response -> next request MUST be CLEAN! + // Thread.start() + join() before response -> next request MUST be CLEAN! RequestGate.disarm(); - RequestGate.open("sf1b-thread-join", null); + RequestGate.open("thread-join", null); Object reqJoin = RequestGate.enter(); try { - Thread t = new Thread(() -> { }, "sf1b-joined"); + Thread t = new Thread(() -> { }, "joined-worker"); RequestGate.startThread(t); t.join(5000); assertFalse("thread terminated before END", t.isAlive()); @@ -3025,14 +3031,14 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx RequestGate.exit(reqJoin); } RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - RequestGate.open("sf1b-next-clean", null); - assertEquals("joined Thread.start() must NOT leave 2s tail taint on next window (SF1b)", + 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("sf1b-subthread-join", null); + RequestGate.open("subthread-join", null); Object reqSubJoin = RequestGate.enter(); try { CustomWorkerThread sub = new CustomWorkerThread(() -> { }); @@ -3043,16 +3049,16 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx RequestGate.exit(reqSubJoin); } RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - RequestGate.open("sf1b-subthread-next-clean", null); - assertEquals("joined Thread subclass must NOT taint next window (SF1b)", + 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); - // Should-Fix 1(c) + B1: + // 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("sf1c-timer-cancel", null); + RequestGate.open("timer-cancel-before-fire", null); Object reqTimer = RequestGate.enter(); try { caller.getMethod("scheduleAndCancelPeriodic", java.util.Timer.class, java.util.TimerTask.class) @@ -3060,16 +3066,16 @@ public void r9DeltaRegressionsNonExecutorSyncHelperTrackedHandleLivenessInlineEx } finally { RequestGate.exit(reqTimer); } - RequestGate.WindowOutcome sf1cOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + RequestGate.WindowOutcome timerCancelOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); assertTrue("originating window notes untracked-async:timer", - sf1cOut.contaminations.contains("untracked-async:timer")); - RequestGate.open("sf1c-next-clean", null); - assertEquals("cancelled periodic TimerTask retained in a field must NOT taint next window (SF1c)", + 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) B1 regression: One-shot TimerTask(delay=0) with a 300ms body STILL RUNNING + // (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); @@ -3085,7 +3091,7 @@ public void run() { } } }; - RequestGate.open("b1-slow-oneshot", null); + RequestGate.open("slow-oneshot", null); Object reqSlowOneShot = RequestGate.enter(); try { caller.getMethod("scheduleOneShotDelay", java.util.Timer.class, java.util.TimerTask.class, long.class) @@ -3096,21 +3102,21 @@ public void run() { 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("b1-during-slow-body", null); - assertEquals("running one-shot TimerTask body MUST contaminate t2 (B1)", - Collections.singletonList("tail:b1-slow-oneshot"), + 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("b1-after-cancel-while-running", null); - assertEquals("cancel() while body is running MUST NOT drop tail immediately (B1)", - Collections.singletonList("tail:b1-slow-oneshot"), + 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) B1/SF1c: Periodic TimerTask that ran >= 1 tick, then cancelled & retained in a field -> + // (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); @@ -3121,7 +3127,7 @@ public void run() { periodicRanOnce.countDown(); } }; - RequestGate.open("b1-periodic-ran-then-cancel", null); + RequestGate.open("periodic-ran-then-cancel", null); Object reqRanPer = RequestGate.enter(); try { caller.getMethod("schedulePeriodicDelay", java.util.Timer.class, java.util.TimerTask.class, @@ -3135,12 +3141,12 @@ public void run() { // 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("b1-periodic-right-after-cancel", null); + RequestGate.open("periodic-right-after-cancel", null); assertEquals("periodic TimerTask cancelled after ticking MUST keep tail active during tail window", - Collections.singletonList("tail:b1-periodic-ran-then-cancel"), + 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("b1-periodic-clean-after-tail", null); + 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); @@ -3152,7 +3158,7 @@ public void run() { // 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("b1-timer-cancel-before-fire", null); + 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) @@ -3162,7 +3168,7 @@ public void run() { RequestGate.exit(reqTcb); } RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - RequestGate.open("b1-timer-cancel-before-fire-next", null); + 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); @@ -3171,7 +3177,7 @@ public void run() { java.util.Timer cancelWhileRunningTimer = new java.util.Timer(true); CountDownLatch timerBodyStarted = new CountDownLatch(1); CountDownLatch timerBodyRelease = new CountDownLatch(1); - RequestGate.open("b1-timer-cancel-running", null); + RequestGate.open("timer-cancel-running", null); Object reqTcr = RequestGate.enter(); try { caller.getMethod("scheduleOneShotDelay", java.util.Timer.class, java.util.TimerTask.class, long.class) @@ -3192,16 +3198,16 @@ public void run() { RequestGate.exit(reqTcr); } RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - RequestGate.open("b1-timer-cancel-running-next", null); + RequestGate.open("timer-cancel-running-next", null); assertEquals("Timer.cancel() while body is running MUST keep tail active", - Collections.singletonList("tail:b1-timer-cancel-running"), + 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("sf1c-oneshot-cancel", null); + RequestGate.open("oneshot-cancel", null); Object reqOneShot = RequestGate.enter(); try { caller.getMethod("scheduleAndCancelOneShot", java.util.Timer.class, java.util.TimerTask.class) @@ -3210,30 +3216,30 @@ public void run() { RequestGate.exit(reqOneShot); } RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - RequestGate.open("sf1c-oneshot-next-clean", null); - assertEquals("cancelled one-shot 30s TimerTask must NOT taint next window (SF1c)", + 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); - // S1: Two-arg submit(Runnable, T) returning a Future subtype (like Guava ListenableFuture) + // 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("s1-listenable-submit2", null); - Object reqS1 = RequestGate.enter(); + 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(reqS1); + RequestGate.exit(reqSubmit2); } - RequestGate.WindowOutcome s1Out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); - assertTrue("two-arg ListenableFuture submit must flag untracked-executor (S1): " + s1Out.contaminations, - s1Out.contaminations.contains("untracked-executor:" + listenableExec.getClass().getName())); + 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())); - // Should-Fix 3 + S4: Known same-thread inline executors (Spring SyncTaskExecutor, + // 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! @@ -3257,7 +3263,7 @@ public void run() { ExecutorService legacyGuavaDirectSvc = (ExecutorService) legacyGuavaDirectSvcCls.getDeclaredConstructor().newInstance(); - RequestGate.open("sf3-inline", null); + RequestGate.open("inline-exec-check", null); Object reqInline = RequestGate.enter(); AtomicBoolean inlineRan1 = new AtomicBoolean(false); AtomicBoolean inlineRan2 = new AtomicBoolean(false); @@ -3290,20 +3296,20 @@ public void run() { 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 (S4)", + 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 (SF3)", + assertEquals("known inline executors must NOT contaminate current window", Collections.emptyList(), RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true).contaminations); - RequestGate.open("sf3-inline-next", null); - assertEquals("known inline executors must NOT taint next window (SF3)", + 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); - // Should-Fix 4 (S4): Real CoverageTcpClient connect test with injected RuntimeException in + // 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()); @@ -3433,7 +3439,7 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO assertTrue("BACKGROUND reports lost:1 from suppressed gap: " + bgLine, bgLine.contains("\"lost\":1")); - // S2 (A -> B -> C): test-3 starts a live thread still alive at END test-4, + // 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); @@ -3479,10 +3485,10 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO 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 (S2)", + assertEquals("B->C gap holding A's finishing audit MUST suppress BACKGROUND", "ACK check-no-bg-bc", in.readLine()); - // S2 (opposite): test-5 starts a thread AND joins it before END -> + // 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 { @@ -3501,12 +3507,12 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO 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 (S2): " + bg56, + 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")); - // S2 (independent suppressBackground[0] branch): test-6 ends completely clean + // 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(); @@ -3529,7 +3535,7 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO 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 (S2)", + assertEquals("suppressBackground[0] alone MUST suppress BACKGROUND when expired job active", "ACK check-suppress-only", in.readLine()); } finally { JobGate.exit(expiredToken); @@ -3550,7 +3556,7 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO 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 (S2): " + bg78, + assertTrue("next clean gap after suppressBackground[0] reports lost:1: " + bg78, bg78 != null && bg78.startsWith("BACKGROUND ") && bg78.contains("\"lost\":1")); } finally { KeployDedupAgent.stop(); @@ -3559,7 +3565,7 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO } // 2. Unix transport: verify BOTH (a) BACKGROUND suppression + lost:1 AND - // (b) Blocker 1 end-to-end on Unix (unverified: ["no-server-entry"], NO "contaminated")! + // (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"); @@ -3684,9 +3690,9 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO } } assertNotNull("expected Unix record for ts/u3", recU3); - assertTrue("Unix uncounted-server record must carry unverified no-server-entry (S4): " + 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 (B1/S4): " + recU3, + 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, @@ -4024,6 +4030,385 @@ public void methodReferencesToNonExecutorHelpersAreNotFlaggedWhileRealExecutorsS 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) diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index e966f4aa..9fdbd97c 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -42,7 +42,7 @@ /** * Real application process launched in forked {@code -javaagent:keploy-sdk.jar} - * JVMs by {@code ForkedAsyncAndHonestyTest} to prove Ruling #3 end-to-end + * 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). */ @@ -173,7 +173,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO AsyncTail.ran(); }); } else if ("/cf-then-accept".equals(path)) { - // Reproduces plg-87's exact bug: fast supplier, slow synchronous thenAccept(audit). + // Fast supplier followed by a slow synchronous thenAccept(audit) dependent. CompletableFuture.supplyAsync(() -> { sleepQuietly(20); return "result"; From e8eba30dc29edcbbfd94c05cc83863678d5c4d7c Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 18:20:22 +0530 Subject: [PATCH 19/26] test(smoke): accept protocol v3 ACK caps and trailing unverified field in smoke-javaagent.sh Signed-off-by: slayerjain --- scripts/smoke-javaagent.sh | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/smoke-javaagent.sh b/scripts/smoke-javaagent.sh index 974df3a0..b98d7a44 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); } } From 90cbdfb2a67f175c5d87dd964035e32605920674 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Fri, 27 Nov 2026 22:41:27 +0530 Subject: [PATCH 20/26] fix(dedup): latch untracked method refs and library async dispatchers, fail-closed HELLO refresh, and re-pin smoke checks Signed-off-by: slayerjain --- README.md | 2 +- .../io/keploy/dedup/KeployDedupAgent.java | 114 ++-- .../java/io/keploy/dedup/OrderedPools.java | 47 ++ .../java/io/keploy/dedup/RequestGate.java | 128 ++-- .../java/io/keploy/dedup/ServerEntries.java | 185 +++++- .../dedup/ForkedAsyncAndHonestyTest.java | 80 ++- .../dedup/HonestProtocolAndAsyncTest.java | 599 ++++++++++++++++-- .../org/example/servers/AsyncHonestyApp.java | 48 +- scripts/smoke-javaagent.sh | 56 +- 9 files changed, 1083 insertions(+), 176 deletions(-) diff --git a/README.md b/README.md index 56b2eb87..4b9faf1e 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ A server sends a response before it is done with the request: a filter's code af 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. -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`. +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, 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"`). 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 51eca2a9..9215399e 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -151,28 +151,34 @@ static String encodeBytecodeFrame(String buildTag, String manifestJson, byte[] z // 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; + static final AtomicBoolean observedNoServerEntry = new AtomicBoolean(); + // Latched true once an untracked executor/async method reference or + // untracked library-to-JDK-pool hand-off (e.g. Spring + // SimpleApplicationEventMulticaster.setTaskExecutor with a plain JDK pool) + // is observed. Permanently drops asyncExecutors to false in HELLO and Unix + // ACK caps; reset only by tests. + static final AtomicBoolean observedPreCapturedUntrackedExecutor = new AtomicBoolean(); 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," + if (observedNoServerEntry.compareAndSet(false, true)) { + log(Level.INFO, "Keploy dedup: " + testId + " recorded coverage outside any counted server request," + " 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); + static void noteObservedUntrackedMethodRef(String api, boolean armed) { + if (observedPreCapturedUntrackedExecutor.compareAndSet(false, true)) { + log(armed ? Level.INFO : Level.FINE, + "Keploy dedup: saw an untracked async method reference to " + api + + ", so background async work cannot be tracked reliably for the rest of this run", null); + } + } + + static void noteObservedUntrackedAsyncLibrary(String description, boolean armed) { + if (observedPreCapturedUntrackedExecutor.compareAndSet(false, true)) { + log(armed ? Level.INFO : Level.FINE, + "Keploy dedup: saw an untracked async dispatcher (" + description + + "), 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 @@ -355,25 +361,28 @@ private static Capabilities computeCapabilities(CoverageCollector collector) { boolean serverEntriesInstalled = agentAttached && endWaitActive && !ServerEntries.hasUncountedServer() && !ServerEntries.hadServerHookFailure() - && !observedNoServerEntry; + && !observedNoServerEntry.get(); 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. + // Also fail closed if any untracked executor/async method reference, + // untracked library/JDK async dispatcher (RxJava Schedulers, Kotlin + // coroutines Dispatchers, OkHttp Dispatcher, NIO Asynchronous*Channel, + // or Spring SimpleApplicationEventMulticaster with a plain JDK pool), + // or async hook failure was observed, refreshing TCP HELLO and Unix + // ACK caps. boolean asyncExecutors = serverEntriesInstalled && executorCallSitesEnabled && !isAsyncCallSitesTurnedOff() && appOnlyActive && !ServerEntries.wasJpmsGuardTriggered() && !ServerEntries.hadAppRewriteFailure() - && !observedPreCapturedUntrackedExecutor; + && !ServerEntries.hadAsyncHookFailure() + && !ServerEntries.hasUnhookedAsyncDispatcher() + && !observedPreCapturedUntrackedExecutor.get(); boolean listenerContamination = agentAttached && !ServerEntries.hadListenerHookFailure() && !ServerEntries.hasUnhookedConsumer(); @@ -1457,6 +1466,12 @@ private static final class CoverageTcpClient implements CoverageWorker { this.port = port; } + private static final String FAIL_CLOSED_FALLBACK_HELLO = + "HELLO {\"proto\":3,\"sdkVersion\":\"\",\"podUid\":\"\",\"podName\":\"\",\"sessionId\":\"\"," + + "\"jvmNonce\":\"\",\"buildId\":\"\"," + + "\"windowCut\":false,\"contaminated\":false,\"classMismatch\":false,\"background\":false," + + "\"ackId\":true,\"nopResync\":true,\"asyncExecutors\":false,\"listenerContamination\":false}"; + private String helloFrame() { RuntimeException injected = testHelloFailure; if (injected != null) { @@ -1473,6 +1488,21 @@ private void maybeSendUpdatedHello(OutputStream out) throws IOException { } } + private boolean refreshHelloOrFallback(OutputStream out, String phase) throws IOException { + try { + maybeSendUpdatedHello(out); + return true; + } catch (RuntimeException | LinkageError e) { + log(Level.FINE, "Failed to refresh HELLO during " + phase + + "; sending fail-closed fallback HELLO", e); + if (!FAIL_CLOSED_FALLBACK_HELLO.equals(lastHelloSent)) { + writeLine(out, FAIL_CLOSED_FALLBACK_HELLO); + lastHelloSent = FAIL_CLOSED_FALLBACK_HELLO; + } + return false; + } + } + @Override public void run() { while (running.get()) { @@ -1542,15 +1572,7 @@ private void connectAndServe() throws IOException { // 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; - } + refreshHelloOrFallback(out, "connect"); out.flush(); } String line; @@ -1646,11 +1668,7 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) // collector has no other sign this test went unmeasured. writeLine(out, IGNORED_REPLY + " " + command.testId); } - try { - maybeSendUpdatedHello(out); - } catch (RuntimeException | LinkageError e) { - log(Level.FINE, "Failed to refresh HELLO before START ACK for " + command.testId, e); - } + refreshHelloOrFallback(out, "START " + command.testId); ack(out, command.testId); // Emit BACKGROUND after START's ACK (matching the unix path) // so building coverageIndex.report() / JSON never delays the @@ -1728,12 +1746,22 @@ private void dispatch(CoverageCommand command, OutputStream out, Phases phases) } // 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); + // an untracked async dispatcher latched, or probeScan was dropped). + // Isolated from the COV try block so a runtime error computing + // HELLO can never suppress COV before ACK; on error, emit the + // fail-closed all-false fallback HELLO and also tag COV unverified + // if the async latch is active so the collector never sees a stale + // honest declaration. + boolean helloRefreshed = refreshHelloOrFallback(out, "END " + command.testId); + if (!helloRefreshed + && (observedPreCapturedUntrackedExecutor.get() + || ServerEntries.hasUnhookedAsyncDispatcher() + || ServerEntries.hadAsyncHookFailure())) { + List updatedUnverified = new ArrayList<>(coverage.unverified); + if (!updatedUnverified.contains("untracked-async")) { + updatedUnverified.add("untracked-async"); + } + coverage = coverage.ended(coverage.windowCut, coverage.contaminated, updatedUnverified); } try { // Always emit exactly one COV before ACK — even when empty — 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 12b9032f..954763d4 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -264,6 +264,53 @@ static boolean isHookedAndVerifiedSpringExecutor(Object executor) { } } + // Variant for Spring configuration hooks (e.g. SimpleApplicationEventMulticaster.setTaskExecutor) + // that may run before a Spring ThreadPoolTaskExecutor/ThreadPoolTaskScheduler is initialized: + // returns true when the executor extends a hooked Spring executor class without overriding + // execute/submit/doExecute AND either passes !orders(executor) now or is not yet initialized + // (in which case its hooked execute() verifies orders(executor) on every invocation). + static boolean isHookedSpringExecutorOrPendingInit(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; + } + if (SPRING_POOL.equals(hookedBase) || SPRING_SCHEDULER.equals(hookedBase)) { + Object m = (SPRING_POOL.equals(hookedBase) ? POOL : SCHEDULED_POOL).get(cls); + if (m instanceof Method) { + try { + ((Method) m).invoke(executor); + } catch (InvocationTargetException ite) { + if (ite.getCause() instanceof IllegalStateException) { + return true; + } + 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 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 f6cb458b..bc4efd1e 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -3101,14 +3101,27 @@ public static void noteIfUntrackedSubmit(Object receiver) { noteUntrackedAsync("untracked-executor:" + receiver.getClass().getName(), 0L); } + private static void recordUntrackedMethodRef(String reason, String target) { + if (!armed) { + noteUnarmedHandOffIfInFlight(); + KeployDedupAgent.noteObservedUntrackedMethodRef(target, false); + return; + } + KeployDedupAgent.noteObservedUntrackedMethodRef(target, true); + if (INSIDE.get() != null || JobGate.runningAttribution() != null || JobGate.expiredRunningName() != null) { + noteUntrackedAsync(reason, 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. + * and hooked/verified Spring executors. Permanently latches + * {@code asyncExecutors=false} on any capture of a real untracked executor + * reference (inside or outside a window, because the captured lambda may be + * stored and invoked in later windows), and contaminates the active window + * or tracked job when captured inside one. * * @param receiver captured receiver of {@code execute(Runnable)} method reference */ @@ -3120,16 +3133,7 @@ public static void noteIfUntrackedExecutorMethodRef(Object 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); + recordUntrackedMethodRef("untracked-executor:" + name, name + "::execute"); } /** @@ -3137,9 +3141,10 @@ public static void noteIfUntrackedExecutorMethodRef(Object receiver) { * 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}. + * hooked/verified Spring executors. Permanently latches + * {@code asyncExecutors=false} on any capture of a real untracked executor + * reference and contaminates the active window or tracked job when captured + * inside one. * * @param receiver captured receiver of {@code submit*} method reference */ @@ -3153,25 +3158,16 @@ public static void noteIfUntrackedSubmitMethodRef(Object 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); + recordUntrackedMethodRef("untracked-executor:" + name, name + "::submit"); } /** * 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}. + * same-thread inline executors. Permanently latches + * {@code asyncExecutors=false} on any capture and contaminates the active + * window or tracked job when captured inside one. * * @param owner declaring owner class of the method reference */ @@ -3183,25 +3179,16 @@ public static void noteIfUntrackedExecutorClass(Class 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); + recordUntrackedMethodRef("untracked-executor:" + name, name + "::execute"); } /** * 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}. + * non-executor types and allow-listed same-thread inline executors. + * Permanently latches {@code asyncExecutors=false} on any capture and + * contaminates the active window or tracked job when captured inside one. * * @param owner declaring owner class of the method reference */ @@ -3216,23 +3203,15 @@ public static void noteIfUntrackedSubmitClass(Class 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); + recordUntrackedMethodRef("untracked-executor:" + name, name + "::submit"); } /** - * 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}. + * Records an untracked async method reference capture (e.g. + * {@code Thread::start}, {@code CompletableFuture::runAsync}, + * {@code ScheduledExecutorService::schedule}). Permanently latches + * {@code asyncExecutors=false} on any capture and contaminates the active + * window or tracked job when captured inside one. * * @param reason contamination reason label describing the method reference */ @@ -3240,16 +3219,41 @@ public static void noteUntrackedAsyncMethodRef(String reason) { if (reason == null || reason.isEmpty()) { return; } + String api = reason.startsWith("untracked-async:method-ref:") + ? reason.substring("untracked-async:method-ref:".length()) + : reason; + recordUntrackedMethodRef(reason, api); + } + + /** + * Called from Spring's {@code SimpleApplicationEventMulticaster.setTaskExecutor} + * hook. Allows {@code null}, allow-listed inline executors, and hooked + * Spring executors; for any other executor (such as a plain JDK + * {@code ThreadPoolExecutor}), latches {@code asyncExecutors=false} so + * untracked Spring-to-JDK-pool event hand-offs never report honest. + * + * @param executor executor configured on the multicaster + */ + public static void noteSpringMulticasterTaskExecutor(Object executor) { + if (executor == null) { + return; + } + if (OrderedPools.isInlineExecutor(executor) + || OrderedPools.isHookedSpringExecutorOrPendingInit(executor)) { + return; + } + String name = executor.getClass().getName(); if (!armed) { noteUnarmedHandOffIfInFlight(); - KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(reason); + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "Spring SimpleApplicationEventMulticaster with " + name, false); return; } - if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { - KeployDedupAgent.noteObservedPreCapturedUntrackedExecutor(reason); - return; + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "Spring SimpleApplicationEventMulticaster with " + name, true); + if (INSIDE.get() != null || JobGate.runningAttribution() != null || JobGate.expiredRunningName() != null) { + noteUntrackedAsync("untracked-executor:" + name, 0L); } - noteUntrackedAsync(reason, 0L); } /** 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 901fe59a..c2ecf38c 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -137,6 +137,26 @@ final class ServerEntries implements ClassFileTransformer { UNHOOKED_CONSUMERS.put("com/google/cloud/pubsub/v1/Subscriber", "GCP Pub/Sub"); } + private static final Map UNHOOKED_ASYNC_DISPATCHERS = new HashMap<>(); + + static { + UNHOOKED_ASYNC_DISPATCHERS.put("rx/schedulers/Schedulers", "RxJava 1 Schedulers"); + UNHOOKED_ASYNC_DISPATCHERS.put("io/reactivex/schedulers/Schedulers", "RxJava 2 Schedulers"); + UNHOOKED_ASYNC_DISPATCHERS.put("io/reactivex/rxjava3/schedulers/Schedulers", "RxJava 3 Schedulers"); + UNHOOKED_ASYNC_DISPATCHERS.put("kotlinx/coroutines/Dispatchers", "Kotlin Coroutines Dispatchers"); + UNHOOKED_ASYNC_DISPATCHERS.put("okhttp3/Dispatcher", "OkHttp Dispatcher"); + UNHOOKED_ASYNC_DISPATCHERS.put("java/nio/channels/AsynchronousChannelGroup", "JDK AsynchronousChannelGroup"); + UNHOOKED_ASYNC_DISPATCHERS.put("java/nio/channels/AsynchronousFileChannel", "JDK AsynchronousFileChannel"); + UNHOOKED_ASYNC_DISPATCHERS.put("java/nio/channels/AsynchronousSocketChannel", "JDK AsynchronousSocketChannel"); + UNHOOKED_ASYNC_DISPATCHERS.put("java/nio/channels/AsynchronousServerSocketChannel", + "JDK AsynchronousServerSocketChannel"); + UNHOOKED_ASYNC_DISPATCHERS.put("sun/nio/ch/SimpleAsynchronousFileChannelImpl", "JDK AsynchronousFileChannel"); + UNHOOKED_ASYNC_DISPATCHERS.put("sun/nio/ch/AsynchronousChannelGroupImpl", "JDK AsynchronousChannelGroup"); + } + + private static final String SPRING_EVENT_MULTICASTER = + "org/springframework/context/event/SimpleApplicationEventMulticaster"; + 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", @@ -147,9 +167,11 @@ final class ServerEntries implements ClassFileTransformer { 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 SEEN_UNHOOKED_ASYNC_DISPATCHERS = 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 asyncHookFailed; private static volatile boolean jpmsGuardTriggered; private static volatile boolean appRewriteFailed; @@ -338,6 +360,14 @@ static boolean hasUnhookedConsumer() { return !SEEN_UNHOOKED_CONSUMERS.isEmpty(); } + static boolean hasUnhookedAsyncDispatcher() { + return !SEEN_UNHOOKED_ASYNC_DISPATCHERS.isEmpty(); + } + + static boolean hadAsyncHookFailure() { + return asyncHookFailed; + } + static boolean isSpringExecutorHooked(String binaryClassName) { return HOOKED_SPRING_CLASSES.contains(binaryClassName); } @@ -404,6 +434,17 @@ static void restoreUnhookedConsumers(Set snapshot) { } } + static Set snapshotUnhookedAsyncDispatchers() { + return new HashSet<>(SEEN_UNHOOKED_ASYNC_DISPATCHERS); + } + + static void restoreUnhookedAsyncDispatchers(Set snapshot) { + SEEN_UNHOOKED_ASYNC_DISPATCHERS.clear(); + if (snapshot != null) { + SEEN_UNHOOKED_ASYNC_DISPATCHERS.addAll(snapshot); + } + } + static void setHookStatusForTests(boolean serverFailed, boolean listenerFailed, boolean jpmsSkipped) { setHookStatusForTests(serverFailed, listenerFailed, jpmsSkipped, false); } @@ -412,9 +453,11 @@ static void setHookStatusForTests(boolean serverFailed, boolean listenerFailed, boolean rewriteFailed) { serverHookFailed = serverFailed; listenerHookFailed = listenerFailed; + asyncHookFailed = false; jpmsGuardTriggered = jpmsSkipped; appRewriteFailed = rewriteFailed; SEEN_UNHOOKED_CONSUMERS.clear(); + SEEN_UNHOOKED_ASYNC_DISPATCHERS.clear(); } // uncounted names the servers whose requests do not count that the app @@ -429,6 +472,9 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (classBeingRedefined != null) { return changedAgain(loader, className, classfileBuffer); } + if (SPRING_EVENT_MULTICASTER.equals(className)) { + return hookSpringEventMulticaster(loader, className, classfileBuffer); + } Entry entry = ENTRIES.get(className); if (entry == null) { String uncounted = UNCOUNTED.get(className); @@ -439,14 +485,19 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (unhookedConsumer != null) { SEEN_UNHOOKED_CONSUMERS.add(unhookedConsumer); } + String unhookedAsync = UNHOOKED_ASYNC_DISPATCHERS.get(className); + if (unhookedAsync != null) { + SEEN_UNHOOKED_ASYNC_DISPATCHERS.add(unhookedAsync); + } if (shouldRewriteExecutorCalls(className)) { + scanUnhookedReferences(classfileBuffer, false); if (!canAccessGate(loader, protectionDomain)) { if (seesGate(loader)) { jpmsGuardTriggered = true; } else { appRewriteFailed = true; } - scanRawConsumerCalls(classfileBuffer); + scanUnhookedReferences(classfileBuffer, true); return null; } try { @@ -463,10 +514,12 @@ public byte[] transform(ClassLoader loader, String className, Class classBein && !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); + // Kafka/RabbitMQ/JMS consumer calls and unhooked async + // dispatchers (RxJava, Kotlin coroutines, OkHttp, NIO + // Asynchronous*Channel) so capabilities stay honest without + // modifying bytecode (skipping known JMS/RabbitMQ pooling + // wrappers used by Spring Boot). + scanUnhookedReferences(classfileBuffer, true); } return null; } @@ -555,6 +608,21 @@ private boolean wasRewritten(ClassLoader loader, String className) { } private byte[] changedAgain(ClassLoader loader, String className, byte[] classfile) { + if (SPRING_EVENT_MULTICASTER.equals(className)) { + synchronized (changed) { + Set names = changed.get(loader); + if (names == null || !names.contains(className)) { + return null; + } + } + try { + return wrapSpringEventMulticaster(classfile); + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not re-hook " + className, t); + return null; + } + } Entry entry = ENTRIES.get(className); if (entry == null) { if (wasRewritten(loader, className)) { @@ -864,7 +932,95 @@ static boolean hasExecutorReference(ClassReader reader) { return false; } - private static void scanRawConsumerCalls(byte[] classfile) { + private byte[] hookSpringEventMulticaster(ClassLoader loader, String className, byte[] classfileBuffer) { + String name = className.replace('/', '.'); + try { + if (isInterface(classfileBuffer)) { + return null; + } + if (!seesGate(loader)) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup cannot inspect " + name + + ".setTaskExecutor: its class loader does not see keploy-sdk.jar", (Throwable) null); + return null; + } + byte[] wrapped = wrapSpringEventMulticaster(classfileBuffer); + if (wrapped == null) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup cannot inspect " + name + + ": setTaskExecutor(Executor) not found"); + return null; + } + synchronized (changed) { + Set names = changed.get(loader); + if (names == null) { + names = new HashSet<>(); + changed.put(loader, names); + } + names.add(className); + } + return wrapped; + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not hook " + name + ".setTaskExecutor", t); + return null; + } + } + + static byte[] wrapSpringEventMulticaster(byte[] classfile) { + ClassReader reader = new ClassReader(classfile); + ClassWriter writer = new ClassWriter(reader, 0); + final boolean[] found = {false}; + final boolean[] alreadyHooked = {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 || !"setTaskExecutor".equals(name) + || !"(Ljava/util/concurrent/Executor;)V".equals(descriptor) + || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE | Opcodes.ACC_STATIC)) != 0) { + return mv; + } + found[0] = true; + return new MethodVisitor(Opcodes.ASM9, mv) { + private boolean injected; + + @Override + public void visitCode() { + super.visitCode(); + if (!injected) { + injected = true; + super.visitVarInsn(Opcodes.ALOAD, 1); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, + "noteSpringMulticasterTaskExecutor", "(Ljava/lang/Object;)V", false); + } + } + + @Override + public void visitMethodInsn(int opcode, String owner, String mname, String desc, + boolean isInterface) { + if (opcode == Opcodes.INVOKESTATIC && GATE.equals(owner) + && "noteSpringMulticasterTaskExecutor".equals(mname)) { + alreadyHooked[0] = true; + } + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + super.visitMaxs(Math.max(maxStack, 1), maxLocals); + } + }; + } + }, 0); + if (!found[0]) { + return null; + } + return alreadyHooked[0] ? classfile : writer.toByteArray(); + } + + private static void scanUnhookedReferences(byte[] classfile, boolean includeRawConsumers) { if (classfile == null || classfile.length < 16) { return; } @@ -872,16 +1028,21 @@ private static void scanRawConsumerCalls(byte[] classfile) { ClassReader reader = new ClassReader(classfile); int itemCount = reader.getItemCount(); char[] buf = new char[reader.getMaxStringLength()]; - boolean hasOwner = false; + boolean hasRawConsumerOwner = 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 (offset != 0 && reader.readByte(offset - 1) == 7) { + String cls = reader.readUTF8(offset, buf); + String unhookedAsync = UNHOOKED_ASYNC_DISPATCHERS.get(cls); + if (unhookedAsync != null) { + SEEN_UNHOOKED_ASYNC_DISPATCHERS.add(unhookedAsync); + } + if (includeRawConsumers && RAW_CONSUMER_OWNERS.contains(cls)) { + hasRawConsumerOwner = true; + } } } - if (!hasOwner) { + if (!hasRawConsumerOwner) { return; } reader.accept(new ClassVisitor(Opcodes.ASM9) { diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index a593631a..a4e2ac32 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -344,6 +344,63 @@ public void forkedVirtualThreadStartAndBuilderFlagAndTrackLiveness() throws Exce } } + @Test(timeout = 120000) + public void forkedPreCapturedAndLazyMethodRefsAndLibraryHandOffsDropAsyncExecutorsAcrossReconnect() + throws Exception { + // 1. Pre-captured field Consumer dispatch = pool::execute initialized at startup + // latches asyncExecutors=false in HELLO and stays false across TCP reconnect. + try (ForkedApp app = startFork("precaptured-tomcat", "2000", false, false, null, null)) { + // Trigger one START/END to ensure any startup-captured latch is reflected in HELLO. + app.runHttpTest("ts/pre-1", "/clean"); + JsonObject latest = parseHello(app.lastHello); + assertTrue("windowCut stays true on Tomcat", latest.get("windowCut").getAsBoolean()); + assertFalse("startup pre-captured pool::execute must latch asyncExecutors=false: " + app.lastHello, + latest.get("asyncExecutors").getAsBoolean()); + + String reconnHello = app.reconnectAndReadHello(); + JsonObject reconn = parseHello(reconnHello); + assertTrue("windowCut stays true across reconnect", reconn.get("windowCut").getAsBoolean()); + assertFalse("asyncExecutors=false must stay latched across reconnect: " + reconnHello, + reconn.get("asyncExecutors").getAsBoolean()); + } + + // 2. Lazy in-window capture (W1 captures pool::execute, W2 invokes cached ref) flips HELLO + // to asyncExecutors=false before W1's COV and stays false across W2 and reconnect. + try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { + JsonObject initial = parseHello(app.initialHello); + assertTrue("initial HELLO starts with asyncExecutors=true", + initial.get("asyncExecutors").getAsBoolean()); + String cov1 = app.runHttpTest("ts/lazy-w1", "/lazy-method-ref?ms=50"); + assertTrue("W1 lazy capture must contaminate COV: " + cov1, + cov1.contains("untracked-executor:")); + JsonObject afterW1 = parseHello(app.lastHello); + assertFalse("W1 lazy capture must refresh HELLO asyncExecutors=false: " + app.lastHello, + afterW1.get("asyncExecutors").getAsBoolean()); + app.runHttpTest("ts/lazy-w2", "/lazy-method-ref?ms=50"); + JsonObject reconn = parseHello(app.reconnectAndReadHello()); + assertFalse("lazy capture stays asyncExecutors=false across reconnect", + reconn.get("asyncExecutors").getAsBoolean()); + } + + // 3. Spring SimpleApplicationEventMulticaster.setTaskExecutor(plainPool) drops asyncExecutors=false. + try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { + assertTrue(parseHello(app.initialHello).get("asyncExecutors").getAsBoolean()); + app.runHttpTest("ts/spring-mc", "/spring-multicaster-plain"); + JsonObject afterMc = parseHello(app.lastHello); + assertFalse("Spring SimpleApplicationEventMulticaster with plain JDK pool must drop asyncExecutors=false: " + + app.lastHello, afterMc.get("asyncExecutors").getAsBoolean()); + } + + // 4. JDK AsynchronousFileChannel usage drops asyncExecutors=false. + try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { + assertTrue(parseHello(app.initialHello).get("asyncExecutors").getAsBoolean()); + app.runHttpTest("ts/nio-afc", "/nio-async-file"); + JsonObject afterNio = parseHello(app.lastHello); + assertFalse("JDK AsynchronousFileChannel must drop asyncExecutors=false: " + app.lastHello, + afterNio.get("asyncExecutors").getAsBoolean()); + } + } + @Test(timeout = 120000) public void forkedKafkaListenerHookEmitsTopicAndBeanAttributionInTcpCov() throws Exception { try (ForkedApp kafka = startFork("kafka", "2000", false, false, null, null)) { @@ -367,6 +424,8 @@ private ForkedApp startFork(String mode, String endWait, boolean externalJacocoP File classes = tmp.newFolder(); for (Class cls : new Class[] { AsyncHonestyApp.class, AsyncHonestyApp.AsyncServlet.class, + AsyncHonestyApp.PreCapturedDispatcher.class, AsyncHonestyApp.LazyInWindowDispatcher.class, + AsyncHonestyApp.NioAsyncFileHelper.class, AsyncHonestyApp.SerializableOnlyExecutor.class, AsyncHonestyApp.ConcreteCustomPool.class, AsyncHonestyApp.MyWorkerThread.class, AsyncHonestyApp.VirtualThreadLauncher.class, AsyncHonestyApp.OrdersListenerBean.class, AsyncHonestyApp.FakeKafkaProps.class, @@ -621,9 +680,9 @@ 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; + Socket sdk; + BufferedReader in; + OutputStream out; final int port; final String initialHello; String lastHello; @@ -641,6 +700,21 @@ private static final class ForkedApp implements AutoCloseable { this.lastHello = initialHello; } + String reconnectAndReadHello() throws IOException { + try { + sdk.close(); + } catch (IOException ignored) { + } + Socket next = collector.accept(); + next.setSoTimeout(60000); + this.sdk = next; + this.in = new BufferedReader(new InputStreamReader(next.getInputStream(), StandardCharsets.UTF_8)); + this.out = next.getOutputStream(); + String hello = this.in.readLine(); + this.lastHello = hello; + return hello; + } + String runHttpTest(String testId, String path) throws IOException { send("START " + testId); String ack = nextNonHello(); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 3fb61f4e..cbd79670 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -111,6 +111,7 @@ public class HonestProtocolAndAsyncTest { private boolean savedObservedPreCapturedUntrackedExecutor; private Set savedCounted; private Set savedUncounted; + private Set savedUnhookedAsyncDispatchers; private long savedHandedJobMaxNanos; private String savedControlSocketPath; private String savedDataSocketPath; @@ -119,16 +120,18 @@ public class HonestProtocolAndAsyncTest { public void setUp() { savedTransformerAdded = KeployDedupAgent.transformerAdded; savedExecutorCallSitesEnabled = KeployDedupAgent.executorCallSitesEnabled; - savedObservedNoServerEntry = KeployDedupAgent.observedNoServerEntry; - savedObservedPreCapturedUntrackedExecutor = KeployDedupAgent.observedPreCapturedUntrackedExecutor; + savedObservedNoServerEntry = KeployDedupAgent.observedNoServerEntry.get(); + savedObservedPreCapturedUntrackedExecutor = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); savedCounted = ServerEntries.snapshotCounted(); savedUncounted = ServerEntries.snapshotUncounted(); + savedUnhookedAsyncDispatchers = ServerEntries.snapshotUnhookedAsyncDispatchers(); savedHandedJobMaxNanos = JobGate.handedJobMaxNanos; savedControlSocketPath = KeployDedupAgent.controlSocketPath; savedDataSocketPath = KeployDedupAgent.dataSocketPath; - KeployDedupAgent.observedNoServerEntry = false; - KeployDedupAgent.observedPreCapturedUntrackedExecutor = false; + KeployDedupAgent.observedNoServerEntry.set(false); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); ServerEntries.restoreUncounted(Collections.emptySet()); + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); ServerEntries.setHookStatusForTests(false, false, false); RequestGate.disarm(); RequestGate.open(); @@ -144,10 +147,11 @@ public void tearDown() throws IOException { } KeployDedupAgent.transformerAdded = savedTransformerAdded; KeployDedupAgent.executorCallSitesEnabled = savedExecutorCallSitesEnabled; - KeployDedupAgent.observedNoServerEntry = savedObservedNoServerEntry; - KeployDedupAgent.observedPreCapturedUntrackedExecutor = savedObservedPreCapturedUntrackedExecutor; + KeployDedupAgent.observedNoServerEntry.set(savedObservedNoServerEntry); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedObservedPreCapturedUntrackedExecutor); ServerEntries.restoreCounted(savedCounted); ServerEntries.restoreUncounted(savedUncounted); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhookedAsyncDispatchers); ServerEntries.setHookStatusForTests(false, false, false); JobGate.handedJobMaxNanos = savedHandedJobMaxNanos; KeployDedupAgent.controlSocketPath = savedControlSocketPath; @@ -4030,8 +4034,79 @@ public void methodReferencesToNonExecutorHelpersAreNotFlaggedWhileRealExecutorsS 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); + assertTrue("in-window real executor method refs must also latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } + + public static final class AsyncMethodRefThreadStartCaller { + private static volatile java.util.function.Consumer captured; + + public static void capture() { + captured = Thread::start; + } + + public static void invoke(Thread t) { + captured.accept(t); + } + } + + public static final class AsyncMethodRefCfRunAsyncCaller { + private static volatile java.util.function.Function> captured; + + public static void capture() { + captured = CompletableFuture::runAsync; + } + + public static CompletableFuture invoke(Runnable r) { + return captured.apply(r); + } + } + + public static final class AsyncMethodRefScheduleCaller { + private static volatile ScheduleTriFn captured; + + @FunctionalInterface + public interface ScheduleTriFn { + java.util.concurrent.ScheduledFuture apply(Runnable r, long delay, TimeUnit unit); + } + + public static void capture(java.util.concurrent.ScheduledExecutorService sched) { + captured = sched::schedule; + } + + public static java.util.concurrent.ScheduledFuture invoke(Runnable r, long delay, TimeUnit unit) { + return captured.apply(r, delay, unit); + } + } + + public static final class LazyInWindowExecutorRefCaller { + private static volatile java.util.function.Consumer cachedBound; + private static volatile java.util.function.BiConsumer cachedUnbound; + + public static void reset() { + cachedBound = null; + cachedUnbound = null; + } + + public static void callBound(Executor pool, Runnable task) { + if (cachedBound == null) { + cachedBound = pool::execute; + } + cachedBound.accept(task); + } + + public static void callUnbound(Executor pool, Runnable task) { + if (cachedUnbound == null) { + cachedUnbound = Executor::execute; + } + cachedUnbound.accept(pool, task); + } + } + + public static final class FakeNioAsyncChannelApp { + public static java.nio.channels.AsynchronousFileChannel openReadOnly(java.nio.file.Path p) throws IOException { + return java.nio.channels.AsynchronousFileChannel.open(p, java.nio.file.StandardOpenOption.READ); + } } public static final class PreCapturedBoundExecCaller { @@ -4147,8 +4222,8 @@ public void preCapturedExecutorMethodRefLatchesAsyncExecutorsFalseOnTcpAndUnix() // and stays permanently latched across reconnect and subsequent windows. KeployDedupAgent.transformerAdded = true; KeployDedupAgent.executorCallSitesEnabled = true; - KeployDedupAgent.observedNoServerEntry = false; - KeployDedupAgent.observedPreCapturedUntrackedExecutor = false; + KeployDedupAgent.observedNoServerEntry.set(false); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); ServerEntries.restoreCounted(Collections.emptySet()); ServerEntries.restoreUncounted(Collections.emptySet()); @@ -4173,7 +4248,7 @@ public void preCapturedExecutorMethodRefLatchesAsyncExecutorsFalseOnTcpAndUnix() // 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); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); // Next START refreshes HELLO with asyncExecutors=false BEFORE ACK! send(out, "START ts/precaptured-1"); @@ -4231,30 +4306,38 @@ public void preCapturedExecutorMethodRefLatchesAsyncExecutorsFalseOnTcpAndUnix() 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); + // 2. Startup (disarmed) AND armed-outside-window capture for ALL four executor + // method-ref forms (bound/unbound execute/submit) latch asyncExecutors=false! + String[] variants = new String[] {"boundExec", "boundSubmit", "unboundExec", "unboundSubmit"}; + for (boolean armedState : new boolean[] {false, true}) { + for (String variant : variants) { + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + if (armedState) { + RequestGate.arm(); + } else { + RequestGate.disarm(); + } + if ("boundExec".equals(variant)) { + boundExec.getMethod("capture", Object.class).invoke(null, tpe); + } else 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 + " (armed=" + armedState + ") must latch observedPreCapturedUntrackedExecutor", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + JsonObject h = parseHello(connectAndReadHello(true)); + assertTrue(variant + " keeps windowCut=true", h.get("windowCut").getAsBoolean()); + assertFalse(variant + " (armed=" + armedState + ") must report asyncExecutors=false on HELLO", + h.get("asyncExecutors").getAsBoolean()); } - 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; + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); System.clearProperty(ENDPOINT_PROPERTY); File sockDir = tmp.newFolder("unix-precaptured-exec"); KeployDedupAgent.controlSocketPath = new File(sockDir, "ctrl.sock").getAbsolutePath(); @@ -4288,7 +4371,7 @@ public void preCapturedExecutorMethodRefLatchesAsyncExecutorsFalseOnTcpAndUnix() // Capture outside any window. boundExec.getMethod("capture", Object.class).invoke(null, tpe); - assertTrue(KeployDedupAgent.observedPreCapturedUntrackedExecutor); + assertTrue(KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); String ack2 = sendUnixControl("START ts/u-pre-2"); assertTrue("Unix START after pre-capture must refresh asyncExecutors=false: " + ack2, @@ -4338,8 +4421,8 @@ public void preCapturedNonExecutorAndInlineMethodRefsDoNotLatchAsyncExecutors() ServerEntries.markSpringExecutorHookedForTests(springExec.getClass().getName()); KeployDedupAgent.transformerAdded = true; KeployDedupAgent.executorCallSitesEnabled = true; - KeployDedupAgent.observedNoServerEntry = false; - KeployDedupAgent.observedPreCapturedUntrackedExecutor = false; + KeployDedupAgent.observedNoServerEntry.set(false); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); ServerEntries.restoreCounted(Collections.emptySet()); ServerEntries.restoreUncounted(Collections.emptySet()); @@ -4351,7 +4434,7 @@ public void preCapturedNonExecutorAndInlineMethodRefsDoNotLatchAsyncExecutors() org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.class) .invoke(null, syncExec, springExec); assertFalse("disarmed pre-capture of TxHelper/inline/hooked-Spring must NOT latch", - KeployDedupAgent.observedPreCapturedUntrackedExecutor); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); // 2. Capture outside any window while ARMED -> must NOT latch! RequestGate.arm(); @@ -4361,7 +4444,7 @@ public void preCapturedNonExecutorAndInlineMethodRefsDoNotLatchAsyncExecutors() 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); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); // 3. TCP HELLO keeps asyncExecutors=true! JsonObject hello = parseHello(connectAndReadHello(true)); @@ -4404,13 +4487,455 @@ public void preCapturedNonExecutorAndInlineMethodRefsDoNotLatchAsyncExecutors() 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); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); } finally { ServerEntries.unmarkSpringExecutorHookedForTests(springExec.getClass().getName()); springExec.shutdown(); } } + @Test(timeout = 60000) + public void inWindowLazyExecutorMethodRefCaptureLatchesAndCoversLaterWindowsOnTcpAndUnix() throws Exception { + Class lazyCaller = rewriteClassWithWrapExecutorCalls(LazyInWindowExecutorRefCaller.class); + + byte[] shopBytes = new byte[] {71, 72, 73}; + File shop = new File(tmp.newFolder("lazy-inwindow-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", 3); + + ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + try { + // 1. TCP transport (bound and unbound lazy capture in W1 -> W2 invoke -> W3 clean). + for (String methodName : new String[] {"callBound", "callUnbound"}) { + lazyCaller.getMethod("reset").invoke(null); + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + KeployDedupAgent.observedNoServerEntry.set(false); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(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(methodName + " initial HELLO asyncExecutors=true", + initial.get("asyncExecutors").getAsBoolean()); + send(out, "ACK_ID"); + + // W1: lazy capture inside request window -> contaminates W1 AND refreshes HELLO before COV! + send(out, "START ts/w1"); + assertEquals("ACK ts/w1", in.readLine()); + CountDownLatch w1Ran = new CountDownLatch(1); + Object tok1 = RequestGate.enter(); + try { + probes[1] = true; + lazyCaller.getMethod(methodName, Executor.class, Runnable.class) + .invoke(null, tpe, (Runnable) w1Ran::countDown); + } finally { + RequestGate.exit(tok1); + } + assertTrue(w1Ran.await(5, TimeUnit.SECONDS)); + send(out, "END ts/w1"); + JsonObject refreshed = parseHello(in.readLine()); + assertTrue(methodName + " keeps windowCut=true", + refreshed.get("windowCut").getAsBoolean()); + assertFalse(methodName + " W1 in-window capture must refresh HELLO asyncExecutors=false BEFORE COV", + refreshed.get("asyncExecutors").getAsBoolean()); + String cov1 = in.readLine(); + assertTrue(methodName + " W1 COV must carry untracked-executor: " + cov1, + cov1.contains("untracked-executor:")); + assertEquals("ACK ts/w1", in.readLine()); + + // W2: invokes already-cached ref -> HELLO already says asyncExecutors=false (never reverts). + send(out, "START ts/w2"); + assertEquals("ACK ts/w2", in.readLine()); + CountDownLatch w2Ran = new CountDownLatch(1); + Object tok2 = RequestGate.enter(); + try { + probes[1] = true; + lazyCaller.getMethod(methodName, Executor.class, Runnable.class) + .invoke(null, tpe, (Runnable) () -> { + probes[0] = true; + w2Ran.countDown(); + }); + } finally { + RequestGate.exit(tok2); + } + assertTrue(w2Ran.await(5, TimeUnit.SECONDS)); + send(out, "END ts/w2"); + assertTrue(in.readLine().startsWith("COV ")); + assertEquals("ACK ts/w2", in.readLine()); + } + + // Reconnect keeps asyncExecutors=false permanently latched. + try (Socket sdk2 = collector.accept()) { + sdk2.setSoTimeout(30000); + BufferedReader in2 = new BufferedReader( + new InputStreamReader(sdk2.getInputStream(), StandardCharsets.UTF_8)); + JsonObject reconn = parseHello(in2.readLine()); + assertFalse(methodName + " reconnect keeps asyncExecutors=false", + reconn.get("asyncExecutors").getAsBoolean()); + } + } finally { + KeployDedupAgent.stop(); + collector.close(); + collector = null; + System.clearProperty(ENDPOINT_PROPERTY); + } + } + + // 2. Unix transport: lazy in-window capture flips END ACK caps to asyncExecutors=false. + lazyCaller.getMethod("reset").invoke(null); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + File sockDir = tmp.newFolder("unix-lazy-inwindow"); + 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. + } + } catch (IOException ignored) { + } + } + }, "unix-lazy-inwindow-reader"); + dataReader.setDaemon(true); + dataReader.start(); + try { + assertTrue(KeployDedupAgent.start()); + String start1 = sendUnixControl("START ts/u-lazy-1"); + assertTrue("Unix START before lazy capture reports asyncExecutors=true: " + start1, + start1.contains("asyncExecutors=true")); + CountDownLatch ran = new CountDownLatch(1); + Object tok = RequestGate.enter(); + try { + lazyCaller.getMethod("callBound", Executor.class, Runnable.class) + .invoke(null, tpe, (Runnable) ran::countDown); + } finally { + RequestGate.exit(tok); + } + assertTrue(ran.await(5, TimeUnit.SECONDS)); + String end1 = sendUnixControl("END ts/u-lazy-1"); + assertTrue("Unix END after in-window lazy capture must report asyncExecutors=false: " + end1, + end1.contains("asyncExecutors=false")); + String start2 = sendUnixControl("START ts/u-lazy-2"); + assertTrue("Unix W2 stays asyncExecutors=false: " + start2, + start2.contains("asyncExecutors=false")); + } finally { + KeployDedupAgent.stop(); + dataServer.close(); + } + } finally { + tpe.shutdownNow(); + } + } + + @Test(timeout = 60000) + public void asyncMethodRefsThreadStartCfRunAsyncAndScheduleLatchAndContaminate() throws Exception { + Class threadCaller = rewriteClassWithWrapExecutorCalls(AsyncMethodRefThreadStartCaller.class); + Class cfCaller = rewriteClassWithWrapExecutorCalls(AsyncMethodRefCfRunAsyncCaller.class); + Class schedCaller = rewriteClassWithWrapExecutorCalls(AsyncMethodRefScheduleCaller.class); + + byte[] shopBytes = new byte[] {74, 75, 76}; + File shop = new File(tmp.newFolder("async-mref-classes"), "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, shop.getParentFile().getParentFile().getParent()); + + java.util.concurrent.ScheduledExecutorService sched = + java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); + try { + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + KeployDedupAgent.observedNoServerEntry.set(false); + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + + String[][] cases = new String[][] { + {"thread", "untracked-async:method-ref:java.lang.Thread.start"}, + {"cf", "untracked-async:method-ref:java.util.concurrent.CompletableFuture.runAsync"}, + {"sched", "untracked-async:method-ref:java.util.concurrent.ScheduledExecutorService.schedule"} + }; + for (String[] tc : cases) { + String kind = tc[0]; + String wantReason = tc[1]; + + // 1. Disarmed capture -> latches asyncExecutors=false on TCP HELLO. + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + invokeAsyncMethodRefCapture(kind, threadCaller, cfCaller, schedCaller, sched); + assertTrue(kind + " disarmed capture must latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + JsonObject hDisarmed = parseHello(connectAndReadHello(true)); + assertFalse(kind + " disarmed HELLO must say asyncExecutors=false", + hDisarmed.get("asyncExecutors").getAsBoolean()); + + // 2. Armed outside-window capture -> latches asyncExecutors=false on Unix ACK. + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.arm(); + invokeAsyncMethodRefCapture(kind, threadCaller, cfCaller, schedCaller, sched); + assertTrue(kind + " armed-outside capture must latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + File sockDir = tmp.newFolder("unix-async-mref-" + kind); + 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-mref-" + kind); + assertTrue(kind + " Unix ACK must say asyncExecutors=false: " + ack, + ack.startsWith("ACK proto=3") && ack.contains("asyncExecutors=false")); + } finally { + KeployDedupAgent.stop(); + } + + // 3. Armed inside-window capture -> contaminates window with wantReason AND latches! + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + RequestGate.open("mref-async-" + kind, null); + Object tok = RequestGate.enter(); + try { + invokeAsyncMethodRefCapture(kind, threadCaller, cfCaller, schedCaller, sched); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue(kind + " in-window capture must contaminate with " + wantReason + ": " + out.contaminations, + out.contaminations.contains(wantReason)); + assertTrue(kind + " in-window capture must also latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } + } finally { + sched.shutdownNow(); + } + } + + private static byte[] readClassBytes(Class cls) throws IOException { + String resource = cls.getName().replace('.', '/') + ".class"; + try (java.io.InputStream in = cls.getClassLoader().getResourceAsStream(resource)) { + assertNotNull("class bytes not found for " + resource, in); + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int n; + while ((n = in.read(buf)) >= 0) { + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } + + private static void invokeAsyncMethodRefCapture(String kind, Class threadCaller, Class cfCaller, + Class schedCaller, java.util.concurrent.ScheduledExecutorService sched) throws Exception { + if ("thread".equals(kind)) { + threadCaller.getMethod("capture").invoke(null); + } else if ("cf".equals(kind)) { + cfCaller.getMethod("capture").invoke(null); + } else { + schedCaller.getMethod("capture", java.util.concurrent.ScheduledExecutorService.class).invoke(null, sched); + } + } + + @Test(timeout = 60000) + public void springMulticasterPlainPoolAndUnhookedLibraryAsyncDispatchersDropAsyncExecutors() throws Exception { + byte[] shopBytes = new byte[] {77, 78, 79}; + File shop = new File(tmp.newFolder("unhooked-async-dispatchers"), "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; + KeployDedupAgent.observedNoServerEntry.set(false); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + + // 1. Spring SimpleApplicationEventMulticaster.setTaskExecutor bytecode hook: + // - null, SyncTaskExecutor, and hooked ThreadPoolTaskExecutor (initialized OR pending init) keep asyncExecutors=true. + // - plain JDK ThreadPoolExecutor latches asyncExecutors=false (both disarmed and armed) and contaminates inside window. + byte[] multicasterBytes = readClassBytes( + org.springframework.context.event.SimpleApplicationEventMulticaster.class); + byte[] hookedBytes = ServerEntries.wrapSpringEventMulticaster(multicasterBytes); + assertNotNull("SimpleApplicationEventMulticaster.setTaskExecutor must be instrumented", hookedBytes); + // Re-wrapping must be idempotent. + byte[] hookedAgain = ServerEntries.wrapSpringEventMulticaster(hookedBytes); + assertNotNull(hookedAgain); + + ClassLoader loader = new ClassLoader(getClass().getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if ("org.springframework.context.event.SimpleApplicationEventMulticaster".equals(name)) { + Class c = defineClass(name, hookedBytes, 0, hookedBytes.length); + if (resolve) { + resolveClass(c); + } + return c; + } + return super.loadClass(name, resolve); + } + }; + Class hookedMulticaster = loader.loadClass( + "org.springframework.context.event.SimpleApplicationEventMulticaster"); + Object mc = hookedMulticaster.getConstructor().newInstance(); + java.lang.reflect.Method setExec = hookedMulticaster.getMethod("setTaskExecutor", Executor.class); + + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor springPool = + new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor(); + ThreadPoolExecutor plainPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()); + try { + ServerEntries.markSpringExecutorHookedForTests(springPool.getClass().getName()); + RequestGate.disarm(); + setExec.invoke(mc, new Object[] {null}); + setExec.invoke(mc, new org.springframework.core.task.SyncTaskExecutor()); + // Pending-init hooked Spring ThreadPoolTaskExecutor must NOT falsely latch! + setExec.invoke(mc, springPool); + springPool.initialize(); + setExec.invoke(mc, springPool); + assertFalse("null / SyncTaskExecutor / hooked Spring executor must NOT latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // Plain JDK ThreadPoolExecutor on SimpleApplicationEventMulticaster MUST latch while disarmed! + setExec.invoke(mc, plainPool); + assertTrue("SimpleApplicationEventMulticaster.setTaskExecutor(plainPool) must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + JsonObject hMc = parseHello(connectAndReadHello(true)); + assertFalse("HELLO must report asyncExecutors=false after plain-pool multicaster", + hMc.get("asyncExecutors").getAsBoolean()); + + // Inside an active window, it also contaminates! + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + RequestGate.open("mc-plain-window", null); + Object tok = RequestGate.enter(); + try { + setExec.invoke(mc, plainPool); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("in-window plain-pool setTaskExecutor must contaminate: " + out.contaminations, + out.contaminations.contains("untracked-executor:" + ThreadPoolExecutor.class.getName())); + assertTrue("in-window plain-pool setTaskExecutor must also latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + ServerEntries.unmarkSpringExecutorHookedForTests(springPool.getClass().getName()); + springPool.shutdown(); + plainPool.shutdownNow(); + } + + // 2. Class-load detection for RxJava 1/2/3, Kotlin coroutines, OkHttp Dispatcher, and NIO AsynchronousChannelGroup. + ServerEntries transformer = new ServerEntries(true, Collections.singleton("com/acme/App"), null); + String[] unhookedInternalNames = new String[] { + "rx/schedulers/Schedulers", + "io/reactivex/schedulers/Schedulers", + "io/reactivex/rxjava3/schedulers/Schedulers", + "kotlinx/coroutines/Dispatchers", + "okhttp3/Dispatcher", + "java/nio/channels/AsynchronousChannelGroup", + "sun/nio/ch/SimpleAsynchronousFileChannelImpl" + }; + for (String internalName : unhookedInternalNames) { + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + transformer.transform(getClass().getClassLoader(), internalName, null, null, new byte[0]); + assertTrue("loading " + internalName + " must mark hasUnhookedAsyncDispatcher", + ServerEntries.hasUnhookedAsyncDispatcher()); + JsonObject h = parseHello(connectAndReadHello(true)); + assertFalse("HELLO must report asyncExecutors=false after loading " + internalName, + h.get("asyncExecutors").getAsBoolean()); + } + + // 3. App-class constant-pool scan catches JDK AsynchronousFileChannel even when JDK class loaded before premain! + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + byte[] nioAppBytes = readClassBytes(FakeNioAsyncChannelApp.class); + transformer.transform(getClass().getClassLoader(), "com/acme/App", null, null, nioAppBytes); + assertTrue("app class referencing AsynchronousFileChannel must mark hasUnhookedAsyncDispatcher", + ServerEntries.hasUnhookedAsyncDispatcher()); + JsonObject hNio = parseHello(connectAndReadHello(true)); + assertFalse("HELLO must report asyncExecutors=false when app uses AsynchronousFileChannel", + hNio.get("asyncExecutors").getAsBoolean()); + } + + @Test(timeout = 60000) + public void helloRefreshFailureSendsFailClosedFallbackHelloAndTagsCovUnverifiedWhenLatched() throws Exception { + byte[] shopBytes = new byte[] {80, 81, 82}; + File shop = new File(tmp.newFolder("hello-refresh-fail-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); + + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + KeployDedupAgent.observedNoServerEntry.set(false); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + + 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)); + JsonObject initial = parseHello(in.readLine()); + assertTrue("initial HELLO starts honest", initial.get("asyncExecutors").getAsBoolean()); + send(out, "ACK_ID"); + + // Latch asyncExecutors=false AND inject HELLO refresh failure on END! + send(out, "START ts/refresh-fail"); + assertEquals("ACK ts/refresh-fail", in.readLine()); + Object tok = RequestGate.enter(); + try { + probes[1] = true; + KeployDedupAgent.noteObservedUntrackedMethodRef("java.util.concurrent.ThreadPoolExecutor::execute", true); + } finally { + RequestGate.exit(tok); + } + KeployDedupAgent.testHelloFailure = new RuntimeException("simulated mid-session HELLO refresh failure"); + try { + send(out, "END ts/refresh-fail"); + // Must emit fail-closed all-false fallback HELLO before COV! + JsonObject fallback = parseHello(in.readLine()); + assertFalse("fallback HELLO must set windowCut=false", fallback.get("windowCut").getAsBoolean()); + assertFalse("fallback HELLO must set asyncExecutors=false", + fallback.get("asyncExecutors").getAsBoolean()); + String cov = in.readLine(); + assertTrue("COV must carry unverified untracked-async backstop on HELLO refresh failure: " + cov, + cov.contains("\"unverified\":[\"untracked-async\"]")); + assertEquals("ACK ts/refresh-fail", in.readLine()); + } finally { + KeployDedupAgent.testHelloFailure = null; + } + } + } + @Test(timeout = 60000) public void observedNoServerEntryLatchesWindowCutFalseBeforeCovAndAcrossReconnect() throws Exception { byte[] shopBytes = new byte[] {41, 42, 43}; @@ -4424,7 +4949,7 @@ public void observedNoServerEntryLatchesWindowCutFalseBeforeCovAndAcrossReconnec // in ServerEntries.UNCOUNTED so initial HELLO starts with windowCut=true, asyncExecutors=true. KeployDedupAgent.transformerAdded = true; KeployDedupAgent.executorCallSitesEnabled = true; - KeployDedupAgent.observedNoServerEntry = false; + KeployDedupAgent.observedNoServerEntry.set(false); ServerEntries.restoreCounted(Collections.emptySet()); ServerEntries.restoreUncounted(Collections.emptySet()); diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index 9fdbd97c..dd0d9b96 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -89,7 +89,10 @@ public static void main(String[] args) throws Exception { String mode = args[0]; AutoCloseable server; int port; - if ("tomcat".equals(mode)) { + if ("tomcat".equals(mode) || "precaptured-tomcat".equals(mode)) { + if ("precaptured-tomcat".equals(mode)) { + PreCapturedDispatcher.touch(); + } File base = Files.createTempDirectory("tomcat-honesty").toFile(); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir(base.getPath()); @@ -240,6 +243,19 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO }); } else if ("/method-ref".equals(path)) { Collections.singletonList(() -> AsyncTail.ran()).forEach(PLAIN_POOL::execute); + } else if ("/lazy-method-ref".equals(path)) { + LazyInWindowDispatcher.dispatch(PLAIN_POOL, () -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + } else if ("/spring-multicaster-plain".equals(path)) { + org.springframework.context.event.SimpleApplicationEventMulticaster mc = + new org.springframework.context.event.SimpleApplicationEventMulticaster(); + mc.setTaskExecutor(PLAIN_POOL); + AsyncTail.ran(); + } else if ("/nio-async-file".equals(path)) { + NioAsyncFileHelper.touch(); + AsyncTail.ran(); } else if ("/virtual-thread-latch".equals(path)) { final java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); VIRTUAL_RELEASE_LATCH = release; @@ -292,6 +308,36 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } } + public static final class PreCapturedDispatcher { + private static final java.util.function.Consumer DISPATCH = PLAIN_POOL::execute; + + public static void touch() { + DISPATCH.accept(() -> { }); + } + } + + public static final class LazyInWindowDispatcher { + private static volatile java.util.function.Consumer cached; + + public static void dispatch(java.util.concurrent.Executor pool, Runnable task) { + if (cached == null) { + cached = pool::execute; + } + cached.accept(task); + } + } + + public static final class NioAsyncFileHelper { + public static void touch() throws IOException { + File f = File.createTempFile("keploy-nio-honesty", ".tmp"); + f.deleteOnExit(); + try (java.nio.channels.AsynchronousFileChannel ch = java.nio.channels.AsynchronousFileChannel.open( + f.toPath(), java.nio.file.StandardOpenOption.READ)) { + ch.size(); + } + } + } + public static final class ConcreteCustomPool extends ThreadPoolExecutor { public ConcreteCustomPool() { super(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), r -> { diff --git a/scripts/smoke-javaagent.sh b/scripts/smoke-javaagent.sh index b98d7a44..05bea5b6 100755 --- a/scripts/smoke-javaagent.sh +++ b/scripts/smoke-javaagent.sh @@ -185,8 +185,9 @@ public final class SmokeHarness { // Keploy fires its first test as soon as the app answers a health // check, so the agent has to be listening before main runs. This START // is main's first act and nothing waits for the control socket: an - // agent that binds it any later fails here. - command("START test-set-0/" + mode); + // agent that binds it any later fails here. Before any serverless END + // runs, windowCut is still true. + command("START test-set-0/" + mode, true); delete(DATA_SOCKET); @@ -218,7 +219,9 @@ public final class SmokeHarness { if (Work.exercise(1) != 4) { throw new IllegalStateException("unexpected application result"); } - command("END test-set-0/" + mode); + // Serverless END records probes with enteredCount == 0, latching + // windowCut=false (and asyncExecutors=false) for the rest of the JVM. + command("END test-set-0/" + mode, false); String json = next(records, mode); String report = null; @@ -230,10 +233,15 @@ public final class SmokeHarness { // e.g. "smoke/Work" — not a source file like "Work.java". JaCoCo's id // of each class the app ran is the id of the bytes the index read, // so the record names no class in classMismatch: one named here - // would lose that class's coverage in Keploy. + // would lose that class's coverage in Keploy. Serverless runs also + // carry exact trailing "unverified":["no-server-entry"] with no + // contaminated or windowCut flags. if (!json.contains("\"id\":\"test-set-0/" + mode + "\"") || !json.contains("smoke/Work") - || json.contains("\"classMismatch\"")) { + || json.contains("\"classMismatch\"") + || json.contains("\"contaminated\"") + || json.contains("\"windowCut\"") + || !json.endsWith("},\"unverified\":[\"no-server-entry\"]}")) { throw new IllegalStateException("unexpected coverage payload for " + mode + ": " + json); } if (report == null @@ -303,16 +311,18 @@ public final class SmokeHarness { URLClassLoader loader = new URLClassLoader(new URL[] {new File(dir).toURI().toURL()}, null); try { Class other = Class.forName("smoke.Work", false, loader); - command("START " + id); + command("START " + id, false); Object result = other.getMethod("exercise", int.class).invoke(null, 1); - command("END " + id); + command("END " + id, false); if (!Integer.valueOf(3).equals(result)) { throw new IllegalStateException("the copy in " + dir + " did not run in " + mode + ": " + result); } String json = next(records, mode); if (!json.contains("\"id\":\"" + id + "\"") || !json.contains("\"smoke/Work\":[") - || !json.contains(",\"classMismatch\":[\"smoke/Work\"]")) { + || json.contains("\"contaminated\"") + || json.contains("\"windowCut\"") + || !json.endsWith(",\"classMismatch\":[\"smoke/Work\"],\"unverified\":[\"no-server-entry\"]}")) { 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); } @@ -375,17 +385,22 @@ public final class SmokeHarness { } } - private static void command(String command) throws Exception { + private static void command(String command, boolean wantWindowCut) throws Exception { try (AFUNIXSocket socket = AFUNIXSocket.newInstance()) { socket.connect(AFUNIXSocketAddress.of(CONTROL_SOCKET), 3000); OutputStream output = socket.getOutputStream(); output.write((command + "\n").getBytes(StandardCharsets.UTF_8)); output.flush(); - // The whole answer: one line saying the command was taken (proto=3 - // with capability flags), then the close. + // The whole answer: one line saying the command was taken (exact + // proto=3 caps grammar with pinned windowCut state), then the close. String ack = readAll(socket.getInputStream()); - if (!ack.startsWith("ACK proto=3 ") || !ack.contains("caps=") || !ack.endsWith("\n")) { - throw new IllegalStateException("not taken: " + command + ": " + ack); + String pattern = "^ACK proto=3 caps=windowCut=" + wantWindowCut + + ",contaminated=true,classMismatch=true,background=(true|false),ackId=true,asyncExecutors=" + + (wantWindowCut ? "(true|false)" : "false") + + ",listenerContamination=(true|false)\\n$"; + if (!ack.matches(pattern)) { + throw new IllegalStateException("unexpected ACK for " + command + " (wantWindowCut=" + + wantWindowCut + "): " + ack); } } } @@ -750,10 +765,14 @@ public final class TomcatHarness { || !json.contains("\"id\":\"" + id + "\"") || !json.contains("\"" + ADAPTER + "\":[") || !json.contains("\"smoke/TomcatHarness$Tail\":[") - || json.contains("\"classMismatch\"")) { + || json.contains("\"classMismatch\"") + || json.contains("\"unverified\"") + || json.contains("\"contaminated\"") + || json.contains("\"windowCut\"")) { throw new IllegalStateException("the record of a request to Tomcat, with JaCoCo attached after" + " keploy-sdk.jar, does not measure " + ADAPTER + " and the servlet's code after the" - + " response with no class in classMismatch in " + mode + " (body " + body + "): " + json); + + " response with no class in classMismatch or unverified/contaminated/windowCut in " + + mode + " (body " + body + "): " + json); } System.out.println(mode + ": " + json); tomcat.stop(); @@ -781,8 +800,11 @@ public final class TomcatHarness { output.write((command + "\n").getBytes(StandardCharsets.UTF_8)); output.flush(); String ack = readAll(socket.getInputStream()); - if (!ack.startsWith("ACK proto=3 ") || !ack.contains("caps=") || !ack.endsWith("\n")) { - throw new IllegalStateException("not taken: " + command + ": " + ack); + String pattern = "^ACK proto=3 caps=windowCut=true,contaminated=true,classMismatch=true," + + "background=(true|false),ackId=true,asyncExecutors=(true|false)," + + "listenerContamination=(true|false)\\n$"; + if (!ack.matches(pattern)) { + throw new IllegalStateException("unexpected ACK for " + command + ": " + ack); } } } From b789b3185864a0eb6c2187364ad4f54f8af23240 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Sat, 28 Nov 2026 07:58:12 +0530 Subject: [PATCH 21/26] fix(dedup): stop Tomcat NIO2 false latch, detect 5 async hand-offs, and harden fallback/overflow honesty - Decide SEEN_UNHOOKED_ASYNC_DISPATCHERS strictly from app-code constant-pool references (CONSTANT_Class and reflective CONSTANT_String) instead of JVM-wide class loads so Tomcat's own NIO2 connector never false-latches asyncExecutors=false, and log once at INFO naming dispatcher + source class. - Catch five additional async hand-offs: Spring ListenableFuture.addCallback, JDK SubmissionPublisher.submit/offer, BlockingQueue enqueue calls (static + Queue runtime instanceof check), SimpleApplicationEventMulticaster.multicastEvent virtual getTaskExecutor() overrides, and Kafka/Rabbit/JMS messaging producers plus JobGate kafka/listener fail-closed latch. - Latch asyncExecutors=false on >64 live untracked async handle overflow, preserve cached identity fields in failClosedFallbackHello, and catch RuntimeException | LinkageError consistently on Unix unixReplyTaken. - Pin scripts/smoke-javaagent.sh Tomcat ACK check to asyncExecutors=true (with 2-part package smoke.app.TomcatHarness) and add forked -javaagent e2e + unit tests covering Tomcat /clean asyncExecutors=true, all five async hand-offs (prefix + index modes), Spring multicaster orders() failure, asyncHookFailed, 64-handle overflow, and cached/initial fallback HELLO. Signed-off-by: slayerjain --- .../main/java/io/keploy/dedup/JobGate.java | 8 + .../io/keploy/dedup/KeployDedupAgent.java | 53 ++++- .../java/io/keploy/dedup/RequestGate.java | 13 ++ .../java/io/keploy/dedup/ServerEntries.java | 189 ++++++++++++++++-- .../fakeexternal/FakeExternalHttpClient.java | 78 ++++++++ .../dedup/ForkedAsyncAndHonestyTest.java | 90 +++++++-- .../dedup/HonestProtocolAndAsyncTest.java | 165 ++++++++++++++- .../org/example/servers/AsyncHonestyApp.java | 146 +++++++++++--- scripts/smoke-javaagent.sh | 16 +- 9 files changed, 679 insertions(+), 79 deletions(-) create mode 100644 keploy-sdk/src/test/java/io/fakeexternal/FakeExternalHttpClient.java 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 d5720b1c..f9f11ac8 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -112,6 +112,14 @@ public static Object enter(Object job, String kind) { try { run = new Run(name(job, kind), CURRENT.get(), false, 0L); begin(run); + if ("kafka".equals(kind) || "listener".equals(kind)) { + // An async message listener firing during a round may be consuming + // a message produced by an earlier HTTP test whose window already + // closed; fail closed on asyncExecutors so earlier windows are not + // hard-removed without their downstream listener coverage. + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "async message listener (" + run.name + ")", true); + } } catch (Throwable t) { // The job runs on. A run counted as going on before this (an // OutOfMemoryError on the job's thread as the window counts it) 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 9215399e..a1f51f85 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -1250,7 +1250,7 @@ private boolean run(String line) { private String unixReplyTaken() { try { return computeCapabilities(collector).toUnixAck(); - } catch (RuntimeException e) { + } catch (RuntimeException | LinkageError e) { log(Level.FINE, "Failed to compute live Unix capabilities; falling back to bare ACK proto=3", e); return UNIX_REPLY_TAKEN; } @@ -1472,12 +1472,54 @@ private static final class CoverageTcpClient implements CoverageWorker { + "\"windowCut\":false,\"contaminated\":false,\"classMismatch\":false,\"background\":false," + "\"ackId\":true,\"nopResync\":true,\"asyncExecutors\":false,\"listenerContamination\":false}"; + private volatile String cachedSdkVersion = ""; + private volatile String cachedPodUid = ""; + private volatile String cachedPodName = ""; + private volatile String cachedSessionId = ""; + private volatile String cachedJvmNonce = ""; + private volatile String cachedBuildId = ""; + private String helloFrame() { RuntimeException injected = testHelloFailure; if (injected != null) { throw injected; } - return computeCapabilities(collector).toHelloFrame(collector.helloBuildId()); + String sdkVersion = IndexReport.versionOf(IndexReport.class); + String podUid = envOrProperty("KEPLOY_DEDUP_POD_UID", "keploy.dedup.pod.uid", ""); + String podName = envOrProperty("KEPLOY_DEDUP_POD_NAME", "keploy.dedup.pod.name", ""); + String sessionId = envOrProperty("KEPLOY_DEDUP_SESSION_ID", "keploy.dedup.session.id", ""); + String nonce = jvmNonce(); + String buildId = collector.helloBuildId(); + cachedSdkVersion = sdkVersion == null ? "" : sdkVersion; + cachedPodUid = podUid == null ? "" : podUid; + cachedPodName = podName == null ? "" : podName; + cachedSessionId = sessionId == null ? "" : sessionId; + cachedJvmNonce = nonce == null ? "" : nonce; + cachedBuildId = buildId == null ? "" : buildId; + Capabilities caps = computeCapabilities(collector); + return buildHelloFrame(cachedSdkVersion, cachedPodUid, cachedPodName, cachedSessionId, + cachedJvmNonce, cachedBuildId, + caps.windowCut, caps.contaminated, caps.classMismatch, caps.background, + true, true, caps.asyncExecutors, caps.listenerContamination); + } + + private String failClosedFallbackHello() { + String sdk = cachedSdkVersion; + String uid = cachedPodUid; + String pod = cachedPodName; + String sid = cachedSessionId; + String nonce = cachedJvmNonce; + String bid = cachedBuildId; + if (sdk.isEmpty() && uid.isEmpty() && pod.isEmpty() && sid.isEmpty() + && nonce.isEmpty() && bid.isEmpty()) { + return FAIL_CLOSED_FALLBACK_HELLO; + } + try { + return buildHelloFrame(sdk, uid, pod, sid, nonce, bid, + false, false, false, false, true, true, false, false); + } catch (RuntimeException | LinkageError ignored) { + return FAIL_CLOSED_FALLBACK_HELLO; + } } private void maybeSendUpdatedHello(OutputStream out) throws IOException { @@ -1495,9 +1537,10 @@ private boolean refreshHelloOrFallback(OutputStream out, String phase) throws IO } catch (RuntimeException | LinkageError e) { log(Level.FINE, "Failed to refresh HELLO during " + phase + "; sending fail-closed fallback HELLO", e); - if (!FAIL_CLOSED_FALLBACK_HELLO.equals(lastHelloSent)) { - writeLine(out, FAIL_CLOSED_FALLBACK_HELLO); - lastHelloSent = FAIL_CLOSED_FALLBACK_HELLO; + String fallback = failClosedFallbackHello(); + if (!fallback.equals(lastHelloSent)) { + writeLine(out, fallback); + lastHelloSent = fallback; } return false; } 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 bc4efd1e..e73616f9 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -3101,6 +3101,13 @@ public static void noteIfUntrackedSubmit(Object receiver) { noteUntrackedAsync("untracked-executor:" + receiver.getClass().getName(), 0L); } + public static void noteIfBlockingQueue(Object receiver) { + if (!(receiver instanceof java.util.concurrent.BlockingQueue)) { + return; + } + noteUntrackedAsync("untracked-async:blocking-queue", 0L); + } + private static void recordUntrackedMethodRef(String reason, String target) { if (!armed) { noteUnarmedHandOffIfInFlight(); @@ -3464,6 +3471,8 @@ private static void noteTrackedHandle(String reason, UntrackedHandle handle, lon } externalUntrackedTailReason = effectiveReason == null || effectiveReason.isEmpty() ? "job" : effectiveReason; if (!addHandleToQueue(EXTERNAL_UNTRACKED_HANDLES, handle, now)) { + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "untracked async handle queue overflow (>64 live handles)", true); noteExternalUntrackedTail(effectiveReason, maxLingeringNanos); } return; @@ -3474,6 +3483,8 @@ private static void noteTrackedHandle(String reason, UntrackedHandle handle, lon JobGate.markUntrackedWindowOnly(jobReason); externalUntrackedTailReason = jobReason; if (!addHandleToQueue(EXTERNAL_UNTRACKED_HANDLES, handle, now)) { + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "untracked async handle queue overflow (>64 live handles)", true); noteExternalUntrackedTail(jobReason, maxLingeringNanos); } } @@ -4652,6 +4663,8 @@ private void addUntrackedHandle(UntrackedHandle handle, long now) { hadUntrackedAsync = true; if (!addHandleToQueue(untrackedHandlesQueue(true), handle, now)) { untrackedHandlesOverflowed = true; + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "untracked async handle queue overflow (>64 live handles)", true); } } 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 c2ecf38c..f410b319 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -152,8 +152,25 @@ final class ServerEntries implements ClassFileTransformer { "JDK AsynchronousServerSocketChannel"); UNHOOKED_ASYNC_DISPATCHERS.put("sun/nio/ch/SimpleAsynchronousFileChannelImpl", "JDK AsynchronousFileChannel"); UNHOOKED_ASYNC_DISPATCHERS.put("sun/nio/ch/AsynchronousChannelGroupImpl", "JDK AsynchronousChannelGroup"); + UNHOOKED_ASYNC_DISPATCHERS.put("java/util/concurrent/SubmissionPublisher", "JDK SubmissionPublisher"); } + private static final Set BLOCKING_QUEUE_OWNERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "java/util/concurrent/BlockingQueue", + "java/util/concurrent/BlockingDeque", + "java/util/concurrent/TransferQueue", + "java/util/concurrent/LinkedBlockingQueue", + "java/util/concurrent/ArrayBlockingQueue", + "java/util/concurrent/LinkedBlockingDeque", + "java/util/concurrent/PriorityBlockingQueue", + "java/util/concurrent/DelayQueue", + "java/util/concurrent/SynchronousQueue", + "java/util/concurrent/LinkedTransferQueue"))); + + private static final Set BLOCKING_QUEUE_ENQUEUE_METHODS = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList("offer", "put", "add", "offerFirst", "offerLast", "putFirst", "putLast", + "addFirst", "addLast", "transfer", "tryTransfer"))); + private static final String SPRING_EVENT_MULTICASTER = "org/springframework/context/event/SimpleApplicationEventMulticaster"; @@ -204,6 +221,27 @@ final class ServerEntries implements ClassFileTransformer { "java/util/Timer", "java/util/TimerTask", "org/springframework/scheduling/TaskScheduler", + "org/springframework/util/concurrent/ListenableFuture", + "org/springframework/util/concurrent/SettableListenableFuture", + "java/util/concurrent/SubmissionPublisher", + "java/util/concurrent/BlockingQueue", + "java/util/concurrent/BlockingDeque", + "java/util/concurrent/TransferQueue", + "java/util/concurrent/LinkedBlockingQueue", + "java/util/concurrent/ArrayBlockingQueue", + "java/util/concurrent/LinkedBlockingDeque", + "java/util/concurrent/PriorityBlockingQueue", + "java/util/concurrent/DelayQueue", + "java/util/concurrent/SynchronousQueue", + "java/util/concurrent/LinkedTransferQueue", + "java/util/Queue", + "org/springframework/kafka/core/KafkaTemplate", + "org/apache/kafka/clients/producer/KafkaProducer", + "org/apache/kafka/clients/producer/Producer", + "org/springframework/amqp/rabbit/core/RabbitTemplate", + "org/springframework/amqp/core/AmqpTemplate", + "org/springframework/jms/core/JmsTemplate", + "org/springframework/jms/core/JmsOperations", "com/google/common/util/concurrent/Futures", "com/google/common/util/concurrent/ListenableFuture", "reactor/core/publisher/Mono", @@ -221,7 +259,9 @@ final class ServerEntries implements ClassFileTransformer { "schedule", "scheduleAtFixedRate", "scheduleWithFixedDelay", "invokeAny", "fork", "subscribe", "start", "startVirtualThread", "cancel", "addListener", "addCallback", "transform", "transformAsync", "catching", "catchingAsync", - "poll", "basicConsume", "receive", "setMessageListener"))); + "poll", "basicConsume", "receive", "setMessageListener", + "offer", "put", "transfer", "tryTransfer", + "send", "sendDefault", "convertAndSend", "convertSendAndReceive", "sendAndReceive"))); // CompletableFuture *Async instance methods rewritten to RequestGate. private static final Map> CF_ASYNC_INSTANCE_METHODS = @@ -451,9 +491,14 @@ static void setHookStatusForTests(boolean serverFailed, boolean listenerFailed, static void setHookStatusForTests(boolean serverFailed, boolean listenerFailed, boolean jpmsSkipped, boolean rewriteFailed) { + setHookStatusForTests(serverFailed, listenerFailed, jpmsSkipped, rewriteFailed, false); + } + + static void setHookStatusForTests(boolean serverFailed, boolean listenerFailed, boolean jpmsSkipped, + boolean rewriteFailed, boolean asyncFailed) { serverHookFailed = serverFailed; listenerHookFailed = listenerFailed; - asyncHookFailed = false; + asyncHookFailed = asyncFailed; jpmsGuardTriggered = jpmsSkipped; appRewriteFailed = rewriteFailed; SEEN_UNHOOKED_CONSUMERS.clear(); @@ -485,19 +530,20 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (unhookedConsumer != null) { SEEN_UNHOOKED_CONSUMERS.add(unhookedConsumer); } - String unhookedAsync = UNHOOKED_ASYNC_DISPATCHERS.get(className); - if (unhookedAsync != null) { - SEEN_UNHOOKED_ASYNC_DISPATCHERS.add(unhookedAsync); - } + // Decide unhooked async dispatchers strictly from app-code references + // (scanUnhookedReferences below), NEVER from JVM-wide class loads — + // otherwise Tomcat's own NIO2 connector loading AsynchronousSocketChannel + // / AsynchronousServerSocketChannel false-latches asyncExecutors=false + // on every Tomcat / Spring Boot app. if (shouldRewriteExecutorCalls(className)) { - scanUnhookedReferences(classfileBuffer, false); + scanUnhookedReferences(className, classfileBuffer, false); if (!canAccessGate(loader, protectionDomain)) { if (seesGate(loader)) { jpmsGuardTriggered = true; } else { appRewriteFailed = true; } - scanUnhookedReferences(classfileBuffer, true); + scanUnhookedReferences(className, classfileBuffer, true); return null; } try { @@ -516,10 +562,9 @@ public byte[] transform(ClassLoader loader, String className, Class classBein // is configured, read-only CP scan still detects direct raw // Kafka/RabbitMQ/JMS consumer calls and unhooked async // dispatchers (RxJava, Kotlin coroutines, OkHttp, NIO - // Asynchronous*Channel) so capabilities stay honest without - // modifying bytecode (skipping known JMS/RabbitMQ pooling - // wrappers used by Spring Boot). - scanUnhookedReferences(classfileBuffer, true); + // Asynchronous*Channel, SubmissionPublisher) referenced by app + // classes so capabilities stay honest without modifying bytecode. + scanUnhookedReferences(className, classfileBuffer, true); } return null; } @@ -977,12 +1022,21 @@ static byte[] wrapSpringEventMulticaster(byte[] classfile) { 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 || !"setTaskExecutor".equals(name) - || !"(Ljava/util/concurrent/Executor;)V".equals(descriptor) - || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE | Opcodes.ACC_STATIC)) != 0) { + if (mv == null || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE | Opcodes.ACC_STATIC)) != 0) { + return mv; + } + final boolean isSetExec = "setTaskExecutor".equals(name) + && "(Ljava/util/concurrent/Executor;)V".equals(descriptor); + final boolean isMulticast = "multicastEvent".equals(name) + && ("(Lorg/springframework/context/ApplicationEvent;)V".equals(descriptor) + || "(Lorg/springframework/context/ApplicationEvent;Lorg/springframework/core/ResolvableType;)V" + .equals(descriptor)); + if (!isSetExec && !isMulticast) { return mv; } - found[0] = true; + if (isSetExec) { + found[0] = true; + } return new MethodVisitor(Opcodes.ASM9, mv) { private boolean injected; @@ -991,7 +1045,15 @@ public void visitCode() { super.visitCode(); if (!injected) { injected = true; - super.visitVarInsn(Opcodes.ALOAD, 1); + if (isSetExec) { + super.visitVarInsn(Opcodes.ALOAD, 1); + } else { + // Invoke this.getTaskExecutor() virtually so subclasses overriding + // getTaskExecutor() without calling setTaskExecutor() are still caught. + super.visitVarInsn(Opcodes.ALOAD, 0); + super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SPRING_EVENT_MULTICASTER, + "getTaskExecutor", "()Ljava/util/concurrent/Executor;", false); + } super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteSpringMulticasterTaskExecutor", "(Ljava/lang/Object;)V", false); } @@ -1020,7 +1082,16 @@ public void visitMaxs(int maxStack, int maxLocals) { return alreadyHooked[0] ? classfile : writer.toByteArray(); } - private static void scanUnhookedReferences(byte[] classfile, boolean includeRawConsumers) { + private static void recordUnhookedAsyncDispatcher(String dispatcher, String sourceClass) { + if (SEEN_UNHOOKED_ASYNC_DISPATCHERS.add(dispatcher)) { + String from = (sourceClass == null || sourceClass.isEmpty()) + ? "" : sourceClass.replace('/', '.'); + LOGGER.log(Level.INFO, "Keploy dedup: observed app reference to unhooked async dispatcher " + + dispatcher + " in " + from + "; declaring asyncExecutors=false"); + } + } + + private static void scanUnhookedReferences(String className, byte[] classfile, boolean includeRawConsumers) { if (classfile == null || classfile.length < 16) { return; } @@ -1031,15 +1102,30 @@ private static void scanUnhookedReferences(byte[] classfile, boolean includeRawC boolean hasRawConsumerOwner = false; for (int i = 1; i < itemCount; i++) { int offset = reader.getItem(i); - if (offset != 0 && reader.readByte(offset - 1) == 7) { + if (offset == 0) { + continue; + } + int tag = reader.readByte(offset - 1); + if (tag == 7) { String cls = reader.readUTF8(offset, buf); String unhookedAsync = UNHOOKED_ASYNC_DISPATCHERS.get(cls); if (unhookedAsync != null) { - SEEN_UNHOOKED_ASYNC_DISPATCHERS.add(unhookedAsync); + recordUnhookedAsyncDispatcher(unhookedAsync, className); } if (includeRawConsumers && RAW_CONSUMER_OWNERS.contains(cls)) { hasRawConsumerOwner = true; } + } else if (tag == 8) { + // Catch reflective Class.forName("java.util.concurrent.SubmissionPublisher") + // and similar string-literal lookups in app classes. + String literal = reader.readUTF8(offset, buf); + if (literal != null && literal.indexOf('.') > 0) { + String slash = literal.replace('.', '/'); + String unhookedAsync = UNHOOKED_ASYNC_DISPATCHERS.get(slash); + if (unhookedAsync != null) { + recordUnhookedAsyncDispatcher(unhookedAsync, className); + } + } } } if (!hasRawConsumerOwner) { @@ -1112,6 +1198,44 @@ private static boolean isTimerSchedule(String owner, String mname, String desc) && desc.startsWith("(Ljava/util/TimerTask;"); } + private static boolean isSpringListenableFutureCallback(int opcode, String owner, String mname, String desc) { + return (opcode == Opcodes.INVOKEINTERFACE || opcode == Opcodes.INVOKEVIRTUAL) + && "addCallback".equals(mname) + && desc != null + && desc.startsWith("(Lorg/springframework/util/concurrent/"); + } + + private static boolean isSubmissionPublisherCall(String owner, String mname) { + return "java/util/concurrent/SubmissionPublisher".equals(owner) + && ("submit".equals(mname) || "offer".equals(mname)); + } + + private static boolean isBlockingQueueEnqueue(String owner, String mname) { + return BLOCKING_QUEUE_OWNERS.contains(owner) && BLOCKING_QUEUE_ENQUEUE_METHODS.contains(mname); + } + + private static boolean isMessagingProducerCall(String owner, String mname) { + if (owner == null || mname == null) { + return false; + } + if ("org/springframework/kafka/core/KafkaTemplate".equals(owner)) { + return "send".equals(mname) || "sendDefault".equals(mname); + } + if ("org/apache/kafka/clients/producer/KafkaProducer".equals(owner) + || "org/apache/kafka/clients/producer/Producer".equals(owner)) { + return "send".equals(mname); + } + if ("org/springframework/amqp/rabbit/core/RabbitTemplate".equals(owner) + || "org/springframework/amqp/core/AmqpTemplate".equals(owner)) { + return "send".equals(mname) || "convertAndSend".equals(mname) || "convertSendAndReceive".equals(mname); + } + if ("org/springframework/jms/core/JmsTemplate".equals(owner) + || "org/springframework/jms/core/JmsOperations".equals(owner)) { + return "send".equals(mname) || "convertAndSend".equals(mname) || "sendAndReceive".equals(mname); + } + return false; + } + private static boolean isGuavaAsyncCall(int opcode, String owner, String mname, String desc) { if ((opcode == Opcodes.INVOKEINTERFACE || opcode == Opcodes.INVOKEVIRTUAL) && "addListener".equals(mname) @@ -1225,6 +1349,13 @@ private static boolean isAsyncMethodRefTarget(Handle h) { if ("start".equals(mname) && "(Ljava/lang/Runnable;)Ljava/lang/Thread;".equals(desc)) { return true; } + if (isSubmissionPublisherCall(owner, mname) + || isBlockingQueueEnqueue(owner, mname) + || isMessagingProducerCall(owner, mname) + || ("addCallback".equals(mname) && desc != null + && desc.startsWith("(Lorg/springframework/util/concurrent/"))) { + return true; + } return isReactorSubscribe(owner, mname); } @@ -1579,6 +1710,24 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, // Flag-only async submission sites (task untouched, 100% app-safe). if (isGuavaAsyncCall(opcode, owner, mname, desc)) { emitUntrackedFlag("untracked-async:guava-future"); + } else if (isSpringListenableFutureCallback(opcode, owner, mname, desc)) { + emitUntrackedFlag("untracked-async:spring-listenable-future"); + } else if (isSubmissionPublisherCall(owner, mname)) { + emitUntrackedFlag("untracked-async:submission-publisher"); + } else if (isBlockingQueueEnqueue(owner, mname)) { + emitUntrackedFlag("untracked-async:blocking-queue"); + } else if (isMessagingProducerCall(owner, mname)) { + emitUntrackedFlag("untracked-async:messaging-produce"); + } else if ((opcode == Opcodes.INVOKEINTERFACE || opcode == Opcodes.INVOKEVIRTUAL) + && "java/util/Queue".equals(owner) + && ("offer".equals(mname) || "add".equals(mname)) + && "(Ljava/lang/Object;)Z".equals(desc)) { + changed[0] = true; + ensureExtraStack(2); + super.visitInsn(Opcodes.DUP2); + super.visitInsn(Opcodes.POP); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "noteIfBlockingQueue", + "(Ljava/lang/Object;)V", false); } else if (opcode == Opcodes.INVOKEVIRTUAL || opcode == Opcodes.INVOKEINTERFACE) { if (isSingleArgExecutorExecute(mname, desc)) { // Decide at runtime by actual receiver (must be java.util.concurrent.Executor, diff --git a/keploy-sdk/src/test/java/io/fakeexternal/FakeExternalHttpClient.java b/keploy-sdk/src/test/java/io/fakeexternal/FakeExternalHttpClient.java new file mode 100644 index 00000000..59060025 --- /dev/null +++ b/keploy-sdk/src/test/java/io/fakeexternal/FakeExternalHttpClient.java @@ -0,0 +1,78 @@ +package io.fakeexternal; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.function.LongConsumer; + +/** + * Simulates third-party external library event loops (such as Netty, + * {@code java.net.http.HttpClient}, an AWS SDK async client, or a Kafka broker + * client) living outside the application package ({@code org.example.servers}). + */ +public final class FakeExternalHttpClient { + + private static final LinkedBlockingQueue LOOP = new LinkedBlockingQueue<>(); + private static final LinkedBlockingQueue BROKER = new LinkedBlockingQueue<>(); + + static { + Thread externalLoop = new Thread(() -> { + while (!Thread.currentThread().isInterrupted()) { + try { + LOOP.take().run(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + }, "fake-external-http-loop"); + externalLoop.setDaemon(true); + externalLoop.start(); + } + + private FakeExternalHttpClient() { + } + + public static void runAsync(final long delayMs, final Runnable task) { + LOOP.offer(() -> { + if (delayMs > 0) { + try { + Thread.sleep(delayMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + task.run(); + }); + } + + public static CompletableFuture fetchAsync(final long delayMs, final String body) { + final CompletableFuture future = new CompletableFuture<>(); + runAsync(delayMs, () -> future.complete(body)); + return future; + } + + public static void startBrokerConsumer(final long deliveryDelayMs, final LongConsumer onRecord) { + Thread container = new Thread(() -> { + while (!Thread.currentThread().isInterrupted()) { + try { + Long rec = BROKER.take(); + if (deliveryDelayMs > 0) { + Thread.sleep(deliveryDelayMs); + } + onRecord.accept(rec.longValue()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } catch (Exception e) { + e.printStackTrace(System.err); + } + } + }, "fake-kafka-container"); + container.setDaemon(true); + container.start(); + } + + public static void publishToBroker(final long payloadMs) { + BROKER.offer(Long.valueOf(payloadMs)); + } +} diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index a4e2ac32..675ba252 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -366,10 +366,15 @@ public void forkedPreCapturedAndLazyMethodRefsAndLibraryHandOffsDropAsyncExecuto // 2. Lazy in-window capture (W1 captures pool::execute, W2 invokes cached ref) flips HELLO // to asyncExecutors=false before W1's COV and stays false across W2 and reconnect. + // First assert Tomcat keeps asyncExecutors=true after a /clean window (proves Tomcat's + // own NIO2 connector never false-latches and the subsequent latch is real). try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { JsonObject initial = parseHello(app.initialHello); assertTrue("initial HELLO starts with asyncExecutors=true", initial.get("asyncExecutors").getAsBoolean()); + app.runHttpTest("ts/lazy-clean", "/clean"); + assertTrue("Tomcat must keep asyncExecutors=true after /clean window: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); String cov1 = app.runHttpTest("ts/lazy-w1", "/lazy-method-ref?ms=50"); assertTrue("W1 lazy capture must contaminate COV: " + cov1, cov1.contains("untracked-executor:")); @@ -385,6 +390,9 @@ public void forkedPreCapturedAndLazyMethodRefsAndLibraryHandOffsDropAsyncExecuto // 3. Spring SimpleApplicationEventMulticaster.setTaskExecutor(plainPool) drops asyncExecutors=false. try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { assertTrue(parseHello(app.initialHello).get("asyncExecutors").getAsBoolean()); + app.runHttpTest("ts/mc-clean", "/clean"); + assertTrue("Tomcat must keep asyncExecutors=true after /clean before multicaster test: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); app.runHttpTest("ts/spring-mc", "/spring-multicaster-plain"); JsonObject afterMc = parseHello(app.lastHello); assertFalse("Spring SimpleApplicationEventMulticaster with plain JDK pool must drop asyncExecutors=false: " @@ -394,6 +402,9 @@ public void forkedPreCapturedAndLazyMethodRefsAndLibraryHandOffsDropAsyncExecuto // 4. JDK AsynchronousFileChannel usage drops asyncExecutors=false. try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { assertTrue(parseHello(app.initialHello).get("asyncExecutors").getAsBoolean()); + app.runHttpTest("ts/nio-clean", "/clean"); + assertTrue("Tomcat must keep asyncExecutors=true after /clean before NIO test: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); app.runHttpTest("ts/nio-afc", "/nio-async-file"); JsonObject afterNio = parseHello(app.lastHello); assertFalse("JDK AsynchronousFileChannel must drop asyncExecutors=false: " + app.lastHello, @@ -401,6 +412,60 @@ public void forkedPreCapturedAndLazyMethodRefsAndLibraryHandOffsDropAsyncExecuto } } + @Test(timeout = 300000) + public void forkedLibraryAndJdkHandOffsNeverSilentlyDropAsyncLines() throws Exception { + String spec = System.getProperty("java.specification.version"); + int major = spec.startsWith("1.") ? 8 : Integer.parseInt(spec); + String[][] cases = { + {"kafka-produce", "8"}, + {"spring-listenable-callback", "8"}, + {"submission-publisher", "9"}, + {"spring-mc-override", "8"}, + {"queue-worker", "8"}, + }; + for (boolean prefixMode : new boolean[] {true, false}) { + for (String[] tc : cases) { + String name = tc[0]; + if (major < Integer.parseInt(tc[1])) { + continue; + } + try (ForkedApp app = startFork("handoff-" + name, "80", prefixMode, false, null, null)) { + app.runHttpTest("ho/" + name + "-warm", "/clean"); + if (!"submission-publisher".equals(name)) { + assertTrue("mode=" + (prefixMode ? "prefix" : "index") + " case=" + name + + " baseline /clean must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + String cov1 = app.runHttpTest("ho/" + name + "-w1", "/handoff-" + name + "?ms=400"); + JsonObject helloAfter1 = parseHello(app.lastHello); + String cov2 = app.runHttpTest("ho/" + name + "-next", "/clean"); + Thread.sleep(700); + String cov3 = app.runHttpTest("ho/" + name + "-after700", "/clean"); + JsonObject helloEnd = parseHello(app.lastHello); + boolean flagged1 = cov1.contains("\"windowCut\":true") + || cov1.contains("\"contaminated\"") + || cov1.contains("\"unverified\""); + boolean asyncOff = !helloAfter1.get("asyncExecutors").getAsBoolean() + || !helloEnd.get("asyncExecutors").getAsBoolean(); + assertTrue("mode=" + (prefixMode ? "prefix" : "index") + " case=" + name + + " must NEVER be silent-missing: W1=" + cov1 + " helloAfter1=" + helloAfter1 + + " helloEnd=" + helloEnd, + flagged1 || asyncOff); + for (String later : new String[] {cov2, cov3}) { + boolean laterFlagged = later.contains("\"windowCut\":true") + || later.contains("\"contaminated\"") + || later.contains("\"unverified\""); + if (!asyncOff && later.contains("\"" + ASYNC_TAIL + "\"")) { + assertTrue("mode=" + (prefixMode ? "prefix" : "index") + " case=" + name + + " clean later window must not silently hold async lines: " + later, + laterFlagged); + } + } + } + } + } + } + @Test(timeout = 120000) public void forkedKafkaListenerHookEmitsTopicAndBeanAttributionInTcpCov() throws Exception { try (ForkedApp kafka = startFork("kafka", "2000", false, false, null, null)) { @@ -422,20 +487,17 @@ private static JsonObject parseHello(String line) { 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.PreCapturedDispatcher.class, AsyncHonestyApp.LazyInWindowDispatcher.class, - AsyncHonestyApp.NioAsyncFileHelper.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()); + java.nio.file.Path serversDir = new File(AsyncHonestyApp.class.getProtectionDomain().getCodeSource() + .getLocation().getPath()).toPath().resolve("org/example/servers"); + java.nio.file.Path dstServers = classes.toPath().resolve("org/example/servers"); + Files.createDirectories(dstServers); + try (java.util.stream.Stream entries = Files.list(serversDir)) { + for (java.nio.file.Path p : (Iterable) entries::iterator) { + String fn = p.getFileName().toString(); + if (fn.endsWith(".class") && (fn.startsWith("AsyncHonestyApp") + || fn.equals("AsyncTail.class") || fn.equals("Tail.class"))) { + Files.copy(p, dstServers.resolve(fn)); + } } } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index cbd79670..e1c3abed 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -4823,7 +4823,50 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE assertFalse("HELLO must report asyncExecutors=false after plain-pool multicaster", hMc.get("asyncExecutors").getAsBoolean()); - // Inside an active window, it also contaminates! + // Initialized hooked Spring ThreadPoolTaskExecutor with non-AbortPolicy (orders() == true) + // MUST be rejected by isHookedSpringExecutorOrPendingInit and latch (kills MC_PENDING_ALLOW)! + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor badSpringPool = + new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor(); + badSpringPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + badSpringPool.initialize(); + try { + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + assertFalse("initialized Spring pool failing orders() must be rejected", + OrderedPools.isHookedSpringExecutorOrPendingInit(badSpringPool)); + setExec.invoke(mc, badSpringPool); + assertTrue("initialized Spring pool failing orders() must latch via setTaskExecutor", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + badSpringPool.shutdown(); + } + + // Subclass overriding getTaskExecutor() to return a plain JDK pool (never calling setTaskExecutor) + // MUST be caught by the multicastEvent() hook! + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + RequestGate.open("mc-override-window", null); + Object overrideMc = hookedMulticaster.getConstructor().newInstance(); + // Create a small dynamic subclass in the same loader overriding getTaskExecutor() -> plainPool: + java.lang.reflect.Field taskExecField = hookedMulticaster.getDeclaredField("taskExecutor"); + taskExecField.setAccessible(true); + taskExecField.set(overrideMc, plainPool); + java.lang.reflect.Method multicast = hookedMulticaster.getMethod("multicastEvent", + org.springframework.context.ApplicationEvent.class); + Object tokOverride = RequestGate.enter(); + try { + multicast.invoke(overrideMc, + new org.springframework.context.PayloadApplicationEvent("src", "ev")); + } finally { + RequestGate.exit(tokOverride); + } + RequestGate.WindowOutcome overrideOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("multicastEvent with plain taskExecutor must contaminate: " + overrideOut.contaminations, + overrideOut.contaminations.contains("untracked-executor:" + ThreadPoolExecutor.class.getName())); + assertTrue("multicastEvent with plain taskExecutor must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // Inside an active window, setTaskExecutor also contaminates! KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); RequestGate.disarm(); RequestGate.open("mc-plain-window", null); @@ -4844,8 +4887,30 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE plainPool.shutdownNow(); } - // 2. Class-load detection for RxJava 1/2/3, Kotlin coroutines, OkHttp Dispatcher, and NIO AsynchronousChannelGroup. + // 2. JVM-wide JDK class loads (e.g. Tomcat 9's NIO2 connector loading AsynchronousSocketChannel / + // AsynchronousServerSocketChannel) must NOT false-latch asyncExecutors=false! ServerEntries transformer = new ServerEntries(true, Collections.singleton("com/acme/App"), null); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + transformer.transform(getClass().getClassLoader(), "java/nio/channels/AsynchronousSocketChannel", null, null, + new byte[0]); + transformer.transform(getClass().getClassLoader(), "java/nio/channels/AsynchronousServerSocketChannel", null, + null, new byte[0]); + assertFalse("JVM-wide NIO2 channel loads (Tomcat connector) must NOT latch hasUnhookedAsyncDispatcher", + ServerEntries.hasUnhookedAsyncDispatcher()); + JsonObject hTomcat = parseHello(connectAndReadHello(true)); + assertTrue("HELLO must keep asyncExecutors=true after Tomcat NIO2 class loads", + hTomcat.get("asyncExecutors").getAsBoolean()); + + // 2b. asyncHookFailed must drop asyncExecutors=false in HELLO (kills CAPS_HOOKFAIL)! + ServerEntries.setHookStatusForTests(false, false, false, false, true); + JsonObject hAsyncHookFail = parseHello(connectAndReadHello(true)); + assertFalse("asyncHookFailed must declare asyncExecutors=false", + hAsyncHookFail.get("asyncExecutors").getAsBoolean()); + ServerEntries.setHookStatusForTests(false, false, false, false, false); + + // 3. App-class constant-pool scan (tag 7 class refs AND tag 8 string refs) catches RxJava 1/2/3, + // Kotlin coroutines, OkHttp Dispatcher, NIO Asynchronous*, and SubmissionPublisher! String[] unhookedInternalNames = new String[] { "rx/schedulers/Schedulers", "io/reactivex/schedulers/Schedulers", @@ -4853,20 +4918,30 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE "kotlinx/coroutines/Dispatchers", "okhttp3/Dispatcher", "java/nio/channels/AsynchronousChannelGroup", - "sun/nio/ch/SimpleAsynchronousFileChannelImpl" + "java/util/concurrent/SubmissionPublisher" }; for (String internalName : unhookedInternalNames) { KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); - transformer.transform(getClass().getClassLoader(), internalName, null, null, new byte[0]); - assertTrue("loading " + internalName + " must mark hasUnhookedAsyncDispatcher", + byte[] appReferencingClass = generateAppReferencingClass("com/acme/App", internalName); + transformer.transform(getClass().getClassLoader(), "com/acme/App", null, null, appReferencingClass); + assertTrue("app class referencing " + internalName + " must mark hasUnhookedAsyncDispatcher", ServerEntries.hasUnhookedAsyncDispatcher()); JsonObject h = parseHello(connectAndReadHello(true)); - assertFalse("HELLO must report asyncExecutors=false after loading " + internalName, + assertFalse("HELLO must report asyncExecutors=false when app references " + internalName, h.get("asyncExecutors").getAsBoolean()); } - // 3. App-class constant-pool scan catches JDK AsynchronousFileChannel even when JDK class loaded before premain! + // 3b. Reflective Class.forName("java.util.concurrent.SubmissionPublisher") string literal in app class! + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + byte[] reflectiveSpApp = generateAppWithStringConstant("com/acme/App", + "java.util.concurrent.SubmissionPublisher"); + transformer.transform(getClass().getClassLoader(), "com/acme/App", null, null, reflectiveSpApp); + assertTrue("reflective SubmissionPublisher literal in app class must mark hasUnhookedAsyncDispatcher", + ServerEntries.hasUnhookedAsyncDispatcher()); + + // 3c. App-class constant-pool scan catches JDK AsynchronousFileChannel even when JDK class loaded before premain! KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); byte[] nioAppBytes = readClassBytes(FakeNioAsyncChannelApp.class); @@ -4876,6 +4951,56 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE JsonObject hNio = parseHello(connectAndReadHello(true)); assertFalse("HELLO must report asyncExecutors=false when app uses AsynchronousFileChannel", hNio.get("asyncExecutors").getAsBoolean()); + + // 4. Untracked handle queue overflow (>64 live handles) permanently latches asyncExecutors=false! + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + RequestGate.disarm(); + RequestGate.open("overflow-window", null); + Object tokOv = RequestGate.enter(); + try { + for (int i = 0; i < 66; i++) { + java.util.concurrent.CompletableFuture pending = new java.util.concurrent.CompletableFuture<>(); + RequestGate.trackUntrackedFuture(pending, "untracked-async:schedule"); + } + } finally { + RequestGate.exit(tokOv); + } + RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(50), true); + assertTrue(">64 live untracked handles overflow must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } + + private static byte[] generateAppReferencingClass(String appInternalName, String targetInternalName) { + org.objectweb.asm.ClassWriter cw = new org.objectweb.asm.ClassWriter(0); + cw.visit(org.objectweb.asm.Opcodes.V1_8, org.objectweb.asm.Opcodes.ACC_PUBLIC, appInternalName, null, + "java/lang/Object", null); + org.objectweb.asm.MethodVisitor mv = cw.visitMethod( + org.objectweb.asm.Opcodes.ACC_PUBLIC | org.objectweb.asm.Opcodes.ACC_STATIC, + "ref", "()Ljava/lang/Class;", null, null); + mv.visitCode(); + mv.visitLdcInsn(org.objectweb.asm.Type.getObjectType(targetInternalName)); + mv.visitInsn(org.objectweb.asm.Opcodes.ARETURN); + mv.visitMaxs(1, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateAppWithStringConstant(String appInternalName, String literal) { + org.objectweb.asm.ClassWriter cw = new org.objectweb.asm.ClassWriter(0); + cw.visit(org.objectweb.asm.Opcodes.V1_8, org.objectweb.asm.Opcodes.ACC_PUBLIC, appInternalName, null, + "java/lang/Object", null); + org.objectweb.asm.MethodVisitor mv = cw.visitMethod( + org.objectweb.asm.Opcodes.ACC_PUBLIC | org.objectweb.asm.Opcodes.ACC_STATIC, + "name", "()Ljava/lang/String;", null, null); + mv.visitCode(); + mv.visitLdcInsn(literal); + mv.visitInsn(org.objectweb.asm.Opcodes.ARETURN); + mv.visitMaxs(1, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); } @Test(timeout = 60000) @@ -4921,8 +5046,10 @@ public void helloRefreshFailureSendsFailClosedFallbackHelloAndTagsCovUnverifiedW KeployDedupAgent.testHelloFailure = new RuntimeException("simulated mid-session HELLO refresh failure"); try { send(out, "END ts/refresh-fail"); - // Must emit fail-closed all-false fallback HELLO before COV! + // Must emit fail-closed all-false fallback HELLO preserving cached identity before COV! JsonObject fallback = parseHello(in.readLine()); + assertEquals("mid-session fallback HELLO must preserve cached jvmNonce", + KeployDedupAgent.jvmNonce(), fallback.get("jvmNonce").getAsString()); assertFalse("fallback HELLO must set windowCut=false", fallback.get("windowCut").getAsBoolean()); assertFalse("fallback HELLO must set asyncExecutors=false", fallback.get("asyncExecutors").getAsBoolean()); @@ -4934,6 +5061,28 @@ public void helloRefreshFailureSendsFailClosedFallbackHelloAndTagsCovUnverifiedW KeployDedupAgent.testHelloFailure = null; } } + + // Also test initial-connect HELLO failure (before any identity was cached) -> + // exercises the static FAIL_CLOSED_FALLBACK_HELLO constant directly. + KeployDedupAgent.stop(); + KeployDedupAgent.testHelloFailure = new RuntimeException("simulated initial-connect HELLO failure"); + try { + assertTrue(KeployDedupAgent.start()); + try (Socket sdk2 = collector.accept()) { + sdk2.setSoTimeout(30000); + BufferedReader in2 = new BufferedReader( + new InputStreamReader(sdk2.getInputStream(), StandardCharsets.UTF_8)); + JsonObject initialFallback = parseHello(in2.readLine()); + assertEquals("initial fallback HELLO has empty jvmNonce when no identity was cached", + "", initialFallback.get("jvmNonce").getAsString()); + assertFalse("initial fallback HELLO must set windowCut=false", + initialFallback.get("windowCut").getAsBoolean()); + assertFalse("initial fallback HELLO must set asyncExecutors=false", + initialFallback.get("asyncExecutors").getAsBoolean()); + } + } finally { + KeployDedupAgent.testHelloFailure = null; + } } @Test(timeout = 60000) diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index dd0d9b96..02c1bdcc 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -63,24 +63,6 @@ public final class AsyncHonestyApp { 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() { } @@ -103,7 +85,10 @@ public static void main(String[] args) throws Exception { tomcat.start(); port = tomcat.getConnector().getLocalPort(); server = tomcat::stop; - } else if ("jetty".equals(mode)) { + } else if ("jetty".equals(mode) || mode.startsWith("handoff-")) { + if (mode.startsWith("handoff-")) { + HandOffFixtures.init(mode.substring("handoff-".length())); + } Server jetty = new Server(0); ServletContextHandler context = new ServletContextHandler(); context.addServlet(new ServletHolder(new AsyncServlet()), "/*"); @@ -211,11 +196,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO // 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"); - }); + final CompletableFuture externalFuture = + io.fakeexternal.FakeExternalHttpClient.fetchAsync(25, "http-200"); externalFuture.thenAccept(v -> { sleepQuietly(ms); AsyncTail.ran(); @@ -291,6 +273,12 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO Thread.currentThread().interrupt(); } } + } else if (path.startsWith("/handoff-")) { + try { + HandOffFixtures.handle(path.substring("/handoff-".length()), ms); + } catch (Exception e) { + throw new IOException(e); + } } else if ("/untracked-schedule".equals(path)) { SCHED.schedule(() -> AsyncTail.ran(), 1, TimeUnit.MILLISECONDS); } else if ("/untracked-thread".equals(path)) { @@ -508,6 +496,7 @@ public static Object makeKafkaProps() { } public static void runListenerBody() { + sleepQuietly(HANDOFF_LISTENER_MS); AsyncTail.ran(); } @@ -577,4 +566,113 @@ private static byte[] generateKafkaListenerConsumer() { cw.visitEnd(); return cw.toByteArray(); } + + static volatile long HANDOFF_LISTENER_MS = 0L; + static volatile long HANDOFF_MC_MS = 0L; + + /** + * Separate lazily-loaded helper so referencing SubmissionPublisher does not + * enter HandOffFixtures' constant pool for unrelated test cases. + */ + public static final class SubmissionPublisherFixture { + private static volatile Object publisher; + + static void init() throws Exception { + Class sp = Class.forName("java.util.concurrent.SubmissionPublisher"); + Object p = sp.getConstructor().newInstance(); + java.util.function.Consumer consumer = item -> { + sleepQuietly((Long) item); + AsyncTail.ran(); + }; + sp.getMethod("consume", java.util.function.Consumer.class).invoke(p, consumer); + publisher = p; + } + + static void submit(long ms) throws Exception { + publisher.getClass().getMethod("submit", Object.class).invoke(publisher, Long.valueOf(ms)); + } + } + + public static final class HandOffFixtures { + private static final LinkedBlockingQueue APP_WORKER_QUEUE = new LinkedBlockingQueue<>(); + private static volatile org.springframework.context.event.SimpleApplicationEventMulticaster overrideMc; + + static void init(String kind) throws Exception { + if ("submission-publisher".equals(kind)) { + SubmissionPublisherFixture.init(); + } else if ("queue-worker".equals(kind)) { + Thread worker = new Thread(() -> { + while (!Thread.currentThread().isInterrupted()) { + try { + APP_WORKER_QUEUE.take().run(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + }, "app-queue-worker"); + worker.setDaemon(true); + worker.start(); + } else if ("kafka-produce".equals(kind)) { + 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(); + final Object consumer = consumerClass.getDeclaredConstructor().newInstance(); + final Method invokeRecord = consumerClass.getDeclaredMethod("invokeRecordListener", Object.class); + invokeRecord.setAccessible(true); + io.fakeexternal.FakeExternalHttpClient.startBrokerConsumer(150, rec -> { + try { + HANDOFF_LISTENER_MS = rec; + invokeRecord.invoke(consumer, "record-" + rec); + } catch (Exception e) { + e.printStackTrace(System.err); + } + }); + } else if ("spring-mc-override".equals(kind)) { + org.springframework.context.event.SimpleApplicationEventMulticaster mc = + new org.springframework.context.event.SimpleApplicationEventMulticaster() { + @Override + protected java.util.concurrent.Executor getTaskExecutor() { + return PLAIN_POOL; + } + }; + mc.addApplicationListener(ev -> { + sleepQuietly(HANDOFF_MC_MS); + AsyncTail.ran(); + }); + overrideMc = mc; + } + } + + static void handle(String kind, final long ms) throws Exception { + if ("spring-listenable-callback".equals(kind)) { + final org.springframework.util.concurrent.SettableListenableFuture f = + new org.springframework.util.concurrent.SettableListenableFuture<>(); + io.fakeexternal.FakeExternalHttpClient.runAsync(30, () -> f.set("sent")); + f.addCallback(v -> { + sleepQuietly(ms); + AsyncTail.ran(); + }, ex -> { }); + } else if ("queue-worker".equals(kind)) { + APP_WORKER_QUEUE.offer(() -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + } else if ("submission-publisher".equals(kind)) { + SubmissionPublisherFixture.submit(ms); + } else if ("kafka-produce".equals(kind)) { + io.fakeexternal.FakeExternalHttpClient.publishToBroker(ms); + } else if ("spring-mc-override".equals(kind)) { + HANDOFF_MC_MS = ms; + overrideMc.multicastEvent(new org.springframework.context.PayloadApplicationEvent<>("src", "x")); + } else { + throw new IllegalArgumentException("unknown handoff fixture: " + kind); + } + } + } } diff --git a/scripts/smoke-javaagent.sh b/scripts/smoke-javaagent.sh index 05bea5b6..96e91018 100755 --- a/scripts/smoke-javaagent.sh +++ b/scripts/smoke-javaagent.sh @@ -623,9 +623,9 @@ done tomcat_core="${work_dir}/tomcat-libs/tomcat-embed-core-${tomcat_version}.jar" tomcat_libs="$(find "${work_dir}/tomcat-libs" -name '*.jar' | sort | paste -sd: -)" -mkdir -p "${work_dir}/tomcat-src/smoke" "${work_dir}/tomcat-classes" -cat > "${work_dir}/tomcat-src/smoke/TomcatHarness.java" <<'JAVA' -package smoke; +mkdir -p "${work_dir}/tomcat-src/smoke/app" "${work_dir}/tomcat-classes" +cat > "${work_dir}/tomcat-src/smoke/app/TomcatHarness.java" <<'JAVA' +package smoke.app; import org.apache.catalina.Context; import org.apache.catalina.startup.Tomcat; @@ -764,7 +764,7 @@ public final class TomcatHarness { if (!"hello".equals(body) || !json.contains("\"id\":\"" + id + "\"") || !json.contains("\"" + ADAPTER + "\":[") - || !json.contains("\"smoke/TomcatHarness$Tail\":[") + || !json.contains("\"smoke/app/TomcatHarness$Tail\":[") || json.contains("\"classMismatch\"") || json.contains("\"unverified\"") || json.contains("\"contaminated\"") @@ -801,7 +801,7 @@ public final class TomcatHarness { output.flush(); String ack = readAll(socket.getInputStream()); String pattern = "^ACK proto=3 caps=windowCut=true,contaminated=true,classMismatch=true," - + "background=(true|false),ackId=true,asyncExecutors=(true|false)," + + "background=(true|false),ackId=true,asyncExecutors=true," + "listenerContamination=(true|false)\\n$"; if (!ack.matches(pattern)) { throw new IllegalStateException("unexpected ACK for " + command + ": " + ack); @@ -829,7 +829,7 @@ public final class TomcatHarness { } JAVA javac -cp "${tomcat_libs}:${agent_jar}" -d "${work_dir}/tomcat-classes" \ - "${work_dir}/tomcat-src/smoke/TomcatHarness.java" + "${work_dir}/tomcat-src/smoke/app/TomcatHarness.java" tomcat_log="${work_dir}/tomcat-jacoco-after.log" tomcat_rc=0 @@ -838,9 +838,9 @@ KEPLOY_JAVA_CLASS_DIRS="${work_dir}/tomcat-classes:${tomcat_core}" \ run_smoke "tomcat-jacoco-after" \ timeout -k 10 180 java \ -javaagent:"${agent_jar}" \ - -javaagent:"${jacoco_jar}=includes=smoke.*:org.apache.catalina.connector.CoyoteAdapter,output=none" \ + -javaagent:"${jacoco_jar}=includes=smoke.app.*:org.apache.catalina.connector.CoyoteAdapter,output=none" \ -cp "${work_dir}/tomcat-classes:${tomcat_libs}:${agent_jar}" \ - smoke.TomcatHarness "tomcat-jacoco-after" "${work_dir}/tomcat-base" 2>"${tomcat_log}" || tomcat_rc=$? + smoke.app.TomcatHarness "tomcat-jacoco-after" "${work_dir}/tomcat-base" 2>"${tomcat_log}" || tomcat_rc=$? if [[ "${tomcat_rc}" -eq 124 || "${tomcat_rc}" -eq 137 ]]; then cat "${tomcat_log}" >&2 echo "tomcat-jacoco-after: the Tomcat harness was killed or did not end within 180 s (exit ${tomcat_rc}; 137 can also be the OOM killer)" >&2 From 4f3a70c7dd3d1b00743d874a6d91496a58425a15 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Sat, 28 Nov 2026 12:46:27 +0530 Subject: [PATCH 22/26] fix(dedup): fail closed on unallowlisted dispatch classes and external async handoffs Remove package scan exclusions so every non-JDK, non-agent class loaded by the JVM (application classes and third-party libraries alike) is scanned for concurrency dispatch primitives and Thread subclasses. Any class referencing a dispatch primitive or extending java.lang.Thread latches asyncExecutors=false unless it is on the explicit per-class allowlist of hooked Spring executors, hooked servlet server internals, or verified non-app-dispatching infrastructure classes (with Caffeine async entry points hooked via latch-on-call). Also latch asyncExecutors=false on background workers started outside any request window, scheduled/Quartz/listener job entry, ConcurrentLinkedQueue and ConcurrentLinkedDeque handoffs, JDK HttpClient/WebSocket async sends, and expired-job handle overflow past the 64-handle cap. Signed-off-by: slayerjain --- .../main/java/io/keploy/dedup/JobGate.java | 6 + .../java/io/keploy/dedup/OrderedPools.java | 9 +- .../java/io/keploy/dedup/RequestGate.java | 53 +- .../java/io/keploy/dedup/ServerEntries.java | 552 +++++++++++++- .../dedup/ForkedAsyncAndHonestyTest.java | 51 +- .../dedup/HonestProtocolAndAsyncTest.java | 687 ++++++++++++++++++ .../java/io/keploy/dedup/JobTailTest.java | 14 +- .../test/java/org/example/jobs/Events.java | 4 + .../org/example/servers/AsyncHonestyApp.java | 163 +++++ scripts/smoke-javaagent.sh | 6 +- 10 files changed, 1489 insertions(+), 56 deletions(-) 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 f9f11ac8..d90015f4 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -119,6 +119,12 @@ public static Object enter(Object job, String kind) { // hard-removed without their downstream listener coverage. KeployDedupAgent.noteObservedUntrackedAsyncLibrary( "async message listener (" + run.name + ")", true); + } else if ("scheduled".equals(kind) || "quartz".equals(kind)) { + // A scheduled job or Quartz run firing during a round may be + // draining an outbox or queue written by an earlier HTTP test + // whose window already closed; fail closed on asyncExecutors. + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "scheduled job (" + run.name + ")", true); } } catch (Throwable t) { // The job runs on. A run counted as going on before this (an 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 954763d4..9f0c0cb0 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/OrderedPools.java @@ -134,6 +134,8 @@ static boolean isSpringAsyncTaskExecutorClass(Class cls) { 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_SIMPLE_SCHEDULER = + "org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler"; private static final String SPRING_TASK_EXECUTOR_ADAPTER = "org.springframework.core.task.support.TaskExecutorAdapter"; private static final String SPRING_ASYNC_ASPECT = @@ -219,6 +221,7 @@ private static boolean isKnownSpringBaseClass(String name) { || SPRING_SCHEDULER.equals(name) || SPRING_CONCURRENT.equals(name) || SPRING_SIMPLE_ASYNC.equals(name) + || SPRING_SIMPLE_SCHEDULER.equals(name) || SPRING_TASK_EXECUTOR_ADAPTER.equals(name) || SPRING_ASYNC_ASPECT.equals(name); } @@ -246,7 +249,8 @@ static boolean isHookedAndVerifiedSpringExecutor(Object executor) { if (SPRING_POOL.equals(name) || SPRING_SCHEDULER.equals(name) || SPRING_CONCURRENT.equals(name) - || SPRING_SIMPLE_ASYNC.equals(name)) { + || SPRING_SIMPLE_ASYNC.equals(name) + || SPRING_SIMPLE_SCHEDULER.equals(name)) { hookedBase = name; break; } @@ -280,7 +284,8 @@ static boolean isHookedSpringExecutorOrPendingInit(Object executor) { if (SPRING_POOL.equals(name) || SPRING_SCHEDULER.equals(name) || SPRING_CONCURRENT.equals(name) - || SPRING_SIMPLE_ASYNC.equals(name)) { + || SPRING_SIMPLE_ASYNC.equals(name) + || SPRING_SIMPLE_SCHEDULER.equals(name)) { hookedBase = name; break; } 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 e73616f9..1007d913 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -3102,12 +3102,42 @@ public static void noteIfUntrackedSubmit(Object receiver) { } public static void noteIfBlockingQueue(Object receiver) { - if (!(receiver instanceof java.util.concurrent.BlockingQueue)) { + if (!(receiver instanceof java.util.concurrent.BlockingQueue) + && !(receiver instanceof java.util.concurrent.ConcurrentLinkedQueue) + && !(receiver instanceof java.util.concurrent.ConcurrentLinkedDeque)) { return; } noteUntrackedAsync("untracked-async:blocking-queue", 0L); } + /** + * Called from runtime-latch entry hooks on framework/library async methods + * (such as Caffeine {@code CacheLoader.asyncReload}/{@code LocalAsyncCache} + * and Spring {@code ConcurrentMapCache.retrieve}): permanently latches + * {@code asyncExecutors=false} on first invocation and contaminates any + * currently active request window or job run. + * + * @param reason human-readable label for the async dispatch entry + */ + public static void noteRuntimeUntrackedDispatch(String reason) { + String label = (reason == null || reason.isEmpty()) ? "library-async" : reason; + if (!armed) { + noteUnarmedHandOffIfInFlight(); + KeployDedupAgent.noteObservedUntrackedAsyncLibrary(label, false); + return; + } + KeployDedupAgent.noteObservedUntrackedAsyncLibrary(label, true); + if (INSIDE.get() != null || JobGate.runningAttribution() != null || JobGate.expiredRunningName() != null) { + noteUntrackedAsync("untracked-async:" + label, 0L); + } + } + + private static void noteBackgroundWorkerOutsideWindow(String reason, boolean isArmed) { + String label = (reason == null || reason.isEmpty()) ? "background-worker" : reason; + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "app background worker/scheduler started outside request window (" + label + ")", isArmed); + } + private static void recordUntrackedMethodRef(String reason, String target) { if (!armed) { noteUnarmedHandOffIfInFlight(); @@ -3350,6 +3380,7 @@ public static void noteIfThread(Object target) { } if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:thread-start", false); return; } noteTrackedUntrackedAsync("untracked-async:thread-start", target, false); @@ -3379,6 +3410,7 @@ public static void trackUntrackedThread(Object thread, String reason) { if (!armed) { if (thread instanceof Thread) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow(reason != null ? reason : "untracked-async:thread-start", false); } return; } @@ -3412,6 +3444,7 @@ public static void trackUntrackedFuture(Object future, String reason) { if (!armed) { if (future instanceof Future) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow(reason != null ? reason : "untracked-async:schedule", false); } return; } @@ -3487,7 +3520,14 @@ private static void noteTrackedHandle(String reason, UntrackedHandle handle, lon "untracked async handle queue overflow (>64 live handles)", true); noteExternalUntrackedTail(jobReason, maxLingeringNanos); } + return; } + // Rewritten app code started a Thread, ScheduledFuture, or TimerTask + // completely outside any request window or tracked job (e.g. a long-lived + // background worker or outbox poller). Latch asyncExecutors=false so + // later requests handing work to it through shared state cannot be + // falsely treated as synchronous. + noteBackgroundWorkerOutsideWindow(effectiveReason, true); } private static boolean addHandleToQueue(ConcurrentLinkedQueue queue, UntrackedHandle handle, @@ -3561,6 +3601,7 @@ public static ScheduledFuture schedule(ScheduledExecutorService executor, Run long delay, TimeUnit unit) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:schedule", false); return executor.schedule(command, delay, unit); } ScheduledFuture sf = executor.schedule(wrapScheduledContext(executor, command), delay, unit); @@ -3582,6 +3623,7 @@ public static ScheduledFuture schedule(ScheduledExecutorService executor, long delay, TimeUnit unit) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:schedule", false); return executor.schedule(callable, delay, unit); } ScheduledFuture sf = executor.schedule(wrapScheduledContext(executor, callable), delay, unit); @@ -3604,6 +3646,7 @@ public static ScheduledFuture scheduleAtFixedRate(ScheduledExecutorService ex long initialDelay, long period, TimeUnit unit) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:schedule", false); return executor.scheduleAtFixedRate(command, initialDelay, period, unit); } ScheduledFuture sf = executor.scheduleAtFixedRate( @@ -3627,6 +3670,7 @@ public static ScheduledFuture scheduleWithFixedDelay(ScheduledExecutorService long initialDelay, long delay, TimeUnit unit) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:schedule", false); return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); } ScheduledFuture sf = executor.scheduleWithFixedDelay( @@ -3653,6 +3697,7 @@ private static long dateDelayMillis(Date time) { public static void timerSchedule(Timer timer, TimerTask task, long delay) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:timer", false); timer.schedule(task, delay); return; } @@ -3670,6 +3715,7 @@ public static void timerSchedule(Timer timer, TimerTask task, long delay) { public static void timerSchedule(Timer timer, TimerTask task, Date time) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:timer", false); timer.schedule(task, time); return; } @@ -3689,6 +3735,7 @@ public static void timerSchedule(Timer timer, TimerTask task, Date time) { public static void timerSchedule(Timer timer, TimerTask task, long delay, long period) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:timer", false); timer.schedule(task, delay, period); return; } @@ -3707,6 +3754,7 @@ public static void timerSchedule(Timer timer, TimerTask task, long delay, long p public static void timerSchedule(Timer timer, TimerTask task, Date firstTime, long period) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:timer", false); timer.schedule(task, firstTime, period); return; } @@ -3726,6 +3774,7 @@ public static void timerSchedule(Timer timer, TimerTask task, Date firstTime, lo public static void timerScheduleAtFixedRate(Timer timer, TimerTask task, long delay, long period) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:timer", false); timer.scheduleAtFixedRate(task, delay, period); return; } @@ -3744,6 +3793,7 @@ public static void timerScheduleAtFixedRate(Timer timer, TimerTask task, long de public static void timerScheduleAtFixedRate(Timer timer, TimerTask task, Date firstTime, long period) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:timer", false); timer.scheduleAtFixedRate(task, firstTime, period); return; } @@ -3797,6 +3847,7 @@ public static T invokeAny(ExecutorService executor, Collection LATCH_ON_CALL = new HashMap<>(); + + static { + addLatchOnCall("com/github/benmanes/caffeine/cache/Caffeine", + "caffeine-async-cache", "buildAsync", "executor", "removalListener", + "evictionListener", "refreshAfterWrite", "scheduler"); + addLatchOnCall("com/github/benmanes/caffeine/cache/CacheLoader", + "caffeine-async-cache", "asyncLoad", "asyncLoadAll", "asyncReload"); + addLatchOnCall("com/github/benmanes/caffeine/cache/LocalAsyncCache", + "caffeine-async-cache", "get", "getAll", "put"); + addLatchOnCall("org/springframework/cache/concurrent/ConcurrentMapCache", + "spring-async-cache", "retrieve"); + } + + private static void addLatchOnCall(String className, String label, String... methods) { + LATCH_ON_CALL.put(className, new LatchEntry(label, new HashSet<>(Arrays.asList(methods)))); + } + // 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<>(); @@ -144,6 +169,10 @@ final class ServerEntries implements ClassFileTransformer { UNHOOKED_ASYNC_DISPATCHERS.put("io/reactivex/schedulers/Schedulers", "RxJava 2 Schedulers"); UNHOOKED_ASYNC_DISPATCHERS.put("io/reactivex/rxjava3/schedulers/Schedulers", "RxJava 3 Schedulers"); UNHOOKED_ASYNC_DISPATCHERS.put("kotlinx/coroutines/Dispatchers", "Kotlin Coroutines Dispatchers"); + UNHOOKED_ASYNC_DISPATCHERS.put("kotlinx/coroutines/GlobalScope", "Kotlin Coroutines GlobalScope"); + UNHOOKED_ASYNC_DISPATCHERS.put("kotlin/concurrent/ThreadsKt", "Kotlin Thread Helper"); + UNHOOKED_ASYNC_DISPATCHERS.put("reactor/core/scheduler/Schedulers", "Project Reactor Schedulers"); + UNHOOKED_ASYNC_DISPATCHERS.put("com/google/common/eventbus/AsyncEventBus", "Guava AsyncEventBus"); UNHOOKED_ASYNC_DISPATCHERS.put("okhttp3/Dispatcher", "OkHttp Dispatcher"); UNHOOKED_ASYNC_DISPATCHERS.put("java/nio/channels/AsynchronousChannelGroup", "JDK AsynchronousChannelGroup"); UNHOOKED_ASYNC_DISPATCHERS.put("java/nio/channels/AsynchronousFileChannel", "JDK AsynchronousFileChannel"); @@ -165,12 +194,251 @@ final class ServerEntries implements ClassFileTransformer { "java/util/concurrent/PriorityBlockingQueue", "java/util/concurrent/DelayQueue", "java/util/concurrent/SynchronousQueue", - "java/util/concurrent/LinkedTransferQueue"))); + "java/util/concurrent/LinkedTransferQueue", + "java/util/concurrent/ConcurrentLinkedQueue", + "java/util/concurrent/ConcurrentLinkedDeque"))); private static final Set BLOCKING_QUEUE_ENQUEUE_METHODS = Collections.unmodifiableSet(new HashSet<>( Arrays.asList("offer", "put", "add", "offerFirst", "offerLast", "putFirst", "putLast", "addFirst", "addLast", "transfer", "tryTransfer"))); + // JDK HTTP/WebSocket async methods checked even in rewritten app classes + // (since java/net/http/* is skipped by isInternalOrAgentClass). Must be + // initialized before DISPATCH_PRIMITIVE_METHODS, which merges it via putAll. + private static final Map> JDK_ASYNC_HTTP_METHODS = buildJdkAsyncHttpMethods(); + // Concurrency dispatch primitives checked by Methodref/InterfaceMethodref + // constant-pool scan on every non-JDK, non-agent, non-allowlisted loaded class. + private static final Map> DISPATCH_PRIMITIVE_METHODS = buildDispatchPrimitiveMethods(); + + private static Map> buildJdkAsyncHttpMethods() { + Map> m = new HashMap<>(); + m.put("java/net/http/HttpClient", setOf("sendAsync")); + m.put("java/net/http/WebSocket$Builder", setOf("buildAsync")); + m.put("java/net/http/WebSocket", setOf("sendText", "sendBinary", "sendPing", "sendPong", "sendClose")); + return Collections.unmodifiableMap(m); + } + + private static Map> buildDispatchPrimitiveMethods() { + Map> m = new HashMap<>(); + Set exec = setOf("execute"); + Set execSvc = setOf("execute", "submit", "invokeAll", "invokeAny"); + Set schedSvc = setOf("execute", "submit", "invokeAll", "invokeAny", + "schedule", "scheduleAtFixedRate", "scheduleWithFixedDelay"); + Set fjp = setOf("execute", "submit", "invokeAll", "invokeAny", "invoke"); + Set stageAsync = setOf( + "thenApplyAsync", "thenAcceptAsync", "thenRunAsync", "thenComposeAsync", + "thenCombineAsync", "thenAcceptBothAsync", "runAfterBothAsync", + "applyToEitherAsync", "acceptEitherAsync", "runAfterEitherAsync", + "handleAsync", "whenCompleteAsync", "exceptionallyAsync", "exceptionallyComposeAsync"); + Set cfAsync = new HashSet<>(stageAsync); + cfAsync.add("runAsync"); + cfAsync.add("supplyAsync"); + cfAsync.add("completeAsync"); + Set clq = setOf("offer", "add", "offerFirst", "offerLast", "addFirst", "addLast"); + + m.put("java/util/concurrent/Executor", exec); + m.put("java/util/concurrent/ExecutorService", execSvc); + m.put("java/util/concurrent/AbstractExecutorService", execSvc); + m.put("java/util/concurrent/ThreadPoolExecutor", execSvc); + m.put("java/util/concurrent/ScheduledExecutorService", schedSvc); + m.put("java/util/concurrent/ScheduledThreadPoolExecutor", schedSvc); + m.put("java/util/concurrent/ForkJoinPool", fjp); + m.put("java/util/concurrent/ForkJoinTask", setOf("fork")); + m.put("java/util/concurrent/ExecutorCompletionService", setOf("submit")); + m.put("java/lang/Thread", setOf("start", "startVirtualThread")); + m.put("java/lang/Thread$Builder", setOf("start")); + m.put("java/lang/Thread$Builder$OfVirtual", setOf("start")); + m.put("java/lang/Thread$Builder$OfPlatform", setOf("start")); + m.put("java/util/Timer", setOf("schedule", "scheduleAtFixedRate")); + m.put("java/util/concurrent/CompletableFuture", Collections.unmodifiableSet(cfAsync)); + m.put("java/util/concurrent/CompletionStage", stageAsync); + m.put("java/util/concurrent/SubmissionPublisher", setOf("submit", "offer")); + // Messaging producers: if a library or dynamically generated proxy outside + // rewritten app classes invokes a broker send/publish, fail closed on load. + m.put("org/springframework/kafka/core/KafkaTemplate", setOf("send", "sendDefault")); + m.put("org/springframework/kafka/core/KafkaOperations", setOf("send", "sendDefault")); + m.put("org/apache/kafka/clients/producer/KafkaProducer", setOf("send")); + m.put("org/apache/kafka/clients/producer/Producer", setOf("send")); + m.put("org/springframework/amqp/rabbit/core/RabbitTemplate", setOf("send", "convertAndSend", "convertSendAndReceive")); + m.put("org/springframework/amqp/rabbit/core/RabbitOperations", setOf("send", "convertAndSend", "convertSendAndReceive")); + m.put("org/springframework/amqp/core/AmqpTemplate", setOf("send", "convertAndSend", "convertSendAndReceive")); + m.put("org/springframework/jms/core/JmsTemplate", setOf("send", "convertAndSend")); + m.put("org/springframework/jms/core/JmsOperations", setOf("send", "convertAndSend")); + m.put("org/springframework/jms/core/JmsMessagingTemplate", setOf("send", "convertAndSend")); + m.put("org/springframework/cloud/stream/function/StreamBridge", setOf("send")); + m.put("reactor/kafka/sender/KafkaSender", setOf("send")); + for (String q : BLOCKING_QUEUE_OWNERS) { + if ("java/util/concurrent/ConcurrentLinkedQueue".equals(q) + || "java/util/concurrent/ConcurrentLinkedDeque".equals(q)) { + m.put(q, clq); + } else { + m.put(q, BLOCKING_QUEUE_ENQUEUE_METHODS); + } + } + m.putAll(JDK_ASYNC_HTTP_METHODS); + return Collections.unmodifiableMap(m); + } + + // Explicit per-class allowlist (no package wildcards): every entry is either + // (a) a hooked & tested Spring async executor or its internal delegate, + // (b) a hooked servlet server connector/lifecycle class (Tomcat, Jetty, + // Undertow/XNIO/JBoss Threads) whose request dispatch enters a hooked + // request entry, or + // (c) a verified non-app-dispatching JDBC pool/driver/DB/Hibernate/ + // Micrometer/Spring Boot startup-shutdown infrastructure class observed + // on Spring PetClinic. + // Unhooked async libraries (Kotlin coroutines, Reactor, OkHttp, Guava, + // Spring Integration, RxJava, Akka/Pekko, gRPC, Netty, HttpAsyncClient, + // NATS, custom callbacks, H2 FileAsync) are absent and fail closed by + // construction. + private static final Set ALLOWLISTED_DISPATCH_CLASSES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + // (a) Hooked Spring async executors & delegates + "org/springframework/context/event/SimpleApplicationEventMulticaster", + "org/springframework/core/task/AsyncTaskExecutor", + "org/springframework/core/task/SimpleAsyncTaskExecutor", + "org/springframework/scheduling/concurrent/SimpleAsyncTaskScheduler", + "org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor", + "org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor$1", + "org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler", + "org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler$1", + "org/springframework/scheduling/concurrent/ConcurrentTaskExecutor", + "org/springframework/aop/interceptor/AsyncExecutionAspectSupport", + // (b1) Tomcat (request dispatch enters hooked CoyoteAdapter) + "org/apache/catalina/core/ContainerBase", + "org/apache/catalina/core/StandardServer", + "org/apache/catalina/core/StandardVirtualThreadExecutor", + "org/apache/catalina/servlets/CGIServlet$CGIRunner", + "org/apache/catalina/startup/Catalina$CatalinaShutdownHook", + "org/apache/catalina/startup/ContextConfig", + "org/apache/catalina/startup/HostConfig", + "org/apache/catalina/startup/UserConfig", + "org/apache/catalina/util/TimeBucketCounter", + "org/apache/catalina/util/TimeBucketCounter$MaintenanceMonitor", + "org/apache/catalina/util/TimeBucketCounterBase", + "org/apache/catalina/util/TimeBucketCounterBase$MaintenanceMonitor", + "org/apache/coyote/AbstractProtocol", + "org/apache/juli/AsyncFileHandler$DropFlushPolicy", + "org/apache/juli/AsyncFileHandler$DropLastPolicy", + "org/apache/juli/ClassLoaderLogManager$Cleaner", + "org/apache/juli/FileHandler", + "org/apache/tomcat/util/net/AbstractEndpoint", + "org/apache/tomcat/util/net/AprEndpoint", + "org/apache/tomcat/util/net/AprEndpoint$Poller", + "org/apache/tomcat/util/net/AprEndpoint$Sendfile", + "org/apache/tomcat/util/net/NioEndpoint", + "org/apache/tomcat/util/net/Nio2Channel", + "org/apache/tomcat/util/net/Nio2Endpoint", + "org/apache/tomcat/util/net/Nio2Endpoint$Nio2Acceptor", + "org/apache/tomcat/util/net/Nio2Endpoint$Nio2SocketWrapper", + "org/apache/tomcat/util/net/Nio2Endpoint$SocketProcessor", + "org/apache/tomcat/util/net/SecureNio2Channel", + "org/apache/tomcat/util/net/SecureNio2Channel$1", + "org/apache/tomcat/util/net/SecureNio2Channel$2", + "org/apache/tomcat/util/net/SecureNio2Channel$3", + "org/apache/tomcat/util/net/SecureNio2Channel$4", + "org/apache/tomcat/util/net/SecureNio2Channel$FutureFlush", + "org/apache/tomcat/util/net/SecureNio2Channel$FutureRead", + "org/apache/tomcat/util/net/SecureNio2Channel$FutureWrite", + "org/apache/tomcat/util/net/SocketProperties", + "org/apache/tomcat/util/net/SocketWrapperBase", + "org/apache/tomcat/util/net/SocketWrapperBase$OperationState", + "org/apache/tomcat/util/net/WriteBuffer", + "org/apache/tomcat/util/threads/ScheduledThreadPoolExecutor", + "org/apache/tomcat/util/threads/TaskQueue", + "org/apache/tomcat/util/threads/TaskThread", + "org/apache/tomcat/util/threads/ThreadPoolExecutor", + "org/apache/tomcat/websocket/WsWebSocketContainer", + // (b2) Jetty (request dispatch enters hooked HttpChannel/ServletChannel) + "org/eclipse/jetty/io/AbstractConnection", + "org/eclipse/jetty/io/SelectorManager", + "org/eclipse/jetty/io/ssl/SslConnection$DecryptedEndPoint", + "org/eclipse/jetty/io/ssl/SslConnection$DecryptedEndPoint$IncompleteWriteCallback", + "org/eclipse/jetty/server/AbstractConnector", + "org/eclipse/jetty/server/AsyncRequestLogWriter", + "org/eclipse/jetty/server/AsyncRequestLogWriter$WriterThread", + "org/eclipse/jetty/server/HttpChannel", + "org/eclipse/jetty/server/HttpConnection", + "org/eclipse/jetty/server/HttpInput", + "org/eclipse/jetty/server/ShutdownMonitor", + "org/eclipse/jetty/server/handler/ShutdownHandler$1", + "org/eclipse/jetty/util/thread/ExecutorThreadPool", + "org/eclipse/jetty/util/thread/QueuedThreadPool", + "org/eclipse/jetty/util/thread/ReservedThreadExecutor", + "org/eclipse/jetty/util/thread/ScheduledExecutorScheduler", + "org/eclipse/jetty/util/thread/ShutdownThread", + "org/eclipse/jetty/util/thread/TimerScheduler", + "org/eclipse/jetty/util/thread/TryExecutor$NoTryExecutor", + "org/eclipse/jetty/util/thread/strategy/EatWhatYouKill", + "org/eclipse/jetty/util/thread/strategy/ExecuteProduceConsume", + "org/eclipse/jetty/util/thread/strategy/ProduceConsume", + "org/eclipse/jetty/util/thread/strategy/ProduceExecuteConsume", + // (b3) Undertow / XNIO / JBoss Threads (request dispatch enters hooked Connectors) + "io/undertow/protocols/ssl/SslConduit", + "io/undertow/server/Connectors", + "io/undertow/server/DefaultByteBufferPool", + "io/undertow/server/HttpServerExchange", + "io/undertow/server/protocol/framed/AbstractFramedChannel", + "io/undertow/server/protocol/framed/ShutdownFallbackExecutor", + "io/undertow/server/protocol/http/HttpReadListener", + "io/undertow/servlet/spec/AsyncContextImpl", + "io/undertow/util/PipeliningExecutor", + "io/undertow/util/SimpleObjectPool$SimplePooledObject", + "org/xnio/AbstractIoFuture", + "org/xnio/AutomaticReference$Cleaner$1", + "org/xnio/ByteBufferPool", + "org/xnio/ChannelListeners", + "org/xnio/ChannelListeners$13", + "org/xnio/XnioIoThread", + "org/xnio/XnioWorker$ExecutorServiceTaskPool", + "org/xnio/XnioWorker$ThreadPoolExecutorTaskPool", + "org/jboss/threads/DelegatingExecutor", + "org/jboss/threads/DelegatingExecutorService", + "org/jboss/threads/DelegatingScheduledExecutorService", + "org/jboss/threads/EnhancedQueueExecutor", + "org/jboss/threads/HandoffRejectedExecutionHandler", + "org/jboss/threads/JBossThread", + "org/jboss/threads/ManagedThreadPoolExecutor", + "org/jboss/threads/ViewExecutor", + "org/jboss/threads/ViewExecutor$TaskWrapper", + // (c) Verified non-app-dispatching JDBC/DB/Hibernate/Caffeine/Micrometer/Spring Boot infra + // (Caffeine async entry points are hooked via LATCH_ON_CALL on Caffeine/CacheLoader/LocalAsyncCache) + "com/github/benmanes/caffeine/cache/BoundedLocalCache", + "com/github/benmanes/caffeine/cache/UnboundedLocalCache", + "com/zaxxer/hikari/pool/HikariPool", + "com/zaxxer/hikari/pool/ProxyLeakTask", + "com/zaxxer/hikari/util/ConcurrentBag", + "com/mysql/cj/jdbc/AbandonedConnectionCleanupThread", + "org/postgresql/Driver", + "org/h2/mvstore/FileStore", + "org/h2/mvstore/MVStore", + "org/h2/mvstore/db/LobStorageMap", + "org/h2/util/MathUtils", + "org/h2/util/Task", + "org/h2/util/Utils", + "org/hibernate/internal/util/collections/BoundedConcurrentHashMap$LIRS", + "org/hibernate/internal/util/collections/BoundedConcurrentHashMap$LRU", + "io/micrometer/core/instrument/HighCardinalityTagsDetector", + "org/springframework/beans/factory/support/DefaultListableBeanFactory", + "org/springframework/boot/actuate/context/ShutdownEndpoint", + "org/springframework/boot/autoconfigure/condition/OnClassCondition$ThreadedOutcomesResolver", + "org/springframework/boot/autoconfigure/preinitialize/BackgroundPreinitializingApplicationListener", + "org/springframework/boot/autoconfigure/ssl/FileWatcher$WatcherThread", + "org/springframework/boot/context/metrics/buffering/BufferingApplicationStartup", + "org/springframework/boot/tomcat/GracefulShutdown", + "org/springframework/boot/tomcat/TomcatWebServer", + "org/springframework/boot/tomcat/TomcatWebServer$1", + "org/springframework/boot/web/embedded/tomcat/GracefulShutdown", + "org/springframework/boot/web/embedded/tomcat/TomcatWebServer", + "org/springframework/boot/web/embedded/tomcat/TomcatWebServer$1", + "org/springframework/context/support/AbstractApplicationContext$1", + "org/springframework/context/support/DefaultLifecycleProcessor", + "org/springframework/jmx/support/ConnectorServerFactoryBean$1"))); + + static Set allowlistedDispatchClasses() { + return ALLOWLISTED_DISPATCH_CLASSES; + } + private static final String SPRING_EVENT_MULTICASTER = "org/springframework/context/event/SimpleApplicationEventMulticaster"; @@ -234,14 +502,22 @@ final class ServerEntries implements ClassFileTransformer { "java/util/concurrent/DelayQueue", "java/util/concurrent/SynchronousQueue", "java/util/concurrent/LinkedTransferQueue", + "java/util/concurrent/ConcurrentLinkedQueue", + "java/util/concurrent/ConcurrentLinkedDeque", "java/util/Queue", + "java/util/Deque", "org/springframework/kafka/core/KafkaTemplate", + "org/springframework/kafka/core/KafkaOperations", "org/apache/kafka/clients/producer/KafkaProducer", "org/apache/kafka/clients/producer/Producer", "org/springframework/amqp/rabbit/core/RabbitTemplate", + "org/springframework/amqp/rabbit/core/RabbitOperations", "org/springframework/amqp/core/AmqpTemplate", "org/springframework/jms/core/JmsTemplate", "org/springframework/jms/core/JmsOperations", + "org/springframework/jms/core/JmsMessagingTemplate", + "org/springframework/cloud/stream/function/StreamBridge", + "reactor/kafka/sender/KafkaSender", "com/google/common/util/concurrent/Futures", "com/google/common/util/concurrent/ListenableFuture", "reactor/core/publisher/Mono", @@ -520,6 +796,10 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (SPRING_EVENT_MULTICASTER.equals(className)) { return hookSpringEventMulticaster(loader, className, classfileBuffer); } + LatchEntry latchEntry = LATCH_ON_CALL.get(className); + if (latchEntry != null) { + return hookLatchOnCall(loader, className, classfileBuffer, latchEntry); + } Entry entry = ENTRIES.get(className); if (entry == null) { String uncounted = UNCOUNTED.get(className); @@ -530,20 +810,15 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (unhookedConsumer != null) { SEEN_UNHOOKED_CONSUMERS.add(unhookedConsumer); } - // Decide unhooked async dispatchers strictly from app-code references - // (scanUnhookedReferences below), NEVER from JVM-wide class loads — - // otherwise Tomcat's own NIO2 connector loading AsynchronousSocketChannel - // / AsynchronousServerSocketChannel false-latches asyncExecutors=false - // on every Tomcat / Spring Boot app. if (shouldRewriteExecutorCalls(className)) { - scanUnhookedReferences(className, classfileBuffer, false); + scanUnhookedReferences(className, classfileBuffer, false, false); if (!canAccessGate(loader, protectionDomain)) { if (seesGate(loader)) { jpmsGuardTriggered = true; } else { appRewriteFailed = true; } - scanUnhookedReferences(className, classfileBuffer, true); + scanUnhookedReferences(className, classfileBuffer, true, true); return null; } try { @@ -556,15 +831,15 @@ public byte[] transform(ClassLoader loader, String className, Class classBein 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 and unhooked async - // dispatchers (RxJava, Kotlin coroutines, OkHttp, NIO - // Asynchronous*Channel, SubmissionPublisher) referenced by app - // classes so capabilities stay honest without modifying bytecode. - scanUnhookedReferences(className, classfileBuffer, true); + } else if (className != null && !isInternalOrAgentClass(className)) { + // Fail-closed read-only constant-pool scan of EVERY non-JDK, + // non-agent loaded class (both app and library classes). Any + // class referencing a concurrency dispatch primitive or unhooked + // async dispatcher latches asyncExecutors=false UNLESS its exact + // name is in ALLOWLISTED_DISPATCH_CLASSES. + boolean checkDispatch = !ALLOWLISTED_DISPATCH_CLASSES.contains(className); + scanUnhookedReferences(className, classfileBuffer, !isKnownMessagingPoolWrapper(className), + checkDispatch); } return null; } @@ -602,6 +877,11 @@ public byte[] transform(ClassLoader loader, String className, Class classBein COUNTED.add(entry.server); } else if (entry.async) { HOOKED_SPRING_CLASSES.add(name); + } else if ("scheduled".equals(entry.job) || "quartz".equals(entry.job)) { + // Loading a scheduled job runner (@Scheduled or Quartz) means + // outbox/background ticks can execute app lines written by an + // earlier request; fail closed on asyncExecutors before W1 COV. + recordUnhookedAsyncDispatcher("scheduled-job:" + entry.job, className); } synchronized (changed) { Set names = changed.get(loader); @@ -668,6 +948,22 @@ private byte[] changedAgain(ClassLoader loader, String className, byte[] classfi return null; } } + LatchEntry latchEntry = LATCH_ON_CALL.get(className); + if (latchEntry != null) { + synchronized (changed) { + Set names = changed.get(loader); + if (names == null || !names.contains(className)) { + return null; + } + } + try { + return wrapLatchOnCall(classfile, latchEntry); + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not re-hook " + className, t); + return null; + } + } Entry entry = ENTRIES.get(className); if (entry == null) { if (wasRewritten(loader, className)) { @@ -972,7 +1268,137 @@ static boolean hasExecutorReference(ClassReader reader) { if (TARGET_ASYNC_METHOD_NAMES.contains(memberName)) { return true; } + } else if (tag == 10 || tag == 11) { + String owner = reader.readClass(offset, buf); + if ("java/util/Collection".equals(owner)) { + int ntOffset = reader.getItem(reader.readUnsignedShort(offset + 2)); + if (ntOffset > 0 && "add".equals(reader.readUTF8(ntOffset, buf))) { + return true; + } + } + } + } + return false; + } + + private byte[] hookLatchOnCall(ClassLoader loader, String className, byte[] classfileBuffer, + LatchEntry latchEntry) { + String name = className.replace('/', '.'); + try { + if (!seesGate(loader)) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup cannot hook " + name + + ": its class loader does not see keploy-sdk.jar", (Throwable) null); + return null; + } + byte[] wrapped = wrapLatchOnCall(classfileBuffer, latchEntry); + if (wrapped == null) { + // Only fail closed if this class version actually references a + // dispatch primitive without exposing the expected methods (e.g. + // Spring 5.3 ConcurrentMapCache has no async retrieve method). + if (hasDispatchPrimitiveReference(classfileBuffer)) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup cannot hook " + name + + ": none of " + latchEntry.methods + " found"); + } + return null; + } + synchronized (changed) { + Set names = changed.get(loader); + if (names == null) { + names = new HashSet<>(); + changed.put(loader, names); + } + names.add(className); + } + return wrapped; + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not hook " + name, t); + return null; + } + } + + static byte[] wrapLatchOnCall(byte[] classfile, final LatchEntry latchEntry) { + ClassReader reader = new ClassReader(classfile); + ClassWriter writer = new ClassWriter(reader, 0); + final boolean[] found = {false}; + final boolean[] alreadyHooked = {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 || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0 + || !latchEntry.methods.contains(name)) { + return mv; + } + found[0] = true; + final String reason = latchEntry.label + ":" + name; + return new MethodVisitor(Opcodes.ASM9, mv) { + private boolean injected; + + @Override + public void visitCode() { + super.visitCode(); + if (!injected) { + injected = true; + super.visitLdcInsn(reason); + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, + "noteRuntimeUntrackedDispatch", "(Ljava/lang/String;)V", false); + } + } + + @Override + public void visitMethodInsn(int opcode, String owner, String mname, String desc, + boolean isInterface) { + if (opcode == Opcodes.INVOKESTATIC && GATE.equals(owner) + && "noteRuntimeUntrackedDispatch".equals(mname)) { + alreadyHooked[0] = true; + } + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + super.visitMaxs(Math.max(maxStack, 1), maxLocals); + } + }; } + }, 0); + if (!found[0]) { + return null; + } + return alreadyHooked[0] ? classfile : writer.toByteArray(); + } + + private static boolean hasDispatchPrimitiveReference(byte[] classfile) { + if (classfile == null || classfile.length < 16) { + return false; + } + try { + ClassReader reader = new ClassReader(classfile); + 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 == 10 || tag == 11) { + String owner = reader.readClass(offset, buf); + Set methods = DISPATCH_PRIMITIVE_METHODS.get(owner); + if (methods != null) { + int ntOffset = reader.getItem(reader.readUnsignedShort(offset + 2)); + if (ntOffset > 0 && methods.contains(reader.readUTF8(ntOffset, buf))) { + return true; + } + } + } + } + } catch (Throwable ignored) { + return true; } return false; } @@ -1086,17 +1512,22 @@ private static void recordUnhookedAsyncDispatcher(String dispatcher, String sour if (SEEN_UNHOOKED_ASYNC_DISPATCHERS.add(dispatcher)) { String from = (sourceClass == null || sourceClass.isEmpty()) ? "" : sourceClass.replace('/', '.'); - LOGGER.log(Level.INFO, "Keploy dedup: observed app reference to unhooked async dispatcher " + LOGGER.log(Level.INFO, "Keploy dedup: observed reference to unhooked async dispatcher " + dispatcher + " in " + from + "; declaring asyncExecutors=false"); } } - private static void scanUnhookedReferences(String className, byte[] classfile, boolean includeRawConsumers) { + private static void scanUnhookedReferences(String className, byte[] classfile, boolean includeRawConsumers, + boolean checkDispatchPrimitives) { if (classfile == null || classfile.length < 16) { return; } + boolean allowlisted = className != null && ALLOWLISTED_DISPATCH_CLASSES.contains(className); try { ClassReader reader = new ClassReader(classfile); + if (!allowlisted && checkDispatchPrimitives && "java/lang/Thread".equals(reader.getSuperName())) { + recordUnhookedAsyncDispatcher("java.lang.Thread subclass", className); + } int itemCount = reader.getItemCount(); char[] buf = new char[reader.getMaxStringLength()]; boolean hasRawConsumerOwner = false; @@ -1108,22 +1539,40 @@ private static void scanUnhookedReferences(String className, byte[] classfile, b int tag = reader.readByte(offset - 1); if (tag == 7) { String cls = reader.readUTF8(offset, buf); - String unhookedAsync = UNHOOKED_ASYNC_DISPATCHERS.get(cls); - if (unhookedAsync != null) { - recordUnhookedAsyncDispatcher(unhookedAsync, className); + if (!allowlisted) { + String unhookedAsync = UNHOOKED_ASYNC_DISPATCHERS.get(cls); + if (unhookedAsync != null) { + recordUnhookedAsyncDispatcher(unhookedAsync, className); + } } if (includeRawConsumers && RAW_CONSUMER_OWNERS.contains(cls)) { hasRawConsumerOwner = true; } } else if (tag == 8) { // Catch reflective Class.forName("java.util.concurrent.SubmissionPublisher") - // and similar string-literal lookups in app classes. - String literal = reader.readUTF8(offset, buf); - if (literal != null && literal.indexOf('.') > 0) { - String slash = literal.replace('.', '/'); - String unhookedAsync = UNHOOKED_ASYNC_DISPATCHERS.get(slash); - if (unhookedAsync != null) { - recordUnhookedAsyncDispatcher(unhookedAsync, className); + // and similar string-literal lookups in non-allowlisted classes. + if (!allowlisted) { + String literal = reader.readUTF8(offset, buf); + if (literal != null && literal.indexOf('.') > 0) { + String slash = literal.replace('.', '/'); + String unhookedAsync = UNHOOKED_ASYNC_DISPATCHERS.get(slash); + if (unhookedAsync != null) { + recordUnhookedAsyncDispatcher(unhookedAsync, className); + } + } + } + } else if ((tag == 10 || tag == 11) && !allowlisted) { + String owner = reader.readClass(offset, buf); + Set methods = checkDispatchPrimitives + ? DISPATCH_PRIMITIVE_METHODS.get(owner) + : JDK_ASYNC_HTTP_METHODS.get(owner); + if (methods != null) { + int ntOffset = reader.getItem(reader.readUnsignedShort(offset + 2)); + if (ntOffset > 0) { + String mname = reader.readUTF8(ntOffset, buf); + if (methods.contains(mname)) { + recordUnhookedAsyncDispatcher(owner.replace('/', '.') + "." + mname, className); + } } } } @@ -1218,7 +1667,8 @@ private static boolean isMessagingProducerCall(String owner, String mname) { if (owner == null || mname == null) { return false; } - if ("org/springframework/kafka/core/KafkaTemplate".equals(owner)) { + if ("org/springframework/kafka/core/KafkaTemplate".equals(owner) + || "org/springframework/kafka/core/KafkaOperations".equals(owner)) { return "send".equals(mname) || "sendDefault".equals(mname); } if ("org/apache/kafka/clients/producer/KafkaProducer".equals(owner) @@ -1226,12 +1676,21 @@ private static boolean isMessagingProducerCall(String owner, String mname) { return "send".equals(mname); } if ("org/springframework/amqp/rabbit/core/RabbitTemplate".equals(owner) + || "org/springframework/amqp/rabbit/core/RabbitOperations".equals(owner) || "org/springframework/amqp/core/AmqpTemplate".equals(owner)) { return "send".equals(mname) || "convertAndSend".equals(mname) || "convertSendAndReceive".equals(mname); } if ("org/springframework/jms/core/JmsTemplate".equals(owner) - || "org/springframework/jms/core/JmsOperations".equals(owner)) { - return "send".equals(mname) || "convertAndSend".equals(mname) || "sendAndReceive".equals(mname); + || "org/springframework/jms/core/JmsOperations".equals(owner) + || "org/springframework/jms/core/JmsMessagingTemplate".equals(owner)) { + return "send".equals(mname) || "convertAndSend".equals(mname) + || "sendAndReceive".equals(mname) || "convertSendAndReceive".equals(mname); + } + if ("org/springframework/cloud/stream/function/StreamBridge".equals(owner)) { + return "send".equals(mname); + } + if ("reactor/kafka/sender/KafkaSender".equals(owner)) { + return "send".equals(mname) || "createOutbound".equals(mname); } return false; } @@ -1280,6 +1739,7 @@ private static boolean isDirectRawConsumerCall(String owner, String mname) { private static boolean isHookedSpringMethodRefOwner(String owner) { return "org/springframework/core/task/SimpleAsyncTaskExecutor".equals(owner) + || "org/springframework/scheduling/concurrent/SimpleAsyncTaskScheduler".equals(owner) || "org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor".equals(owner) || "org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler".equals(owner) || "org/springframework/scheduling/concurrent/ConcurrentTaskExecutor".equals(owner); @@ -1719,9 +2179,20 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, } else if (isMessagingProducerCall(owner, mname)) { emitUntrackedFlag("untracked-async:messaging-produce"); } else if ((opcode == Opcodes.INVOKEINTERFACE || opcode == Opcodes.INVOKEVIRTUAL) - && "java/util/Queue".equals(owner) - && ("offer".equals(mname) || "add".equals(mname)) - && "(Ljava/lang/Object;)Z".equals(desc)) { + && (("java/util/Queue".equals(owner) + && ("offer".equals(mname) || "add".equals(mname)) + && "(Ljava/lang/Object;)Z".equals(desc)) + || ("java/util/Deque".equals(owner) + && ((("offer".equals(mname) || "add".equals(mname) + || "offerFirst".equals(mname) + || "offerLast".equals(mname)) + && "(Ljava/lang/Object;)Z".equals(desc)) + || (("addFirst".equals(mname) || "addLast".equals(mname) + || "push".equals(mname)) + && "(Ljava/lang/Object;)V".equals(desc)))) + || ("java/util/Collection".equals(owner) + && "add".equals(mname) + && "(Ljava/lang/Object;)Z".equals(desc)))) { changed[0] = true; ensureExtraStack(2); super.visitInsn(Opcodes.DUP2); @@ -1828,6 +2299,17 @@ static byte[] wrap(byte[] classfile, Set methods, String job, boolean as return wrapper.wrapped.isEmpty() ? null : writer.toByteArray(); } + static final class LatchEntry { + + final String label; + final Set methods; + + private LatchEntry(String label, Set methods) { + this.label = label; + this.methods = Collections.unmodifiableSet(methods); + } + } + private static final class Entry { private final String server; diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index 675ba252..a1e1a26c 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -412,16 +412,26 @@ public void forkedPreCapturedAndLazyMethodRefsAndLibraryHandOffsDropAsyncExecuto } } - @Test(timeout = 300000) + @Test(timeout = 420000) public void forkedLibraryAndJdkHandOffsNeverSilentlyDropAsyncLines() throws Exception { String spec = System.getProperty("java.specification.version"); int major = spec.startsWith("1.") ? 8 : Integer.parseInt(spec); + // Each tuple: {name, minJdk, expectBaselineHonest} + // Cases whose startup creates an unhooked library/background worker or + // scheduled outbox poller fail closed at startup (expectBaselineHonest=false); + // in-window-only hand-offs keep asyncExecutors=true on baseline /clean. String[][] cases = { - {"kafka-produce", "8"}, - {"spring-listenable-callback", "8"}, - {"submission-publisher", "9"}, - {"spring-mc-override", "8"}, - {"queue-worker", "8"}, + {"kafka-produce", "8", "false"}, + {"kafka-direct-produce", "8", "true"}, + {"spring-listenable-callback", "8", "true"}, + {"submission-publisher", "9", "false"}, + {"spring-mc-override", "8", "true"}, + {"queue-worker", "8", "false"}, + {"clq-worker", "8", "false"}, + {"deque-worker", "8", "false"}, + {"collection-add", "8", "false"}, + {"lib-callback", "8", "true"}, + {"scheduled-outbox", "8", "false"}, }; for (boolean prefixMode : new boolean[] {true, false}) { for (String[] tc : cases) { @@ -429,33 +439,46 @@ public void forkedLibraryAndJdkHandOffsNeverSilentlyDropAsyncLines() throws Exce if (major < Integer.parseInt(tc[1])) { continue; } + boolean expectBaseTrue = Boolean.parseBoolean(tc[2]); try (ForkedApp app = startFork("handoff-" + name, "80", prefixMode, false, null, null)) { app.runHttpTest("ho/" + name + "-warm", "/clean"); - if (!"submission-publisher".equals(name)) { + // In index mode, DirectKafkaProducerCaller is defined dynamically + // outside KEPLOY_JAVA_CLASS_DIRS, so the read-only scan latches + // asyncExecutors=false immediately at class load (fail closed). + boolean dynamicNonIndexedProducer = "kafka-direct-produce".equals(name) && !prefixMode; + if (expectBaseTrue && !dynamicNonIndexedProducer) { assertTrue("mode=" + (prefixMode ? "prefix" : "index") + " case=" + name + " baseline /clean must keep asyncExecutors=true: " + app.lastHello, parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); } + if (dynamicNonIndexedProducer) { + assertFalse("mode=index case=kafka-direct-produce must fail closed on non-indexed producer load: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } String cov1 = app.runHttpTest("ho/" + name + "-w1", "/handoff-" + name + "?ms=400"); JsonObject helloAfter1 = parseHello(app.lastHello); String cov2 = app.runHttpTest("ho/" + name + "-next", "/clean"); Thread.sleep(700); String cov3 = app.runHttpTest("ho/" + name + "-after700", "/clean"); - JsonObject helloEnd = parseHello(app.lastHello); boolean flagged1 = cov1.contains("\"windowCut\":true") || cov1.contains("\"contaminated\"") || cov1.contains("\"unverified\""); - boolean asyncOff = !helloAfter1.get("asyncExecutors").getAsBoolean() - || !helloEnd.get("asyncExecutors").getAsBoolean(); + boolean asyncOffAtW1 = !helloAfter1.get("asyncExecutors").getAsBoolean(); + // Strict W1 honesty: W1's own COV must be flagged OR under a non-honest + // HELLO BEFORE W1's COV (never relying on a late latch at helloEnd). assertTrue("mode=" + (prefixMode ? "prefix" : "index") + " case=" + name - + " must NEVER be silent-missing: W1=" + cov1 + " helloAfter1=" + helloAfter1 - + " helloEnd=" + helloEnd, - flagged1 || asyncOff); + + " must be W1-flagged or latched BEFORE W1 COV: W1=" + cov1 + + " helloAfter1=" + helloAfter1, + flagged1 || asyncOffAtW1); + if ("kafka-direct-produce".equals(name) && prefixMode) { + assertTrue("kafka-direct-produce must flag W1 COV at the call site: " + cov1, + cov1.contains("untracked-async:messaging-produce")); + } for (String later : new String[] {cov2, cov3}) { boolean laterFlagged = later.contains("\"windowCut\":true") || later.contains("\"contaminated\"") || later.contains("\"unverified\""); - if (!asyncOff && later.contains("\"" + ASYNC_TAIL + "\"")) { + if (!asyncOffAtW1 && later.contains("\"" + ASYNC_TAIL + "\"")) { assertTrue("mode=" + (prefixMode ? "prefix" : "index") + " case=" + name + " clean later window must not silently hold async lines: " + later, laterFlagged); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index e1c3abed..650c199e 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -4971,6 +4971,693 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); } + @Test(timeout = 60000) + public void perClassDispatchAllowlistFailClosedAndLatchOnCallHooks() throws Exception { + ClassLoader loader = getClass().getClassLoader(); + ServerEntries transformer = new ServerEntries(true, Collections.singleton("com/acme/App"), null); + + // 1. Every entry in ALLOWLISTED_DISPATCH_CLASSES must be an exact internal + // class name (no wildcards/prefixes) and must never include unhooked + // async frameworks. + Set allowlisted = ServerEntries.allowlistedDispatchClasses(); + assertFalse("allowlist must be non-empty", allowlisted.isEmpty()); + String[] forbiddenPrefixes = { + "kotlinx/", "kotlin/", "reactor/", "okhttp3/", "com/google/common/", + "org/springframework/integration/", "rx/", "io/reactivex/", "io/grpc/", + "io/netty/", "org/apache/hc/", "org/apache/http/", "akka/", + "org/apache/pekko/", "io/nats/", "io/fakeexternal/", "org/h2/store/fs/async/" + }; + for (String cls : allowlisted) { + assertFalse("allowlist entry must not end with '/': " + cls, cls.endsWith("/")); + assertFalse("allowlist entry must not contain '*': " + cls, cls.contains("*")); + assertFalse("allowlist entry must use internal '/' format: " + cls, cls.contains(".")); + for (String bad : forbiddenPrefixes) { + assertFalse("unhooked async framework must never be allowlisted: " + cls, cls.startsWith(bad)); + } + // Positive control: allowlisted class referencing Executor.execute must NOT latch. + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + transformer.transform(loader, cls, null, null, generateExecutorCaller(cls)); + assertFalse("allowlisted class must not false-latch on load: " + cls, + ServerEntries.hasUnhookedAsyncDispatcher()); + } + + // 2. Any non-allowlisted library class calling a concurrency dispatch primitive + // (Executor.execute, Thread.start, CompletableFuture.supplyAsync, BlockingQueue.offer, + // ConcurrentLinkedQueue.add, HttpClient.sendAsync) latches asyncExecutors=false + // without any package exclusion hiding it. + String[][] unhookedLibCallers = { + {"kotlinx/coroutines/scheduling/CoroutineScheduler", "java/lang/Thread", "start", "()V", "virtual"}, + {"kotlin/concurrent/ThreadsKt", "java/lang/Thread", "start", "()V", "virtual"}, + {"reactor/core/scheduler/ParallelScheduler", "java/util/concurrent/ScheduledExecutorService", + "schedule", "(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture;", "interface"}, + {"okhttp3/internal/concurrent/TaskRunner", "java/util/concurrent/Executor", "execute", "(Ljava/lang/Runnable;)V", "interface"}, + {"com/google/common/eventbus/AsyncEventBus", "java/util/concurrent/Executor", "execute", "(Ljava/lang/Runnable;)V", "interface"}, + {"org/springframework/integration/channel/ExecutorChannel", "java/util/concurrent/Executor", "execute", "(Ljava/lang/Runnable;)V", "interface"}, + {"io/fakeexternal/CustomCallbackClient", "java/util/concurrent/LinkedBlockingQueue", "offer", "(Ljava/lang/Object;)Z", "virtual"}, + {"com/thirdparty/ClqBus", "java/util/concurrent/ConcurrentLinkedQueue", "add", "(Ljava/lang/Object;)Z", "virtual"}, + {"com/thirdparty/CfHelper", "java/util/concurrent/CompletableFuture", "supplyAsync", + "(Ljava/util/function/Supplier;)Ljava/util/concurrent/CompletableFuture;", "static"}, + {"com/thirdparty/JdkHttpAsync", "java/net/http/HttpClient", "sendAsync", + "(Ljava/net/http/HttpRequest;Ljava/net/http/HttpResponse$BodyHandler;)Ljava/util/concurrent/CompletableFuture;", "virtual"}, + }; + for (String[] spec : unhookedLibCallers) { + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + byte[] bytes = generateMethodRefCaller(spec[0], spec[1], spec[2], spec[3], spec[4]); + assertNull("non-app library class must never be bytecode-rewritten: " + spec[0], + transformer.transform(loader, spec[0], null, null, bytes)); + assertTrue("non-allowlisted library class calling " + spec[1] + "." + spec[2] + + " must latch asyncExecutors=false: " + spec[0], + ServerEntries.hasUnhookedAsyncDispatcher()); + } + + // 2b. Even a rewritten app class calling JDK HttpClient.sendAsync latches asyncExecutors=false. + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + byte[] appHttpAsync = generateMethodRefCaller("com/acme/App", "java/net/http/HttpClient", "sendAsync", + "(Ljava/net/http/HttpRequest;Ljava/net/http/HttpResponse$BodyHandler;)Ljava/util/concurrent/CompletableFuture;", + "virtual"); + transformer.transform(loader, "com/acme/App", null, null, appHttpAsync); + assertTrue("app class calling HttpClient.sendAsync must latch asyncExecutors=false", + ServerEntries.hasUnhookedAsyncDispatcher()); + + // 2c. Non-allowlisted library Thread subclass (e.g. Kotlin's kotlin.concurrent.thread + // anonymous Thread subclass whose INVOKEVIRTUAL targets itself rather than java/lang/Thread) + // must latch asyncExecutors=false on load by construction. + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + ClassWriter threadSubCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + threadSubCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "kotlin/concurrent/ThreadsKt$thread$thread$1", + null, "java/lang/Thread", null); + emitDefaultCtor(threadSubCw); + threadSubCw.visitEnd(); + assertNull("non-allowlisted Thread subclass must not be rewritten", + transformer.transform(loader, "kotlin/concurrent/ThreadsKt$thread$thread$1", null, null, + threadSubCw.toByteArray())); + assertTrue("non-allowlisted library Thread subclass must latch asyncExecutors=false", + ServerEntries.hasUnhookedAsyncDispatcher()); + + // 3. LATCH_ON_CALL hooks: loading sync Caffeine / CacheLoader / LocalAsyncCache / + // Spring ConcurrentMapCache does NOT latch; invoking their async methods DOES + // latch asyncExecutors=false and contaminates the active window! + String[][] latchHooks = { + {"com/github/benmanes/caffeine/cache/Caffeine", "buildAsync", "class"}, + {"com/github/benmanes/caffeine/cache/CacheLoader", "asyncReload", "interface"}, + {"com/github/benmanes/caffeine/cache/LocalAsyncCache", "get", "interface"}, + {"org/springframework/cache/concurrent/ConcurrentMapCache", "retrieve", "class"}, + }; + for (String[] hook : latchHooks) { + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + byte[] raw = generateLatchHookStandIn(hook[0], hook[1], "interface".equals(hook[2])); + byte[] hooked = transformer.transform(loader, hook[0], null, null, raw); + assertNotNull("LATCH_ON_CALL class must be instrumented: " + hook[0], hooked); + assertFalse("loading " + hook[0] + " alone must not latch asyncExecutors", + ServerEntries.hasUnhookedAsyncDispatcher()); + assertFalse("loading " + hook[0] + " alone must not latch observedPreCapturedUntrackedExecutor", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // Invoke the hooked method inside an active window via a concrete subclass or instance. + ByteLoader bl = new ByteLoader(loader); + Class defined = bl.define(hook[0].replace('/', '.'), hooked); + Object instance; + if ("interface".equals(hook[2])) { + String implName = hook[0] + "$TestImpl"; + byte[] implBytes = generateInterfaceImpl(implName, hook[0]); + instance = bl.define(implName.replace('/', '.'), implBytes).getDeclaredConstructor().newInstance(); + } else { + instance = defined.getDeclaredConstructor().newInstance(); + } + RequestGate.disarm(); + RequestGate.open("latch-hook-" + hook[1], null); + Object tok = RequestGate.enter(); + try { + defined.getMethod(hook[1]).invoke(instance); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome out = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("invoking " + hook[0] + "." + hook[1] + " must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + assertFalse("invoking " + hook[0] + "." + hook[1] + " inside window must contaminate: " + + out.contaminations, out.contaminations.isEmpty()); + } + } + + @Test(timeout = 60000) + public void isolatedCallSiteAndJobGateLatchesForListenableFutureDirectQueueAndScheduledJobs() throws Exception { + ClassLoader loader = getClass().getClassLoader(); + + // 1. Direct LinkedBlockingQueue.offer call site (static owner IS LinkedBlockingQueue, + // not java/util/Queue) must contaminate with untracked-async:blocking-queue. + String bqClsName = "com/acme/DirectBlockingQueueCaller"; + ClassWriter bqCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + bqCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, bqClsName, null, "java/lang/Object", null); + emitDefaultCtor(bqCw); + MethodVisitor bqMv = bqCw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "enqueue", + "(Ljava/util/concurrent/LinkedBlockingQueue;Ljava/lang/Object;)Z", null, null); + bqMv.visitCode(); + bqMv.visitVarInsn(Opcodes.ALOAD, 0); + bqMv.visitVarInsn(Opcodes.ALOAD, 1); + bqMv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/LinkedBlockingQueue", + "offer", "(Ljava/lang/Object;)Z", false); + bqMv.visitInsn(Opcodes.IRETURN); + bqMv.visitMaxs(2, 2); + bqMv.visitEnd(); + bqCw.visitEnd(); + + ServerEntries bqEntries = new ServerEntries(true, Collections.singleton(bqClsName), null); + byte[] bqRewritten = bqEntries.transform(loader, bqClsName, null, null, bqCw.toByteArray()); + assertNotNull("direct LinkedBlockingQueue caller must be rewritten", bqRewritten); + Class bqCls = new ByteLoader(loader).define(bqClsName.replace('/', '.'), bqRewritten); + RequestGate.disarm(); + RequestGate.open("direct-bq", null); + Object tok = RequestGate.enter(); + try { + bqCls.getMethod("enqueue", LinkedBlockingQueue.class, Object.class) + .invoke(null, new LinkedBlockingQueue(), "item"); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome bqOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("direct LinkedBlockingQueue.offer must contaminate: " + bqOut.contaminations, + bqOut.contaminations.contains("untracked-async:blocking-queue")); + + // 2. Spring ListenableFuture.addCallback call site in a rewritten app class must + // contaminate with untracked-async:spring-listenable-future. + String lfCbIface = "org/springframework/util/concurrent/ListenableFutureCallback"; + String lfIface = "org/springframework/util/concurrent/ListenableFuture"; + String lfImpl = "com/acme/StubListenableFuture"; + String lfCaller = "com/acme/SpringListenableCaller"; + String addCbDesc = "(L" + lfCbIface + ";)V"; + ByteLoader lfLoader = new ByteLoader(loader); + + ClassWriter lfCbCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + lfCbCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT, + lfCbIface, null, "java/lang/Object", null); + lfCbCw.visitEnd(); + Class lfCbCls = lfLoader.define(lfCbIface.replace('/', '.'), lfCbCw.toByteArray()); + + ClassWriter lfIfaceCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + lfIfaceCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT, + lfIface, null, "java/lang/Object", null); + lfIfaceCw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, "addCallback", + addCbDesc, null, null).visitEnd(); + lfIfaceCw.visitEnd(); + Class lfIfaceCls = lfLoader.define(lfIface.replace('/', '.'), lfIfaceCw.toByteArray()); + + ClassWriter lfImplCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + lfImplCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, lfImpl, null, "java/lang/Object", new String[] {lfIface}); + emitDefaultCtor(lfImplCw); + MethodVisitor implMv = lfImplCw.visitMethod(Opcodes.ACC_PUBLIC, "addCallback", + addCbDesc, null, null); + implMv.visitCode(); + implMv.visitInsn(Opcodes.RETURN); + implMv.visitMaxs(0, 2); + implMv.visitEnd(); + lfImplCw.visitEnd(); + Object lfInstance = lfLoader.define(lfImpl.replace('/', '.'), lfImplCw.toByteArray()) + .getDeclaredConstructor().newInstance(); + + ClassWriter lfCallerCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + lfCallerCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, lfCaller, null, "java/lang/Object", null); + emitDefaultCtor(lfCallerCw); + MethodVisitor callerMv = lfCallerCw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "attach", + "(L" + lfIface + ";L" + lfCbIface + ";)V", null, null); + callerMv.visitCode(); + callerMv.visitVarInsn(Opcodes.ALOAD, 0); + callerMv.visitVarInsn(Opcodes.ALOAD, 1); + callerMv.visitMethodInsn(Opcodes.INVOKEINTERFACE, lfIface, "addCallback", addCbDesc, true); + callerMv.visitInsn(Opcodes.RETURN); + callerMv.visitMaxs(2, 2); + callerMv.visitEnd(); + lfCallerCw.visitEnd(); + + ServerEntries lfEntries = new ServerEntries(true, Collections.singleton(lfCaller), null); + byte[] lfRewritten = lfEntries.transform(lfLoader, lfCaller, null, null, lfCallerCw.toByteArray()); + assertNotNull("Spring ListenableFuture caller must be rewritten", lfRewritten); + Class lfCallerCls = lfLoader.define(lfCaller.replace('/', '.'), lfRewritten); + RequestGate.disarm(); + RequestGate.open("spring-lf", null); + tok = RequestGate.enter(); + try { + lfCallerCls.getMethod("attach", lfIfaceCls, lfCbCls).invoke(null, lfInstance, null); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome lfOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("Spring ListenableFuture.addCallback must contaminate: " + lfOut.contaminations, + lfOut.contaminations.contains("untracked-async:spring-listenable-future")); + + // 3. Scheduled job classes (ScheduledMethodRunnable / JobRunShell) latch on load. + ServerEntries schedEntries = new ServerEntries(true, Collections.singleton("com/acme/App"), null); + for (String jobCls : new String[] { + "org/springframework/scheduling/support/ScheduledMethodRunnable", + "org/quartz/core/JobRunShell" + }) { + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + ClassWriter jobCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + jobCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, jobCls, null, "java/lang/Object", null); + emitDefaultCtor(jobCw); + MethodVisitor runMv = jobCw.visitMethod(Opcodes.ACC_PUBLIC, "run", "()V", null, null); + runMv.visitCode(); + runMv.visitInsn(Opcodes.RETURN); + runMv.visitMaxs(0, 1); + runMv.visitEnd(); + jobCw.visitEnd(); + assertNotNull("scheduled job class must still be hooked: " + jobCls, + schedEntries.transform(loader, jobCls, null, null, jobCw.toByteArray())); + assertTrue("loading scheduled job class must latch asyncExecutors=false: " + jobCls, + ServerEntries.hasUnhookedAsyncDispatcher()); + } + + // 4. JobGate.enter for async message listeners ("kafka", "listener") and scheduled jobs + // ("scheduled", "quartz") must each independently latch observedPreCapturedUntrackedExecutor. + RequestGate.arm(); + try { + for (String kind : new String[] {"kafka", "listener", "scheduled", "quartz"}) { + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + Object jobTok = JobGate.enter("unit-" + kind, kind); + try { + assertTrue("JobGate.enter(" + kind + ") must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + JobGate.exit(jobTok); + } + } + } finally { + RequestGate.disarm(); + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + } + } + + @Test(timeout = 60000) + public void queueRuntimeCheckDirectSubmissionPublisherMessagingProducerAndExternalOverflow() throws Exception { + ClassLoader loader = getClass().getClassLoader(); + + // 1. Runtime Queue/Deque/Collection instanceof check (kills QUEUE_RUNTIME_NOOP): + // static java.util.Queue / Deque / Collection call sites must contaminate for + // BlockingQueue & ConcurrentLinkedQueue, and stay clean for ArrayDeque / ArrayList. + String qClsName = "com/acme/QueueRuntimeCaller"; + ServerEntries qEntries = new ServerEntries(true, Collections.singleton(qClsName), null); + byte[] qRewritten = qEntries.transform(loader, qClsName, null, null, generateQueueRuntimeCaller(qClsName)); + assertNotNull("Queue/Deque/Collection caller must be rewritten", qRewritten); + Class qCls = new ByteLoader(loader).define(qClsName.replace('/', '.'), qRewritten); + + // BlockingQueue via static java.util.Queue -> contaminates! + RequestGate.disarm(); + RequestGate.open("q-blocking", null); + Object tok = RequestGate.enter(); + try { + qCls.getMethod("offerQueue", java.util.Queue.class, Object.class) + .invoke(null, new LinkedBlockingQueue(), "item"); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome qOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("static Queue backed by LinkedBlockingQueue must contaminate: " + qOut.contaminations, + qOut.contaminations.contains("untracked-async:blocking-queue")); + + // LinkedBlockingDeque via static java.util.Deque -> contaminates! + RequestGate.disarm(); + RequestGate.open("q-deque", null); + tok = RequestGate.enter(); + try { + qCls.getMethod("offerLastDeque", java.util.Deque.class, Object.class) + .invoke(null, new java.util.concurrent.LinkedBlockingDeque(), "item"); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome dOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("static Deque backed by LinkedBlockingDeque must contaminate: " + dOut.contaminations, + dOut.contaminations.contains("untracked-async:blocking-queue")); + + // LinkedBlockingQueue via static java.util.Collection.add -> contaminates! + RequestGate.disarm(); + RequestGate.open("q-collection", null); + tok = RequestGate.enter(); + try { + qCls.getMethod("addCollection", java.util.Collection.class, Object.class) + .invoke(null, new LinkedBlockingQueue(), "item"); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome cOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("static Collection backed by LinkedBlockingQueue must contaminate: " + cOut.contaminations, + cOut.contaminations.contains("untracked-async:blocking-queue")); + + // ConcurrentLinkedQueue via static java.util.Queue -> contaminates! + RequestGate.disarm(); + RequestGate.open("q-clq", null); + tok = RequestGate.enter(); + try { + qCls.getMethod("offerQueue", java.util.Queue.class, Object.class) + .invoke(null, new java.util.concurrent.ConcurrentLinkedQueue(), "item"); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome clqOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("static Queue backed by ConcurrentLinkedQueue must contaminate: " + clqOut.contaminations, + clqOut.contaminations.contains("untracked-async:blocking-queue")); + + // Negative controls: ArrayDeque & ArrayList must NOT contaminate! + RequestGate.disarm(); + RequestGate.open("q-plain", null); + tok = RequestGate.enter(); + try { + qCls.getMethod("offerQueue", java.util.Queue.class, Object.class) + .invoke(null, new java.util.ArrayDeque(), "item"); + qCls.getMethod("offerLastDeque", java.util.Deque.class, Object.class) + .invoke(null, new java.util.ArrayDeque(), "item"); + qCls.getMethod("addCollection", java.util.Collection.class, Object.class) + .invoke(null, new ArrayList(), "item"); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome plainOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("plain ArrayDeque/ArrayList must not contaminate: " + plainOut.contaminations, + plainOut.contaminations.isEmpty()); + + // 2. Direct bytecode SubmissionPublisher.submit call site (kills SUBPUB_FLAG_DROP): + String spClsName = "com/acme/DirectSubPubCaller"; + ServerEntries spEntries = new ServerEntries(true, Collections.singleton(spClsName), null); + byte[] spRewritten = spEntries.transform(loader, spClsName, null, null, + generateDirectSubmissionPublisherCaller(spClsName)); + assertNotNull("direct SubmissionPublisher.submit caller must be rewritten", spRewritten); + assertTrue("rewritten SubmissionPublisher caller must emit untracked-async:submission-publisher", + containsLdcString(spRewritten, "untracked-async:submission-publisher")); + String spec = System.getProperty("java.specification.version", "1.8"); + int major = spec.startsWith("1.") ? 8 : Integer.parseInt(spec); + if (major >= 9) { + Class spCaller = new ByteLoader(loader).define(spClsName.replace('/', '.'), spRewritten); + Class spType = Class.forName("java.util.concurrent.SubmissionPublisher"); + Object pub = spType.getConstructor().newInstance(); + try { + RequestGate.disarm(); + RequestGate.open("sp-direct", null); + tok = RequestGate.enter(); + try { + spCaller.getMethod("publish", Object.class, Object.class).invoke(null, pub, "msg"); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome spOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("direct SubmissionPublisher.submit must contaminate W1: " + spOut.contaminations, + spOut.contaminations.contains("untracked-async:submission-publisher")); + } finally { + spType.getMethod("close").invoke(pub); + } + } + + // 3. Direct bytecode messaging producer call sites (kills MSG_PRODUCE_FLAG_DROP) + // with NO listener running: KafkaTemplate, KafkaOperations, RabbitOperations, + // JmsMessagingTemplate, StreamBridge, and Reactor KafkaSender! + String[][] msgProducers = { + {"org/springframework/kafka/core/KafkaTemplate", "send", "class"}, + {"org/springframework/kafka/core/KafkaOperations", "send", "interface"}, + {"org/springframework/amqp/rabbit/core/RabbitOperations", "convertAndSend", "interface"}, + {"org/springframework/jms/core/JmsMessagingTemplate", "convertAndSend", "class"}, + {"org/springframework/cloud/stream/function/StreamBridge", "send", "class"}, + {"reactor/kafka/sender/KafkaSender", "send", "interface"}, + }; + for (int i = 0; i < msgProducers.length; i++) { + final String owner = msgProducers[i][0]; + final String method = msgProducers[i][1]; + final boolean isIface = "interface".equals(msgProducers[i][2]); + final String callerName = "com/acme/MsgProducerCaller" + i; + ServerEntries msgEntries = new ServerEntries(true, Collections.singleton(callerName), null); + byte[] callerBytes = generateMsgProducerCaller(callerName, owner, method, isIface); + byte[] rewrittenCaller = msgEntries.transform(loader, callerName, null, null, callerBytes); + assertNotNull("messaging producer caller must be rewritten for " + owner, rewrittenCaller); + + final byte[] ownerBytes = generateMsgProducerStub(owner, method, isIface); + final String implName = owner + "$StubImpl"; + final byte[] implBytes = isIface ? generateMsgProducerImpl(implName, owner, method) : null; + ClassLoader msgLoader = new ClassLoader(loader) { + @Override + protected Class findClass(String name) throws ClassNotFoundException { + String internal = name.replace('.', '/'); + if (owner.equals(internal)) { + return defineClass(name, ownerBytes, 0, ownerBytes.length); + } + if (isIface && implName.equals(internal)) { + return defineClass(name, implBytes, 0, implBytes.length); + } + if (callerName.equals(internal)) { + return defineClass(name, rewrittenCaller, 0, rewrittenCaller.length); + } + throw new ClassNotFoundException(name); + } + }; + Object producer = msgLoader.loadClass((isIface ? implName : owner).replace('/', '.')) + .getDeclaredConstructor().newInstance(); + Class callerCls = msgLoader.loadClass(callerName.replace('/', '.')); + + RequestGate.disarm(); + RequestGate.open("msg-prod-" + i, null); + tok = RequestGate.enter(); + try { + callerCls.getMethod("produce", Object.class).invoke(null, producer); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome mOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("direct " + owner + "." + method + " must contaminate W1 with untracked-async:messaging-produce: " + + mOut.contaminations, mOut.contaminations.contains("untracked-async:messaging-produce")); + } + + // 4. External untracked handle queue overflow (>64 live handles) for BOTH active-job + // and expired-job branches (kills OVERFLOW_EXT_NOLATCH deterministically). + RequestGate.disarm(); + RequestGate.open("ext-ov-active-init", null); + Object jobTok = JobGate.enter(new Object(), "quartz"); + try { + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + for (int i = 0; i < 66; i++) { + RequestGate.trackUntrackedFuture(new CompletableFuture(), "untracked-async:schedule"); + } + assertTrue("active-job >64 external handle overflow must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + JobGate.exit(jobTok); + } + + RequestGate.disarm(); + RequestGate.open("ext-ov-expired-init", null); + JobGate.Attribution expiredAttr = new JobGate.Attribution( + "quartz:expired.job", true, System.nanoTime() - TimeUnit.SECONDS.toNanos(5)); + Object expTok = JobGate.enterAs(expiredAttr); + try { + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + for (int i = 0; i < 66; i++) { + RequestGate.trackUntrackedFuture(new CompletableFuture(), "untracked-async:schedule"); + } + assertTrue("expired-job >64 external handle overflow must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + JobGate.exit(expTok); + } + + // 5. App code starting a background thread outside any request window or job + // must latch asyncExecutors=false (closes app-owned queue/outbox workers). + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + Thread bg = new Thread(() -> { }, "app-outside-bg"); + RequestGate.startThread(bg); + bg.join(5000); + assertTrue("Thread.start outside window/job while unarmed must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + RequestGate.open("bg-armed-outside", null); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + Thread bgArmed = new Thread(() -> { }, "app-outside-bg-armed"); + RequestGate.startThread(bgArmed); + bgArmed.join(5000); + assertTrue("Thread.start outside window/job while armed must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } + + private static boolean containsLdcString(byte[] classfile, final String needle) { + final boolean[] found = {false}; + new org.objectweb.asm.ClassReader(classfile).accept(new org.objectweb.asm.ClassVisitor(Opcodes.ASM9) { + @Override + public MethodVisitor visitMethod(int access, String name, String desc, String sig, String[] ex) { + return new MethodVisitor(Opcodes.ASM9) { + @Override + public void visitLdcInsn(Object value) { + if (needle.equals(value)) { + found[0] = true; + } + } + }; + } + }, 0); + return found[0]; + } + + private static byte[] generateMethodRefCaller(String clsName, String owner, String mname, String desc, + String kind) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, clsName, null, "java/lang/Object", null); + emitDefaultCtor(cw); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "call", "()V", null, null); + mv.visitCode(); + int op = "static".equals(kind) ? Opcodes.INVOKESTATIC + : "interface".equals(kind) ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL; + if (op != Opcodes.INVOKESTATIC) { + mv.visitInsn(Opcodes.ACONST_NULL); + } + org.objectweb.asm.Type[] args = org.objectweb.asm.Type.getArgumentTypes(desc); + for (org.objectweb.asm.Type arg : args) { + if (arg.getSort() == org.objectweb.asm.Type.LONG) { + mv.visitInsn(Opcodes.LCONST_0); + } else { + mv.visitInsn(Opcodes.ACONST_NULL); + } + } + mv.visitMethodInsn(op, owner, mname, desc, op == Opcodes.INVOKEINTERFACE); + org.objectweb.asm.Type ret = org.objectweb.asm.Type.getReturnType(desc); + if (ret.getSort() != org.objectweb.asm.Type.VOID) { + mv.visitInsn(ret.getSize() == 2 ? Opcodes.POP2 : Opcodes.POP); + } + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateLatchHookStandIn(String clsName, String methodName, boolean isInterface) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + int acc = Opcodes.ACC_PUBLIC | (isInterface ? (Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT) : 0); + cw.visit(Opcodes.V1_8, acc, clsName, null, "java/lang/Object", null); + if (!isInterface) { + emitDefaultCtor(cw); + } + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, methodName, "()V", null, null); + mv.visitCode(); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(0, 1); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateInterfaceImpl(String implName, String ifaceName) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, implName, null, "java/lang/Object", new String[] {ifaceName}); + emitDefaultCtor(cw); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateQueueRuntimeCaller(String clsName) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, clsName, null, "java/lang/Object", null); + emitDefaultCtor(cw); + + MethodVisitor m1 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "offerQueue", + "(Ljava/util/Queue;Ljava/lang/Object;)Z", null, null); + m1.visitCode(); + m1.visitVarInsn(Opcodes.ALOAD, 0); + m1.visitVarInsn(Opcodes.ALOAD, 1); + m1.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Queue", "offer", "(Ljava/lang/Object;)Z", true); + m1.visitInsn(Opcodes.IRETURN); + m1.visitMaxs(2, 2); + m1.visitEnd(); + + MethodVisitor m2 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "offerLastDeque", + "(Ljava/util/Deque;Ljava/lang/Object;)Z", null, null); + m2.visitCode(); + m2.visitVarInsn(Opcodes.ALOAD, 0); + m2.visitVarInsn(Opcodes.ALOAD, 1); + m2.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Deque", "offerLast", "(Ljava/lang/Object;)Z", true); + m2.visitInsn(Opcodes.IRETURN); + m2.visitMaxs(2, 2); + m2.visitEnd(); + + MethodVisitor m3 = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "addCollection", + "(Ljava/util/Collection;Ljava/lang/Object;)Z", null, null); + m3.visitCode(); + m3.visitVarInsn(Opcodes.ALOAD, 0); + m3.visitVarInsn(Opcodes.ALOAD, 1); + m3.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Collection", "add", "(Ljava/lang/Object;)Z", true); + m3.visitInsn(Opcodes.IRETURN); + m3.visitMaxs(2, 2); + m3.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateDirectSubmissionPublisherCaller(String clsName) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, clsName, null, "java/lang/Object", null); + emitDefaultCtor(cw); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "publish", + "(Ljava/lang/Object;Ljava/lang/Object;)I", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/concurrent/SubmissionPublisher"); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/SubmissionPublisher", + "submit", "(Ljava/lang/Object;)I", false); + mv.visitInsn(Opcodes.IRETURN); + mv.visitMaxs(2, 2); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateMsgProducerStub(String owner, String method, boolean isIface) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + int acc = Opcodes.ACC_PUBLIC | (isIface ? (Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT) : 0); + cw.visit(Opcodes.V1_8, acc, owner, null, "java/lang/Object", null); + if (!isIface) { + emitDefaultCtor(cw); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, method, "(Ljava/lang/String;)V", null, null); + mv.visitCode(); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(0, 2); + mv.visitEnd(); + } else { + cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, method, "(Ljava/lang/String;)V", null, null) + .visitEnd(); + } + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateMsgProducerImpl(String implName, String ifaceName, String method) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, implName, null, "java/lang/Object", new String[] {ifaceName}); + emitDefaultCtor(cw); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, method, "(Ljava/lang/String;)V", null, null); + mv.visitCode(); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(0, 2); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateMsgProducerCaller(String callerName, String owner, String method, boolean isIface) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, callerName, null, "java/lang/Object", null); + emitDefaultCtor(cw); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "produce", + "(Ljava/lang/Object;)V", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitTypeInsn(Opcodes.CHECKCAST, owner); + mv.visitLdcInsn("payload"); + mv.visitMethodInsn(isIface ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL, + owner, method, "(Ljava/lang/String;)V", isIface); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(2, 1); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + private static byte[] generateAppReferencingClass(String appInternalName, String targetInternalName) { org.objectweb.asm.ClassWriter cw = new org.objectweb.asm.ClassWriter(0); cw.visit(org.objectweb.asm.Opcodes.V1_8, org.objectweb.asm.Opcodes.ACC_PUBLIC, appInternalName, null, 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 84e8e722..3be76619 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/JobTailTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/JobTailTest.java @@ -316,15 +316,15 @@ private final class App implements AutoCloseable { String test(String id, String... jobs) throws IOException { String fullId = "test-set-0/" + id; send(sdkOut, "START " + fullId); - assertEquals("ACK", sdkIn.readLine()); + assertEquals("ACK", nextNonHello()); for (String job : jobs) { command(job); } send(sdkOut, "END " + fullId); - String cov = sdkIn.readLine(); + String cov = nextNonHello(); assertTrue(cov, cov != null && cov.startsWith("COV ")); String line; - while (!(line = sdkIn.readLine()).equals("ACK")) { + while (!(line = nextNonHello()).equals("ACK")) { assertTrue(line, line.startsWith("CLASSES ") || line.startsWith("MANIFEST ")); } cov = cov.substring("COV ".length()); @@ -332,6 +332,14 @@ String test(String id, String... jobs) throws IOException { return cov; } + private String nextNonHello() throws IOException { + String line; + while ((line = sdkIn.readLine()) != null && line.startsWith("HELLO ")) { + // Skip asynchronous HELLO capability refresh frames. + } + return line; + } + // command has JobApp fire a job, and returns once its run is over. void command(String job) throws IOException { send(commandOut, job); diff --git a/keploy-sdk/src/test/java/org/example/jobs/Events.java b/keploy-sdk/src/test/java/org/example/jobs/Events.java index d441ae77..ac311edc 100644 --- a/keploy-sdk/src/test/java/org/example/jobs/Events.java +++ b/keploy-sdk/src/test/java/org/example/jobs/Events.java @@ -89,6 +89,10 @@ static void finish() { CountDownLatch drained = new CountDownLatch(1); POOL.getThreadPoolExecutor().execute(drained::countDown); awaitOrFail(drained); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (POOL.getThreadPoolExecutor().getActiveCount() > 0 && System.nanoTime() < deadline) { + Thread.yield(); + } } static void close() { diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index 02c1bdcc..b19fdbeb 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -595,7 +595,27 @@ static void submit(long ms) throws Exception { public static final class HandOffFixtures { private static final LinkedBlockingQueue APP_WORKER_QUEUE = new LinkedBlockingQueue<>(); + private static final java.util.concurrent.ConcurrentLinkedQueue APP_CLQ = + new java.util.concurrent.ConcurrentLinkedQueue<>(); + private static final java.util.Deque APP_DEQUE = + new java.util.concurrent.LinkedBlockingDeque<>(); + private static final java.util.Collection APP_COLLECTION = new LinkedBlockingQueue<>(); + private static final java.util.Queue OUTBOX_QUEUE = + new java.util.concurrent.ConcurrentLinkedQueue<>(); private static volatile org.springframework.context.event.SimpleApplicationEventMulticaster overrideMc; + private static volatile org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler outboxScheduler; + private static volatile Object fakeKafkaTemplate; + private static volatile Method directKafkaSendMethod; + + public static final class OutboxPoller { + public void drain() { + Long ms; + while ((ms = OUTBOX_QUEUE.poll()) != null) { + sleepQuietly(ms.longValue()); + AsyncTail.ran(); + } + } + } static void init(String kind) throws Exception { if ("submission-publisher".equals(kind)) { @@ -613,6 +633,75 @@ static void init(String kind) throws Exception { }, "app-queue-worker"); worker.setDaemon(true); worker.start(); + } else if ("clq-worker".equals(kind)) { + Thread worker = new Thread(() -> { + while (!Thread.currentThread().isInterrupted()) { + Runnable r = APP_CLQ.poll(); + if (r == null) { + java.util.concurrent.locks.LockSupport.parkNanos(2_000_000L); + continue; + } + r.run(); + } + }, "app-clq-worker"); + worker.setDaemon(true); + worker.start(); + } else if ("deque-worker".equals(kind)) { + Thread worker = new Thread(() -> { + while (!Thread.currentThread().isInterrupted()) { + try { + ((java.util.concurrent.BlockingDeque) APP_DEQUE).takeFirst().run(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + }, "app-deque-worker"); + worker.setDaemon(true); + worker.start(); + } else if ("collection-add".equals(kind)) { + Thread worker = new Thread(() -> { + while (!Thread.currentThread().isInterrupted()) { + try { + ((LinkedBlockingQueue) APP_COLLECTION).take().run(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + }, "app-collection-worker"); + worker.setDaemon(true); + worker.start(); + } else if ("scheduled-outbox".equals(kind)) { + org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler ts = + new org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler(); + ts.initialize(); + ts.scheduleWithFixedDelay( + new org.springframework.scheduling.support.ScheduledMethodRunnable(new OutboxPoller(), "drain"), + 250L); + outboxScheduler = ts; + } else if ("kafka-direct-produce".equals(kind)) { + // Define a stand-in org/springframework/kafka/core/KafkaTemplate and an + // app caller class in org/example/servers/ that invokes KafkaTemplate.send() + // directly in bytecode (no listener running) so W1's own COV must flag! + final byte[] tplBytes = generateKafkaTemplateStub(); + final byte[] callerBytes = generateKafkaProducerCaller(); + ClassLoader loader = new ClassLoader(AsyncHonestyApp.class.getClassLoader()) { + @Override + protected Class findClass(String name) throws ClassNotFoundException { + if ("org.springframework.kafka.core.KafkaTemplate".equals(name)) { + return defineClass(name, tplBytes, 0, tplBytes.length); + } + if ("org.example.servers.DirectKafkaProducerCaller".equals(name)) { + return defineClass(name, callerBytes, 0, callerBytes.length); + } + throw new ClassNotFoundException(name); + } + }; + Class tplCls = loader.loadClass("org.springframework.kafka.core.KafkaTemplate"); + Class callerCls = loader.loadClass("org.example.servers.DirectKafkaProducerCaller"); + fakeKafkaTemplate = tplCls.getDeclaredConstructor().newInstance(); + directKafkaSendMethod = callerCls.getMethod("produce", Object.class, String.class, Object.class); } else if ("kafka-produce".equals(kind)) { byte[] consumerBytes = generateKafkaListenerConsumer(); Class consumerClass = new ClassLoader(AsyncHonestyApp.class.getClassLoader()) { @@ -649,6 +738,56 @@ protected java.util.concurrent.Executor getTaskExecutor() { } } + private static byte[] generateKafkaTemplateStub() { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "org/springframework/kafka/core/KafkaTemplate", + 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 send = cw.visitMethod(Opcodes.ACC_PUBLIC, "send", + "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", null, null); + send.visitCode(); + send.visitInsn(Opcodes.ACONST_NULL); + send.visitInsn(Opcodes.ARETURN); + send.visitMaxs(1, 3); + send.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateKafkaProducerCaller() { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "org/example/servers/DirectKafkaProducerCaller", + 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 prod = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "produce", + "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V", null, null); + prod.visitCode(); + prod.visitVarInsn(Opcodes.ALOAD, 0); + prod.visitTypeInsn(Opcodes.CHECKCAST, "org/springframework/kafka/core/KafkaTemplate"); + prod.visitVarInsn(Opcodes.ALOAD, 1); + prod.visitVarInsn(Opcodes.ALOAD, 2); + prod.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/springframework/kafka/core/KafkaTemplate", + "send", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", false); + prod.visitInsn(Opcodes.POP); + prod.visitInsn(Opcodes.RETURN); + prod.visitMaxs(3, 3); + prod.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + static void handle(String kind, final long ms) throws Exception { if ("spring-listenable-callback".equals(kind)) { final org.springframework.util.concurrent.SettableListenableFuture f = @@ -663,6 +802,30 @@ static void handle(String kind, final long ms) throws Exception { sleepQuietly(ms); AsyncTail.ran(); }); + } else if ("clq-worker".equals(kind)) { + APP_CLQ.offer(() -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + } else if ("deque-worker".equals(kind)) { + APP_DEQUE.offerLast(() -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + } else if ("collection-add".equals(kind)) { + APP_COLLECTION.add(() -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + } else if ("lib-callback".equals(kind)) { + io.fakeexternal.FakeExternalHttpClient.runAsync(30, () -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + } else if ("scheduled-outbox".equals(kind)) { + OUTBOX_QUEUE.add(Long.valueOf(ms)); + } else if ("kafka-direct-produce".equals(kind)) { + directKafkaSendMethod.invoke(null, fakeKafkaTemplate, "orders-topic", Long.valueOf(ms)); } else if ("submission-publisher".equals(kind)) { SubmissionPublisherFixture.submit(ms); } else if ("kafka-produce".equals(kind)) { diff --git a/scripts/smoke-javaagent.sh b/scripts/smoke-javaagent.sh index 96e91018..0d21a82a 100755 --- a/scripts/smoke-javaagent.sh +++ b/scripts/smoke-javaagent.sh @@ -800,8 +800,12 @@ public final class TomcatHarness { output.write((command + "\n").getBytes(StandardCharsets.UTF_8)); output.flush(); String ack = readAll(socket.getInputStream()); + // TomcatHarness is inside KEPLOY_JAVA_CLASS_DIRS and starts its own + // in-process coverage-data-receiver Thread outside any request window, + // so the agent honestly latches asyncExecutors=false while Tomcat's + // own CoyoteAdapter counting stays windowCut=true. String pattern = "^ACK proto=3 caps=windowCut=true,contaminated=true,classMismatch=true," - + "background=(true|false),ackId=true,asyncExecutors=true," + + "background=(true|false),ackId=true,asyncExecutors=false," + "listenerContamination=(true|false)\\n$"; if (!ack.matches(pattern)) { throw new IllegalStateException("unexpected ACK for " + command + ": " + ack); From d00e09be28bb2d3d1331f3a967f12a565df4f6ac Mon Sep 17 00:00:00 2001 From: slayerjain Date: Sat, 28 Nov 2026 14:14:13 +0530 Subject: [PATCH 23/26] fix(dedup): fail closed on off-window executor hand-offs and JDK pool subclasses Fail closed by construction when an application or library hands work to a non-inline executor outside any active request window or tracked job (latching asyncExecutors=false across armed and unarmed paths, including CompletableFuture.supplyAsync) or loads a non-allowlisted subclass of a JDK concurrency primitive (Thread, ThreadPoolExecutor, ScheduledThreadPoolExecutor, ForkJoinPool, Timer, AbstractExecutorService). Also: - Reply IGNORED on the TCP control socket for unknown or malformed commands while keeping the connection alive. - Move the Tomcat smoke test's coverage data receiver out-of-process so tomcat-jacoco-after pins asyncExecutors=true on a plain Tomcat application. - Add JDK 11 to the java-agent GitHub Actions matrix and open java.base/java.io for Tomcat 9 named-module testing on JDK 11. - Add isolated unit tests for Collection.add, Deque owner scanning, off-window executor hand-offs, JDK pool subclasses, and forked end-to-end tests. Signed-off-by: slayerjain --- .github/workflows/java-agent.yml | 2 +- .../io/keploy/dedup/KeployDedupAgent.java | 4 + .../java/io/keploy/dedup/RequestGate.java | 28 ++++ .../java/io/keploy/dedup/ServerEntries.java | 27 +++- .../java/io/fakeexternal/SubPoolExecutor.java | 22 +++ .../keploy/dedup/CoverageTcpClientTest.java | 21 +++ .../dedup/ForkedAsyncAndHonestyTest.java | 3 + .../dedup/HonestProtocolAndAsyncTest.java | 146 ++++++++++++++++++ .../java/io/keploy/dedup/ServerTailTest.java | 3 + .../org/example/servers/AsyncHonestyApp.java | 74 +++++++++ scripts/smoke-javaagent.sh | 129 ++++++++++------ 11 files changed, 409 insertions(+), 50 deletions(-) create mode 100644 keploy-sdk/src/test/java/io/fakeexternal/SubPoolExecutor.java diff --git a/.github/workflows/java-agent.yml b/.github/workflows/java-agent.yml index c65e9445..d6052e97 100644 --- a/.github/workflows/java-agent.yml +++ b/.github/workflows/java-agent.yml @@ -27,7 +27,7 @@ jobs: strategy: fail-fast: false matrix: - java-version: ["8", "17", "21"] + java-version: ["8", "11", "17", "21"] steps: - name: Checkout 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 a1f51f85..4473d2db 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -1661,6 +1661,10 @@ private void connectAndServe() throws IOException { } CoverageCommand command = CoverageCommand.parse(trimmed); if (command == null) { + synchronized (testCaseLock) { + writeLine(out, IGNORED_REPLY); + out.flush(); + } continue; } Phases phases = new Phases(); 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 1007d913..62dc8ade 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -460,6 +460,7 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def if (!armed) { if (task != null) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(executor, false); } return task; } @@ -483,6 +484,7 @@ private static Runnable handInternal(Object executor, Runnable task, boolean def Window window = INSIDE.get(); JobGate.Attribution job = currentOrExpiredJob(window); if (window == null && job == null) { + noteExecutorHandOffOutsideWindow(executor, true); return task; } if (OrderedPools.isInlineExecutor(executor)) { @@ -525,6 +527,7 @@ public static Callable hand(Object executor, Callable task) { if (!armed) { if (task != null) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(executor, false); } return task; } @@ -549,6 +552,7 @@ public static Callable hand(Object executor, Callable task) { Window window = INSIDE.get(); JobGate.Attribution job = currentOrExpiredJob(window); if (window == null && job == null) { + noteExecutorHandOffOutsideWindow(executor, true); return task; } if (OrderedPools.isInlineExecutor(executor)) { @@ -589,6 +593,7 @@ private static Supplier handSupplierInternal(Object executor, Supplier if (!armed) { if (supplier != null) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(executor, false); } return supplier; } @@ -613,6 +618,7 @@ private static Supplier handSupplierInternal(Object executor, Supplier Window window = INSIDE.get(); JobGate.Attribution job = currentOrExpiredJob(window); if (window == null && job == null) { + noteExecutorHandOffOutsideWindow(executor, true); return supplier; } if (OrderedPools.isInlineExecutor(executor)) { @@ -656,6 +662,7 @@ private static void noteUnarmedHandOffIfInFlight() { public static void execute(Executor executor, Runnable task) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(executor, false); executor.execute(task); return; } @@ -679,6 +686,7 @@ public static void execute(Executor executor, Runnable task) { public static Future submit(ExecutorService executor, Runnable task) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(executor, false); return executor.submit(task); } Runnable handed = hand(executor, task); @@ -706,6 +714,7 @@ public static Future submit(ExecutorService executor, Runnable task) { public static Future submit(ExecutorService executor, Runnable task, T result) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(executor, false); return executor.submit(task, result); } Runnable handed = hand(executor, task); @@ -732,6 +741,7 @@ public static Future submit(ExecutorService executor, Runnable task, T re public static Future submit(ExecutorService executor, Callable task) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(executor, false); return executor.submit(task); } Callable handed = hand(executor, task); @@ -758,6 +768,7 @@ public static Future submit(ExecutorService executor, Callable task) { public static CompletableFuture runAsync(Runnable task) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(null, false); return CompletableFuture.runAsync(task); } Runnable handed = handInternal(null, task, true); @@ -782,6 +793,7 @@ public static CompletableFuture runAsync(Runnable task) { public static CompletableFuture runAsync(Runnable task, Executor executor) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(executor, false); return CompletableFuture.runAsync(task, executor); } Runnable handed = handInternal(executor, task, true); @@ -807,6 +819,7 @@ public static CompletableFuture runAsync(Runnable task, Executor executor) public static CompletableFuture supplyAsync(Supplier supplier) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(null, false); return CompletableFuture.supplyAsync(supplier); } Supplier handed = handSupplierInternal(null, supplier, true); @@ -832,6 +845,7 @@ public static CompletableFuture supplyAsync(Supplier supplier) { public static CompletableFuture supplyAsync(Supplier supplier, Executor executor) { if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(executor, false); return CompletableFuture.supplyAsync(supplier, executor); } Supplier handed = handSupplierInternal(executor, supplier, true); @@ -3132,6 +3146,20 @@ public static void noteRuntimeUntrackedDispatch(String reason) { } } + /** + * An executor hand-off made with no request window and no job open (at startup, from a + * {@code @PostConstruct}, or from any thread no window owns) can start a long-lived worker + * that later runs work a request hands it through shared state (an {@code ArrayDeque} under a + * lock, a volatile field, wait/notify): fail closed exactly as {@code Thread.start} does. + * Same-thread inline executors start no worker and are left alone. + */ + private static void noteExecutorHandOffOutsideWindow(Object executor, boolean isArmed) { + if (executor != null && OrderedPools.isInlineExecutor(executor)) { + return; + } + noteBackgroundWorkerOutsideWindow("untracked-async:executor-outside-window", isArmed); + } + private static void noteBackgroundWorkerOutsideWindow(String reason, boolean isArmed) { String label = (reason == null || reason.isEmpty()) ? "background-worker" : reason; KeployDedupAgent.noteObservedUntrackedAsyncLibrary( 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 fc24e31c..a0363e2b 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -320,6 +320,7 @@ private static Map> buildDispatchPrimitiveMethods() { "org/apache/coyote/AbstractProtocol", "org/apache/juli/AsyncFileHandler$DropFlushPolicy", "org/apache/juli/AsyncFileHandler$DropLastPolicy", + "org/apache/juli/AsyncFileHandler$LoggerExecutorService", "org/apache/juli/ClassLoaderLogManager$Cleaner", "org/apache/juli/FileHandler", "org/apache/tomcat/util/net/AbstractEndpoint", @@ -344,10 +345,12 @@ private static Map> buildDispatchPrimitiveMethods() { "org/apache/tomcat/util/net/SocketWrapperBase", "org/apache/tomcat/util/net/SocketWrapperBase$OperationState", "org/apache/tomcat/util/net/WriteBuffer", + "org/apache/tomcat/util/threads/InlineExecutorService", "org/apache/tomcat/util/threads/ScheduledThreadPoolExecutor", "org/apache/tomcat/util/threads/TaskQueue", "org/apache/tomcat/util/threads/TaskThread", "org/apache/tomcat/util/threads/ThreadPoolExecutor", + "org/apache/tomcat/util/threads/VirtualThreadExecutor", "org/apache/tomcat/websocket/WsWebSocketContainer", // (b2) Jetty (request dispatch enters hooked HttpChannel/ServletChannel) "org/eclipse/jetty/io/AbstractConnection", @@ -390,13 +393,17 @@ private static Map> buildDispatchPrimitiveMethods() { "org/xnio/ChannelListeners", "org/xnio/ChannelListeners$13", "org/xnio/XnioIoThread", + "org/xnio/XnioWorker", + "org/xnio/XnioWorker$DefaultThreadPoolExecutor", "org/xnio/XnioWorker$ExecutorServiceTaskPool", "org/xnio/XnioWorker$ThreadPoolExecutorTaskPool", "org/jboss/threads/DelegatingExecutor", "org/jboss/threads/DelegatingExecutorService", "org/jboss/threads/DelegatingScheduledExecutorService", "org/jboss/threads/EnhancedQueueExecutor", + "org/jboss/threads/EnhancedQueueExecutorBase0", "org/jboss/threads/HandoffRejectedExecutionHandler", + "org/jboss/threads/JBossScheduledThreadPoolExecutor", "org/jboss/threads/JBossThread", "org/jboss/threads/ManagedThreadPoolExecutor", "org/jboss/threads/ViewExecutor", @@ -439,6 +446,15 @@ static Set allowlistedDispatchClasses() { return ALLOWLISTED_DISPATCH_CLASSES; } + // JDK classes whose subclasses dispatch work through inherited JDK code (scanned like Thread). + private static final Set JDK_DISPATCH_SUPERCLASSES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + "java/util/concurrent/AbstractExecutorService", + "java/util/concurrent/ThreadPoolExecutor", + "java/util/concurrent/ScheduledThreadPoolExecutor", + "java/util/concurrent/ForkJoinPool", + "java/util/Timer"))); + private static final String SPRING_EVENT_MULTICASTER = "org/springframework/context/event/SimpleApplicationEventMulticaster"; @@ -1525,8 +1541,15 @@ private static void scanUnhookedReferences(String className, byte[] classfile, b boolean allowlisted = className != null && ALLOWLISTED_DISPATCH_CLASSES.contains(className); try { ClassReader reader = new ClassReader(classfile); - if (!allowlisted && checkDispatchPrimitives && "java/lang/Thread".equals(reader.getSuperName())) { - recordUnhookedAsyncDispatcher("java.lang.Thread subclass", className); + if (!allowlisted && checkDispatchPrimitives && (reader.getAccess() & Opcodes.ACC_INTERFACE) == 0) { + String superName = reader.getSuperName(); + if ("java/lang/Thread".equals(superName)) { + recordUnhookedAsyncDispatcher("java.lang.Thread subclass", className); + } else if (JDK_DISPATCH_SUPERCLASSES.contains(superName)) { + // A JDK pool or timer subclass dispatches through inherited JDK code, and its + // callers name the subclass as the Methodref owner, which no table matches. + recordUnhookedAsyncDispatcher(superName.replace('/', '.') + " subclass", className); + } } int itemCount = reader.getItemCount(); char[] buf = new char[reader.getMaxStringLength()]; diff --git a/keploy-sdk/src/test/java/io/fakeexternal/SubPoolExecutor.java b/keploy-sdk/src/test/java/io/fakeexternal/SubPoolExecutor.java new file mode 100644 index 00000000..36e61c20 --- /dev/null +++ b/keploy-sdk/src/test/java/io/fakeexternal/SubPoolExecutor.java @@ -0,0 +1,22 @@ +package io.fakeexternal; + +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * External library stand-in that dispatches work through its own + * {@link ThreadPoolExecutor} subclass type so call sites reference the subclass + * owner rather than a JDK executor interface. + */ +public final class SubPoolExecutor extends ThreadPoolExecutor { + private static final SubPoolExecutor INSTANCE = new SubPoolExecutor(); + + private SubPoolExecutor() { + super(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); + } + + public static void fire(Runnable task) { + INSTANCE.execute(task); + } +} 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 06318162..09d7e5e0 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java @@ -121,6 +121,27 @@ public void endWithNoStartNamesTheTestThenAnswersAck() throws Exception { } } + @Test + public void unknownOrMalformedTcpCommandAnswersIgnoredAndKeepsConnectionAlive() throws Exception { + 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()); + + send(out, "FOO"); + assertEquals("IGNORED", in.readLine()); + send(out, "START"); + assertEquals("IGNORED", in.readLine()); + send(out, "PROTO 4"); + assertEquals("IGNORED", in.readLine()); + send(out, "NOP"); + assertEquals("ACK", in.readLine()); + } + } + @Test public void aStartWhoseResetFailedNamesTheTestThenAnswersAckAndSoDoesItsEnd() throws Exception { jacoco = new FakeJacoco(); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index a1e1a26c..adfcb7fd 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -432,6 +432,9 @@ public void forkedLibraryAndJdkHandOffsNeverSilentlyDropAsyncLines() throws Exce {"collection-add", "8", "false"}, {"lib-callback", "8", "true"}, {"scheduled-outbox", "8", "false"}, + {"exec-worker-deque", "8", "false"}, + {"spring-tpte-worker", "8", "false"}, + {"lib-subpool", "8", "true"}, }; for (boolean prefixMode : new boolean[] {true, false}) { for (String[] tc : cases) { diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 650c199e..1772a65f 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -5249,6 +5249,152 @@ public void isolatedCallSiteAndJobGateLatchesForListenableFutureDirectQueueAndSc } } + @Test(timeout = 60000) + public void isolatedCollectionAndDequePreScanExecutorOutsideWindowAndJdkPoolSubclasses() throws Exception { + ClassLoader loader = getClass().getClassLoader(); + + // 1. Isolated Collection.add-only caller (no Queue/Deque in constant pool). + String colClsName = "com/acme/CollectionOnlyCaller"; + ClassWriter colCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + colCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, colClsName, null, "java/lang/Object", null); + emitDefaultCtor(colCw); + MethodVisitor colMv = colCw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "push", + "(Ljava/util/Collection;Ljava/lang/Object;)Z", null, null); + colMv.visitCode(); + colMv.visitVarInsn(Opcodes.ALOAD, 0); + colMv.visitVarInsn(Opcodes.ALOAD, 1); + colMv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Collection", "add", "(Ljava/lang/Object;)Z", true); + colMv.visitInsn(Opcodes.IRETURN); + colMv.visitMaxs(2, 2); + colMv.visitEnd(); + colCw.visitEnd(); + ServerEntries colEntries = new ServerEntries(true, Collections.singleton(colClsName), null); + byte[] colRewritten = colEntries.transform(loader, colClsName, null, null, colCw.toByteArray()); + assertNotNull("Collection.add-only caller must be rewritten", colRewritten); + Class colCls = new ByteLoader(loader).define(colClsName.replace('/', '.'), colRewritten); + RequestGate.disarm(); + RequestGate.open("col-only-bq", null); + Object tok = RequestGate.enter(); + try { + colCls.getMethod("push", java.util.Collection.class, Object.class) + .invoke(null, new LinkedBlockingQueue(), "x"); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome colOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("Collection.add backed by LinkedBlockingQueue must contaminate: " + colOut.contaminations, + colOut.contaminations.contains("untracked-async:blocking-queue")); + + // 2. Isolated Deque.addFirst-only caller (no Queue/Collection/offer in constant pool). + String dqClsName = "com/acme/DequeOnlyCaller"; + ClassWriter dqCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + dqCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, dqClsName, null, "java/lang/Object", null); + emitDefaultCtor(dqCw); + MethodVisitor dqMv = dqCw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "pushFirst", + "(Ljava/util/Deque;Ljava/lang/Object;)V", null, null); + dqMv.visitCode(); + dqMv.visitVarInsn(Opcodes.ALOAD, 0); + dqMv.visitVarInsn(Opcodes.ALOAD, 1); + dqMv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Deque", "addFirst", "(Ljava/lang/Object;)V", true); + dqMv.visitInsn(Opcodes.RETURN); + dqMv.visitMaxs(2, 2); + dqMv.visitEnd(); + dqCw.visitEnd(); + ServerEntries dqEntries = new ServerEntries(true, Collections.singleton(dqClsName), null); + byte[] dqRewritten = dqEntries.transform(loader, dqClsName, null, null, dqCw.toByteArray()); + assertNotNull("Deque.addFirst-only caller must be rewritten", dqRewritten); + Class dqCls = new ByteLoader(loader).define(dqClsName.replace('/', '.'), dqRewritten); + RequestGate.disarm(); + RequestGate.open("dq-only-bq", null); + tok = RequestGate.enter(); + try { + dqCls.getMethod("pushFirst", java.util.Deque.class, Object.class) + .invoke(null, new java.util.concurrent.LinkedBlockingDeque(), "x"); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome dqOut = RequestGate.awaitWindow(TimeUnit.SECONDS.toNanos(2), true); + assertTrue("Deque.addFirst backed by LinkedBlockingDeque must contaminate: " + dqOut.contaminations, + dqOut.contaminations.contains("untracked-async:blocking-queue")); + + // 3. Any non-inline executor hand-off outside a window and job (armed or unarmed) + // must latch asyncExecutors=false; inline executors must NOT latch. + ExecutorService pool = Executors.newSingleThreadExecutor(); + org.springframework.core.task.SyncTaskExecutor inlineExec = + new org.springframework.core.task.SyncTaskExecutor(); + try { + // Inline executor outside window: armed and unarmed must stay clean. + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.execute(inlineExec, () -> { }); + assertFalse("unarmed inline executor must not latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + RequestGate.arm(); + RequestGate.execute(inlineExec, () -> { }); + assertFalse("armed inline executor must not latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // Non-inline execute / submit / runAsync / supplyAsync outside window (armed + unarmed): ALL latch! + for (boolean armedMode : new boolean[] {false, true}) { + if (armedMode) { + RequestGate.arm(); + } else { + RequestGate.disarm(); + } + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.execute(pool, () -> { }); + assertTrue("execute outside window (armed=" + armedMode + ") must latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.submit(pool, () -> { }).get(5, TimeUnit.SECONDS); + assertTrue("submit(Runnable) outside window (armed=" + armedMode + ") must latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.submit(pool, () -> "ok").get(5, TimeUnit.SECONDS); + assertTrue("submit(Callable) outside window (armed=" + armedMode + ") must latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.runAsync(() -> { }, pool).get(5, TimeUnit.SECONDS); + assertTrue("runAsync outside window (armed=" + armedMode + ") must latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.supplyAsync(() -> "ok", pool).get(5, TimeUnit.SECONDS); + assertTrue("supplyAsync outside window (armed=" + armedMode + ") must latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } + + // 4. Non-allowlisted library subclasses of JDK concurrency types must latch on load. + ServerEntries subEntries = new ServerEntries(true, Collections.singleton("com/acme/App"), null); + String[][] jdkSubclasses = { + {"io/fakeexternal/CustomTpe", "java/util/concurrent/ThreadPoolExecutor"}, + {"io/fakeexternal/CustomStpe", "java/util/concurrent/ScheduledThreadPoolExecutor"}, + {"io/fakeexternal/CustomFjp", "java/util/concurrent/ForkJoinPool"}, + {"io/fakeexternal/CustomTimer", "java/util/Timer"}, + {"io/fakeexternal/CustomAes", "java/util/concurrent/AbstractExecutorService"}, + }; + for (String[] spec : jdkSubclasses) { + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + ClassWriter subCw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + subCw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, spec[0], null, spec[1], null); + emitDefaultCtor(subCw); + subCw.visitEnd(); + assertNull("library subclass must not be rewritten: " + spec[0], + subEntries.transform(loader, spec[0], null, null, subCw.toByteArray())); + assertTrue("non-allowlisted subclass of " + spec[1] + " must latch asyncExecutors=false", + ServerEntries.hasUnhookedAsyncDispatcher()); + } + } finally { + pool.shutdownNow(); + RequestGate.disarm(); + ServerEntries.restoreUnhookedAsyncDispatchers(Collections.emptySet()); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + } + } + @Test(timeout = 60000) public void queueRuntimeCheckDirectSubmissionPublisherMessagingProducerAndExternalOverflow() throws Exception { ClassLoader loader = getClass().getClassLoader(); 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 036fdbec..6a242302 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ServerTailTest.java @@ -482,6 +482,9 @@ private Result run(Fork fork) throws Exception { command.add(String.join(File.pathSeparator, modulePath)); command.add("--add-modules"); command.add("org.apache.tomcat.embed.core"); + // Tomcat 9.0's JreCompat.disableCanonCaches reflects on java.io.FileSystem.useCanonCaches on JDK 11. + command.add("--add-opens"); + command.add("java.base/java.io=org.apache.tomcat.embed.core"); } command.add("-cp"); command.add(String.join(File.pathSeparator, classPath)); diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index b19fdbeb..cdfea6c7 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -604,6 +604,10 @@ public static final class HandOffFixtures { new java.util.concurrent.ConcurrentLinkedQueue<>(); private static volatile org.springframework.context.event.SimpleApplicationEventMulticaster overrideMc; private static volatile org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler outboxScheduler; + private static final java.util.ArrayDeque EXEC_DEQUE = new java.util.ArrayDeque<>(); + private static final java.util.ArrayDeque SPRING_TPTE_DEQUE = new java.util.ArrayDeque<>(); + private static volatile ExecutorService execWorkerPool; + private static volatile org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor springTptePool; private static volatile Object fakeKafkaTemplate; private static volatile Method directKafkaSendMethod; @@ -680,6 +684,55 @@ static void init(String kind) throws Exception { new org.springframework.scheduling.support.ScheduledMethodRunnable(new OutboxPoller(), "drain"), 250L); outboxScheduler = ts; + } else if ("exec-worker-deque".equals(kind)) { + ExecutorService pool = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "app-exec-deque-worker"); + t.setDaemon(true); + return t; + }); + execWorkerPool = pool; + pool.execute(() -> { + while (!Thread.currentThread().isInterrupted()) { + Runnable task; + synchronized (EXEC_DEQUE) { + while (EXEC_DEQUE.isEmpty()) { + try { + EXEC_DEQUE.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + task = EXEC_DEQUE.removeFirst(); + } + task.run(); + } + }); + } else if ("spring-tpte-worker".equals(kind)) { + org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor tpte = + new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor(); + tpte.setCorePoolSize(1); + tpte.setMaxPoolSize(1); + tpte.setDaemon(true); + tpte.initialize(); + springTptePool = tpte; + tpte.execute(() -> { + while (!Thread.currentThread().isInterrupted()) { + Runnable task; + synchronized (SPRING_TPTE_DEQUE) { + while (SPRING_TPTE_DEQUE.isEmpty()) { + try { + SPRING_TPTE_DEQUE.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + task = SPRING_TPTE_DEQUE.removeFirst(); + } + task.run(); + } + }); } else if ("kafka-direct-produce".equals(kind)) { // Define a stand-in org/springframework/kafka/core/KafkaTemplate and an // app caller class in org/example/servers/ that invokes KafkaTemplate.send() @@ -824,6 +877,27 @@ static void handle(String kind, final long ms) throws Exception { }); } else if ("scheduled-outbox".equals(kind)) { OUTBOX_QUEUE.add(Long.valueOf(ms)); + } else if ("exec-worker-deque".equals(kind)) { + synchronized (EXEC_DEQUE) { + EXEC_DEQUE.addLast(() -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + EXEC_DEQUE.notify(); + } + } else if ("spring-tpte-worker".equals(kind)) { + synchronized (SPRING_TPTE_DEQUE) { + SPRING_TPTE_DEQUE.addLast(() -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); + SPRING_TPTE_DEQUE.notify(); + } + } else if ("lib-subpool".equals(kind)) { + io.fakeexternal.SubPoolExecutor.fire(() -> { + sleepQuietly(ms); + AsyncTail.ran(); + }); } else if ("kafka-direct-produce".equals(kind)) { directKafkaSendMethod.invoke(null, fakeKafkaTemplate, "orders-topic", Long.valueOf(ms)); } else if ("submission-publisher".equals(kind)) { diff --git a/scripts/smoke-javaagent.sh b/scripts/smoke-javaagent.sh index 0d21a82a..d4ab66e1 100755 --- a/scripts/smoke-javaagent.sh +++ b/scripts/smoke-javaagent.sh @@ -623,13 +623,60 @@ done tomcat_core="${work_dir}/tomcat-libs/tomcat-embed-core-${tomcat_version}.jar" tomcat_libs="$(find "${work_dir}/tomcat-libs" -name '*.jar' | sort | paste -sd: -)" -mkdir -p "${work_dir}/tomcat-src/smoke/app" "${work_dir}/tomcat-classes" +mkdir -p "${work_dir}/tomcat-src/smoke/app" "${work_dir}/tomcat-classes" "${work_dir}/driver-src/smoke/driver" "${work_dir}/driver-classes" +# Out-of-process Unix-domain data-socket receiver (mirrors Keploy's collector) +# so TomcatHarness runs as a plain Tomcat app with no harness-owned Thread or +# BlockingQueue inside KEPLOY_JAVA_CLASS_DIRS and pins asyncExecutors=true. +cat > "${work_dir}/driver-src/smoke/driver/DataReceiver.java" <<'JAVA' +package smoke.driver; + +import org.newsclub.net.unix.AFUNIXServerSocket; +import org.newsclub.net.unix.AFUNIXSocket; +import org.newsclub.net.unix.AFUNIXSocketAddress; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +public final class DataReceiver { + public static void main(String[] args) throws Exception { + File sock = new File(args[0]); + File outFile = new File(args[1]); + if (sock.exists() && !sock.delete()) { + throw new IllegalStateException("failed to delete " + sock); + } + try (AFUNIXServerSocket server = AFUNIXServerSocket.newInstance()) { + server.bind(AFUNIXSocketAddress.of(sock), 8); + for (int i = 0; i < 2; i++) { + try (AFUNIXSocket conn = server.accept(); + InputStream in = conn.getInputStream()) { + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + byte[] tmp = new byte[1024]; + int n; + while ((n = in.read(tmp)) != -1) { + buf.write(tmp, 0, n); + } + String line = new String(buf.toByteArray(), StandardCharsets.UTF_8) + .replace("\r", "").replace("\n", "") + "\n"; + try (FileOutputStream fos = new FileOutputStream(outFile, true)) { + fos.write(line.getBytes(StandardCharsets.UTF_8)); + } + } + } + } + } +} +JAVA +javac -cp "${agent_jar}" -d "${work_dir}/driver-classes" \ + "${work_dir}/driver-src/smoke/driver/DataReceiver.java" + cat > "${work_dir}/tomcat-src/smoke/app/TomcatHarness.java" <<'JAVA' package smoke.app; import org.apache.catalina.Context; import org.apache.catalina.startup.Tomcat; -import org.newsclub.net.unix.AFUNIXServerSocket; import org.newsclub.net.unix.AFUNIXSocket; import org.newsclub.net.unix.AFUNIXSocketAddress; @@ -641,8 +688,8 @@ import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; +import java.nio.file.Files; +import java.util.List; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -650,7 +697,6 @@ import javax.servlet.http.HttpServletResponse; public final class TomcatHarness { private static final File CONTROL_SOCKET = new File("/tmp/coverage_control.sock"); - private static final File DATA_SOCKET = new File("/tmp/coverage_data.sock"); private static final String ADAPTER = "org/apache/catalina/connector/CoyoteAdapter"; // Hello answers, then runs Tail once the END waits for the request @@ -699,14 +745,14 @@ public final class TomcatHarness { // leave the JVM up, and the case would hang instead of failing. public static void main(String[] args) { try { - run(args[0], new File(args[1])); + run(args[0], new File(args[1]), new File(args[2])); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } - private static void run(String mode, File base) throws Exception { + private static void run(String mode, File base, File recordsFile) throws Exception { if (!base.mkdirs()) { throw new IllegalStateException("failed to create " + base); } @@ -720,37 +766,11 @@ public final class TomcatHarness { tomcat.start(); int port = tomcat.getConnector().getLocalPort(); - if (DATA_SOCKET.exists() && !DATA_SOCKET.delete()) { - throw new IllegalStateException("failed to delete " + DATA_SOCKET); - } - final BlockingQueue records = new LinkedBlockingQueue(); - Thread receiver = new Thread(new Runnable() { - @Override - public void run() { - try (AFUNIXServerSocket server = AFUNIXServerSocket.newInstance()) { - server.bind(AFUNIXSocketAddress.of(DATA_SOCKET), 8); - for (;;) { - try (AFUNIXSocket socket = server.accept()) { - records.add(readAll(socket.getInputStream())); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }, "coverage-data-receiver"); - receiver.setDaemon(true); - receiver.start(); - long deadline = System.currentTimeMillis() + 10000L; - while (!DATA_SOCKET.exists() && System.currentTimeMillis() < deadline) { - Thread.sleep(50L); - } - String id = "test-set-0/" + mode; command("START " + id); String body = get(port); command("END " + id); - String report = next(records, mode); + String report = next(recordsFile, 0, mode); // The JaCoCo measuring is the one attached after keploy-sdk.jar (the // SDK started none of its own), and the index read Tomcat's jar. if (!report.startsWith("{\"kind\":\"index\",") @@ -760,7 +780,7 @@ public final class TomcatHarness { throw new IllegalStateException("the first record on the data socket was no INDEX report with source" + " override, jacoco attached and Tomcat's jar among its roots in " + mode + ": " + report); } - String json = next(records, mode); + String json = next(recordsFile, 1, mode); if (!"hello".equals(body) || !json.contains("\"id\":\"" + id + "\"") || !json.contains("\"" + ADAPTER + "\":[") @@ -800,12 +820,9 @@ public final class TomcatHarness { output.write((command + "\n").getBytes(StandardCharsets.UTF_8)); output.flush(); String ack = readAll(socket.getInputStream()); - // TomcatHarness is inside KEPLOY_JAVA_CLASS_DIRS and starts its own - // in-process coverage-data-receiver Thread outside any request window, - // so the agent honestly latches asyncExecutors=false while Tomcat's - // own CoyoteAdapter counting stays windowCut=true. + // Plain Tomcat app with out-of-process collector must retain asyncExecutors=true. String pattern = "^ACK proto=3 caps=windowCut=true,contaminated=true,classMismatch=true," - + "background=(true|false),ackId=true,asyncExecutors=false," + + "background=(true|false),ackId=true,asyncExecutors=true," + "listenerContamination=(true|false)\\n$"; if (!ack.matches(pattern)) { throw new IllegalStateException("unexpected ACK for " + command + ": " + ack); @@ -813,12 +830,18 @@ public final class TomcatHarness { } } - private static String next(BlockingQueue records, String mode) throws InterruptedException { - String record = records.poll(10, TimeUnit.SECONDS); - if (record == null) { - throw new IllegalStateException("timed out waiting for a record on the data socket in " + mode); + private static String next(File recordsFile, int index, String mode) throws Exception { + long deadline = System.currentTimeMillis() + 10000L; + while (System.currentTimeMillis() < deadline) { + if (recordsFile.exists()) { + List lines = Files.readAllLines(recordsFile.toPath(), StandardCharsets.UTF_8); + if (lines.size() > index && !lines.get(index).isEmpty()) { + return lines.get(index); + } + } + Thread.sleep(50L); } - return record; + throw new IllegalStateException("timed out waiting for record #" + index + " on the data socket in " + mode); } private static String readAll(InputStream input) throws IOException { @@ -836,15 +859,27 @@ javac -cp "${tomcat_libs}:${agent_jar}" -d "${work_dir}/tomcat-classes" \ "${work_dir}/tomcat-src/smoke/app/TomcatHarness.java" tomcat_log="${work_dir}/tomcat-jacoco-after.log" +tomcat_records="${work_dir}/tomcat-records.jsonl" +rm -f /tmp/coverage_data.sock "${tomcat_records}" +java -cp "${work_dir}/driver-classes:${agent_jar}" \ + smoke.driver.DataReceiver /tmp/coverage_data.sock "${tomcat_records}" 2>"${work_dir}/tomcat-receiver.log" & +tomcat_receiver_pid=$! +for _ in $(seq 1 100); do + [[ -S /tmp/coverage_data.sock ]] && break + sleep 0.1 +done tomcat_rc=0 +echo "Running Java agent smoke: tomcat-jacoco-after" +rm -f /tmp/coverage_control.sock "/tmp/keploy-sdk-smoke-tomcat-jacoco-after.exec" KEPLOY_JAVA_DEDUP_DIAGNOSTICS=1 KEPLOY_JAVA_END_WAIT_MS=2000 \ KEPLOY_JAVA_CLASS_DIRS="${work_dir}/tomcat-classes:${tomcat_core}" \ -run_smoke "tomcat-jacoco-after" \ timeout -k 10 180 java \ -javaagent:"${agent_jar}" \ -javaagent:"${jacoco_jar}=includes=smoke.app.*:org.apache.catalina.connector.CoyoteAdapter,output=none" \ -cp "${work_dir}/tomcat-classes:${tomcat_libs}:${agent_jar}" \ - smoke.app.TomcatHarness "tomcat-jacoco-after" "${work_dir}/tomcat-base" 2>"${tomcat_log}" || tomcat_rc=$? + smoke.app.TomcatHarness "tomcat-jacoco-after" "${work_dir}/tomcat-base" "${tomcat_records}" 2>"${tomcat_log}" || tomcat_rc=$? +kill "${tomcat_receiver_pid}" 2>/dev/null || true +wait "${tomcat_receiver_pid}" 2>/dev/null || true if [[ "${tomcat_rc}" -eq 124 || "${tomcat_rc}" -eq 137 ]]; then cat "${tomcat_log}" >&2 echo "tomcat-jacoco-after: the Tomcat harness was killed or did not end within 180 s (exit ${tomcat_rc}; 137 can also be the OOM killer)" >&2 From 4c609a71b80d054fe620a7d42c698446a0ed59dd Mon Sep 17 00:00:00 2001 From: slayerjain Date: Sat, 28 Nov 2026 16:38:07 +0530 Subject: [PATCH 24/26] feat(dedup): enforce allowlist at JDK concurrency sinks via bootstrap bridge Signed-off-by: slayerjain --- .../main/java/io/keploy/dedup/BuildTable.java | 3 + .../io/keploy/dedup/JdkSinkBootstrap.java | 279 +++++++++++ .../java/io/keploy/dedup/JdkSinkHandler.java | 73 +++ .../io/keploy/dedup/JdkSinkTransformer.java | 189 ++++++++ .../io/keploy/dedup/KeployDedupAgent.java | 24 +- .../main/java/io/keploy/dedup/ProbeScan.java | 4 + .../java/io/keploy/dedup/RequestGate.java | 258 ++++++++-- .../java/io/keploy/dedup/ServerEntries.java | 6 + .../java/io/keploy/dedup/SinkAllowlist.java | 453 ++++++++++++++++++ .../dedup/bootstrap/KeploySinkBridge.java | 245 ++++++++++ .../java/io/fakeexternal/SubForkJoinPool.java | 20 + .../keploy/dedup/CoverageTcpClientTest.java | 6 +- .../dedup/ForkedAsyncAndHonestyTest.java | 123 ++++- .../dedup/HonestProtocolAndAsyncTest.java | 4 + .../io/keploy/dedup/JdkSinkBridgeTest.java | 281 +++++++++++ .../org/example/servers/AsyncHonestyApp.java | 441 ++++++++++++++++- .../java/org/example/servers/AsyncWork.java | 26 +- 17 files changed, 2380 insertions(+), 55 deletions(-) create mode 100644 keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkBootstrap.java create mode 100644 keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkHandler.java create mode 100644 keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkTransformer.java create mode 100644 keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java create mode 100644 keploy-sdk/src/main/java/io/keploy/dedup/bootstrap/KeploySinkBridge.java create mode 100644 keploy-sdk/src/test/java/io/fakeexternal/SubForkJoinPool.java create mode 100644 keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java 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 14439718..9ce3d681 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/BuildTable.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/BuildTable.java @@ -456,6 +456,7 @@ boolean request(Runnable send) { * the WARNING then says that ask is not sent, as it was ACKed and logged as sent later. */ private boolean start(Runnable send, boolean handover) { + JdkSinkBootstrap.enterInternal(); try { threads.newThread(() -> loop(send)).start(); return true; @@ -468,6 +469,8 @@ private boolean start(Runnable send, boolean handover) { ? ": the ask for the build table that waited for the send before it is not sent (Keploy" + " asks again on its next run)" : ""), t); return false; + } finally { + JdkSinkBootstrap.exitInternal(); } } diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkBootstrap.java b/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkBootstrap.java new file mode 100644 index 00000000..6dcd6360 --- /dev/null +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkBootstrap.java @@ -0,0 +1,279 @@ +package io.keploy.dedup; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.instrument.Instrumentation; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.Timer; + +/** + * Installs {@code io.keploy.dedup.bootstrap.KeploySinkBridge} onto the + * bootstrap class loader (before it is ever loaded by any other class loader), + * opens {@code java.base} read-access to the bootstrap unnamed module on JDK 9+ + * via {@code Instrumentation.redefineModule}, registers the runtime sink + * handler, and retransforms the 5+1 JDK concurrency sink classes. + * + *

NOTE: This class intentionally avoids static imports or direct bytecode + * references to {@code KeploySinkBridge} inside {@link #install(Instrumentation)} + * until AFTER {@code appendToBootstrapClassLoaderSearch} completes, guaranteeing + * parent-first resolution resolves the single bootstrap-loaded class everywhere. + */ +final class JdkSinkBootstrap { + + private static final Logger LOGGER = Logger.getLogger(KeployDedupAgent.class.getName()); + private static final String BRIDGE_CLASS_NAME = "io.keploy.dedup.bootstrap.KeploySinkBridge"; + private static final String BRIDGE_CLASS_RESOURCE = "io/keploy/dedup/bootstrap/KeploySinkBridge.class"; + private static final String BRIDGE_HANDLER_RESOURCE = "io/keploy/dedup/bootstrap/KeploySinkBridge$Handler.class"; + + private static final AtomicBoolean INSTALLED = new AtomicBoolean(false); + private static volatile boolean active; + private static volatile boolean failed; + + private JdkSinkBootstrap() { + } + + static boolean isActive() { + return active; + } + + static boolean hasFailed() { + return failed || (active && BridgeAccess.hasCallbackError()); + } + + static void setActiveForTest(boolean value) { + active = value; + if (value) { + failed = false; + } + } + + static boolean install(Instrumentation instrumentation) { + if (instrumentation == null || !instrumentation.isRetransformClassesSupported()) { + failed = true; + return false; + } + if (!INSTALLED.compareAndSet(false, true)) { + return active; + } + try { + File jarFile = buildBootstrapBridgeJar(); + instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(jarFile)); + + // Load KeploySinkBridge AND KeploySinkBridge$Handler explicitly via + // the bootstrap class loader (null) so both java.base and + // io.keploy.dedup.* share the exact same bootstrap classes with zero + // loader constraint conflicts. + Class bridgeClass = Class.forName(BRIDGE_CLASS_NAME, true, null); + Class handlerClass = Class.forName(BRIDGE_CLASS_NAME + "$Handler", true, null); + if (bridgeClass.getClassLoader() != null || handlerClass.getClassLoader() != null) { + LOGGER.log(Level.WARNING, + "Keploy dedup: KeploySinkBridge was loaded by non-bootstrap classloader " + + bridgeClass.getClassLoader() + "/" + handlerClass.getClassLoader() + + "; JDK sink hooks disabled (fail-closed)"); + failed = true; + return false; + } + + // On JDK 9+, java.base is a named module and does not read the bootstrap + // class loader's unnamed module unless granted via Instrumentation.redefineModule. + grantJavaBaseReadAccess(instrumentation, bridgeClass); + + // Register RequestGate's handler BEFORE retransforming JDK classes, + // with internal guard active during setup. + BridgeAccess.installHandler(); + + JdkSinkTransformer transformer = new JdkSinkTransformer(); + instrumentation.addTransformer(transformer, true); + + List> targets = new ArrayList<>(); + targets.add(Thread.class); + targets.add(ThreadPoolExecutor.class); + targets.add(ScheduledThreadPoolExecutor.class); + targets.add(ForkJoinPool.class); + targets.add(Timer.class); + try { + Class vt = Class.forName("java.lang.VirtualThread", false, null); + if (instrumentation.isModifiableClass(vt)) { + targets.add(vt); + } + } catch (ClassNotFoundException ignored) { + // JDK < 21: VirtualThread does not exist. + } + + List> modifiable = new ArrayList<>(); + for (Class c : targets) { + if (instrumentation.isModifiableClass(c)) { + modifiable.add(c); + } else { + LOGGER.log(Level.WARNING, "Keploy dedup: JDK sink class is not modifiable: " + c.getName()); + failed = true; + return false; + } + } + + BridgeAccess.enterInternal(); + try { + instrumentation.retransformClasses(modifiable.toArray(new Class[0])); + } finally { + BridgeAccess.exitInternal(); + } + + boolean allCoreHooked = JdkSinkTransformer.hookedThreadStart + && JdkSinkTransformer.hookedTpeExecute + && JdkSinkTransformer.hookedStpeDelayedExecute + && JdkSinkTransformer.hookedFjpSubmit + && JdkSinkTransformer.hookedTimerSched; + if (!allCoreHooked) { + LOGGER.log(Level.WARNING, + "Keploy dedup: incomplete JDK sink instrumentation (thread=" + + JdkSinkTransformer.hookedThreadStart + + ", tpe=" + JdkSinkTransformer.hookedTpeExecute + + ", stpe=" + JdkSinkTransformer.hookedStpeDelayedExecute + + ", fjp=" + JdkSinkTransformer.hookedFjpSubmit + + ", timer=" + JdkSinkTransformer.hookedTimerSched + ")"); + failed = true; + return false; + } + active = true; + if (SinkAllowlist.AUDIT) { + System.err.println("KEPLOY_SINK_BOOTSTRAP_INSTALLED bridgeCL=" + bridgeClass.getClassLoader() + + " thread=" + JdkSinkTransformer.hookedThreadStart + + " vthread=" + JdkSinkTransformer.hookedVirtualThreadStart + + " tpe=" + JdkSinkTransformer.hookedTpeExecute + + " stpe=" + JdkSinkTransformer.hookedStpeDelayedExecute + + " fjp=" + JdkSinkTransformer.hookedFjpSubmit + + " timer=" + JdkSinkTransformer.hookedTimerSched + + " handler=" + (BridgeAccess.hasHandler())); + } + return true; + } catch (Throwable t) { + failed = true; + LOGGER.log(Level.WARNING, + "Keploy dedup: could not install bootstrap JDK sink bridge; asyncExecutors will fail closed", t); + return false; + } + } + + static void enterInternal() { + if (active) { + BridgeAccess.enterInternal(); + } + } + + static void exitInternal() { + if (active) { + BridgeAccess.exitInternal(); + } + } + + static boolean isInternal() { + return active && BridgeAccess.isInternal(); + } + + private static void grantJavaBaseReadAccess(Instrumentation instrumentation, Class bridgeClass) + throws Exception { + Method getModule; + try { + getModule = Class.class.getMethod("getModule"); + } catch (NoSuchMethodException jdk8) { + // JDK 8 has no JPMS modules. + return; + } + Object javaBaseModule = getModule.invoke(Object.class); + Object bridgeModule = getModule.invoke(bridgeClass); + if (javaBaseModule == null || bridgeModule == null) { + return; + } + Class moduleClass = Class.forName("java.lang.Module"); + Method redefineModule = Instrumentation.class.getMethod("redefineModule", + moduleClass, Set.class, Map.class, Map.class, Set.class, Map.class); + redefineModule.invoke(instrumentation, + javaBaseModule, + Collections.singleton(bridgeModule), + Collections.emptyMap(), + Collections.emptyMap(), + Collections.emptySet(), + Collections.emptyMap()); + } + + private static File buildBootstrapBridgeJar() throws IOException { + ClassLoader cl = JdkSinkBootstrap.class.getClassLoader(); + byte[] bridgeBytes = readResource(cl, BRIDGE_CLASS_RESOURCE); + byte[] handlerBytes = readResource(cl, BRIDGE_HANDLER_RESOURCE); + File tempJar = Files.createTempFile("keploy-sink-bridge-", ".jar").toFile(); + tempJar.deleteOnExit(); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(tempJar))) { + writeJarEntry(jos, BRIDGE_CLASS_RESOURCE, bridgeBytes); + writeJarEntry(jos, BRIDGE_HANDLER_RESOURCE, handlerBytes); + } + return tempJar; + } + + private static byte[] readResource(ClassLoader cl, String resource) throws IOException { + try (InputStream is = cl != null ? cl.getResourceAsStream(resource) + : ClassLoader.getSystemResourceAsStream(resource)) { + if (is == null) { + throw new IOException("Missing bootstrap bridge resource: " + resource); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(4096); + byte[] buf = new byte[4096]; + int n; + while ((n = is.read(buf)) != -1) { + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } + + private static void writeJarEntry(JarOutputStream jos, String name, byte[] bytes) throws IOException { + jos.putNextEntry(new JarEntry(name)); + jos.write(bytes); + jos.closeEntry(); + } + + // Separate nested holder so KeploySinkBridge is NEVER referenced by + // JdkSinkBootstrap's constant pool until AFTER appendToBootstrapClassLoaderSearch. + private static final class BridgeAccess { + static void installHandler() { + io.keploy.dedup.bootstrap.KeploySinkBridge.handler = new JdkSinkHandler(); + } + + static void enterInternal() { + io.keploy.dedup.bootstrap.KeploySinkBridge.enterInternal(); + } + + static void exitInternal() { + io.keploy.dedup.bootstrap.KeploySinkBridge.exitInternal(); + } + + static boolean isInternal() { + return io.keploy.dedup.bootstrap.KeploySinkBridge.isInternal(); + } + + static boolean hasHandler() { + return io.keploy.dedup.bootstrap.KeploySinkBridge.handler != null; + } + + static boolean hasCallbackError() { + return io.keploy.dedup.bootstrap.KeploySinkBridge.lastCallbackError != null; + } + } +} diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkHandler.java b/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkHandler.java new file mode 100644 index 00000000..d02a87af --- /dev/null +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkHandler.java @@ -0,0 +1,73 @@ +package io.keploy.dedup; + +import io.keploy.dedup.bootstrap.KeploySinkBridge; + +/** + * Runtime sink handler installed into {@link KeploySinkBridge#handler} strictly + * AFTER {@link JdkSinkBootstrap} has loaded both {@link KeploySinkBridge} and + * {@link KeploySinkBridge.Handler} via the bootstrap class loader. + */ +final class JdkSinkHandler implements KeploySinkBridge.Handler { + + @Override + public void onThreadStart(Thread thread) { + String[] caller = new String[1]; + boolean allowed = SinkAllowlist.isAllowlistedThreadStart(thread, caller); + SinkAllowlist.audit("thread-start", allowed, thread != null ? thread.getName() : "null", + thread, null, caller[0]); + if (!allowed) { + RequestGate.handleUntrackedSink("thread-start", thread, null, caller[0]); + } + } + + @Override + public void onVirtualThreadStart(Thread thread) { + String[] caller = new String[1]; + boolean allowed = SinkAllowlist.isAllowlistedVirtualThreadStart(thread, caller); + SinkAllowlist.audit("virtual-thread-start", allowed, thread != null ? thread.getName() : "null", + thread, null, caller[0]); + if (!allowed) { + RequestGate.handleUntrackedSink("virtual-thread-start", thread, null, caller[0]); + } + } + + @Override + public void onTpeExecute(Object executor, Object command) { + String[] caller = new String[1]; + boolean allowed = SinkAllowlist.isAllowlistedTpeExecute(executor, command, caller); + SinkAllowlist.audit("tpe-execute", allowed, "", executor, command, caller[0]); + if (!allowed) { + RequestGate.handleUntrackedSink("tpe-execute", executor, command, caller[0]); + } + } + + @Override + public void onStpeDelayedExecute(Object executor, Object task) { + String[] caller = new String[1]; + boolean allowed = SinkAllowlist.isAllowlistedStpeDelayedExecute(executor, task, caller); + SinkAllowlist.audit("stpe-delayed-execute", allowed, "", executor, task, caller[0]); + if (!allowed) { + RequestGate.handleUntrackedSink("stpe-delayed-execute", executor, task, caller[0]); + } + } + + @Override + public void onFjpExternalSubmit(Object pool, Object task) { + String[] caller = new String[1]; + boolean allowed = SinkAllowlist.isAllowlistedFjpSubmit(pool, task, caller); + SinkAllowlist.audit("fjp-submit", allowed, "", pool, task, caller[0]); + if (!allowed) { + RequestGate.handleUntrackedSink("fjp-submit", pool, task, caller[0]); + } + } + + @Override + public void onTimerSched(Object timer, Object task) { + String[] caller = new String[1]; + boolean allowed = SinkAllowlist.isAllowlistedTimerSched(timer, task, caller); + SinkAllowlist.audit("timer-sched", allowed, "", timer, task, caller[0]); + if (!allowed) { + RequestGate.handleUntrackedSink("timer-sched", timer, task, caller[0]); + } + } +} diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkTransformer.java b/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkTransformer.java new file mode 100644 index 00000000..3454dfa8 --- /dev/null +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkTransformer.java @@ -0,0 +1,189 @@ +package io.keploy.dedup; + +import java.lang.instrument.ClassFileTransformer; +import java.security.ProtectionDomain; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +/** + * Retransforms the 5+1 JDK concurrency sinks to invoke + * {@code io.keploy.dedup.bootstrap.KeploySinkBridge} at method entry using + * {@code ClassWriter(reader, 0)} (zero frame recomputation, zero class loading + * during transform, 100% legal under {@code Instrumentation.retransformClasses} + * on JDK 8, 11, 17, and 21). + */ +final class JdkSinkTransformer implements ClassFileTransformer { + + private static final Logger LOGGER = Logger.getLogger(KeployDedupAgent.class.getName()); + static final String BRIDGE_INTERNAL = "io/keploy/dedup/bootstrap/KeploySinkBridge"; + + static final String THREAD = "java/lang/Thread"; + static final String VIRTUAL_THREAD = "java/lang/VirtualThread"; + static final String TPE = "java/util/concurrent/ThreadPoolExecutor"; + static final String STPE = "java/util/concurrent/ScheduledThreadPoolExecutor"; + static final String FJP = "java/util/concurrent/ForkJoinPool"; + static final String TIMER = "java/util/Timer"; + + // Volatile diagnostics counters for unit/mutant verification that each sink + // was actually instrumented in the running JVM. + static volatile boolean hookedThreadStart; + static volatile boolean hookedVirtualThreadStart; + static volatile boolean hookedTpeExecute; + static volatile boolean hookedStpeDelayedExecute; + static volatile boolean hookedFjpSubmit; + static volatile boolean hookedTimerSched; + + @Override + public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, + ProtectionDomain protectionDomain, byte[] classfileBuffer) { + if (loader != null || className == null || classfileBuffer == null) { + return null; + } + if (!isTargetSinkClass(className)) { + return null; + } + try { + return instrumentSinkClass(className, classfileBuffer); + } catch (Throwable t) { + LOGGER.log(Level.WARNING, "Keploy dedup failed to instrument JDK sink " + className, t); + return null; + } + } + + static boolean isTargetSinkClass(String internalName) { + return THREAD.equals(internalName) + || VIRTUAL_THREAD.equals(internalName) + || TPE.equals(internalName) + || STPE.equals(internalName) + || FJP.equals(internalName) + || TIMER.equals(internalName); + } + + static byte[] instrumentSinkClass(final String className, byte[] classfile) { + ClassReader reader = new ClassReader(classfile); + ClassWriter writer = new ClassWriter(reader, 0); + final boolean[] changed = {false}; + reader.accept(new ClassVisitor(Opcodes.ASM9, writer) { + @Override + public MethodVisitor visitMethod(int access, final String name, final String descriptor, + String signature, String[] exceptions) { + MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions); + if (mv == null || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE | Opcodes.ACC_STATIC)) != 0) { + return mv; + } + final SinkHook hook = matchHook(className, name, descriptor); + if (hook == null) { + return mv; + } + changed[0] = true; + recordHooked(className); + return new MethodVisitor(Opcodes.ASM9, mv) { + private boolean injected; + + @Override + public void visitCode() { + super.visitCode(); + if (!injected) { + injected = true; + super.visitVarInsn(Opcodes.ALOAD, 0); + if (hook.secondArgIndex > 0) { + super.visitVarInsn(Opcodes.ALOAD, hook.secondArgIndex); + } + super.visitMethodInsn(Opcodes.INVOKESTATIC, BRIDGE_INTERNAL, + hook.bridgeMethod, hook.bridgeDesc, false); + } + } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + int needed = hook.secondArgIndex > 0 ? 2 : 1; + super.visitMaxs(Math.max(maxStack, needed), maxLocals); + } + }; + } + }, 0); + return changed[0] ? writer.toByteArray() : null; + } + + private static SinkHook matchHook(String className, String name, String desc) { + if (THREAD.equals(className)) { + if ("start".equals(name) + && ("()V".equals(desc) || "(Ljdk/internal/vm/ThreadContainer;)V".equals(desc))) { + return new SinkHook("onThreadStart", "(Ljava/lang/Thread;)V", 0); + } + return null; + } + if (VIRTUAL_THREAD.equals(className)) { + if ("start".equals(name) + && ("()V".equals(desc) || "(Ljdk/internal/vm/ThreadContainer;)V".equals(desc))) { + return new SinkHook("onVirtualThreadStart", "(Ljava/lang/Thread;)V", 0); + } + return null; + } + if (TPE.equals(className)) { + if ("execute".equals(name) && "(Ljava/lang/Runnable;)V".equals(desc)) { + return new SinkHook("onTpeExecute", "(Ljava/lang/Object;Ljava/lang/Object;)V", 1); + } + return null; + } + if (STPE.equals(className)) { + if ("delayedExecute".equals(name) + && "(Ljava/util/concurrent/RunnableScheduledFuture;)V".equals(desc)) { + return new SinkHook("onStpeDelayedExecute", "(Ljava/lang/Object;Ljava/lang/Object;)V", 1); + } + return null; + } + if (FJP.equals(className)) { + if (("externalPush".equals(name) || "externalSubmit".equals(name) || "lazySubmit".equals(name)) + && desc.startsWith("(Ljava/util/concurrent/ForkJoinTask;)")) { + return new SinkHook("onFjpExternalSubmit", "(Ljava/lang/Object;Ljava/lang/Object;)V", 1); + } + if ("poolSubmit".equals(name) + && desc.startsWith("(ZLjava/util/concurrent/ForkJoinTask;)")) { + return new SinkHook("onFjpExternalSubmit", "(Ljava/lang/Object;Ljava/lang/Object;)V", 2); + } + return null; + } + if (TIMER.equals(className)) { + if ("sched".equals(name) && "(Ljava/util/TimerTask;JJ)V".equals(desc)) { + return new SinkHook("onTimerSched", "(Ljava/lang/Object;Ljava/lang/Object;)V", 1); + } + return null; + } + return null; + } + + private static void recordHooked(String className) { + if (THREAD.equals(className)) { + hookedThreadStart = true; + } else if (VIRTUAL_THREAD.equals(className)) { + hookedVirtualThreadStart = true; + } else if (TPE.equals(className)) { + hookedTpeExecute = true; + } else if (STPE.equals(className)) { + hookedStpeDelayedExecute = true; + } else if (FJP.equals(className)) { + hookedFjpSubmit = true; + } else if (TIMER.equals(className)) { + hookedTimerSched = true; + } + } + + private static final class SinkHook { + final String bridgeMethod; + final String bridgeDesc; + final int secondArgIndex; + + SinkHook(String bridgeMethod, String bridgeDesc, int secondArgIndex) { + this.bridgeMethod = bridgeMethod; + this.bridgeDesc = bridgeDesc; + this.secondArgIndex = secondArgIndex; + } + } +} 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 4473d2db..2a531539 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -382,6 +382,8 @@ private static Capabilities computeCapabilities(CoverageCollector collector) { && !ServerEntries.hadAppRewriteFailure() && !ServerEntries.hadAsyncHookFailure() && !ServerEntries.hasUnhookedAsyncDispatcher() + && JdkSinkBootstrap.isActive() + && !JdkSinkBootstrap.hasFailed() && !observedPreCapturedUntrackedExecutor.get(); boolean listenerContamination = agentAttached && !ServerEntries.hadListenerHookFailure() @@ -645,7 +647,12 @@ private static boolean start(CoverageIndex index, Instrumentation instrumentatio Thread thread = new Thread(worker, threadName); thread.setDaemon(true); coverageThread = thread; - thread.start(); + JdkSinkBootstrap.enterInternal(); + try { + thread.start(); + } finally { + JdkSinkBootstrap.exitInternal(); + } registerShutdownHook(); return true; } @@ -697,6 +704,9 @@ static void countRequests(Instrumentation instrumentation, boolean jacocoAttache instrumentation.addTransformer(new ServerEntries(requests, allowed, prefix), retransformable); transformerAdded = true; executorCallSitesEnabled = hasCallSiteRewrites; + if (!asyncCallSitesOff) { + JdkSinkBootstrap.install(instrumentation); + } } 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); @@ -1662,7 +1672,7 @@ private void connectAndServe() throws IOException { CoverageCommand command = CoverageCommand.parse(trimmed); if (command == null) { synchronized (testCaseLock) { - writeLine(out, IGNORED_REPLY); + writeLine(out, UNIX_REPLY_IGNORED); out.flush(); } continue; @@ -2237,6 +2247,7 @@ private void warmup() { final long began = System.nanoTime(); final AppWarmup warmup = new AppWarmup(instrumentation); Thread thread; + JdkSinkBootstrap.enterInternal(); try { thread = warmupThreads.newThread(() -> runWarmup(warmup, began)); thread.start(); @@ -2246,6 +2257,8 @@ private void warmup() { log(Level.WARNING, "Keploy dedup: no warmup, as its thread could not start; the app's classes" + " initialize when the app first uses them", t); return; + } finally { + JdkSinkBootstrap.exitInternal(); } try { thread.join(warmupWaitMillis); @@ -2933,7 +2946,12 @@ public void run() { } }, "keploy-index-report"); t.setDaemon(true); - t.start(); + JdkSinkBootstrap.enterInternal(); + try { + t.start(); + } finally { + JdkSinkBootstrap.exitInternal(); + } } catch (Throwable ignored) { reportPrecomputeStarted.set(false); } diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/ProbeScan.java b/keploy-sdk/src/main/java/io/keploy/dedup/ProbeScan.java index f5be4218..51eb36c1 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ProbeScan.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ProbeScan.java @@ -264,10 +264,13 @@ synchronized List pass(Set app) throws ReflectiveOperationException // take it: creating the pool or its thread fails (out of memory, or the // container's limit on threads). private void submit(FutureTask> task) { + JdkSinkBootstrap.enterInternal(); try { pool().execute(task); } catch (Throwable t) { task.run(); + } finally { + JdkSinkBootstrap.exitInternal(); } } @@ -393,6 +396,7 @@ private ExecutorService pool() { return thread; }); created.allowCoreThreadTimeOut(true); + RequestGate.registerAgentInternalPool(created); pool = created; } return pool; 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 62dc8ade..07b120c7 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -210,6 +210,152 @@ private static boolean declaresCfMethod(Class type, String name, Class... // runs, counts in; null on any other thread. private static final ThreadLocal INSIDE = new ThreadLocal<>(); + // Scoped depth > 0 while RequestGate or a hooked Spring executor is + // delegating a proven permit-holding Hand to an underlying JDK sink + // (TPE.execute, STPE.delayedExecute, FJP external submit, Thread.start + // for worker growth or SimpleAsyncTaskExecutor). + private static final ThreadLocal TRACKED_DISPATCH_DEPTH = new ThreadLocal<>(); + + // Weak identity set of Keploy's own agent-internal pools (e.g. ProbeScan's + // scan pool) so agent work never false-latches JDK sinks. + private static final ConcurrentHashMap AGENT_INTERNAL_POOLS = + new ConcurrentHashMap<>(); + private static final ReferenceQueue DEAD_AGENT_POOLS = new ReferenceQueue<>(); + + // Tracked Executor wrapper for 1-arg CompletableFuture.*Async stages when + // RequestGate holds a permit: delegates to ForkJoinPool.commonPool() inside + // TRACKED_DISPATCH_DEPTH so even deferred completion from another thread is + // proven tracked at the ForkJoinPool sink. + private static final Executor TRACKED_COMMON_POOL = new Executor() { + @Override + public void execute(Runnable command) { + enterTrackedDispatch(); + try { + java.util.concurrent.ForkJoinPool.commonPool().execute(command); + } finally { + exitTrackedDispatch(); + } + } + }; + + static void registerAgentInternalPool(Object pool) { + if (pool == null) { + return; + } + drainDeadAgentPools(); + AGENT_INTERNAL_POOLS.put(new WeakIdentityKey(pool, DEAD_AGENT_POOLS), Boolean.TRUE); + } + + static boolean isAgentInternalPool(Object pool) { + if (pool == null || AGENT_INTERNAL_POOLS.isEmpty()) { + return false; + } + return AGENT_INTERNAL_POOLS.containsKey(new LookupKey(pool)); + } + + private static void drainDeadAgentPools() { + Reference ref; + while ((ref = DEAD_AGENT_POOLS.poll()) != null) { + AGENT_INTERNAL_POOLS.remove(ref); + } + } + + static boolean isTrackedTask(Object task) { + return task instanceof Hand; + } + + /** + * Marks entry into a proven tracked dispatch scope when {@code handed} is a + * {@link Hand} permit, allowing downstream JDK sinks to recognize it. + * + * @param handed task returned by {@link #hand(Object, Runnable)} or {@link #hand(Object, Callable)} + */ + public static void enterTrackedDispatch(Object handed) { + if (handed instanceof Hand) { + enterTrackedDispatch(); + } + } + + /** + * Exits a proven tracked dispatch scope entered by {@link #enterTrackedDispatch(Object)}. + * + * @param handed task passed to {@link #enterTrackedDispatch(Object)} + */ + public static void exitTrackedDispatch(Object handed) { + if (handed instanceof Hand) { + exitTrackedDispatch(); + } + } + + static void enterTrackedDispatch() { + Integer cur = TRACKED_DISPATCH_DEPTH.get(); + TRACKED_DISPATCH_DEPTH.set(cur == null ? Integer.valueOf(1) : Integer.valueOf(cur.intValue() + 1)); + } + + static void exitTrackedDispatch() { + Integer cur = TRACKED_DISPATCH_DEPTH.get(); + if (cur == null || cur.intValue() <= 1) { + TRACKED_DISPATCH_DEPTH.remove(); + } else { + TRACKED_DISPATCH_DEPTH.set(Integer.valueOf(cur.intValue() - 1)); + } + } + + static boolean isTrackedDispatchActive() { + Integer cur = TRACKED_DISPATCH_DEPTH.get(); + return cur != null && cur.intValue() > 0; + } + + static boolean isInsideTrackedWindowOrJob() { + return INSIDE.get() != null + || JobGate.runningAttribution() != null + || JobGate.expiredRunningName() != null; + } + + private static Executor wrapTrackedExecutor(final Executor delegate) { + if (delegate == null) { + return TRACKED_COMMON_POOL; + } + return new Executor() { + @Override + public void execute(Runnable command) { + enterTrackedDispatch(); + try { + delegate.execute(command); + } finally { + exitTrackedDispatch(); + } + } + }; + } + + static void handleUntrackedSink(String sink, Object receiver, Object task, String caller) { + String target = caller != null ? caller + : (receiver != null ? receiver.getClass().getName() + : (task != null ? task.getClass().getName() : "unknown")); + String reason = "untracked-sink:" + sink + ":" + target; + if (!armed) { + noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow(reason, false); + return; + } + Window window = INSIDE.get(); + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + noteBackgroundWorkerOutsideWindow(reason, true); + return; + } + if (receiver instanceof Thread) { + noteTrackedUntrackedAsync(reason, receiver, false); + } else if (task instanceof Future) { + noteTrackedUntrackedAsync(reason, task, false); + KeployDedupAgent.noteObservedUntrackedAsyncLibrary("untracked async pool/scheduler (" + reason + ")", true); + } else { + noteUntrackedAsync(reason, 0L); + KeployDedupAgent.noteObservedUntrackedAsyncLibrary("untracked async pool/scheduler (" + reason + ")", true); + } + } + // 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 @@ -668,11 +814,14 @@ public static void execute(Executor executor, Runnable task) { } Runnable handed = hand(executor, task); registerForExecutor(executor, handed, task); + enterTrackedDispatch(handed); try { executor.execute(handed); } catch (Throwable t) { dropped(handed, task); throw t; + } finally { + exitTrackedDispatch(handed); } } @@ -692,11 +841,14 @@ public static Future submit(ExecutorService executor, Runnable task) { Runnable handed = hand(executor, task); registerForExecutor(executor, handed, task); Future future; + enterTrackedDispatch(handed); try { future = executor.submit(handed); } catch (Throwable t) { dropped(handed, task); throw t; + } finally { + exitTrackedDispatch(handed); } trackSubmitted(future, handed, task); return future; @@ -720,11 +872,14 @@ public static Future submit(ExecutorService executor, Runnable task, T re Runnable handed = hand(executor, task); registerForExecutor(executor, handed, task); Future future; + enterTrackedDispatch(handed); try { future = executor.submit(handed, result); } catch (Throwable t) { dropped(handed, task); throw t; + } finally { + exitTrackedDispatch(handed); } trackSubmitted(future, handed, task); return future; @@ -747,11 +902,14 @@ public static Future submit(ExecutorService executor, Callable task) { Callable handed = hand(executor, task); registerForExecutor(executor, handed, task); Future future; + enterTrackedDispatch(handed); try { future = executor.submit(handed); } catch (Throwable t) { dropped(handed, task); throw t; + } finally { + exitTrackedDispatch(handed); } trackSubmitted(future, handed, task); return future; @@ -773,11 +931,14 @@ public static CompletableFuture runAsync(Runnable task) { } Runnable handed = handInternal(null, task, true); CompletableFuture cf; + enterTrackedDispatch(handed); try { cf = CompletableFuture.runAsync(handed); } catch (Throwable t) { dropped(handed, task); throw t; + } finally { + exitTrackedDispatch(handed); } attachCompletionRelease(cf, handed, task); return cf; @@ -799,11 +960,14 @@ public static CompletableFuture runAsync(Runnable task, Executor executor) Runnable handed = handInternal(executor, task, true); registerForExecutor(executor, handed, task); CompletableFuture cf; + enterTrackedDispatch(handed); try { cf = CompletableFuture.runAsync(handed, executor); } catch (Throwable t) { dropped(handed, task); throw t; + } finally { + exitTrackedDispatch(handed); } attachCompletionRelease(cf, handed, task); return cf; @@ -824,11 +988,14 @@ public static CompletableFuture supplyAsync(Supplier supplier) { } Supplier handed = handSupplierInternal(null, supplier, true); CompletableFuture cf; + enterTrackedDispatch(handed); try { cf = CompletableFuture.supplyAsync(handed); } catch (Throwable t) { dropped(handed, supplier); throw t; + } finally { + exitTrackedDispatch(handed); } attachCompletionRelease(cf, handed, supplier); return cf; @@ -851,11 +1018,14 @@ public static CompletableFuture supplyAsync(Supplier supplier, Executo Supplier handed = handSupplierInternal(executor, supplier, true); registerForExecutor(executor, handed, supplier); CompletableFuture cf; + enterTrackedDispatch(handed); try { cf = CompletableFuture.supplyAsync(handed, executor); } catch (Throwable t) { dropped(handed, supplier); throw t; + } finally { + exitTrackedDispatch(handed); } attachCompletionRelease(cf, handed, supplier); return cf; @@ -1112,6 +1282,9 @@ public static CompletableFuture completeAsync(CompletableFuture cf, Hand hand = supplier == null ? null : prepareCfStageHand(cf, null, false); Supplier target = hand == null ? supplier : wrapSupplier(hand, supplier); CompletableFuture out; + if (hand != null) { + enterTrackedDispatch(); + } try { out = (CompletableFuture) invokeCfReflect(CF_COMPLETE_ASYNC_1, cf, target); } catch (Throwable t) { @@ -1119,6 +1292,10 @@ public static CompletableFuture completeAsync(CompletableFuture cf, hand.releaseIfPending(); } throw sneakyThrow(t); + } finally { + if (hand != null) { + exitTrackedDispatch(); + } } return finishCfStage(out, hand); } @@ -1139,7 +1316,8 @@ public static CompletableFuture completeAsync(CompletableFuture cf, Supplier target = hand == null ? supplier : wrapSupplier(hand, supplier); CompletableFuture out; try { - out = (CompletableFuture) invokeCfReflect(CF_COMPLETE_ASYNC_2, cf, target, executor); + Executor targetExecutor = hand == null ? executor : wrapTrackedExecutor(executor); + out = (CompletableFuture) invokeCfReflect(CF_COMPLETE_ASYNC_2, cf, target, targetExecutor); } catch (Throwable t) { if (hand != null) { hand.releaseIfPending(); @@ -1166,7 +1344,7 @@ public static CompletableFuture thenApplyAsync(CompletableFuture cf } CompletableFuture out; try { - out = cf.thenApplyAsync(wrapFunction(hand, fn)); + out = cf.thenApplyAsync(wrapFunction(hand, fn), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1192,7 +1370,7 @@ public static CompletableFuture thenApplyAsync(CompletableFuture cf } CompletableFuture out; try { - out = cf.thenApplyAsync(wrapFunction(hand, fn), executor); + out = cf.thenApplyAsync(wrapFunction(hand, fn), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1216,7 +1394,7 @@ public static CompletableFuture thenAcceptAsync(CompletableFuture c } CompletableFuture out; try { - out = cf.thenAcceptAsync(wrapConsumer(hand, action)); + out = cf.thenAcceptAsync(wrapConsumer(hand, action), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1241,7 +1419,7 @@ public static CompletableFuture thenAcceptAsync(CompletableFuture c } CompletableFuture out; try { - out = cf.thenAcceptAsync(wrapConsumer(hand, action), executor); + out = cf.thenAcceptAsync(wrapConsumer(hand, action), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1264,7 +1442,7 @@ public static CompletableFuture thenRunAsync(CompletableFuture cf, } CompletableFuture out; try { - out = cf.thenRunAsync(wrapStageRunnable(hand, action)); + out = cf.thenRunAsync(wrapStageRunnable(hand, action), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1289,7 +1467,7 @@ public static CompletableFuture thenRunAsync(CompletableFuture cf, } CompletableFuture out; try { - out = cf.thenRunAsync(wrapStageRunnable(hand, action), executor); + out = cf.thenRunAsync(wrapStageRunnable(hand, action), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1314,7 +1492,7 @@ public static CompletableFuture thenComposeAsync(CompletableFuture } CompletableFuture out; try { - out = cf.thenComposeAsync(wrapFunction(hand, fn)); + out = cf.thenComposeAsync(wrapFunction(hand, fn), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1340,7 +1518,7 @@ public static CompletableFuture thenComposeAsync(CompletableFuture } CompletableFuture out; try { - out = cf.thenComposeAsync(wrapFunction(hand, fn), executor); + out = cf.thenComposeAsync(wrapFunction(hand, fn), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1367,7 +1545,7 @@ public static CompletableFuture thenCombineAsync(CompletableFuture< } CompletableFuture out; try { - out = cf.thenCombineAsync(other, wrapBiFunction(hand, fn)); + out = cf.thenCombineAsync(other, wrapBiFunction(hand, fn), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1396,7 +1574,7 @@ public static CompletableFuture thenCombineAsync(CompletableFuture< } CompletableFuture out; try { - out = cf.thenCombineAsync(other, wrapBiFunction(hand, fn), executor); + out = cf.thenCombineAsync(other, wrapBiFunction(hand, fn), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1422,7 +1600,7 @@ public static CompletableFuture thenAcceptBothAsync(CompletableFutu } CompletableFuture out; try { - out = cf.thenAcceptBothAsync(other, wrapBiConsumer(hand, action)); + out = cf.thenAcceptBothAsync(other, wrapBiConsumer(hand, action), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1449,7 +1627,7 @@ public static CompletableFuture thenAcceptBothAsync(CompletableFutu } CompletableFuture out; try { - out = cf.thenAcceptBothAsync(other, wrapBiConsumer(hand, action), executor); + out = cf.thenAcceptBothAsync(other, wrapBiConsumer(hand, action), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1474,7 +1652,7 @@ public static CompletableFuture runAfterBothAsync(CompletableFuture } CompletableFuture out; try { - out = cf.runAfterBothAsync(other, wrapStageRunnable(hand, action)); + out = cf.runAfterBothAsync(other, wrapStageRunnable(hand, action), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1500,7 +1678,7 @@ public static CompletableFuture runAfterBothAsync(CompletableFuture } CompletableFuture out; try { - out = cf.runAfterBothAsync(other, wrapStageRunnable(hand, action), executor); + out = cf.runAfterBothAsync(other, wrapStageRunnable(hand, action), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1526,7 +1704,7 @@ public static CompletableFuture applyToEitherAsync(CompletableFuture out; try { - out = cf.applyToEitherAsync(other, wrapFunction(hand, fn)); + out = cf.applyToEitherAsync(other, wrapFunction(hand, fn), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1553,7 +1731,7 @@ public static CompletableFuture applyToEitherAsync(CompletableFuture out; try { - out = cf.applyToEitherAsync(other, wrapFunction(hand, fn), executor); + out = cf.applyToEitherAsync(other, wrapFunction(hand, fn), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1578,7 +1756,7 @@ public static CompletableFuture acceptEitherAsync(CompletableFuture } CompletableFuture out; try { - out = cf.acceptEitherAsync(other, wrapConsumer(hand, action)); + out = cf.acceptEitherAsync(other, wrapConsumer(hand, action), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1604,7 +1782,7 @@ public static CompletableFuture acceptEitherAsync(CompletableFuture } CompletableFuture out; try { - out = cf.acceptEitherAsync(other, wrapConsumer(hand, action), executor); + out = cf.acceptEitherAsync(other, wrapConsumer(hand, action), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1629,7 +1807,7 @@ public static CompletableFuture runAfterEitherAsync(CompletableFuture< } CompletableFuture out; try { - out = cf.runAfterEitherAsync(other, wrapStageRunnable(hand, action)); + out = cf.runAfterEitherAsync(other, wrapStageRunnable(hand, action), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1655,7 +1833,7 @@ public static CompletableFuture runAfterEitherAsync(CompletableFuture< } CompletableFuture out; try { - out = cf.runAfterEitherAsync(other, wrapStageRunnable(hand, action), executor); + out = cf.runAfterEitherAsync(other, wrapStageRunnable(hand, action), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1680,7 +1858,7 @@ public static CompletableFuture handleAsync(CompletableFuture cf, } CompletableFuture out; try { - out = cf.handleAsync(wrapBiFunction(hand, fn)); + out = cf.handleAsync(wrapBiFunction(hand, fn), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1706,7 +1884,7 @@ public static CompletableFuture handleAsync(CompletableFuture cf, } CompletableFuture out; try { - out = cf.handleAsync(wrapBiFunction(hand, fn), executor); + out = cf.handleAsync(wrapBiFunction(hand, fn), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1730,7 +1908,7 @@ public static CompletableFuture whenCompleteAsync(CompletableFuture cf } CompletableFuture out; try { - out = cf.whenCompleteAsync(wrapBiConsumer(hand, action)); + out = cf.whenCompleteAsync(wrapBiConsumer(hand, action), TRACKED_COMMON_POOL); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1755,7 +1933,7 @@ public static CompletableFuture whenCompleteAsync(CompletableFuture cf } CompletableFuture out; try { - out = cf.whenCompleteAsync(wrapBiConsumer(hand, action), executor); + out = cf.whenCompleteAsync(wrapBiConsumer(hand, action), wrapTrackedExecutor(executor)); } catch (Throwable t) { hand.releaseIfPending(); throw t; @@ -1778,7 +1956,7 @@ public static CompletableFuture exceptionallyAsync(CompletableFuture c Function target = hand == null ? fn : wrapFunction(hand, fn); CompletableFuture out; try { - out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_ASYNC_1, cf, target); + out = hand == null ? (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_ASYNC_1, cf, target) : (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_ASYNC_2, cf, target, TRACKED_COMMON_POOL); } catch (Throwable t) { if (hand != null) { hand.releaseIfPending(); @@ -1804,7 +1982,7 @@ public static CompletableFuture exceptionallyAsync(CompletableFuture c Function target = hand == null ? fn : wrapFunction(hand, fn); CompletableFuture out; try { - out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_ASYNC_2, cf, target, executor); + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_ASYNC_2, cf, target, hand == null ? executor : wrapTrackedExecutor(executor)); } catch (Throwable t) { if (hand != null) { hand.releaseIfPending(); @@ -1829,7 +2007,7 @@ public static CompletableFuture exceptionallyComposeAsync(CompletableFutu Function> target = hand == null ? fn : wrapFunction(hand, fn); CompletableFuture out; try { - out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE_ASYNC_1, cf, target); + out = hand == null ? (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE_ASYNC_1, cf, target) : (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE_ASYNC_2, cf, target, TRACKED_COMMON_POOL); } catch (Throwable t) { if (hand != null) { hand.releaseIfPending(); @@ -1855,7 +2033,7 @@ public static CompletableFuture exceptionallyComposeAsync(CompletableFutu Function> target = hand == null ? fn : wrapFunction(hand, fn); CompletableFuture out; try { - out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE_ASYNC_2, cf, target, executor); + out = (CompletableFuture) invokeCfReflect(CF_EXCEPTIONALLY_COMPOSE_ASYNC_2, cf, target, hand == null ? executor : wrapTrackedExecutor(executor)); } catch (Throwable t) { if (hand != null) { hand.releaseIfPending(); @@ -3075,14 +3253,16 @@ public static void noteIfUntrackedExecutor(Object receiver) { if (!(receiver instanceof Executor)) { return; } + if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + return; + } if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(receiver, false); return; } if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { - return; - } - if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + noteExecutorHandOffOutsideWindow(receiver, true); return; } noteUntrackedAsync("untracked-executor:" + receiver.getClass().getName(), 0L); @@ -3102,19 +3282,27 @@ public static void noteIfUntrackedSubmit(Object receiver) { && !OrderedPools.isSpringAsyncTaskExecutor(receiver)) { return; } + if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + return; + } if (!armed) { noteUnarmedHandOffIfInFlight(); + noteExecutorHandOffOutsideWindow(receiver, false); return; } if (INSIDE.get() == null && JobGate.runningAttribution() == null && JobGate.expiredRunningName() == null) { - return; - } - if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + noteExecutorHandOffOutsideWindow(receiver, true); return; } noteUntrackedAsync("untracked-executor:" + receiver.getClass().getName(), 0L); } + /** + * Marks an active request window or job run contaminated if {@code receiver} + * is a JDK concurrent/blocking queue enqueued from application bytecode. + * + * @param receiver target queue receiver + */ public static void noteIfBlockingQueue(Object receiver) { if (!(receiver instanceof java.util.concurrent.BlockingQueue) && !(receiver instanceof java.util.concurrent.ConcurrentLinkedQueue) 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 a0363e2b..a450fb93 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -2559,6 +2559,8 @@ private void handing(Method method) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "hand", "(Ljava/lang/Object;" + taskType + ")" + taskType, false); mv.visitVarInsn(Opcodes.ASTORE, handed); + mv.visitVarInsn(Opcodes.ALOAD, handed); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "enterTrackedDispatch", "(Ljava/lang/Object;)V", false); mv.visitLabel(start); slot = 0; if (!isStatic) { @@ -2572,6 +2574,8 @@ private void handing(Method method) { mv.visitMethodInsn(isStatic ? Opcodes.INVOKESTATIC : Opcodes.INVOKESPECIAL, owner, renamedPrefix + method.name, method.descriptor, false); mv.visitLabel(end); + mv.visitVarInsn(Opcodes.ALOAD, handed); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "exitTrackedDispatch", "(Ljava/lang/Object;)V", false); if (returns.getSort() == Type.OBJECT) { mv.visitInsn(Opcodes.DUP); mv.visitVarInsn(Opcodes.ALOAD, handed); @@ -2587,6 +2591,8 @@ private void handing(Method method) { new Object[] {"java/lang/Throwable"}); } mv.visitVarInsn(Opcodes.ALOAD, handed); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "exitTrackedDispatch", "(Ljava/lang/Object;)V", false); + mv.visitVarInsn(Opcodes.ALOAD, handed); mv.visitVarInsn(Opcodes.ALOAD, taskSlot); mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "dropped", "(Ljava/lang/Object;Ljava/lang/Object;)V", false); diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java b/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java new file mode 100644 index 00000000..7e6fdfb6 --- /dev/null +++ b/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java @@ -0,0 +1,453 @@ +package io.keploy.dedup; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ForkJoinWorkerThread; + +/** + * Explicit, closed, exact-class allowlist for JDK concurrency sinks hooked via + * {@code io.keploy.dedup.bootstrap.KeploySinkBridge}. + * + *

No package wildcards or prefixes are used. A sink invocation keeps + * {@code asyncExecutors=true} ONLY if: + *

    + *
  1. it carries proven {@link RequestGate} tracking ({@code RequestGate.Hand} + * or active {@code TRACKED_DISPATCH_DEPTH}),
  2. + *
  3. it is Keploy's own agent-internal thread/pool,
  4. + *
  5. it is a reviewed JVM/JDK bootstrap housekeeping class,
  6. + *
  7. it is an explicitly reviewed HTTP server request-hosting worker pool + * (Tomcat, Jetty, Undertow/XNIO) whose requests enter a hooked + * {@link ServerEntries} entry, or a {@link JobGate}-hooked scheduler, or
  8. + *
  9. it is a reviewed infrastructure class verified from source never to + * execute an application-supplied Runnable, lambda, or listener.
  10. + *
+ * Everything else fails closed. + */ +final class SinkAllowlist { + + static final boolean AUDIT = "1".equals(System.getenv("KEPLOY_JAVA_SINK_AUDIT")) + || "true".equalsIgnoreCase(System.getenv("KEPLOY_JAVA_SINK_AUDIT")) + || "true".equalsIgnoreCase(System.getProperty("keploy.java.sink.audit")); + + // Exact JVM/JDK internal Thread subclasses (bootstrap/platform CL only). + private static final Set JVM_INTERNAL_THREAD_CLASSES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + "java.lang.ref.Reference$ReferenceHandler", + "java.lang.ref.Finalizer$FinalizerThread", + "jdk.internal.ref.CleanerImpl$InnocuousThread", + "jdk.internal.misc.InnocuousThread", + "jdk.internal.misc.CarrierThread", + "sun.misc.InnocuousThread", + "java.util.logging.LogManager$Cleaner" + ))); + + // Exact JVM/JDK internal callers that spawn housekeeping Threads (bootstrap/platform CL only). + private static final Set JVM_INTERNAL_CALLER_CLASSES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + "java.lang.ApplicationShutdownHooks", + "java.lang.ProcessHandleImpl", + "java.lang.ProcessImpl", + "java.lang.UNIXProcess", + "jdk.internal.ref.CleanerImpl", + "jdk.internal.ref.CleanerFactory", + "sun.misc.Cleaner", + "java.lang.ref.Cleaner", + "java.util.logging.LogManager", + "sun.net.www.http.KeepAliveCache", + "sun.net.www.http.KeepAliveCache$1", + "sun.nio.ch.AsynchronousChannelGroupImpl", + "java.lang.VirtualThread", + "java.util.concurrent.DelayScheduler", + "jdk.internal.misc.Signal", + "sun.misc.Signal" + ))); + + // Exact reviewed HTTP server request-hosting worker Thread subclasses + // (requests on these threads enter hooked CoyoteAdapter / HttpChannel / Connectors). + private static final Set SERVER_WORKER_THREAD_CLASSES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + // Tomcat (CoyoteAdapter) + "org.apache.tomcat.util.threads.TaskThread", + "org.apache.catalina.startup.Catalina$CatalinaShutdownHook", + "org.apache.juli.ClassLoaderLogManager$Cleaner", + // Jetty (HttpChannel / ServletChannel) + "org.eclipse.jetty.util.thread.ShutdownThread", + // Undertow / XNIO / JBoss Threads (Connectors) + "org.xnio.nio.WorkerThread", + "org.jboss.threads.JBossThread", + // JobGate-hooked Quartz scheduler threads + "org.quartz.simpl.SimpleThreadPool$WorkerThread", + "org.quartz.core.QuartzSchedulerThread" + ))); + + // Exact reviewed HTTP server request-hosting classes that start plain java.lang.Thread + // instances (acceptors, pollers, Jetty QueuedThreadPool workers, Tomcat container background). + private static final Set SERVER_THREAD_START_CALLERS = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + // Tomcat (CoyoteAdapter) + "org.apache.tomcat.util.net.AbstractEndpoint", + "org.apache.tomcat.util.net.NioEndpoint", + "org.apache.tomcat.util.net.Nio2Endpoint", + "org.apache.tomcat.util.net.AprEndpoint", + "org.apache.tomcat.util.threads.ThreadPoolExecutor", + "org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor", + "org.apache.catalina.core.StandardServer", + "org.apache.catalina.core.ContainerBase", + "org.apache.catalina.startup.Catalina", + "org.apache.juli.AsyncFileHandler$LoggerExecutorService", + // Jetty (HttpChannel / ServletChannel) + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", + "org.eclipse.jetty.util.thread.ExecutorThreadPool", + "org.eclipse.jetty.util.thread.TimerScheduler", + // Undertow / XNIO / JBoss Threads (Connectors) + "org.xnio.nio.NioXnioWorker", + "org.xnio.XnioWorker", + "org.jboss.threads.EnhancedQueueExecutor", + "org.jboss.threads.JBossScheduledThreadPoolExecutor", + // JobGate-hooked Quartz scheduler + "org.quartz.simpl.SimpleThreadPool", + "org.quartz.core.QuartzScheduler" + ))); + + // Exact reviewed HTTP server request-hosting classes that dispatch onto + // ThreadPoolExecutor / ScheduledThreadPoolExecutor for server I/O or + // maintenance (requests enter hooked CoyoteAdapter / HttpChannel / Connectors). + private static final Set SERVER_POOL_CALLERS = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + // Tomcat (CoyoteAdapter) + "org.apache.tomcat.util.net.AbstractEndpoint", + "org.apache.tomcat.util.net.NioEndpoint", + "org.apache.tomcat.util.net.Nio2Endpoint", + "org.apache.tomcat.util.net.AprEndpoint", + "org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor", + "org.apache.catalina.core.StandardServer", + "org.apache.catalina.core.ContainerBase", + // Jetty (HttpChannel / ServletChannel) + "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", + "org.eclipse.jetty.util.thread.ExecutorThreadPool", + // Undertow / XNIO / JBoss Threads (Connectors) + "org.xnio.XnioWorker", + "org.jboss.threads.JBossScheduledThreadPoolExecutor" + ))); + + // Exact reviewed HTTP server request-hosting ThreadPoolExecutor / STPE subclasses. + private static final Set SERVER_POOL_CLASSES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + // Tomcat (CoyoteAdapter) + "org.apache.tomcat.util.threads.ThreadPoolExecutor", + "org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor", + "org.apache.juli.AsyncFileHandler$LoggerExecutorService", + // Undertow / XNIO / JBoss Threads (Connectors) + "org.xnio.XnioWorker$DefaultThreadPoolExecutor", + "org.jboss.threads.JBossScheduledThreadPoolExecutor", + "org.jboss.threads.ManagedThreadPoolExecutor" + ))); + + // Exact reviewed ScheduledThreadPoolExecutor / TPE task classes from + // servers or JobGate-hooked schedulers that never execute arbitrary unhooked app callbacks. + private static final Set SERVER_TASK_CLASSES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + // Tomcat container utility/maintenance tasks + "org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessorMonitor", + "org.apache.catalina.core.StandardServer$1", + "org.apache.catalina.util.TimeBucketCounterBase$MaintenanceMonitor", + "org.apache.catalina.util.TimeBucketCounter$MaintenanceMonitor", + "org.apache.tomcat.util.net.NioEndpoint$SocketProcessor", + "org.apache.tomcat.util.net.Nio2Endpoint$SocketProcessor", + // Jetty internal scheduled tasks + "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler$ScheduledFutureTask", + "org.eclipse.jetty.io.IdleTimeout$1", + // Spring @Scheduled (hooked into JobGate via ScheduledMethodRunnable) + "org.springframework.scheduling.support.ScheduledMethodRunnable", + "org.springframework.scheduling.support.DelegatingErrorHandlingRunnable", + "org.springframework.scheduling.concurrent.ReschedulingRunnable" + ))); + + // Exact zero-app-callback infrastructure classes measured on Spring PetClinic + // (each entry carries an exact library version + class/method/source-line + // citation verified from the dependency JAR proving no user Runnable, + // lambda, or listener executes on it; exact class names only, no prefixes). + static final Set INFRA_THREAD_CALLERS = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + // HikariCP 7.1.0 (HikariPool.java:90-132): private addConnectionExecutor, + // closeConnectionExecutor, and houseKeepingExecutorService spawn internal + // housekeeper/connection-adder/connection-closer threads only. + "com.zaxxer.hikari.pool.HikariPool", + // MySQL Connector/J 26.10.0 (AbandonedConnectionCleanupThread.java:83-105): + // private cleanupThreadExecutorService polls ReferenceQueue + // to close leaked sockets; never runs user callbacks. + "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread", + // H2 2.5.252 (MathUtils.java:65-122): getSecureRandom() spawns one + // "Generate Seed" daemon thread calling SecureRandom.generateSeed(). + "org.h2.util.MathUtils", + // Spring Boot AutoConfigure 4.2.0 (OnClassCondition.java:141-166): + // ThreadedOutcomesResolver evaluates @ConditionalOnClass checks on a + // startup thread joined in resolveOutcomes(); never runs user callbacks. + "org.springframework.boot.autoconfigure.condition.OnClassCondition$ThreadedOutcomesResolver", + // Spring Boot AutoConfigure 4.2.0 + // (BackgroundPreinitializingApplicationListener.java:70-98): spawns one + // "background-preinit" startup thread warming built-in framework + // initializers and joined before startup finishes; never runs user tasks. + "org.springframework.boot.autoconfigure.preinitialize.BackgroundPreinitializingApplicationListener", + // Spring Boot Tomcat 4.2.0 (TomcatWebServer.java:102-141): spawns one + // non-daemon "container-0" await thread calling Tomcat.getServer().await(). + "org.springframework.boot.tomcat.TomcatWebServer", + // Spring Boot Tomcat 4.2.0 (GracefulShutdown.java:42-69): spawns one + // "tomcat-shutdown" thread closing Tomcat connectors on shutdown. + "org.springframework.boot.tomcat.GracefulShutdown", + // Spring Boot 2/3 equivalent package for TomcatWebServer / GracefulShutdown. + "org.springframework.boot.web.embedded.tomcat.TomcatWebServer", + "org.springframework.boot.web.embedded.tomcat.GracefulShutdown" + ))); + + static final Set INFRA_POOL_CALLERS = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + // HikariCP 7.1.0 (HikariPool.java:90-132): dispatches only private + // HouseKeeper, PoolEntryCreator, and closeConnection tasks. + "com.zaxxer.hikari.pool.HikariPool", + // MySQL Connector/J 26.10.0 (AbandonedConnectionCleanupThread.java:83-105): + // submits only its own singleton ReferenceQueue cleanup Runnable. + "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread" + ))); + + static final Set INFRA_TASK_CLASSES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList( + // MySQL Connector/J 26.10.0 (AbandonedConnectionCleanupThread.java:83-105). + "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread" + ))); + + private SinkAllowlist() { + } + + static boolean isAllowlistedThreadStart(Thread thread, String[] callerOut) { + if (thread == null) { + return true; + } + if (RequestGate.isTrackedDispatchActive()) { + return true; + } + Class cls = thread.getClass(); + String clsName = cls.getName(); + if (isBootstrapOrPlatform(cls) && JVM_INTERNAL_THREAD_CLASSES.contains(clsName)) { + return true; + } + if (SERVER_WORKER_THREAD_CLASSES.contains(clsName)) { + return true; + } + if (thread instanceof ForkJoinWorkerThread) { + // A ForkJoinWorkerThread is only allowed if its pool was triggered + // by an active RequestGate tracked dispatch (handled above) or + // commonPool compensation while already inside a tracked window/job; + // any other FJP worker start (e.g. unhooked ForkJoinPool subclass or + // ForkJoinTask.adapt outside window) fails closed. + if (RequestGate.isInsideTrackedWindowOrJob() + && ((ForkJoinWorkerThread) thread).getPool() == java.util.concurrent.ForkJoinPool.commonPool()) { + return true; + } + String caller = firstExternalCaller(); + if (callerOut != null && callerOut.length > 0) { + callerOut[0] = caller; + } + return isAllowlistedJvmCaller(caller); + } + String caller = firstExternalCaller(); + if (callerOut != null && callerOut.length > 0) { + callerOut[0] = caller; + } + if (caller == null) { + return false; + } + if (isAllowlistedJvmCaller(caller)) { + return true; + } + if (SERVER_THREAD_START_CALLERS.contains(caller)) { + return true; + } + if (INFRA_THREAD_CALLERS.contains(caller)) { + return true; + } + return false; + } + + static boolean isAllowlistedVirtualThreadStart(Thread thread, String[] callerOut) { + if (thread == null) { + return true; + } + if (RequestGate.isTrackedDispatchActive()) { + return true; + } + String caller = firstExternalCaller(true); + if (callerOut != null && callerOut.length > 0) { + callerOut[0] = caller; + } + // Tomcat virtual-thread request executor enters hooked CoyoteAdapter. + if ("org.apache.tomcat.util.threads.VirtualThreadExecutor".equals(caller) + || "org.apache.catalina.core.StandardVirtualThreadExecutor".equals(caller)) { + return true; + } + return false; + } + + static boolean isAllowlistedTpeExecute(Object executor, Object command, String[] callerOut) { + if (RequestGate.isTrackedDispatchActive() || RequestGate.isTrackedTask(command)) { + return true; + } + if (RequestGate.isAgentInternalPool(executor)) { + return true; + } + if (executor != null && SERVER_POOL_CLASSES.contains(executor.getClass().getName())) { + return true; + } + if (command != null && (SERVER_TASK_CLASSES.contains(command.getClass().getName()) + || INFRA_TASK_CLASSES.contains(command.getClass().getName()))) { + return true; + } + String caller = firstExternalCaller(); + if (callerOut != null && callerOut.length > 0) { + callerOut[0] = caller; + } + if (caller != null && (SERVER_POOL_CALLERS.contains(caller) + || INFRA_POOL_CALLERS.contains(caller) + || isAllowlistedJvmCaller(caller))) { + return true; + } + return false; + } + + static boolean isAllowlistedStpeDelayedExecute(Object executor, Object task, String[] callerOut) { + if (RequestGate.isTrackedDispatchActive() || RequestGate.isTrackedTask(task)) { + return true; + } + if (RequestGate.isAgentInternalPool(executor)) { + return true; + } + if (executor != null && SERVER_POOL_CLASSES.contains(executor.getClass().getName())) { + return true; + } + if (task != null && (SERVER_TASK_CLASSES.contains(task.getClass().getName()) + || INFRA_TASK_CLASSES.contains(task.getClass().getName()))) { + return true; + } + String caller = firstExternalCaller(); + if (callerOut != null && callerOut.length > 0) { + callerOut[0] = caller; + } + if (caller != null && (SERVER_POOL_CALLERS.contains(caller) + || INFRA_POOL_CALLERS.contains(caller) + || isAllowlistedJvmCaller(caller))) { + return true; + } + return false; + } + + static boolean isAllowlistedFjpSubmit(Object pool, Object task, String[] callerOut) { + if (RequestGate.isTrackedDispatchActive() || RequestGate.isTrackedTask(task)) { + return true; + } + // JDK 21 VirtualThread continuations run on VirtualThread.DEFAULT_SCHEDULER; + // VirtualThread.start() was already audited (and latched/contaminated if + // non-allowlisted) before submitting the continuation. + if (task != null && "java.lang.VirtualThread$VThreadContinuation".equals(task.getClass().getName())) { + return true; + } + String caller = firstExternalCaller(); + if (callerOut != null && callerOut.length > 0) { + callerOut[0] = caller; + } + if ("java.lang.VirtualThread".equals(caller)) { + return true; + } + return false; + } + + static boolean isAllowlistedTimerSched(Object timer, Object task, String[] callerOut) { + if (RequestGate.isTrackedDispatchActive()) { + return true; + } + String caller = firstExternalCaller(); + if (callerOut != null && callerOut.length > 0) { + callerOut[0] = caller; + } + if (caller != null && (isAllowlistedJvmCaller(caller) + || "org.eclipse.jetty.util.thread.TimerScheduler".equals(caller) + || INFRA_POOL_CALLERS.contains(caller))) { + return true; + } + return false; + } + + static void audit(String sink, boolean allowed, String detail, Object recv, Object task, String caller) { + if (!AUDIT) { + return; + } + System.err.println("KEPLOY_SINK_AUDIT sink=" + sink + + " allowed=" + allowed + + " detail=" + detail + + " recv=" + (recv == null ? "null" : recv.getClass().getName()) + + " task=" + (task == null ? "null" : task.getClass().getName()) + + " caller=" + (caller == null ? "null" : caller)); + } + + private static boolean isAllowlistedJvmCaller(String caller) { + return caller != null && JVM_INTERNAL_CALLER_CLASSES.contains(caller); + } + + private static boolean isBootstrapOrPlatform(Class cls) { + ClassLoader cl = cls.getClassLoader(); + if (cl == null) { + return true; + } + // JDK 9+ platform classloader (e.g. java.logging). + ClassLoader sys = ClassLoader.getSystemClassLoader(); + return sys != null && cl == sys.getParent(); + } + + // Walks the current thread's stack to find the first caller outside the + // sink bridge, Keploy's own RequestGate/SinkAllowlist, and the JDK sink + // wrapper methods themselves (e.g. ThreadPoolExecutor.addWorker -> execute, + // AbstractExecutorService.submit -> execute, Timer.schedule -> sched). + // Note: reflection (java.lang.reflect.Method.invoke) and MethodHandles are + // NOT skipped — they return their own class name, which is NOT in any + // allowlist, so reflective/MethodHandle dispatch fails closed by construction. + static String firstExternalCaller() { + return firstExternalCaller(false); + } + + static String firstExternalCaller(boolean skipVirtualThreadFrames) { + StackTraceElement[] frames = Thread.currentThread().getStackTrace(); + for (int i = 1; i < frames.length; i++) { + String cn = frames[i].getClassName(); + if ("io.keploy.dedup.bootstrap.KeploySinkBridge".equals(cn) + || "io.keploy.dedup.SinkAllowlist".equals(cn) + || "io.keploy.dedup.RequestGate".equals(cn) + || "io.keploy.dedup.JdkSinkHandler".equals(cn) + || "io.keploy.dedup.JdkSinkBootstrap".equals(cn) + || "java.lang.Thread".equals(cn) + || "java.lang.System$2".equals(cn) + || "jdk.internal.vm.ThreadContainers".equals(cn) + || "jdk.internal.vm.SharedThreadContainer".equals(cn) + || (skipVirtualThreadFrames && ("java.lang.VirtualThread".equals(cn) + || "java.lang.ThreadBuilders$VirtualThreadBuilder".equals(cn) + || "java.lang.ThreadBuilders$PlatformThreadBuilder".equals(cn) + || "java.lang.ThreadBuilders$BaseThreadBuilder".equals(cn))) + || "java.util.concurrent.ThreadPoolExecutor".equals(cn) + || "java.util.concurrent.ThreadPoolExecutor$Worker".equals(cn) + || "java.util.concurrent.ScheduledThreadPoolExecutor".equals(cn) + || "java.util.concurrent.AbstractExecutorService".equals(cn) + || "java.util.concurrent.Executors$DelegatedExecutorService".equals(cn) + || "java.util.concurrent.Executors$FinalizableDelegatedExecutorService".equals(cn) + || "java.util.concurrent.Executors$DelegatedScheduledExecutorService".equals(cn) + || "java.util.concurrent.ForkJoinPool".equals(cn) + || "java.util.concurrent.ForkJoinTask".equals(cn) + || "java.util.concurrent.CompletableFuture".equals(cn) + || "java.util.Timer".equals(cn)) { + continue; + } + return cn; + } + return null; + } +} diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/bootstrap/KeploySinkBridge.java b/keploy-sdk/src/main/java/io/keploy/dedup/bootstrap/KeploySinkBridge.java new file mode 100644 index 00000000..73da15c9 --- /dev/null +++ b/keploy-sdk/src/main/java/io/keploy/dedup/bootstrap/KeploySinkBridge.java @@ -0,0 +1,245 @@ +package io.keploy.dedup.bootstrap; + +/** + * Bootstrap-classloader bridge invoked from bytecode injected into JDK + * concurrency sinks ({@code Thread.start}, {@code VirtualThread.start}, + * {@code ThreadPoolExecutor.execute}, {@code ScheduledThreadPoolExecutor.delayedExecute}, + * {@code ForkJoinPool} external submission, and {@code Timer.sched}). + * + *

Loaded exclusively by the bootstrap class loader (via + * {@code Instrumentation.appendToBootstrapClassLoaderSearch}) and uses only + * {@code java.lang.*} types so {@code java.base} classes can invoke it across + * JDK 8, 11, 17, and 21 without any JVM CLI flags. + */ +public final class KeploySinkBridge { + + /** + * Runtime sink handler registered by the Keploy agent once initialized. + * Uses only {@code java.lang.*} types so this interface stays loadable by + * the bootstrap class loader. + */ + public interface Handler { + /** + * Invoked at entry to {@code Thread.start}. + * + * @param thread the platform thread being started + */ + void onThreadStart(Thread thread); + + /** + * Invoked at entry to {@code VirtualThread.start} (JDK 21+). + * + * @param thread the virtual thread being started + */ + void onVirtualThreadStart(Thread thread); + + /** + * Invoked at entry to {@code ThreadPoolExecutor.execute}. + * + * @param executor target pool instance + * @param command runnable being executed + */ + void onTpeExecute(Object executor, Object command); + + /** + * Invoked at entry to {@code ScheduledThreadPoolExecutor.delayedExecute}. + * + * @param executor target scheduled pool instance + * @param task scheduled task + */ + void onStpeDelayedExecute(Object executor, Object task); + + /** + * Invoked at entry to {@code ForkJoinPool} external submission. + * + * @param pool target fork-join pool instance + * @param task submitted task + */ + void onFjpExternalSubmit(Object pool, Object task); + + /** + * Invoked at entry to {@code Timer.sched}. + * + * @param timer target timer instance + * @param task timer task being scheduled + */ + void onTimerSched(Object timer, Object task); + } + + /** Active runtime handler installed by the Keploy agent. */ + public static volatile Handler handler; + + /** Diagnostic flag set if a sink callback ever threw unexpectedly. */ + public static volatile Throwable lastCallbackError; + + // Re-entrancy and agent-internal depth guard. Always > 0 while executing + // inside a sink callback or inside Keploy's own agent threads/pools, so + // Keploy's own threads never latch and sink callbacks can never recurse. + private static final ThreadLocal INTERNAL_DEPTH = new ThreadLocal(); + + private static void reportError(Throwable t) { + if (lastCallbackError == null) { + lastCallbackError = t; + try { + System.err.println("KEPLOY_SINK_BRIDGE_ERROR: " + t); + t.printStackTrace(System.err); + } catch (Throwable ignored) { + // Never disrupt JDK caller. + } + } + } + + private KeploySinkBridge() { + } + + /** Marks the current thread as executing Keploy-internal work. */ + public static void enterInternal() { + Integer cur = INTERNAL_DEPTH.get(); + INTERNAL_DEPTH.set(cur == null ? Integer.valueOf(1) : Integer.valueOf(cur.intValue() + 1)); + } + + /** Unmarks one level of Keploy-internal work on the current thread. */ + public static void exitInternal() { + Integer cur = INTERNAL_DEPTH.get(); + if (cur == null || cur.intValue() <= 1) { + INTERNAL_DEPTH.remove(); + } else { + INTERNAL_DEPTH.set(Integer.valueOf(cur.intValue() - 1)); + } + } + + /** + * Returns whether the current thread is inside Keploy-internal work or a + * sink callback. + * + * @return {@code true} when internal depth is positive + */ + public static boolean isInternal() { + Integer cur = INTERNAL_DEPTH.get(); + return cur != null && cur.intValue() > 0; + } + + /** + * Bridge entry point for {@code Thread.start}. + * + * @param thread the platform thread being started + */ + public static void onThreadStart(Thread thread) { + Handler h = handler; + if (h == null || isInternal()) { + return; + } + enterInternal(); + try { + h.onThreadStart(thread); + } catch (Throwable t) { + reportError(t); + } finally { + exitInternal(); + } + } + + /** + * Bridge entry point for {@code VirtualThread.start} (JDK 21+). + * + * @param thread the virtual thread being started + */ + public static void onVirtualThreadStart(Thread thread) { + Handler h = handler; + if (h == null || isInternal()) { + return; + } + enterInternal(); + try { + h.onVirtualThreadStart(thread); + } catch (Throwable t) { + reportError(t); + } finally { + exitInternal(); + } + } + + /** + * Bridge entry point for {@code ThreadPoolExecutor.execute}. + * + * @param executor target pool instance + * @param command runnable being executed + */ + public static void onTpeExecute(Object executor, Object command) { + Handler h = handler; + if (h == null || isInternal()) { + return; + } + enterInternal(); + try { + h.onTpeExecute(executor, command); + } catch (Throwable t) { + reportError(t); + } finally { + exitInternal(); + } + } + + /** + * Bridge entry point for {@code ScheduledThreadPoolExecutor.delayedExecute}. + * + * @param executor target scheduled pool instance + * @param task scheduled task + */ + public static void onStpeDelayedExecute(Object executor, Object task) { + Handler h = handler; + if (h == null || isInternal()) { + return; + } + enterInternal(); + try { + h.onStpeDelayedExecute(executor, task); + } catch (Throwable t) { + reportError(t); + } finally { + exitInternal(); + } + } + + /** + * Bridge entry point for {@code ForkJoinPool} external submission. + * + * @param pool target fork-join pool instance + * @param task submitted task + */ + public static void onFjpExternalSubmit(Object pool, Object task) { + Handler h = handler; + if (h == null || isInternal()) { + return; + } + enterInternal(); + try { + h.onFjpExternalSubmit(pool, task); + } catch (Throwable t) { + reportError(t); + } finally { + exitInternal(); + } + } + + /** + * Bridge entry point for {@code Timer.sched}. + * + * @param timer target timer instance + * @param task timer task being scheduled + */ + public static void onTimerSched(Object timer, Object task) { + Handler h = handler; + if (h == null || isInternal()) { + return; + } + enterInternal(); + try { + h.onTimerSched(timer, task); + } catch (Throwable t) { + reportError(t); + } finally { + exitInternal(); + } + } +} diff --git a/keploy-sdk/src/test/java/io/fakeexternal/SubForkJoinPool.java b/keploy-sdk/src/test/java/io/fakeexternal/SubForkJoinPool.java new file mode 100644 index 00000000..3c1ddddb --- /dev/null +++ b/keploy-sdk/src/test/java/io/fakeexternal/SubForkJoinPool.java @@ -0,0 +1,20 @@ +package io.fakeexternal; + +import java.util.concurrent.ForkJoinPool; + +/** + * Simulated external library dispatching through its own {@link ForkJoinPool} + * subclass so tests verify unallowlisted library FJP subclasses fail closed. + */ +public final class SubForkJoinPool extends ForkJoinPool { + + private static final SubForkJoinPool INSTANCE = new SubForkJoinPool(); + + private SubForkJoinPool() { + super(2); + } + + public static void fire(Runnable task) { + INSTANCE.execute(task); + } +} 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 09d7e5e0..a0dafc4e 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/CoverageTcpClientTest.java @@ -132,11 +132,11 @@ public void unknownOrMalformedTcpCommandAnswersIgnoredAndKeepsConnectionAlive() assertHello(in.readLine()); send(out, "FOO"); - assertEquals("IGNORED", in.readLine()); + assertEquals("IGNORED proto=3", in.readLine()); send(out, "START"); - assertEquals("IGNORED", in.readLine()); + assertEquals("IGNORED proto=3", in.readLine()); send(out, "PROTO 4"); - assertEquals("IGNORED", in.readLine()); + assertEquals("IGNORED proto=3", in.readLine()); send(out, "NOP"); assertEquals("ACK", in.readLine()); } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index adfcb7fd..8462f959 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -169,8 +169,8 @@ public void forkedExternalCfDependentAndConcreteAsyncFormsAreTrackedOrFlagged() 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("unallowlisted external library thread start must be flagged by JDK sink: " + covExt, + covExt.contains("untracked-sink:thread-start:io.fakeexternal.FakeExternalHttpClient")); assertTrue("external CF audit probe must land in COV: " + covExt, covExt.contains("\"" + ASYNC_TAIL + "\"")); @@ -504,6 +504,125 @@ public void forkedKafkaListenerHookEmitsTopicAndBeanAttributionInTcpCov() throws } } + @Test(timeout = 120000) + public void forkedBootstrapBridgeLoadsInBootstrapClassLoaderAndAgentThreadsNeverLatch() throws Exception { + try (ForkedApp app = startFork("tomcat", "2000", false, false, null, null)) { + JsonObject initial = parseHello(app.initialHello); + assertTrue("initial HELLO must declare asyncExecutors=true with bootstrap sink bridge: " + app.initialHello, + initial.get("asyncExecutors").getAsBoolean()); + String covCheck = app.runHttpTest("ts/bootstrap-cl", "/bootstrap-check"); + assertFalse("bootstrap-check must not contaminate COV: " + covCheck, covCheck.contains("contaminated")); + assertTrue("asyncExecutors must remain true after /bootstrap-check and agent-internal threads: " + + app.lastHello, parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covClean = app.runHttpTest("ts/bootstrap-clean", "/clean"); + assertFalse("clean baseline must not contaminate COV: " + covClean, covClean.contains("contaminated")); + assertTrue("asyncExecutors must remain true after /clean: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + } + + @Test(timeout = 300000) + public void forkedDirectJdkSinkBypassesFailClosedWithExactSinkReasons() throws Exception { + // Each tuple: {fixture, expectedSinkPrefix, expectAsyncFalseLatch, warmCommonPoolFirst} + // These invoke JDK sinks via reflection/MethodHandle with zero call-site + // rewrites, proving each of the 5 core JDK sink hooks independently fails closed. + String[][] cases = { + {"reflect-thread-start", "untracked-sink:thread-start:", "false", "false"}, + {"mh-thread-start", "untracked-sink:thread-start:", "false", "false"}, + {"mh-tpe-execute", "untracked-sink:tpe-execute:", "true", "false"}, + {"reflect-stpe-schedule", "untracked-sink:stpe-delayed-execute:", "true", "false"}, + {"reflect-fjp-submit", "untracked-sink:fjp-submit:", "true", "true"}, + {"reflect-timer-schedule", "untracked-sink:timer-sched:", "true", "false"}, + }; + for (String[] tc : cases) { + String name = tc[0]; + String expectedSink = tc[1]; + boolean expectLatch = Boolean.parseBoolean(tc[2]); + boolean warmFjp = Boolean.parseBoolean(tc[3]); + try (ForkedApp app = startFork("sink-" + name, "80", false, false, null, null)) { + app.runHttpTest("sink/" + name + "-warm", warmFjp ? "/warm-common-pool" : "/clean"); + assertTrue("case=" + name + " baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String cov1 = app.runHttpTest("sink/" + name + "-w1", "/sink-" + name + "?ms=250"); + assertTrue("case=" + name + " must fail closed with " + expectedSink + ", got W1=" + cov1, + cov1.contains(expectedSink)); + if (expectLatch) { + assertFalse("case=" + name + " must latch asyncExecutors=false: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + } + } + } + + @Test(timeout = 180000) + public void forkedJdk21VirtualThreadSinkBypassesFailClosed() 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); + + try (ForkedApp app = startFork("sink-reflect-vthread-start", "80", false, false, null, null)) { + app.runHttpTest("vt/reflect-warm", "/clean"); + assertTrue("baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String cov1 = app.runHttpTest("vt/reflect-w1", "/sink-reflect-vthread-start?ms=250"); + assertTrue("reflective VirtualThread.start must fail closed with virtual-thread-start sink: " + cov1, + cov1.contains("untracked-sink:virtual-thread-start:")); + } + + for (String name : new String[] {"vthread-exec-worker", "vthread-exec-inwindow"}) { + try (ForkedApp app = startFork("sink-" + name, "80", false, false, null, null)) { + app.runHttpTest("vt/" + name + "-warm", "/clean"); + String cov1 = app.runHttpTest("vt/" + name + "-w1", "/sink-" + name + "?ms=300"); + boolean flagged = cov1.contains("\"contaminated\"") || cov1.contains("\"windowCut\":true"); + boolean asyncOff = !parseHello(app.lastHello).get("asyncExecutors").getAsBoolean(); + assertTrue("JDK 21 virtual-thread executor case=" + name + " must fail closed: W1=" + cov1 + + " hello=" + app.lastHello, flagged || asyncOff); + } + } + } + + @Test(timeout = 420000) + public void forkedAppSubPoolsAndReflectiveStartupWorkersFailClosed() throws Exception { + // Isolated forks in both prefix and index modes for app/library JDK pool + // subclasses and reflective startup workers. + String[][] cases = { + {"app-tpe-sub-worker", "false"}, + {"app-tpe-sub-submit-worker", "false"}, + {"app-fjp-sub-worker", "false"}, + {"app-fjp-sub-inwindow", "true"}, + {"fjtask-worker", "false"}, + {"app-timer-sub-poller", "false"}, + {"app-timer-sub-inwindow", "false"}, + {"app-stpe-sub-poller", "false"}, + {"lib-fjp-sub", "true"}, + {"reflect-worker-startup", "false"}, + }; + for (boolean prefixMode : new boolean[] {true, false}) { + for (String[] tc : cases) { + String name = tc[0]; + boolean expectBaseTrue = Boolean.parseBoolean(tc[1]); + try (ForkedApp app = startFork("sink-" + name, "80", prefixMode, false, null, null)) { + app.runHttpTest("sp/" + name + "-warm", "/clean"); + if (expectBaseTrue) { + assertTrue("mode=" + (prefixMode ? "prefix" : "index") + " case=" + name + + " baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } else { + assertFalse("mode=" + (prefixMode ? "prefix" : "index") + " case=" + name + + " startup worker/timer must latch asyncExecutors=false at boot: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + String cov1 = app.runHttpTest("sp/" + name + "-w1", "/sink-" + name + "?ms=300"); + boolean flagged = cov1.contains("\"contaminated\"") || cov1.contains("\"windowCut\":true"); + boolean asyncOff = !parseHello(app.lastHello).get("asyncExecutors").getAsBoolean(); + assertTrue("mode=" + (prefixMode ? "prefix" : "index") + " case=" + name + + " must fail closed at or before W1: W1=" + cov1 + " hello=" + app.lastHello, + flagged || asyncOff); + } + } + } + } + private static JsonObject parseHello(String line) { assertNotNull("HELLO line must not be null", line); assertTrue("expected HELLO frame, got: " + line, line.startsWith("HELLO {")); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index 1772a65f..a6f57f18 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -107,6 +107,7 @@ public class HonestProtocolAndAsyncTest { private ClassLoader savedContextLoader; private boolean savedTransformerAdded; private boolean savedExecutorCallSitesEnabled; + private boolean savedJdkSinkBootstrapActive; private boolean savedObservedNoServerEntry; private boolean savedObservedPreCapturedUntrackedExecutor; private Set savedCounted; @@ -120,6 +121,8 @@ public class HonestProtocolAndAsyncTest { public void setUp() { savedTransformerAdded = KeployDedupAgent.transformerAdded; savedExecutorCallSitesEnabled = KeployDedupAgent.executorCallSitesEnabled; + savedJdkSinkBootstrapActive = JdkSinkBootstrap.isActive(); + JdkSinkBootstrap.setActiveForTest(true); savedObservedNoServerEntry = KeployDedupAgent.observedNoServerEntry.get(); savedObservedPreCapturedUntrackedExecutor = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); savedCounted = ServerEntries.snapshotCounted(); @@ -147,6 +150,7 @@ public void tearDown() throws IOException { } KeployDedupAgent.transformerAdded = savedTransformerAdded; KeployDedupAgent.executorCallSitesEnabled = savedExecutorCallSitesEnabled; + JdkSinkBootstrap.setActiveForTest(savedJdkSinkBootstrapActive); KeployDedupAgent.observedNoServerEntry.set(savedObservedNoServerEntry); KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedObservedPreCapturedUntrackedExecutor); ServerEntries.restoreCounted(savedCounted); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java new file mode 100644 index 00000000..8bae7fe8 --- /dev/null +++ b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java @@ -0,0 +1,281 @@ +package io.keploy.dedup; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import io.keploy.dedup.bootstrap.KeploySinkBridge; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; + +/** + * Unit tests for {@link KeploySinkBridge} re-entrancy / agent-internal guards + * and {@link SinkAllowlist} exact-class rules. + */ +public class JdkSinkBridgeTest { + + @Test + public void reentrancyGuardPreventsNestedSinkCallbackRecursion() { + final KeploySinkBridge.Handler previous = KeploySinkBridge.handler; + final AtomicInteger threadCalls = new AtomicInteger(); + final AtomicInteger tpeCalls = new AtomicInteger(); + final AtomicInteger stpeCalls = new AtomicInteger(); + final AtomicInteger fjpCalls = new AtomicInteger(); + final AtomicInteger timerCalls = new AtomicInteger(); + final AtomicInteger vtCalls = new AtomicInteger(); + try { + KeploySinkBridge.handler = new KeploySinkBridge.Handler() { + @Override + public void onThreadStart(Thread thread) { + int n = threadCalls.incrementAndGet(); + assertTrue("re-entrancy depth must be active inside callback", KeploySinkBridge.isInternal()); + // Recursive calls back into every bridge method MUST be suppressed. + KeploySinkBridge.onThreadStart(thread); + KeploySinkBridge.onVirtualThreadStart(thread); + KeploySinkBridge.onTpeExecute(this, thread); + KeploySinkBridge.onStpeDelayedExecute(this, thread); + KeploySinkBridge.onFjpExternalSubmit(this, thread); + KeploySinkBridge.onTimerSched(this, thread); + assertEquals("must not recurse", 1, n); + } + + @Override + public void onVirtualThreadStart(Thread thread) { + vtCalls.incrementAndGet(); + KeploySinkBridge.onVirtualThreadStart(thread); + } + + @Override + public void onTpeExecute(Object executor, Object command) { + tpeCalls.incrementAndGet(); + KeploySinkBridge.onTpeExecute(executor, command); + } + + @Override + public void onStpeDelayedExecute(Object executor, Object task) { + stpeCalls.incrementAndGet(); + KeploySinkBridge.onStpeDelayedExecute(executor, task); + } + + @Override + public void onFjpExternalSubmit(Object pool, Object task) { + fjpCalls.incrementAndGet(); + KeploySinkBridge.onFjpExternalSubmit(pool, task); + } + + @Override + public void onTimerSched(Object timer, Object task) { + timerCalls.incrementAndGet(); + KeploySinkBridge.onTimerSched(timer, task); + } + }; + + assertFalse(KeploySinkBridge.isInternal()); + KeploySinkBridge.onThreadStart(Thread.currentThread()); + assertFalse(KeploySinkBridge.isInternal()); + assertEquals(1, threadCalls.get()); + assertEquals(0, vtCalls.get()); + assertEquals(0, tpeCalls.get()); + assertEquals(0, stpeCalls.get()); + assertEquals(0, fjpCalls.get()); + assertEquals(0, timerCalls.get()); + + KeploySinkBridge.onVirtualThreadStart(Thread.currentThread()); + KeploySinkBridge.onTpeExecute(new Object(), new Object()); + KeploySinkBridge.onStpeDelayedExecute(new Object(), new Object()); + KeploySinkBridge.onFjpExternalSubmit(new Object(), new Object()); + KeploySinkBridge.onTimerSched(new Object(), new Object()); + assertEquals(1, vtCalls.get()); + assertEquals(1, tpeCalls.get()); + assertEquals(1, stpeCalls.get()); + assertEquals(1, fjpCalls.get()); + assertEquals(1, timerCalls.get()); + } finally { + KeploySinkBridge.handler = previous; + assertFalse(KeploySinkBridge.isInternal()); + } + } + + @Test + public void agentInternalScopeAndPoolsNeverTriggerSinkHandlerOrLatch() { + final KeploySinkBridge.Handler previous = KeploySinkBridge.handler; + final AtomicInteger calls = new AtomicInteger(); + ExecutorService agentPool = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "keploy-test-agent-pool"); + t.setDaemon(true); + return t; + }); + try { + KeploySinkBridge.handler = new KeploySinkBridge.Handler() { + @Override + public void onThreadStart(Thread thread) { + calls.incrementAndGet(); + } + + @Override + public void onVirtualThreadStart(Thread thread) { + calls.incrementAndGet(); + } + + @Override + public void onTpeExecute(Object executor, Object command) { + calls.incrementAndGet(); + } + + @Override + public void onStpeDelayedExecute(Object executor, Object task) { + calls.incrementAndGet(); + } + + @Override + public void onFjpExternalSubmit(Object pool, Object task) { + calls.incrementAndGet(); + } + + @Override + public void onTimerSched(Object timer, Object task) { + calls.incrementAndGet(); + } + }; + + // Nested enterInternal/exitInternal suppresses all sink notifications. + KeploySinkBridge.enterInternal(); + try { + KeploySinkBridge.enterInternal(); + try { + KeploySinkBridge.onThreadStart(Thread.currentThread()); + KeploySinkBridge.onTpeExecute(agentPool, (Runnable) () -> { }); + KeploySinkBridge.onStpeDelayedExecute(agentPool, new Object()); + KeploySinkBridge.onFjpExternalSubmit(ForkJoinPool.commonPool(), new Object()); + KeploySinkBridge.onTimerSched(new Object(), new Object()); + } finally { + KeploySinkBridge.exitInternal(); + } + assertTrue("outer internal scope must still be active", KeploySinkBridge.isInternal()); + KeploySinkBridge.onThreadStart(Thread.currentThread()); + } finally { + KeploySinkBridge.exitInternal(); + } + assertFalse("internal depth must clear after matching exits", KeploySinkBridge.isInternal()); + assertEquals("agent-internal scope must never invoke handler", 0, calls.get()); + + // Registered agent-internal pool is explicitly allowlisted at TPE/STPE sinks. + assertFalse("unregistered plain pool must NOT be allowlisted", + SinkAllowlist.isAllowlistedTpeExecute(agentPool, (Runnable) () -> { }, new String[1])); + RequestGate.registerAgentInternalPool(agentPool); + assertTrue("registered agent-internal pool must be allowlisted at TPE sink", + SinkAllowlist.isAllowlistedTpeExecute(agentPool, (Runnable) () -> { }, new String[1])); + assertTrue("registered agent-internal pool must be allowlisted at STPE sink", + SinkAllowlist.isAllowlistedStpeDelayedExecute(agentPool, new Object(), new String[1])); + } finally { + KeploySinkBridge.handler = previous; + agentPool.shutdownNow(); + } + } + + @Test + public void userCallbackPoolsAndUntrackedCommonPoolAreNeverAllowlisted() { + ExecutorService plain = Executors.newSingleThreadExecutor(); + try { + String[] caller = new String[1]; + assertFalse("plain ThreadPoolExecutor without RequestGate.hand must NOT be allowlisted", + SinkAllowlist.isAllowlistedTpeExecute(plain, (Runnable) () -> { }, caller)); + assertFalse("ForkJoinPool.commonPool without RequestGate.hand must NOT be allowlisted", + SinkAllowlist.isAllowlistedFjpSubmit(ForkJoinPool.commonPool(), (Runnable) () -> { }, caller)); + assertFalse("plain Thread.start from test class must NOT be allowlisted", + SinkAllowlist.isAllowlistedThreadStart(new Thread(() -> { }), caller)); + assertFalse("plain Timer.sched from test class must NOT be allowlisted", + SinkAllowlist.isAllowlistedTimerSched(new Object(), new Object(), caller)); + + // Inside tracked dispatch, sinks are allowed. + RequestGate.enterTrackedDispatch(); + try { + assertTrue(SinkAllowlist.isAllowlistedTpeExecute(plain, (Runnable) () -> { }, caller)); + assertTrue(SinkAllowlist.isAllowlistedFjpSubmit(ForkJoinPool.commonPool(), (Runnable) () -> { }, caller)); + assertTrue(SinkAllowlist.isAllowlistedThreadStart(new Thread(() -> { }), caller)); + } finally { + RequestGate.exitTrackedDispatch(); + } + } finally { + plain.shutdownNow(); + } + } + + @Test + public void infraAllowlistContainsOnlyExactCitedZeroCallbackClassesAndExcludesUserCallbackPools() { + // Every PetClinic-measured zero-callback infra class has an explicit positive row. + String[] expectedThreadCallers = { + "com.zaxxer.hikari.pool.HikariPool", + "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread", + "org.h2.util.MathUtils", + "org.springframework.boot.autoconfigure.condition.OnClassCondition$ThreadedOutcomesResolver", + "org.springframework.boot.autoconfigure.preinitialize.BackgroundPreinitializingApplicationListener", + "org.springframework.boot.tomcat.TomcatWebServer", + "org.springframework.boot.tomcat.GracefulShutdown", + "org.springframework.boot.web.embedded.tomcat.TomcatWebServer", + "org.springframework.boot.web.embedded.tomcat.GracefulShutdown", + }; + assertEquals("exact count of INFRA_THREAD_CALLERS must match reviewed rows", + expectedThreadCallers.length, SinkAllowlist.INFRA_THREAD_CALLERS.size()); + for (String cls : expectedThreadCallers) { + assertTrue("expected cited infra thread caller: " + cls, + SinkAllowlist.INFRA_THREAD_CALLERS.contains(cls)); + assertFalse("no package prefix wildcards allowed: " + cls, cls.endsWith(".") || cls.endsWith("*")); + } + + String[] expectedPoolCallers = { + "com.zaxxer.hikari.pool.HikariPool", + "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread", + }; + assertEquals("exact count of INFRA_POOL_CALLERS must match reviewed rows", + expectedPoolCallers.length, SinkAllowlist.INFRA_POOL_CALLERS.size()); + for (String cls : expectedPoolCallers) { + assertTrue("expected cited infra pool caller: " + cls, + SinkAllowlist.INFRA_POOL_CALLERS.contains(cls)); + } + + assertEquals(1, SinkAllowlist.INFRA_TASK_CLASSES.size()); + assertTrue(SinkAllowlist.INFRA_TASK_CLASSES.contains("com.mysql.cj.jdbc.AbandonedConnectionCleanupThread")); + + // Anything that can run user Runnables, lambdas, or listeners is NEVER allowlisted. + String[] forbidden = { + "java.util.concurrent.ForkJoinPool", + "java.util.concurrent.CompletableFuture", + "org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor", + "org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler", + "org.springframework.core.task.SimpleAsyncTaskExecutor", + "reactor.core.scheduler.Schedulers", + "io.netty.util.concurrent.SingleThreadEventExecutor", + "com.google.common.eventbus.AsyncEventBus", + "kotlinx.coroutines.Dispatchers", + }; + for (String cls : forbidden) { + assertFalse("user-callback class must NEVER be in INFRA_THREAD_CALLERS: " + cls, + SinkAllowlist.INFRA_THREAD_CALLERS.contains(cls)); + assertFalse("user-callback class must NEVER be in INFRA_POOL_CALLERS: " + cls, + SinkAllowlist.INFRA_POOL_CALLERS.contains(cls)); + assertFalse("user-callback class must NEVER be in INFRA_TASK_CLASSES: " + cls, + SinkAllowlist.INFRA_TASK_CLASSES.contains(cls)); + } + } + + @Test + public void unarmedHandOffOutsideWindowLatchesAsyncExecutorsFalse() { + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + ExecutorService pool = Executors.newSingleThreadExecutor(); + try { + assertFalse("fresh state must not be latched", KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + RequestGate.hand(pool, (Runnable) () -> { }); + assertTrue("unarmed RequestGate.hand(pool, task) must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + pool.shutdownNow(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + } + } +} diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index cdfea6c7..23349838 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -58,12 +58,18 @@ public final class AsyncHonestyApp { 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; + private static final class SerializablePoolHolder { + static final ExecutorService SYNC = new SerializableOnlyExecutor(false); + static final ExecutorService ASYNC = new SerializableOnlyExecutor(true); + } + + private static final class ConcretePoolHolder { + static final ConcreteCustomPool POOL = new ConcreteCustomPool(); + } + private AsyncHonestyApp() { } @@ -85,9 +91,11 @@ public static void main(String[] args) throws Exception { tomcat.start(); port = tomcat.getConnector().getLocalPort(); server = tomcat::stop; - } else if ("jetty".equals(mode) || mode.startsWith("handoff-")) { + } else if ("jetty".equals(mode) || mode.startsWith("handoff-") || mode.startsWith("sink-")) { if (mode.startsWith("handoff-")) { HandOffFixtures.init(mode.substring("handoff-".length())); + } else if (mode.startsWith("sink-")) { + SinkFixtures.init(mode.substring("sink-".length())); } Server jetty = new Server(0); ServletContextHandler context = new ServletContextHandler(); @@ -178,20 +186,20 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO }, PLAIN_POOL); } else if ("/unknown-serializable".equals(path)) { Runnable serializableTask = (Runnable & Serializable) () -> AsyncTail.ran(); - SERIALIZABLE_ONLY_POOL.execute(serializableTask); + SerializablePoolHolder.SYNC.execute(serializableTask); java.util.concurrent.Callable serializableCall = (java.util.concurrent.Callable & Serializable) () -> { AsyncTail.ran(); return "ok"; }; - SERIALIZABLE_ONLY_POOL.submit(serializableCall); + SerializablePoolHolder.SYNC.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); + SerializablePoolHolder.ASYNC.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 @@ -210,7 +218,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO return v + "-stage"; }, PLAIN_POOL); } else if ("/concrete-pool".equals(path)) { - CONCRETE_POOL.execute(() -> AsyncTail.ran()); + ConcretePoolHolder.POOL.execute(() -> AsyncTail.ran()); } else if ("/subclassed-thread".equals(path)) { MyWorkerThread t = new MyWorkerThread(() -> AsyncTail.ran()); t.setDaemon(true); @@ -279,6 +287,22 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } catch (Exception e) { throw new IOException(e); } + } else if (path.startsWith("/sink-")) { + try { + SinkFixtures.handle(path.substring("/sink-".length()), ms); + } catch (Exception e) { + throw new IOException(e); + } + } else if ("/bootstrap-check".equals(path)) { + ClassLoader cl = io.keploy.dedup.bootstrap.KeploySinkBridge.class.getClassLoader(); + ClassLoader hcl = io.keploy.dedup.bootstrap.KeploySinkBridge.Handler.class.getClassLoader(); + if (cl != null || hcl != null) { + throw new IOException("Expected bootstrap CL (null), got bridge=" + cl + " handler=" + hcl); + } + Tail.ran(); + } else if ("/warm-common-pool".equals(path)) { + CompletableFuture.supplyAsync(() -> "warm").join(); + Tail.ran(); } else if ("/untracked-schedule".equals(path)) { SCHED.schedule(() -> AsyncTail.ran(), 1, TimeUnit.MILLISECONDS); } else if ("/untracked-thread".equals(path)) { @@ -912,4 +936,405 @@ static void handle(String kind, final long ms) throws Exception { } } } + + /** + * Isolated sink-bypass and JDK-pool-subclass fixtures. Each scenario lives in + * its own nested class so loading one scenario never loads references from + * another scenario or pollutes clean baselines. + */ + public static final class SinkFixtures { + + static final java.util.ArrayDeque DEQUE = new java.util.ArrayDeque<>(); + static final Object LOCK = new Object(); + static volatile Object keepAlive; + + static Runnable workerLoop() { + return new Runnable() { + @Override + public void run() { + while (!Thread.currentThread().isInterrupted()) { + Runnable task; + synchronized (LOCK) { + while (DEQUE.isEmpty()) { + try { + LOCK.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + task = DEQUE.poll(); + } + if (task != null) { + task.run(); + } + } + } + }; + } + + static Runnable pollerTick() { + return new Runnable() { + @Override + public void run() { + Runnable task; + synchronized (LOCK) { + task = DEQUE.poll(); + } + if (task != null) { + task.run(); + } + } + }; + } + + static Runnable asyncTailTask(final long ms) { + return new Runnable() { + @Override + public void run() { + sleepQuietly(ms); + AsyncTail.ran(); + } + }; + } + + static void feed(long ms) { + synchronized (LOCK) { + DEQUE.add(asyncTailTask(ms)); + LOCK.notifyAll(); + } + } + + static void init(String kind) throws Exception { + switch (kind) { + case "app-tpe-sub-worker": + AppTpeSubWorkerFixture.init(); + break; + case "app-tpe-sub-submit-worker": + AppTpeSubSubmitWorkerFixture.init(); + break; + case "app-fjp-sub-worker": + AppFjpSubWorkerFixture.init(); + break; + case "app-fjp-sub-inwindow": + AppFjpSubInWindowFixture.init(); + break; + case "fjtask-worker": + FjTaskWorkerFixture.init(); + break; + case "app-timer-sub-poller": + AppTimerSubPollerFixture.init(); + break; + case "app-timer-sub-inwindow": + AppTimerSubInWindowFixture.init(); + break; + case "app-stpe-sub-poller": + AppStpeSubPollerFixture.init(); + break; + case "reflect-worker-startup": + ReflectWorkerStartupFixture.init(); + break; + case "vthread-exec-worker": + VirtualThreadExecWorkerFixture.init(); + break; + case "vthread-exec-inwindow": + VirtualThreadExecInWindowFixture.init(); + break; + default: + // In-window-only reflective / MethodHandle / library fixtures need no startup init. + break; + } + } + + static void handle(String kind, long ms) throws Exception { + switch (kind) { + case "app-tpe-sub-worker": + case "app-tpe-sub-submit-worker": + case "app-fjp-sub-worker": + case "fjtask-worker": + case "app-timer-sub-poller": + case "app-stpe-sub-poller": + case "reflect-worker-startup": + case "vthread-exec-worker": + feed(ms); + break; + case "app-fjp-sub-inwindow": + AppFjpSubInWindowFixture.handle(ms); + break; + case "app-timer-sub-inwindow": + AppTimerSubInWindowFixture.handle(ms); + break; + case "lib-fjp-sub": + LibFjpSubFixture.handle(ms); + break; + case "vthread-exec-inwindow": + VirtualThreadExecInWindowFixture.handle(ms); + break; + case "reflect-thread-start": + ReflectThreadStartFixture.handle(ms); + break; + case "mh-thread-start": + MethodHandleThreadStartFixture.handle(ms); + break; + case "mh-tpe-execute": + MethodHandleTpeExecuteFixture.handle(ms); + break; + case "reflect-stpe-schedule": + ReflectStpeScheduleFixture.handle(ms); + break; + case "reflect-fjp-submit": + ReflectFjpSubmitFixture.handle(ms); + break; + case "reflect-timer-schedule": + ReflectTimerScheduleFixture.handle(ms); + break; + case "reflect-vthread-start": + ReflectVirtualThreadStartFixture.handle(ms); + break; + default: + throw new IllegalArgumentException("unknown sink fixture: " + kind); + } + } + } + + public static final class AppTpeSub extends ThreadPoolExecutor { + AppTpeSub() { + super(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); + } + } + + public static final class AppFjpSub extends java.util.concurrent.ForkJoinPool { + AppFjpSub() { + super(2); + } + } + + public static final class AppStpeSub extends java.util.concurrent.ScheduledThreadPoolExecutor { + AppStpeSub() { + super(1); + } + } + + public static final class AppTimerSub extends java.util.Timer { + AppTimerSub() { + super(true); + } + } + + public static final class AppTpeSubWorkerFixture { + static void init() { + AppTpeSub pool = new AppTpeSub(); + SinkFixtures.keepAlive = pool; + pool.execute(SinkFixtures.workerLoop()); + } + } + + public static final class AppTpeSubSubmitWorkerFixture { + static void init() { + AppTpeSub pool = new AppTpeSub(); + SinkFixtures.keepAlive = pool; + pool.submit(SinkFixtures.workerLoop()); + } + } + + public static final class AppFjpSubWorkerFixture { + static void init() { + AppFjpSub pool = new AppFjpSub(); + SinkFixtures.keepAlive = pool; + pool.execute(SinkFixtures.workerLoop()); + } + } + + public static final class AppFjpSubInWindowFixture { + static volatile AppFjpSub pool; + + static void init() { + pool = new AppFjpSub(); + } + + static void handle(long ms) { + pool.execute(SinkFixtures.asyncTailTask(ms)); + } + } + + public static final class FjTaskWorkerFixture { + static void init() { + java.util.concurrent.ForkJoinPool.commonPool().execute(ForkJoinTask.adapt(SinkFixtures.workerLoop())); + } + } + + public static final class AppTimerSubPollerFixture { + static void init() { + AppTimerSub timer = new AppTimerSub(); + SinkFixtures.keepAlive = timer; + timer.schedule(new java.util.TimerTask() { + @Override + public void run() { + SinkFixtures.pollerTick().run(); + } + }, 0L, 50L); + } + } + + public static final class AppTimerSubInWindowFixture { + static volatile AppTimerSub timer; + + static void init() { + timer = new AppTimerSub(); + } + + static void handle(final long ms) { + timer.schedule(new java.util.TimerTask() { + @Override + public void run() { + SinkFixtures.asyncTailTask(ms).run(); + } + }, 1L); + } + } + + public static final class AppStpeSubPollerFixture { + static void init() { + AppStpeSub pool = new AppStpeSub(); + SinkFixtures.keepAlive = pool; + pool.scheduleWithFixedDelay(SinkFixtures.pollerTick(), 0L, 50L, TimeUnit.MILLISECONDS); + } + } + + public static final class LibFjpSubFixture { + static void handle(long ms) { + io.fakeexternal.SubForkJoinPool.fire(SinkFixtures.asyncTailTask(ms)); + } + } + + public static final class ReflectWorkerStartupFixture { + static void init() throws Exception { + Class threadCls = Class.forName("java.lang.Thread"); + Object thread = threadCls.getConstructor(Runnable.class).newInstance(SinkFixtures.workerLoop()); + threadCls.getMethod("setDaemon", boolean.class).invoke(thread, Boolean.TRUE); + threadCls.getMethod("start").invoke(thread); + SinkFixtures.keepAlive = thread; + } + } + + public static final class ReflectThreadStartFixture { + static void handle(long ms) throws Exception { + Class threadCls = Class.forName("java.lang.Thread"); + Object thread = threadCls.getConstructor(Runnable.class).newInstance(SinkFixtures.asyncTailTask(ms)); + threadCls.getMethod("setDaemon", boolean.class).invoke(thread, Boolean.TRUE); + threadCls.getMethod("start").invoke(thread); + } + } + + public static final class MethodHandleThreadStartFixture { + static void handle(long ms) throws Exception { + try { + Class threadCls = Class.forName("java.lang.Thread"); + Thread t = (Thread) threadCls.getConstructor(Runnable.class).newInstance(SinkFixtures.asyncTailTask(ms)); + t.setDaemon(true); + java.lang.invoke.MethodHandle mh = java.lang.invoke.MethodHandles.lookup().findVirtual( + Thread.class, "start", java.lang.invoke.MethodType.methodType(void.class)); + mh.invokeExact(t); + } catch (Throwable t) { + throw new RuntimeException(t); + } + } + } + + public static final class MethodHandleTpeExecuteFixture { + static volatile Object pool; + + static void handle(long ms) throws Exception { + try { + Class tpeCls = Class.forName("java.util.concurrent.ThreadPoolExecutor"); + Object p = pool; + if (p == null) { + p = tpeCls.getConstructor(int.class, int.class, long.class, TimeUnit.class, + java.util.concurrent.BlockingQueue.class).newInstance( + Integer.valueOf(1), Integer.valueOf(1), Long.valueOf(0L), + TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); + pool = p; + } + java.lang.invoke.MethodHandle mh = java.lang.invoke.MethodHandles.lookup().findVirtual( + tpeCls, "execute", java.lang.invoke.MethodType.methodType(void.class, Runnable.class)); + mh.invoke(p, SinkFixtures.asyncTailTask(ms)); + } catch (Throwable t) { + throw new RuntimeException(t); + } + } + } + + public static final class ReflectStpeScheduleFixture { + static volatile Object pool; + + static void handle(long ms) throws Exception { + Class stpeCls = Class.forName("java.util.concurrent.ScheduledThreadPoolExecutor"); + Object p = pool; + if (p == null) { + p = stpeCls.getConstructor(int.class).newInstance(Integer.valueOf(1)); + pool = p; + } + stpeCls.getMethod("schedule", Runnable.class, long.class, TimeUnit.class) + .invoke(p, SinkFixtures.asyncTailTask(ms), Long.valueOf(1L), TimeUnit.MILLISECONDS); + } + } + + public static final class ReflectFjpSubmitFixture { + static void handle(long ms) throws Exception { + Class fjpCls = Class.forName("java.util.concurrent.ForkJoinPool"); + Object common = fjpCls.getMethod("commonPool").invoke(null); + fjpCls.getMethod("execute", Runnable.class).invoke(common, SinkFixtures.asyncTailTask(ms)); + } + } + + public static final class ReflectTimerScheduleFixture { + static volatile Object timer; + + static void handle(final long ms) throws Exception { + Class timerCls = Class.forName("java.util.Timer"); + Object t = timer; + if (t == null) { + t = timerCls.getConstructor(boolean.class).newInstance(Boolean.TRUE); + timer = t; + } + java.util.TimerTask task = new java.util.TimerTask() { + @Override + public void run() { + SinkFixtures.asyncTailTask(ms).run(); + } + }; + timerCls.getMethod("schedule", java.util.TimerTask.class, long.class) + .invoke(t, task, Long.valueOf(1L)); + } + } + + public static final class ReflectVirtualThreadStartFixture { + static void handle(long ms) throws Exception { + Class threadCls = Class.forName("java.lang.Thread"); + threadCls.getMethod("startVirtualThread", Runnable.class) + .invoke(null, SinkFixtures.asyncTailTask(ms)); + } + } + + public static final class VirtualThreadExecWorkerFixture { + static void init() throws Exception { + ExecutorService vt = (ExecutorService) Executors.class + .getMethod("newVirtualThreadPerTaskExecutor").invoke(null); + SinkFixtures.keepAlive = vt; + vt.execute(SinkFixtures.workerLoop()); + } + } + + public static final class VirtualThreadExecInWindowFixture { + static volatile ExecutorService vt; + + static void init() throws Exception { + vt = (ExecutorService) Executors.class + .getMethod("newVirtualThreadPerTaskExecutor").invoke(null); + } + + static void handle(long ms) { + vt.submit(SinkFixtures.asyncTailTask(ms)); + } + } } 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 c64e7394..62f423a8 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncWork.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncWork.java @@ -68,8 +68,22 @@ public final class AsyncWork { SCHEDULER.setDaemon(true); SCHEDULER.setThreadNamePrefix("app-poller-"); SCHEDULER.initialize(); - SCHEDULER.scheduleWithFixedDelay(() -> poll(FIRE), 10); - startSimplePoller(); + } + + private static final class ScheduledPollerHolder { + static final boolean STARTED; + static { + SCHEDULER.scheduleWithFixedDelay(() -> poll(FIRE), 10); + STARTED = true; + } + } + + private static final class SimplePollerHolder { + static final boolean STARTED; + static { + startSimplePoller(); + STARTED = true; + } } // On Spring 6.1+, a SimpleAsyncTaskScheduler's poller, whose trigger @@ -129,10 +143,14 @@ public static void hand(String how, long millis) throws Exception { }); break; case "scheduled": - fire(FIRE, millis); + if (ScheduledPollerHolder.STARTED) { + fire(FIRE, millis); + } break; case "simplescheduled": - fire(SIMPLE_FIRE, millis); + if (SimplePollerHolder.STARTED) { + fire(SIMPLE_FIRE, millis); + } break; case "priority": String result = PriorityPool.handOff(); From 5a3c5da46a11a39b3c5165d890045da9b1753b09 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Sat, 28 Nov 2026 17:55:51 +0530 Subject: [PATCH 25/26] fix(dedup): hook Servlet AsyncContext.start by interface, tighten sink allowlist, fix JDK 21 test flake Instrument every implementation of javax.servlet.AsyncContext and jakarta.servlet.AsyncContext found transitively at class load so AsyncContext.start(Runnable) routes tasks through RequestGate.handAsyncContext (holding the dispatching request window open past AsyncContext.complete(), releasing permits on thrown start(), and latching asyncExecutors=false outside any active window). Remove all user-callback-capable classes from SinkAllowlist (XnioWorker$DefaultThreadPoolExecutor, ManagedThreadPoolExecutor, JBossThread, DelegatingErrorHandlingRunnable, ReschedulingRunnable, AsynchronousChannelGroupImpl), add source citations, use StackWalker (with SHOW_REFLECT_FRAMES) on JDK 9+ for lazy caller lookup, and skip stack walks outside active windows after asyncExecutors has already latched false. Join the audit threads in HonestProtocolAndAsyncTest.untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostOnTcpAndUnix before starting subsequent windows so Thread.isAlive() cannot race with test-2/test-3 under load. Signed-off-by: slayerjain --- .../java/io/keploy/dedup/JdkSinkHandler.java | 28 ++ .../java/io/keploy/dedup/RequestGate.java | 37 ++ .../java/io/keploy/dedup/ServerEntries.java | 339 ++++++++++++++- .../java/io/keploy/dedup/SinkAllowlist.java | 343 ++++++++++----- .../dedup/ForkedAsyncAndHonestyTest.java | 70 +++ .../dedup/HonestProtocolAndAsyncTest.java | 15 +- .../io/keploy/dedup/JdkSinkBridgeTest.java | 404 +++++++++++++++--- .../org/example/servers/AsyncHonestyApp.java | 51 ++- 8 files changed, 1125 insertions(+), 162 deletions(-) diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkHandler.java b/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkHandler.java index d02a87af..d2b03ec7 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkHandler.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JdkSinkHandler.java @@ -9,8 +9,21 @@ */ final class JdkSinkHandler implements KeploySinkBridge.Handler { + // Fast-path: when the JVM is already permanently latched asyncExecutors=false, + // no request window or job is active on this thread, and sink audit logging + // is off, skip stack walking altogether. In-window / in-job calls ALWAYS + // walk so per-window contamination remains exact. + private static boolean canSkipPostLatchOutsideWindow() { + return !SinkAllowlist.AUDIT + && KeployDedupAgent.observedPreCapturedUntrackedExecutor.get() + && !RequestGate.isInsideTrackedWindowOrJob(); + } + @Override public void onThreadStart(Thread thread) { + if (canSkipPostLatchOutsideWindow()) { + return; + } String[] caller = new String[1]; boolean allowed = SinkAllowlist.isAllowlistedThreadStart(thread, caller); SinkAllowlist.audit("thread-start", allowed, thread != null ? thread.getName() : "null", @@ -22,6 +35,9 @@ public void onThreadStart(Thread thread) { @Override public void onVirtualThreadStart(Thread thread) { + if (canSkipPostLatchOutsideWindow()) { + return; + } String[] caller = new String[1]; boolean allowed = SinkAllowlist.isAllowlistedVirtualThreadStart(thread, caller); SinkAllowlist.audit("virtual-thread-start", allowed, thread != null ? thread.getName() : "null", @@ -33,6 +49,9 @@ public void onVirtualThreadStart(Thread thread) { @Override public void onTpeExecute(Object executor, Object command) { + if (canSkipPostLatchOutsideWindow()) { + return; + } String[] caller = new String[1]; boolean allowed = SinkAllowlist.isAllowlistedTpeExecute(executor, command, caller); SinkAllowlist.audit("tpe-execute", allowed, "", executor, command, caller[0]); @@ -43,6 +62,9 @@ public void onTpeExecute(Object executor, Object command) { @Override public void onStpeDelayedExecute(Object executor, Object task) { + if (canSkipPostLatchOutsideWindow()) { + return; + } String[] caller = new String[1]; boolean allowed = SinkAllowlist.isAllowlistedStpeDelayedExecute(executor, task, caller); SinkAllowlist.audit("stpe-delayed-execute", allowed, "", executor, task, caller[0]); @@ -53,6 +75,9 @@ public void onStpeDelayedExecute(Object executor, Object task) { @Override public void onFjpExternalSubmit(Object pool, Object task) { + if (canSkipPostLatchOutsideWindow()) { + return; + } String[] caller = new String[1]; boolean allowed = SinkAllowlist.isAllowlistedFjpSubmit(pool, task, caller); SinkAllowlist.audit("fjp-submit", allowed, "", pool, task, caller[0]); @@ -63,6 +88,9 @@ public void onFjpExternalSubmit(Object pool, Object task) { @Override public void onTimerSched(Object timer, Object task) { + if (canSkipPostLatchOutsideWindow()) { + return; + } String[] caller = new String[1]; boolean allowed = SinkAllowlist.isAllowlistedTimerSched(timer, task, caller); SinkAllowlist.audit("timer-sched", allowed, "", timer, task, caller[0]); 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 07b120c7..d95d010d 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -584,6 +584,43 @@ public static Runnable hand(Object executor, Runnable task) { return handInternal(executor, task, false); } + /** + * Wraps a {@link Runnable} dispatched via {@code javax.servlet.AsyncContext#start} + * or {@code jakarta.servlet.AsyncContext#start} so the dispatching request's + * window (or tracked job) stays open until the runnable completes—even if + * the runnable calls {@code AsyncContext.complete()} and continues working. + * When invoked outside any active window or tracked job (or while unarmed), + * latches {@code asyncExecutors=false} (fail closed). + * + * @param task runnable passed to {@code AsyncContext.start(Runnable)} + * @return wrapped runnable holding the window permit, or {@code task} unchanged + */ + public static Runnable handAsyncContext(Runnable task) { + if (!armed) { + if (task != null) { + noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow("untracked-async:async-context-outside-window", false); + } + return task; + } + if (task == null || task instanceof Handed) { + return task; + } + Window window = INSIDE.get(); + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + noteBackgroundWorkerOutsideWindow("untracked-async:async-context-outside-window", true); + return task; + } + Handed handed = task instanceof Future + ? new HandedFuture(window, job, task, false) + : new Handed(window, job, task, false); + if (window != null) { + window.running.incrementAndGet(); + } + return handed; + } + private static JobGate.Attribution currentOrExpiredJob(Window window) { if (window != null) { return null; 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 a450fb93..466110b1 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,7 @@ package io.keploy.dedup; import java.io.File; +import java.io.InputStream; import java.lang.instrument.ClassFileTransformer; import java.net.URI; import java.net.URL; @@ -50,6 +51,9 @@ final class ServerEntries implements ClassFileTransformer { static final String RENAMED = "keploy$request$"; static final String JOB_RENAMED = "keploy$job$"; static final String ASYNC_RENAMED = "keploy$async$"; + private static final String JAVAX_ASYNC_CONTEXT = "javax/servlet/AsyncContext"; + private static final String JAKARTA_ASYNC_CONTEXT = "jakarta/servlet/AsyncContext"; + private static final String ASYNC_CONTEXT_START_DESC = "(Ljava/lang/Runnable;)V"; private static final String RUNNABLE = "Ljava/lang/Runnable;"; private static final String CALLABLE = "Ljava/util/concurrent/Callable;"; // The type of the executor a task is for, when a method takes it as an @@ -479,6 +483,9 @@ static Set allowlistedDispatchClasses() { // 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<>(); + // Per-loader cache of whether a type (class or interface) implements or + // extends javax/servlet/AsyncContext or jakarta/servlet/AsyncContext. + private static final Map> ASYNC_CONTEXT_TYPES = 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 @@ -629,6 +636,9 @@ private static Set setOf(String... values) { // 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<>(); + // Implementations of javax/jakarta AsyncContext whose start(Runnable) was + // hooked on load, by their loader: re-applied on retransform. + private final Map> asyncContextHooked = new WeakHashMap<>(); // Whether servers' requests count (END waits for them); jobs' runs // count either way. private final boolean requests; @@ -826,26 +836,37 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (unhookedConsumer != null) { SEEN_UNHOOKED_CONSUMERS.add(unhookedConsumer); } + byte[] currentBytes = classfileBuffer; + boolean hookedAsyncContext = false; + if (className != null && !isInternalOrAgentClass(className)) { + byte[] asyncCtxWrapped = maybeHookAsyncContextStart(loader, className, protectionDomain, currentBytes); + if (asyncCtxWrapped != null) { + currentBytes = asyncCtxWrapped; + hookedAsyncContext = true; + } + } if (shouldRewriteExecutorCalls(className)) { - scanUnhookedReferences(className, classfileBuffer, false, false); + scanUnhookedReferences(className, currentBytes, false, false); if (!canAccessGate(loader, protectionDomain)) { if (seesGate(loader)) { jpmsGuardTriggered = true; } else { appRewriteFailed = true; } - scanUnhookedReferences(className, classfileBuffer, true, true); - return null; + scanUnhookedReferences(className, currentBytes, true, true); + return hookedAsyncContext ? currentBytes : null; } try { - byte[] updated = wrapExecutorCalls(classfileBuffer); + byte[] updated = wrapExecutorCalls(currentBytes); if (updated != null) { recordRewritten(loader, className); + return updated; } - return updated; + return hookedAsyncContext ? currentBytes : null; } catch (Throwable t) { appRewriteFailed = true; LOGGER.log(Level.FINE, "Keploy dedup skipped executor call-site wrap for " + className, t); + return hookedAsyncContext ? currentBytes : null; } } else if (className != null && !isInternalOrAgentClass(className)) { // Fail-closed read-only constant-pool scan of EVERY non-JDK, @@ -854,10 +875,10 @@ public byte[] transform(ClassLoader loader, String className, Class classBein // async dispatcher latches asyncExecutors=false UNLESS its exact // name is in ALLOWLISTED_DISPATCH_CLASSES. boolean checkDispatch = !ALLOWLISTED_DISPATCH_CLASSES.contains(className); - scanUnhookedReferences(className, classfileBuffer, !isKnownMessagingPoolWrapper(className), + scanUnhookedReferences(className, currentBytes, !isKnownMessagingPoolWrapper(className), checkDispatch); } - return null; + return hookedAsyncContext ? currentBytes : null; } // With the wait off, servers are left as they are, and so no task // counts as a request's; the executors still count a task a job's @@ -938,6 +959,286 @@ private void recordRewritten(ClassLoader loader, String className) { } } + private void recordAsyncContextHooked(ClassLoader loader, String className) { + synchronized (asyncContextHooked) { + Set names = asyncContextHooked.get(loader); + if (names == null) { + names = new HashSet<>(); + asyncContextHooked.put(loader, names); + } + names.add(className); + } + } + + private boolean wasAsyncContextHooked(ClassLoader loader, String className) { + if (className == null) { + return false; + } + synchronized (asyncContextHooked) { + Set names = asyncContextHooked.get(loader); + return names != null && names.contains(className); + } + } + + private static Boolean lookupCachedAsyncContextType(ClassLoader loader, String internalName) { + synchronized (ASYNC_CONTEXT_TYPES) { + Map map = ASYNC_CONTEXT_TYPES.get(loader); + return map == null ? null : map.get(internalName); + } + } + + private static void cacheAsyncContextType(ClassLoader loader, String internalName, boolean value) { + if (internalName == null) { + return; + } + synchronized (ASYNC_CONTEXT_TYPES) { + Map map = ASYNC_CONTEXT_TYPES.get(loader); + if (map == null) { + map = new HashMap<>(); + ASYNC_CONTEXT_TYPES.put(loader, map); + } + map.put(internalName, value); + } + } + + private static boolean isDirectOrCachedAsyncContext(ClassLoader loader, String superName, String[] interfaces) { + if (JAVAX_ASYNC_CONTEXT.equals(superName) || JAKARTA_ASYNC_CONTEXT.equals(superName) + || Boolean.TRUE.equals(lookupCachedAsyncContextType(loader, superName))) { + return true; + } + if (interfaces != null) { + for (String iface : interfaces) { + if (JAVAX_ASYNC_CONTEXT.equals(iface) || JAKARTA_ASYNC_CONTEXT.equals(iface) + || Boolean.TRUE.equals(lookupCachedAsyncContextType(loader, iface))) { + return true; + } + } + } + return false; + } + + private static boolean hasConcreteStartRunnableMethod(ClassReader reader) { + final boolean[] found = {false}; + reader.accept(new ClassVisitor(Opcodes.ASM9) { + @Override + public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, + String[] exceptions) { + if ("start".equals(name) && ASYNC_CONTEXT_START_DESC.equals(descriptor) + && (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE | Opcodes.ACC_STATIC + | Opcodes.ACC_BRIDGE | Opcodes.ACC_SYNTHETIC)) == 0) { + found[0] = true; + } + return null; + } + }, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); + return found[0]; + } + + private static boolean isAsyncContextHierarchy(ClassLoader loader, String superName, String[] interfaces, + Set visited) { + if (isDirectOrCachedAsyncContext(loader, superName, interfaces)) { + return true; + } + if (interfaces != null) { + for (String iface : interfaces) { + if (isAsyncContextType(loader, iface, visited)) { + return true; + } + } + } + if (superName != null && !"java/lang/Object".equals(superName)) { + return isAsyncContextType(loader, superName, visited); + } + return false; + } + + private static boolean isAsyncContextType(ClassLoader loader, String internalName, Set visited) { + if (internalName == null || "java/lang/Object".equals(internalName)) { + return false; + } + if (JAVAX_ASYNC_CONTEXT.equals(internalName) || JAKARTA_ASYNC_CONTEXT.equals(internalName)) { + return true; + } + if (!visited.add(internalName)) { + return false; + } + Boolean cached = lookupCachedAsyncContextType(loader, internalName); + if (cached != null) { + return cached; + } + String resource = internalName + ".class"; + try (InputStream in = loader != null + ? loader.getResourceAsStream(resource) + : ClassLoader.getSystemResourceAsStream(resource)) { + if (in == null) { + return false; + } + ClassReader parentReader = new ClassReader(in); + boolean matches = isAsyncContextHierarchy(loader, parentReader.getSuperName(), + parentReader.getInterfaces(), visited); + cacheAsyncContextType(loader, internalName, matches); + return matches; + } catch (Throwable ignored) { + return false; + } + } + + private byte[] maybeHookAsyncContextStart(ClassLoader loader, String className, ProtectionDomain protectionDomain, + byte[] classfileBuffer) { + if (classfileBuffer == null || classfileBuffer.length < 16) { + return null; + } + ClassReader reader; + try { + reader = new ClassReader(classfileBuffer); + } catch (Throwable ignored) { + return null; + } + boolean isIface = (reader.getAccess() & Opcodes.ACC_INTERFACE) != 0; + if (isIface || !hasConcreteStartRunnableMethod(reader)) { + // Fast zero-I/O propagation for interfaces and abstract/base classes + // so dynamically defined multi-level AsyncContext subclasses resolve + // through the cache without getResourceAsStream. + if (isDirectOrCachedAsyncContext(loader, reader.getSuperName(), reader.getInterfaces())) { + cacheAsyncContextType(loader, className, true); + } + return null; + } + if (!isAsyncContextHierarchy(loader, reader.getSuperName(), reader.getInterfaces(), new HashSet())) { + cacheAsyncContextType(loader, className, false); + return null; + } + cacheAsyncContextType(loader, className, true); + String name = className.replace('/', '.'); + try { + if (!canAccessGate(loader, protectionDomain)) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup cannot hook AsyncContext.start on " + name + + ": its loader/module cannot access keploy-sdk.jar"); + return null; + } + if (carriesAsyncContextStartChange(classfileBuffer)) { + recordAsyncContextHooked(loader, className); + return null; + } + byte[] wrapped = wrapAsyncContextStart(classfileBuffer); + if (wrapped == null) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not wrap AsyncContext.start on " + name); + return null; + } + recordAsyncContextHooked(loader, className); + LOGGER.log(Level.INFO, "Keploy dedup counts Servlet AsyncContext.start tasks (" + name + ")"); + return wrapped; + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not hook AsyncContext.start on " + name, t); + return null; + } + } + + static boolean carriesAsyncContextStartChange(byte[] classfile) { + final boolean[] carries = {false}; + new ClassReader(classfile).accept(new ClassVisitor(Opcodes.ASM9) { + @Override + public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, + String[] exceptions) { + if ((ASYNC_RENAMED + "start").equals(name) && ASYNC_CONTEXT_START_DESC.equals(descriptor)) { + carries[0] = true; + } + return null; + } + }, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); + return carries[0]; + } + + static byte[] wrapAsyncContextStart(byte[] classfile) { + ClassReader reader = new ClassReader(classfile); + ClassWriter writer = new ClassWriter(reader, 0); + final String[] ownerHolder = {null}; + final int[] versionHolder = {0}; + final Method[] targetHolder = {null}; + reader.accept(new ClassVisitor(Opcodes.ASM9, writer) { + @Override + public void visit(int version, int access, String name, String signature, String superName, + String[] interfaces) { + versionHolder[0] = version & 0xFFFF; + ownerHolder[0] = name; + super.visit(version, access, name, signature, superName, interfaces); + } + + @Override + public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, + String[] exceptions) { + if ("start".equals(name) && ASYNC_CONTEXT_START_DESC.equals(descriptor) + && (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE | Opcodes.ACC_STATIC + | Opcodes.ACC_BRIDGE | Opcodes.ACC_SYNTHETIC)) == 0) { + targetHolder[0] = new Method(access, name, descriptor, signature, exceptions); + int renamedAccess = (access & ~(Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED)) + | Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC; + return super.visitMethod(renamedAccess, ASYNC_RENAMED + name, descriptor, signature, exceptions); + } + return super.visitMethod(access, name, descriptor, signature, exceptions); + } + + @Override + public void visitEnd() { + Method method = targetHolder[0]; + if (method != null) { + int access = method.access & ~Opcodes.ACC_SYNCHRONIZED; + MethodVisitor mv = super.visitMethod(access, method.name, method.descriptor, + method.signature, method.exceptions); + mv.visitCode(); + Label start = new Label(); + Label end = new Label(); + Label thrown = new Label(); + mv.visitTryCatchBlock(start, end, thrown, null); + + // Runnable handed = RequestGate.handAsyncContext(r); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "handAsyncContext", + "(Ljava/lang/Runnable;)Ljava/lang/Runnable;", false); + mv.visitVarInsn(Opcodes.ASTORE, 2); + // RequestGate.enterTrackedDispatch(handed); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "enterTrackedDispatch", + "(Ljava/lang/Object;)V", false); + mv.visitLabel(start); + // this.keploy$async$start(handed); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, ownerHolder[0], ASYNC_RENAMED + method.name, + method.descriptor, false); + mv.visitLabel(end); + // RequestGate.exitTrackedDispatch(handed); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "exitTrackedDispatch", + "(Ljava/lang/Object;)V", false); + mv.visitInsn(Opcodes.RETURN); + + mv.visitLabel(thrown); + if (versionHolder[0] >= Opcodes.V1_6) { + mv.visitFrame(Opcodes.F_FULL, 3, + new Object[] {ownerHolder[0], "java/lang/Runnable", "java/lang/Runnable"}, + 1, new Object[] {"java/lang/Throwable"}); + } + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "exitTrackedDispatch", + "(Ljava/lang/Object;)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "dropped", + "(Ljava/lang/Object;Ljava/lang/Object;)V", false); + mv.visitInsn(Opcodes.ATHROW); + mv.visitMaxs(3, 3); + mv.visitEnd(); + } + super.visitEnd(); + } + }, 0); + return targetHolder[0] == null ? null : writer.toByteArray(); + } + private boolean wasRewritten(ClassLoader loader, String className) { if (!shouldRewriteExecutorCalls(className)) { return false; @@ -982,15 +1283,35 @@ private byte[] changedAgain(ClassLoader loader, String className, byte[] classfi } Entry entry = ENTRIES.get(className); if (entry == null) { + byte[] currentBytes = classfile; + boolean changedAny = false; + if (wasAsyncContextHooked(loader, className)) { + try { + if (!carriesAsyncContextStartChange(currentBytes)) { + byte[] wrapped = wrapAsyncContextStart(currentBytes); + if (wrapped != null) { + currentBytes = wrapped; + changedAny = true; + } + } + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not re-hook AsyncContext.start on " + className, t); + } + } if (wasRewritten(loader, className)) { try { - return wrapExecutorCalls(classfile); + byte[] updated = wrapExecutorCalls(currentBytes); + if (updated != null) { + currentBytes = updated; + changedAny = true; + } } 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; + return changedAny ? currentBytes : null; } synchronized (changed) { Set names = changed.get(loader); diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java b/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java index 7e6fdfb6..f26ac524 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java @@ -1,10 +1,14 @@ package io.keploy.dedup; +import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ForkJoinWorkerThread; +import java.util.function.Function; +import java.util.stream.Stream; /** * Explicit, closed, exact-class allowlist for JDK concurrency sinks hooked via @@ -16,12 +20,15 @@ *

  • it carries proven {@link RequestGate} tracking ({@code RequestGate.Hand} * or active {@code TRACKED_DISPATCH_DEPTH}),
  • *
  • it is Keploy's own agent-internal thread/pool,
  • - *
  • it is a reviewed JVM/JDK bootstrap housekeeping class,
  • + *
  • it is a reviewed JVM/JDK bootstrap housekeeping class that never runs + * user callbacks,
  • *
  • it is an explicitly reviewed HTTP server request-hosting worker pool * (Tomcat, Jetty, Undertow/XNIO) whose requests enter a hooked - * {@link ServerEntries} entry, or a {@link JobGate}-hooked scheduler, or
  • - *
  • it is a reviewed infrastructure class verified from source never to - * execute an application-supplied Runnable, lambda, or listener.
  • + * {@link ServerEntries} entry (and whose {@code AsyncContext.start} + * dispatches enter {@link RequestGate#handAsyncContext}), or a + * {@link JobGate}-hooked Quartz/Spring {@code @Scheduled} scheduler, or + *
  • it is a reviewed infrastructure class verified from its JAR source + * never to execute an application-supplied Runnable, lambda, or listener.
  • * * Everything else fails closed. */ @@ -32,61 +39,97 @@ final class SinkAllowlist { || "true".equalsIgnoreCase(System.getProperty("keploy.java.sink.audit")); // Exact JVM/JDK internal Thread subclasses (bootstrap/platform CL only). - private static final Set JVM_INTERNAL_THREAD_CLASSES = Collections.unmodifiableSet(new HashSet<>( + // Every class below is a closed JDK runtime daemon/housekeeping thread that + // never runs arbitrary unhooked application Runnables directly: + static final Set JVM_INTERNAL_THREAD_CLASSES = Collections.unmodifiableSet(new HashSet<>( Arrays.asList( + // OpenJDK java.base/java/lang/ref/Reference.java (ReferenceHandler): + // processes JVM GC ReferenceQueue pending list. "java.lang.ref.Reference$ReferenceHandler", + // OpenJDK java.base/java/lang/ref/Finalizer.java (FinalizerThread): + // runs JVM GC finalize() queue. "java.lang.ref.Finalizer$FinalizerThread", + // OpenJDK java.base/jdk/internal/ref/CleanerImpl.java & + // jdk/internal/misc/InnocuousThread.java (JDK 9+) / + // sun/misc/InnocuousThread.java (JDK 8): Cleaner & innocuous daemon threads. "jdk.internal.ref.CleanerImpl$InnocuousThread", "jdk.internal.misc.InnocuousThread", - "jdk.internal.misc.CarrierThread", "sun.misc.InnocuousThread", + // OpenJDK 21 java.base/jdk/internal/misc/CarrierThread.java: + // VirtualThread DEFAULT_SCHEDULER carrier thread (every VirtualThread.start + // is independently audited at onVirtualThreadStart). + "jdk.internal.misc.CarrierThread", + // OpenJDK java.logging/java/util/logging/LogManager.java (Cleaner): + // JVM shutdown hook resetting java.util.logging handlers. "java.util.logging.LogManager$Cleaner" ))); // Exact JVM/JDK internal callers that spawn housekeeping Threads (bootstrap/platform CL only). - private static final Set JVM_INTERNAL_CALLER_CLASSES = Collections.unmodifiableSet(new HashSet<>( + // Note: sun.nio.ch.AsynchronousChannelGroupImpl is intentionally ABSENT because + // it executes user CompletionHandler callbacks. + static final Set JVM_INTERNAL_CALLER_CLASSES = Collections.unmodifiableSet(new HashSet<>( Arrays.asList( + // OpenJDK java.base/java/lang/ApplicationShutdownHooks.java (runHooks): + // starts registered Runtime shutdown hooks during JVM exit. "java.lang.ApplicationShutdownHooks", + // OpenJDK java.base/java/lang/ProcessHandleImpl.java, ProcessImpl.java, + // UNIXProcess.java: OS child-process reaper thread (waitpid loop only). "java.lang.ProcessHandleImpl", "java.lang.ProcessImpl", "java.lang.UNIXProcess", + // OpenJDK java.base/jdk/internal/ref/CleanerImpl.java, CleanerFactory.java, + // java/lang/ref/Cleaner.java, sun/misc/Cleaner.java: PhantomReference cleaners. "jdk.internal.ref.CleanerImpl", "jdk.internal.ref.CleanerFactory", "sun.misc.Cleaner", "java.lang.ref.Cleaner", + // OpenJDK java.logging/java/util/logging/LogManager.java: logging shutdown cleaner. "java.util.logging.LogManager", + // OpenJDK java.base/sun/net/www/http/KeepAliveCache.java (JDK 8 uses anonymous + // PrivilegedAction KeepAliveCache$1): idle HTTP keep-alive socket eviction timer. "sun.net.www.http.KeepAliveCache", "sun.net.www.http.KeepAliveCache$1", - "sun.nio.ch.AsynchronousChannelGroupImpl", + // OpenJDK 21 java.base/java/lang/VirtualThread.java & + // java/util/concurrent/DelayScheduler.java: VirtualThread carrier/unparker internals. "java.lang.VirtualThread", "java.util.concurrent.DelayScheduler", + // OpenJDK java.base/jdk/internal/misc/Signal.java (JDK 9+) / + // sun/misc/Signal.java (JDK 8): OS signal dispatcher (SIGTERM handler). "jdk.internal.misc.Signal", "sun.misc.Signal" ))); // Exact reviewed HTTP server request-hosting worker Thread subclasses - // (requests on these threads enter hooked CoyoteAdapter / HttpChannel / Connectors). - private static final Set SERVER_WORKER_THREAD_CLASSES = Collections.unmodifiableSet(new HashSet<>( + // (requests on these threads enter hooked CoyoteAdapter / HttpChannel / Connectors, + // and AsyncContext.start dispatches enter RequestGate.handAsyncContext). + // Note: org.jboss.threads.JBossThread is intentionally ABSENT because generic + // EnhancedQueueExecutor/WildFly managed pools also spawn JBossThread workers. + static final Set SERVER_WORKER_THREAD_CLASSES = Collections.unmodifiableSet(new HashSet<>( Arrays.asList( - // Tomcat (CoyoteAdapter) + // Apache Tomcat 9.0.121 / 11.0.27 (org/apache/tomcat/util/threads/TaskThread.java): + // Tomcat connector & container utility threads. "org.apache.tomcat.util.threads.TaskThread", + // Apache Tomcat (org/apache/catalina/startup/Catalina.java): shutdown hook thread. "org.apache.catalina.startup.Catalina$CatalinaShutdownHook", + // Apache Tomcat JULI (org/apache/juli/ClassLoaderLogManager.java): log cleaner. "org.apache.juli.ClassLoaderLogManager$Cleaner", - // Jetty (HttpChannel / ServletChannel) + // Eclipse Jetty 9.4.57 (org/eclipse/jetty/util/thread/ShutdownThread.java): lifecycle shutdown. "org.eclipse.jetty.util.thread.ShutdownThread", - // Undertow / XNIO / JBoss Threads (Connectors) + // XNIO 3.8.x (org/xnio/nio/WorkerThread.java): Undertow I/O selector threads. "org.xnio.nio.WorkerThread", - "org.jboss.threads.JBossThread", - // JobGate-hooked Quartz scheduler threads + // Quartz 2.3.2 (org/quartz/simpl/SimpleThreadPool.java, QuartzSchedulerThread.java): + // JobGate-hooked via JobRunShell.run. "org.quartz.simpl.SimpleThreadPool$WorkerThread", "org.quartz.core.QuartzSchedulerThread" ))); // Exact reviewed HTTP server request-hosting classes that start plain java.lang.Thread - // instances (acceptors, pollers, Jetty QueuedThreadPool workers, Tomcat container background). - private static final Set SERVER_THREAD_START_CALLERS = Collections.unmodifiableSet(new HashSet<>( + // instances (acceptors, pollers, request-hosting worker growth, container background). + static final Set SERVER_THREAD_START_CALLERS = Collections.unmodifiableSet(new HashSet<>( Arrays.asList( - // Tomcat (CoyoteAdapter) + // Apache Tomcat 9.0.121 / 11.0.27 (AbstractEndpoint, NioEndpoint, Nio2Endpoint, + // AprEndpoint, ThreadPoolExecutor, ScheduledThreadPoolExecutor, StandardServer, + // ContainerBase, Catalina, AsyncFileHandler): request dispatch enters CoyoteAdapter. "org.apache.tomcat.util.net.AbstractEndpoint", "org.apache.tomcat.util.net.NioEndpoint", "org.apache.tomcat.util.net.Nio2Endpoint", @@ -97,17 +140,16 @@ final class SinkAllowlist { "org.apache.catalina.core.ContainerBase", "org.apache.catalina.startup.Catalina", "org.apache.juli.AsyncFileHandler$LoggerExecutorService", - // Jetty (HttpChannel / ServletChannel) + // Eclipse Jetty 9.4.57 (QueuedThreadPool, ScheduledExecutorScheduler, + // ExecutorThreadPool, TimerScheduler): request dispatch enters HttpChannel. "org.eclipse.jetty.util.thread.QueuedThreadPool", "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", "org.eclipse.jetty.util.thread.ExecutorThreadPool", "org.eclipse.jetty.util.thread.TimerScheduler", - // Undertow / XNIO / JBoss Threads (Connectors) + // XNIO 3.8.x (NioXnioWorker, XnioWorker): Undertow request dispatch enters Connectors. "org.xnio.nio.NioXnioWorker", "org.xnio.XnioWorker", - "org.jboss.threads.EnhancedQueueExecutor", - "org.jboss.threads.JBossScheduledThreadPoolExecutor", - // JobGate-hooked Quartz scheduler + // Quartz 2.3.2 (SimpleThreadPool, QuartzScheduler): JobGate-hooked via JobRunShell.run. "org.quartz.simpl.SimpleThreadPool", "org.quartz.core.QuartzScheduler" ))); @@ -115,9 +157,10 @@ final class SinkAllowlist { // Exact reviewed HTTP server request-hosting classes that dispatch onto // ThreadPoolExecutor / ScheduledThreadPoolExecutor for server I/O or // maintenance (requests enter hooked CoyoteAdapter / HttpChannel / Connectors). - private static final Set SERVER_POOL_CALLERS = Collections.unmodifiableSet(new HashSet<>( + static final Set SERVER_POOL_CALLERS = Collections.unmodifiableSet(new HashSet<>( Arrays.asList( - // Tomcat (CoyoteAdapter) + // Apache Tomcat 9.0.121 / 11.0.27: connector I/O & ScheduledThreadPoolExecutor.java:45-120 + // delegates Tomcat container maintenance tasks to its internal ScheduledExecutorService. "org.apache.tomcat.util.net.AbstractEndpoint", "org.apache.tomcat.util.net.NioEndpoint", "org.apache.tomcat.util.net.Nio2Endpoint", @@ -125,45 +168,45 @@ final class SinkAllowlist { "org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor", "org.apache.catalina.core.StandardServer", "org.apache.catalina.core.ContainerBase", - // Jetty (HttpChannel / ServletChannel) + // Eclipse Jetty 9.4.57: internal idle-timeout & connector executor dispatch. "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", "org.eclipse.jetty.util.thread.ExecutorThreadPool", - // Undertow / XNIO / JBoss Threads (Connectors) - "org.xnio.XnioWorker", - "org.jboss.threads.JBossScheduledThreadPoolExecutor" + // XNIO 3.8.x: Undertow worker dispatch into Connectors. + "org.xnio.XnioWorker" ))); // Exact reviewed HTTP server request-hosting ThreadPoolExecutor / STPE subclasses. - private static final Set SERVER_POOL_CLASSES = Collections.unmodifiableSet(new HashSet<>( + // Note: org.xnio.XnioWorker$DefaultThreadPoolExecutor and + // org.jboss.threads.ManagedThreadPoolExecutor are intentionally ABSENT because + // they can execute arbitrary user Runnables without entering a hooked entry. + static final Set SERVER_POOL_CLASSES = Collections.unmodifiableSet(new HashSet<>( Arrays.asList( - // Tomcat (CoyoteAdapter) + // Apache Tomcat 9.0.121 / 11.0.27 (org/apache/tomcat/util/threads/*): + // connector request pool (CoyoteAdapter) & async JULI file logger. "org.apache.tomcat.util.threads.ThreadPoolExecutor", "org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor", - "org.apache.juli.AsyncFileHandler$LoggerExecutorService", - // Undertow / XNIO / JBoss Threads (Connectors) - "org.xnio.XnioWorker$DefaultThreadPoolExecutor", - "org.jboss.threads.JBossScheduledThreadPoolExecutor", - "org.jboss.threads.ManagedThreadPoolExecutor" + "org.apache.juli.AsyncFileHandler$LoggerExecutorService" ))); - // Exact reviewed ScheduledThreadPoolExecutor / TPE task classes from - // servers or JobGate-hooked schedulers that never execute arbitrary unhooked app callbacks. - private static final Set SERVER_TASK_CLASSES = Collections.unmodifiableSet(new HashSet<>( + // Exact reviewed server or JobGate-hooked task classes that never execute + // arbitrary unhooked application callbacks. + // Note: Spring's generic wrappers DelegatingErrorHandlingRunnable and + // ReschedulingRunnable are intentionally ABSENT because they can wrap + // arbitrary unhooked user Runnables. + static final Set SERVER_TASK_CLASSES = Collections.unmodifiableSet(new HashSet<>( Arrays.asList( - // Tomcat container utility/maintenance tasks + // Apache Tomcat 9.0.121 / 11.0.27: container maintenance & NIO socket processors. "org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessorMonitor", "org.apache.catalina.core.StandardServer$1", "org.apache.catalina.util.TimeBucketCounterBase$MaintenanceMonitor", "org.apache.catalina.util.TimeBucketCounter$MaintenanceMonitor", "org.apache.tomcat.util.net.NioEndpoint$SocketProcessor", "org.apache.tomcat.util.net.Nio2Endpoint$SocketProcessor", - // Jetty internal scheduled tasks + // Eclipse Jetty 9.4.57: internal idle-timeout scheduled task. "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler$ScheduledFutureTask", "org.eclipse.jetty.io.IdleTimeout$1", - // Spring @Scheduled (hooked into JobGate via ScheduledMethodRunnable) - "org.springframework.scheduling.support.ScheduledMethodRunnable", - "org.springframework.scheduling.support.DelegatingErrorHandlingRunnable", - "org.springframework.scheduling.concurrent.ReschedulingRunnable" + // Spring 5.3.39 / 6.2.12 (ScheduledMethodRunnable.java): directly hooked into JobGate. + "org.springframework.scheduling.support.ScheduledMethodRunnable" ))); // Exact zero-app-callback infrastructure classes measured on Spring PetClinic @@ -219,10 +262,50 @@ final class SinkAllowlist { "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread" ))); + // Reflective JDK 9+ StackWalker handle so caller lookup walks only top frames + // lazily without materializing a full StackTraceElement[]; falls back cleanly + // to Thread.getStackTrace() on JDK 8 while compiling with --release 8. + private static final Object STACK_WALKER; + private static final Method STACK_WALKER_WALK; + private static final Method STACK_FRAME_GET_CLASS_NAME; + + static { + Object walker = null; + Method walkMethod = null; + Method getClassNameMethod = null; + try { + Class swClass = Class.forName("java.lang.StackWalker"); + Class sfClass = Class.forName("java.lang.StackWalker$StackFrame"); + Class optClass = Class.forName("java.lang.StackWalker$Option"); + @SuppressWarnings({"unchecked", "rawtypes"}) + Object showReflect = Enum.valueOf((Class) optClass, "SHOW_REFLECT_FRAMES"); + Method getInstance = swClass.getMethod("getInstance", optClass); + walker = getInstance.invoke(null, showReflect); + walkMethod = swClass.getMethod("walk", Function.class); + getClassNameMethod = sfClass.getMethod("getClassName"); + } catch (Throwable ignored) { + // JDK 8: fall back to Thread.currentThread().getStackTrace(). + walker = null; + walkMethod = null; + getClassNameMethod = null; + } + STACK_WALKER = walker; + STACK_WALKER_WALK = walkMethod; + STACK_FRAME_GET_CLASS_NAME = getClassNameMethod; + } + private SinkAllowlist() { } + static boolean usesStackWalker() { + return STACK_WALKER != null && STACK_WALKER_WALK != null && STACK_FRAME_GET_CLASS_NAME != null; + } + static boolean isAllowlistedThreadStart(Thread thread, String[] callerOut) { + return isAllowlistedThreadStart(thread, null, callerOut); + } + + static boolean isAllowlistedThreadStart(Thread thread, String explicitCaller, String[] callerOut) { if (thread == null) { return true; } @@ -247,16 +330,20 @@ static boolean isAllowlistedThreadStart(Thread thread, String[] callerOut) { && ((ForkJoinWorkerThread) thread).getPool() == java.util.concurrent.ForkJoinPool.commonPool()) { return true; } - String caller = firstExternalCaller(); + String caller = explicitCaller != null ? explicitCaller : firstExternalCaller(); if (callerOut != null && callerOut.length > 0) { callerOut[0] = caller; } return isAllowlistedJvmCaller(caller); } - String caller = firstExternalCaller(); + String caller = explicitCaller != null ? explicitCaller : firstExternalCaller(); if (callerOut != null && callerOut.length > 0) { callerOut[0] = caller; } + return isAllowlistedThreadStartCaller(caller); + } + + static boolean isAllowlistedThreadStartCaller(String caller) { if (caller == null) { return false; } @@ -273,17 +360,22 @@ static boolean isAllowlistedThreadStart(Thread thread, String[] callerOut) { } static boolean isAllowlistedVirtualThreadStart(Thread thread, String[] callerOut) { + return isAllowlistedVirtualThreadStart(thread, null, callerOut); + } + + static boolean isAllowlistedVirtualThreadStart(Thread thread, String explicitCaller, String[] callerOut) { if (thread == null) { return true; } if (RequestGate.isTrackedDispatchActive()) { return true; } - String caller = firstExternalCaller(true); + String caller = explicitCaller != null ? explicitCaller : firstExternalCaller(true); if (callerOut != null && callerOut.length > 0) { callerOut[0] = caller; } - // Tomcat virtual-thread request executor enters hooked CoyoteAdapter. + // Tomcat virtual-thread request executor enters hooked CoyoteAdapter + // (and AsyncContext.start enters RequestGate.handAsyncContext). if ("org.apache.tomcat.util.threads.VirtualThreadExecutor".equals(caller) || "org.apache.catalina.core.StandardVirtualThreadExecutor".equals(caller)) { return true; @@ -292,6 +384,10 @@ static boolean isAllowlistedVirtualThreadStart(Thread thread, String[] callerOut } static boolean isAllowlistedTpeExecute(Object executor, Object command, String[] callerOut) { + return isAllowlistedTpeExecute(executor, command, null, callerOut); + } + + static boolean isAllowlistedTpeExecute(Object executor, Object command, String explicitCaller, String[] callerOut) { if (RequestGate.isTrackedDispatchActive() || RequestGate.isTrackedTask(command)) { return true; } @@ -305,19 +401,19 @@ static boolean isAllowlistedTpeExecute(Object executor, Object command, String[] || INFRA_TASK_CLASSES.contains(command.getClass().getName()))) { return true; } - String caller = firstExternalCaller(); + String caller = explicitCaller != null ? explicitCaller : firstExternalCaller(); if (callerOut != null && callerOut.length > 0) { callerOut[0] = caller; } - if (caller != null && (SERVER_POOL_CALLERS.contains(caller) - || INFRA_POOL_CALLERS.contains(caller) - || isAllowlistedJvmCaller(caller))) { - return true; - } - return false; + return isAllowlistedPoolCaller(caller); } static boolean isAllowlistedStpeDelayedExecute(Object executor, Object task, String[] callerOut) { + return isAllowlistedStpeDelayedExecute(executor, task, null, callerOut); + } + + static boolean isAllowlistedStpeDelayedExecute(Object executor, Object task, String explicitCaller, + String[] callerOut) { if (RequestGate.isTrackedDispatchActive() || RequestGate.isTrackedTask(task)) { return true; } @@ -331,19 +427,24 @@ static boolean isAllowlistedStpeDelayedExecute(Object executor, Object task, Str || INFRA_TASK_CLASSES.contains(task.getClass().getName()))) { return true; } - String caller = firstExternalCaller(); + String caller = explicitCaller != null ? explicitCaller : firstExternalCaller(); if (callerOut != null && callerOut.length > 0) { callerOut[0] = caller; } - if (caller != null && (SERVER_POOL_CALLERS.contains(caller) + return isAllowlistedPoolCaller(caller); + } + + static boolean isAllowlistedPoolCaller(String caller) { + return caller != null && (SERVER_POOL_CALLERS.contains(caller) || INFRA_POOL_CALLERS.contains(caller) - || isAllowlistedJvmCaller(caller))) { - return true; - } - return false; + || isAllowlistedJvmCaller(caller)); } static boolean isAllowlistedFjpSubmit(Object pool, Object task, String[] callerOut) { + return isAllowlistedFjpSubmit(pool, task, null, callerOut); + } + + static boolean isAllowlistedFjpSubmit(Object pool, Object task, String explicitCaller, String[] callerOut) { if (RequestGate.isTrackedDispatchActive() || RequestGate.isTrackedTask(task)) { return true; } @@ -353,7 +454,7 @@ static boolean isAllowlistedFjpSubmit(Object pool, Object task, String[] callerO if (task != null && "java.lang.VirtualThread$VThreadContinuation".equals(task.getClass().getName())) { return true; } - String caller = firstExternalCaller(); + String caller = explicitCaller != null ? explicitCaller : firstExternalCaller(); if (callerOut != null && callerOut.length > 0) { callerOut[0] = caller; } @@ -364,10 +465,14 @@ static boolean isAllowlistedFjpSubmit(Object pool, Object task, String[] callerO } static boolean isAllowlistedTimerSched(Object timer, Object task, String[] callerOut) { + return isAllowlistedTimerSched(timer, task, null, callerOut); + } + + static boolean isAllowlistedTimerSched(Object timer, Object task, String explicitCaller, String[] callerOut) { if (RequestGate.isTrackedDispatchActive()) { return true; } - String caller = firstExternalCaller(); + String caller = explicitCaller != null ? explicitCaller : firstExternalCaller(); if (callerOut != null && callerOut.length > 0) { callerOut[0] = caller; } @@ -405,49 +510,91 @@ private static boolean isBootstrapOrPlatform(Class cls) { return sys != null && cl == sys.getParent(); } - // Walks the current thread's stack to find the first caller outside the - // sink bridge, Keploy's own RequestGate/SinkAllowlist, and the JDK sink - // wrapper methods themselves (e.g. ThreadPoolExecutor.addWorker -> execute, - // AbstractExecutorService.submit -> execute, Timer.schedule -> sched). - // Note: reflection (java.lang.reflect.Method.invoke) and MethodHandles are - // NOT skipped — they return their own class name, which is NOT in any - // allowlist, so reflective/MethodHandle dispatch fails closed by construction. static String firstExternalCaller() { return firstExternalCaller(false); } - static String firstExternalCaller(boolean skipVirtualThreadFrames) { + // Walks the current thread's stack (lazily via JDK 9+ StackWalker, or via + // Thread.getStackTrace() on JDK 8) to find the first caller outside the + // sink bridge, Keploy's own RequestGate/SinkAllowlist, and the JDK sink + // wrapper methods themselves (e.g. ThreadPoolExecutor.addWorker -> execute, + // AbstractExecutorService.submit -> execute, Timer.schedule -> sched). + // Reflection (java.lang.reflect.Method.invoke) and MethodHandles are NEVER + // skipped — they return their own class name, which is NOT in any allowlist, + // so reflective/MethodHandle dispatch fails closed by construction. + static String firstExternalCaller(final boolean skipVirtualThreadFrames) { + if (STACK_WALKER != null && STACK_WALKER_WALK != null && STACK_FRAME_GET_CLASS_NAME != null) { + try { + Function, String> finder = new Function, String>() { + @Override + public String apply(Stream stream) { + final boolean[] seenSelf = {false}; + Optional found = stream + .map(SinkAllowlist::frameClassName) + .filter(cn -> { + if (cn == null) { + return false; + } + if (!seenSelf[0]) { + if ("io.keploy.dedup.SinkAllowlist".equals(cn)) { + seenSelf[0] = true; + } + return false; + } + return !isSkippedCallerFrame(cn, skipVirtualThreadFrames); + }) + .findFirst(); + return found.orElse(null); + } + }; + return (String) STACK_WALKER_WALK.invoke(STACK_WALKER, finder); + } catch (Throwable ignored) { + // Fall back to getStackTrace below. + } + } StackTraceElement[] frames = Thread.currentThread().getStackTrace(); for (int i = 1; i < frames.length; i++) { String cn = frames[i].getClassName(); - if ("io.keploy.dedup.bootstrap.KeploySinkBridge".equals(cn) - || "io.keploy.dedup.SinkAllowlist".equals(cn) - || "io.keploy.dedup.RequestGate".equals(cn) - || "io.keploy.dedup.JdkSinkHandler".equals(cn) - || "io.keploy.dedup.JdkSinkBootstrap".equals(cn) - || "java.lang.Thread".equals(cn) - || "java.lang.System$2".equals(cn) - || "jdk.internal.vm.ThreadContainers".equals(cn) - || "jdk.internal.vm.SharedThreadContainer".equals(cn) - || (skipVirtualThreadFrames && ("java.lang.VirtualThread".equals(cn) - || "java.lang.ThreadBuilders$VirtualThreadBuilder".equals(cn) - || "java.lang.ThreadBuilders$PlatformThreadBuilder".equals(cn) - || "java.lang.ThreadBuilders$BaseThreadBuilder".equals(cn))) - || "java.util.concurrent.ThreadPoolExecutor".equals(cn) - || "java.util.concurrent.ThreadPoolExecutor$Worker".equals(cn) - || "java.util.concurrent.ScheduledThreadPoolExecutor".equals(cn) - || "java.util.concurrent.AbstractExecutorService".equals(cn) - || "java.util.concurrent.Executors$DelegatedExecutorService".equals(cn) - || "java.util.concurrent.Executors$FinalizableDelegatedExecutorService".equals(cn) - || "java.util.concurrent.Executors$DelegatedScheduledExecutorService".equals(cn) - || "java.util.concurrent.ForkJoinPool".equals(cn) - || "java.util.concurrent.ForkJoinTask".equals(cn) - || "java.util.concurrent.CompletableFuture".equals(cn) - || "java.util.Timer".equals(cn)) { - continue; + if (!isSkippedCallerFrame(cn, skipVirtualThreadFrames)) { + return cn; } - return cn; } return null; } + + private static String frameClassName(Object stackFrame) { + try { + return (String) STACK_FRAME_GET_CLASS_NAME.invoke(stackFrame); + } catch (Throwable ignored) { + return null; + } + } + + private static boolean isSkippedCallerFrame(String cn, boolean skipVirtualThreadFrames) { + return "io.keploy.dedup.bootstrap.KeploySinkBridge".equals(cn) + || "io.keploy.dedup.SinkAllowlist".equals(cn) + || "io.keploy.dedup.SinkAllowlist$1".equals(cn) + || "io.keploy.dedup.RequestGate".equals(cn) + || "io.keploy.dedup.JdkSinkHandler".equals(cn) + || "io.keploy.dedup.JdkSinkBootstrap".equals(cn) + || "java.lang.Thread".equals(cn) + || "java.lang.System$2".equals(cn) + || "jdk.internal.vm.ThreadContainers".equals(cn) + || "jdk.internal.vm.SharedThreadContainer".equals(cn) + || (skipVirtualThreadFrames && ("java.lang.VirtualThread".equals(cn) + || "java.lang.ThreadBuilders$VirtualThreadBuilder".equals(cn) + || "java.lang.ThreadBuilders$PlatformThreadBuilder".equals(cn) + || "java.lang.ThreadBuilders$BaseThreadBuilder".equals(cn))) + || "java.util.concurrent.ThreadPoolExecutor".equals(cn) + || "java.util.concurrent.ThreadPoolExecutor$Worker".equals(cn) + || "java.util.concurrent.ScheduledThreadPoolExecutor".equals(cn) + || "java.util.concurrent.AbstractExecutorService".equals(cn) + || "java.util.concurrent.Executors$DelegatedExecutorService".equals(cn) + || "java.util.concurrent.Executors$FinalizableDelegatedExecutorService".equals(cn) + || "java.util.concurrent.Executors$DelegatedScheduledExecutorService".equals(cn) + || "java.util.concurrent.ForkJoinPool".equals(cn) + || "java.util.concurrent.ForkJoinTask".equals(cn) + || "java.util.concurrent.CompletableFuture".equals(cn) + || "java.util.Timer".equals(cn); + } } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index 8462f959..44b782b7 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -581,6 +581,76 @@ public void forkedJdk21VirtualThreadSinkBypassesFailClosed() throws Exception { } } + @Test(timeout = 360000) + public void forkedServletAsyncContextStartAfterCompleteNeverLeaksAcrossServers() throws Exception { + // Servlet AsyncContext.start(r) where r calls ctx.complete() and then keeps + // executing AsyncTail.ran() must NEVER silently drop lines from W1 or leak + // them cleanly into W2, across Tomcat, Jetty, and Undertow in both modes. + String[] servers = {"tomcat", "jetty", "undertow"}; + for (boolean prefixMode : new boolean[] {true, false}) { + for (String server : servers) { + String label = "server=" + server + " mode=" + (prefixMode ? "prefix" : "index"); + boolean isUndertow = "undertow".equals(server); + // 1. Short endWait=80ms: post-complete runnable outlives END -> W1 must be + // windowCut:true AND W2 must carry tail contamination (zero silent leakage). + try (ForkedApp app = startFork(server, "80", prefixMode, false, null, null)) { + JsonObject hello = parseHello(app.initialHello); + assertTrue(label + " must declare windowCut=true: " + app.initialHello, + hello.get("windowCut").getAsBoolean()); + app.runHttpTest("ac/" + server + "-warm", "/clean"); + if (!isUndertow) { + assertTrue(label + " must keep asyncExecutors=true after /clean: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + String cov1 = app.runHttpTest("ac/" + server + "-cut", "/async-after-complete?ms=400"); + assertTrue(label + " W1 must report windowCut:true: " + cov1, + cov1.contains("\"windowCut\":true")); + String cov2 = app.runHttpTest("ac/" + server + "-next", "/clean"); + assertTrue(label + " W2 while post-complete task runs must carry tail:ac/" + + server + "-cut: " + cov2, + cov2.contains("\"tail:ac/" + server + "-cut\"")); + Thread.sleep(600); + String cov3 = app.runHttpTest("ac/" + server + "-drained", "/clean"); + assertFalse(label + " W3 after drain must not be windowCut: " + cov3, + cov3.contains("windowCut")); + if (!isUndertow) { + assertFalse(label + " W3 after drain must not carry tail:ac/" + server + "-cut: " + cov3, + cov3.contains("\"tail:ac/" + server + "-cut\"")); + assertFalse(label + " W3 after drain must not be contaminated: " + cov3, + cov3.contains("contaminated")); + } + } + + // 2. Sufficient endWait=2000ms: END waits until the post-complete runnable + // finishes -> AsyncTail lands IN-WINDOW inside W1 with zero silent leakage! + try (ForkedApp app = startFork(server, "2000", prefixMode, false, null, null)) { + String warmCov = app.runHttpTest("ac/" + server + "-warm2", "/clean"); + String cov1 = app.runHttpTest("ac/" + server + "-inwindow", "/async-after-complete?ms=250"); + assertFalse(label + " sufficient wait must not cut: " + cov1, cov1.contains("windowCut")); + assertTrue(label + " post-complete AsyncTail must land IN-WINDOW in W1: " + cov1, + cov1.contains("\"" + ASYNC_TAIL + "\"")); + String cov2 = app.runHttpTest("ac/" + server + "-clean", "/clean"); + assertFalse(label + " W2 must not contain AsyncTail: " + cov2, + cov2.contains("\"" + ASYNC_TAIL + "\"")); + if (!isUndertow) { + assertFalse(label + " sufficient wait must not contaminate W1: " + cov1, + cov1.contains("contaminated")); + assertFalse(label + " W2 after in-window completion must be clean: " + cov2, + cov2.contains("contaminated")); + } else { + // Undertow's EnhancedQueueExecutor/JBossThread is NOT allowlisted: either + // the warm request flags untracked-sink:thread-start or startup latched + // asyncExecutors=false. + boolean failClosed = warmCov.contains("untracked-sink:thread-start:") + || !parseHello(app.lastHello).get("asyncExecutors").getAsBoolean(); + assertTrue(label + " Undertow JBossThread must not be allowlisted: warm=" + warmCov + + " hello=" + app.lastHello, failClosed); + } + } + } + } + } + @Test(timeout = 420000) public void forkedAppSubPoolsAndReflectiveStartupWorkersFailClosed() throws Exception { // Isolated forks in both prefix and index modes for app/library JDK pool diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index a6f57f18..551dad2c 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -3389,10 +3389,11 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO assertEquals("ACK ts/test-1", in.readLine()); CountDownLatch allowAudit = new CountDownLatch(1); CountDownLatch auditDone = new CountDownLatch(1); + Thread audit; Object req1 = RequestGate.enter(); try { probes[0] = true; - Thread audit = new Thread(() -> { + audit = new Thread(() -> { try { allowAudit.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { @@ -3415,6 +3416,8 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO // 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)); + audit.join(5000); + assertFalse("audit thread must exit before START ts/test-2", audit.isAlive()); // START test-2 clears probe[2] but MUST NOT emit BACKGROUND! send(out, "START ts/test-2"); @@ -3452,10 +3455,11 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO // test-4->test-5) MUST be suppressed! CountDownLatch allowLongAudit = new CountDownLatch(1); CountDownLatch longAuditDone = new CountDownLatch(1); + Thread longAudit; Object req3 = RequestGate.enter(); try { probes[0] = true; - Thread longAudit = new Thread(() -> { + longAudit = new Thread(() -> { try { allowLongAudit.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { @@ -3490,6 +3494,8 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO // Now longAudit finishes in the gap between END test-4 and START test-5! allowLongAudit.countDown(); assertTrue(longAuditDone.await(5, TimeUnit.SECONDS)); + longAudit.join(5000); + assertFalse("longAudit thread must exit before START ts/test-5", longAudit.isAlive()); send(out, "START ts/test-5"); assertEquals("ACK ts/test-5", in.readLine()); send(out, "NOP check-no-bg-bc"); @@ -3607,10 +3613,11 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO assertTrue(sendUnixControl("START ts/u1").startsWith("ACK proto=3")); CountDownLatch allowAudit = new CountDownLatch(1); CountDownLatch auditDone = new CountDownLatch(1); + Thread audit; Object req1 = RequestGate.enter(); try { probes[0] = true; - Thread audit = new Thread(() -> { + audit = new Thread(() -> { try { allowAudit.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { @@ -3627,6 +3634,8 @@ public void untrackedAsyncThreadSuppressesBackgroundAndIncrementsBackgroundLostO assertTrue(sendUnixControl("END ts/u1").startsWith("ACK proto=3")); allowAudit.countDown(); assertTrue(auditDone.await(5, TimeUnit.SECONDS)); + audit.join(5000); + assertFalse("unix audit thread must exit before START ts/u2", audit.isAlive()); assertTrue(sendUnixControl("START ts/u2").startsWith("ACK proto=3")); // Clean counted request on Unix -> emits BACKGROUND(u2->u3) with lost:1 from u1->u2! diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java index 8bae7fe8..04b5e2e8 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java @@ -2,14 +2,23 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import io.keploy.dedup.bootstrap.KeploySinkBridge; +import java.lang.reflect.Method; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; /** * Unit tests for {@link KeploySinkBridge} re-entrancy / agent-internal guards @@ -206,62 +215,359 @@ public void userCallbackPoolsAndUntrackedCommonPoolAreNeverAllowlisted() { @Test public void infraAllowlistContainsOnlyExactCitedZeroCallbackClassesAndExcludesUserCallbackPools() { - // Every PetClinic-measured zero-callback infra class has an explicit positive row. - String[] expectedThreadCallers = { - "com.zaxxer.hikari.pool.HikariPool", - "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread", - "org.h2.util.MathUtils", - "org.springframework.boot.autoconfigure.condition.OnClassCondition$ThreadedOutcomesResolver", - "org.springframework.boot.autoconfigure.preinitialize.BackgroundPreinitializingApplicationListener", - "org.springframework.boot.tomcat.TomcatWebServer", - "org.springframework.boot.tomcat.GracefulShutdown", - "org.springframework.boot.web.embedded.tomcat.TomcatWebServer", - "org.springframework.boot.web.embedded.tomcat.GracefulShutdown", - }; - assertEquals("exact count of INFRA_THREAD_CALLERS must match reviewed rows", - expectedThreadCallers.length, SinkAllowlist.INFRA_THREAD_CALLERS.size()); - for (String cls : expectedThreadCallers) { - assertTrue("expected cited infra thread caller: " + cls, - SinkAllowlist.INFRA_THREAD_CALLERS.contains(cls)); - assertFalse("no package prefix wildcards allowed: " + cls, cls.endsWith(".") || cls.endsWith("*")); - } + ExecutorService plain = Executors.newSingleThreadExecutor(); + Thread plainThread = new Thread(() -> { }); + Runnable plainTask = () -> { }; + String[] callerOut = new String[1]; + try { + // Behaviour rows: every PetClinic-measured zero-callback infra caller + // passes the real SinkAllowlist.isAllowlisted* behaviour predicates. + String[] expectedThreadCallers = { + "com.zaxxer.hikari.pool.HikariPool", + "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread", + "org.h2.util.MathUtils", + "org.springframework.boot.autoconfigure.condition.OnClassCondition$ThreadedOutcomesResolver", + "org.springframework.boot.autoconfigure.preinitialize.BackgroundPreinitializingApplicationListener", + "org.springframework.boot.tomcat.TomcatWebServer", + "org.springframework.boot.tomcat.GracefulShutdown", + "org.springframework.boot.web.embedded.tomcat.TomcatWebServer", + "org.springframework.boot.web.embedded.tomcat.GracefulShutdown", + }; + assertEquals("exact count of INFRA_THREAD_CALLERS must match reviewed rows", + expectedThreadCallers.length, SinkAllowlist.INFRA_THREAD_CALLERS.size()); + for (String cls : expectedThreadCallers) { + assertFalse("no package prefix wildcards allowed: " + cls, cls.endsWith(".") || cls.endsWith("*")); + assertTrue("behaviour: cited infra thread caller must be allowed: " + cls, + SinkAllowlist.isAllowlistedThreadStart(plainThread, cls, callerOut)); + assertEquals(cls, callerOut[0]); + } - String[] expectedPoolCallers = { - "com.zaxxer.hikari.pool.HikariPool", - "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread", - }; - assertEquals("exact count of INFRA_POOL_CALLERS must match reviewed rows", - expectedPoolCallers.length, SinkAllowlist.INFRA_POOL_CALLERS.size()); - for (String cls : expectedPoolCallers) { - assertTrue("expected cited infra pool caller: " + cls, - SinkAllowlist.INFRA_POOL_CALLERS.contains(cls)); + String[] expectedPoolCallers = { + "com.zaxxer.hikari.pool.HikariPool", + "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread", + }; + assertEquals("exact count of INFRA_POOL_CALLERS must match reviewed rows", + expectedPoolCallers.length, SinkAllowlist.INFRA_POOL_CALLERS.size()); + for (String cls : expectedPoolCallers) { + assertTrue("behaviour: cited infra pool caller must be allowed at TPE: " + cls, + SinkAllowlist.isAllowlistedTpeExecute(plain, plainTask, cls, callerOut)); + assertTrue("behaviour: cited infra pool caller must be allowed at STPE: " + cls, + SinkAllowlist.isAllowlistedStpeDelayedExecute(plain, plainTask, cls, callerOut)); + assertTrue("behaviour: cited infra pool caller must be allowed at Timer: " + cls, + SinkAllowlist.isAllowlistedTimerSched(new Object(), plainTask, cls, callerOut)); + } + + assertEquals(1, SinkAllowlist.INFRA_TASK_CLASSES.size()); + assertTrue(SinkAllowlist.INFRA_TASK_CLASSES.contains("com.mysql.cj.jdbc.AbandonedConnectionCleanupThread")); + + // Anything that can run user Runnables, lambdas, CompletionHandlers, or + // listeners — including previously removed entries — MUST return false + // from every SinkAllowlist behaviour predicate! + String[] forbidden = { + "java.util.concurrent.ForkJoinPool", + "java.util.concurrent.CompletableFuture", + "org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor", + "org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler", + "org.springframework.core.task.SimpleAsyncTaskExecutor", + "org.springframework.scheduling.support.DelegatingErrorHandlingRunnable", + "org.springframework.scheduling.support.ReschedulingRunnable", + "org.xnio.XnioWorker$DefaultThreadPoolExecutor", + "org.jboss.threads.ManagedThreadPoolExecutor", + "org.jboss.threads.JBossThread", + "sun.nio.ch.AsynchronousChannelGroupImpl", + "reactor.core.scheduler.Schedulers", + "io.netty.util.concurrent.SingleThreadEventExecutor", + "com.google.common.eventbus.AsyncEventBus", + "kotlinx.coroutines.Dispatchers", + "java.lang.reflect.Method", + }; + for (String cls : forbidden) { + assertFalse("behaviour: forbidden class must be rejected at Thread.start: " + cls, + SinkAllowlist.isAllowlistedThreadStart(plainThread, cls, callerOut)); + assertFalse("behaviour: forbidden class must be rejected at VirtualThread.start: " + cls, + SinkAllowlist.isAllowlistedVirtualThreadStart(plainThread, cls, callerOut)); + assertFalse("behaviour: forbidden class must be rejected at TPE.execute: " + cls, + SinkAllowlist.isAllowlistedTpeExecute(plain, plainTask, cls, callerOut)); + assertFalse("behaviour: forbidden class must be rejected at STPE.delayedExecute: " + cls, + SinkAllowlist.isAllowlistedStpeDelayedExecute(plain, plainTask, cls, callerOut)); + assertFalse("behaviour: forbidden class must be rejected at FJP.submit: " + cls, + SinkAllowlist.isAllowlistedFjpSubmit(ForkJoinPool.commonPool(), plainTask, cls, callerOut)); + assertFalse("behaviour: forbidden class must be rejected at Timer.sched: " + cls, + SinkAllowlist.isAllowlistedTimerSched(new Object(), plainTask, cls, callerOut)); + assertFalse("forbidden class must NOT be in SERVER_POOL_CLASSES: " + cls, + SinkAllowlist.SERVER_POOL_CLASSES.contains(cls)); + assertFalse("forbidden class must NOT be in SERVER_TASK_CLASSES: " + cls, + SinkAllowlist.SERVER_TASK_CLASSES.contains(cls)); + assertFalse("forbidden class must NOT be in SERVER_WORKER_THREAD_CLASSES: " + cls, + SinkAllowlist.SERVER_WORKER_THREAD_CLASSES.contains(cls)); + assertFalse("forbidden class must NOT be in JVM_INTERNAL_CALLER_CLASSES: " + cls, + SinkAllowlist.JVM_INTERNAL_CALLER_CLASSES.contains(cls)); + } + } finally { + plain.shutdownNow(); } + } + + @Test + public void stackWalkerIsUsedOnJdk9PlusAndSurfacesDirectAndReflectiveCallers() throws Exception { + String spec = System.getProperty("java.specification.version"); + boolean jdk9Plus = !spec.startsWith("1."); + assertEquals("StackWalker must be active on JDK 9+ and fall back cleanly on JDK 8", + jdk9Plus, SinkAllowlist.usesStackWalker()); + + String directCaller = SinkAllowlist.firstExternalCaller(); + assertEquals("direct caller must resolve to this test class", + JdkSinkBridgeTest.class.getName(), directCaller); + + Method m = SinkAllowlist.class.getDeclaredMethod("firstExternalCaller"); + m.setAccessible(true); + String reflectiveCaller = (String) m.invoke(null); + assertNotNull("reflective caller must not be null", reflectiveCaller); + assertFalse("reflective caller must never be allowlisted: " + reflectiveCaller, + SinkAllowlist.isAllowlistedThreadStartCaller(reflectiveCaller)); + } + + public static boolean isTrackedDispatchActiveForTest() { + return RequestGate.isTrackedDispatchActive(); + } - assertEquals(1, SinkAllowlist.INFRA_TASK_CLASSES.size()); - assertTrue(SinkAllowlist.INFRA_TASK_CLASSES.contains("com.mysql.cj.jdbc.AbandonedConnectionCleanupThread")); - - // Anything that can run user Runnables, lambdas, or listeners is NEVER allowlisted. - String[] forbidden = { - "java.util.concurrent.ForkJoinPool", - "java.util.concurrent.CompletableFuture", - "org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor", - "org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler", - "org.springframework.core.task.SimpleAsyncTaskExecutor", - "reactor.core.scheduler.Schedulers", - "io.netty.util.concurrent.SingleThreadEventExecutor", - "com.google.common.eventbus.AsyncEventBus", - "kotlinx.coroutines.Dispatchers", + @Test + public void asyncContextInterfaceHookWrapsJavaxJakartaAndTransitiveSubclasses() throws Exception { + final ServerEntries transformer = new ServerEntries(true); + final byte[] jakartaIface = generateMarkerInterface("jakarta/servlet/AsyncContext"); + final byte[] javaxImpl = generateAsyncContextImpl( + "org/example/synthetic/JavaxAsyncCtxImpl", "java/lang/Object", + new String[] {"javax/servlet/AsyncContext"}); + final byte[] jakartaBase = generateAsyncContextBase( + "org/example/synthetic/JakartaBaseAsyncCtx", "java/lang/Object", + new String[] {"jakarta/servlet/AsyncContext"}); + final byte[] jakartaSub = generateAsyncContextImpl( + "org/example/synthetic/JakartaSubAsyncCtx", "org/example/synthetic/JakartaBaseAsyncCtx", + null); + + final byte[][] transformedJavax = {null}; + final byte[][] transformedJakartaSub = {null}; + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + ClassLoader cl = new ClassLoader(JdkSinkBridgeTest.class.getClassLoader()) { + @Override + public java.io.InputStream getResourceAsStream(String name) { + if ("jakarta/servlet/AsyncContext.class".equals(name)) { + return new java.io.ByteArrayInputStream(jakartaIface); + } + if ("org/example/synthetic/JakartaBaseAsyncCtx.class".equals(name)) { + return new java.io.ByteArrayInputStream(jakartaBase); + } + return super.getResourceAsStream(name); + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + String internal = name.replace('.', '/'); + byte[] raw; + if ("jakarta/servlet/AsyncContext".equals(internal)) { + raw = jakartaIface; + } else if ("org/example/synthetic/JavaxAsyncCtxImpl".equals(internal)) { + raw = javaxImpl; + } else if ("org/example/synthetic/JakartaBaseAsyncCtx".equals(internal)) { + raw = jakartaBase; + } else if ("org/example/synthetic/JakartaSubAsyncCtx".equals(internal)) { + raw = jakartaSub; + } else { + throw new ClassNotFoundException(name); + } + byte[] out = transformer.transform(this, internal, null, + JdkSinkBridgeTest.class.getProtectionDomain(), raw); + if ("org/example/synthetic/JavaxAsyncCtxImpl".equals(internal)) { + transformedJavax[0] = out; + } else if ("org/example/synthetic/JakartaSubAsyncCtx".equals(internal)) { + transformedJakartaSub[0] = out; + } + byte[] effective = out != null ? out : raw; + return defineClass(name, effective, 0, effective.length); + } }; - for (String cls : forbidden) { - assertFalse("user-callback class must NEVER be in INFRA_THREAD_CALLERS: " + cls, - SinkAllowlist.INFRA_THREAD_CALLERS.contains(cls)); - assertFalse("user-callback class must NEVER be in INFRA_POOL_CALLERS: " + cls, - SinkAllowlist.INFRA_POOL_CALLERS.contains(cls)); - assertFalse("user-callback class must NEVER be in INFRA_TASK_CLASSES: " + cls, - SinkAllowlist.INFRA_TASK_CLASSES.contains(cls)); + + Class javaxCls = cl.loadClass("org.example.synthetic.JavaxAsyncCtxImpl"); + Class jakartaSubCls = cl.loadClass("org.example.synthetic.JakartaSubAsyncCtx"); + assertNotNull("javax AsyncContext impl must be transformed by interface", transformedJavax[0]); + assertNotNull("transitive jakarta AsyncContext subclass must be transformed by interface", + transformedJakartaSub[0]); + + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + try { + // 1. Inside an armed window: AsyncContext.start(r) holds the window open until r finishes! + RequestGate.open("ac-unit-1", null); + Object reqToken = RequestGate.enter(); + final CountDownLatch taskStarted = new CountDownLatch(1); + final CountDownLatch releaseTask = new CountDownLatch(1); + final AtomicBoolean trackedDuringStart = new AtomicBoolean(false); + final AtomicReference workerRef = new AtomicReference<>(); + + Object javaxInst = javaxCls.getDeclaredConstructor(AtomicBoolean.class, AtomicReference.class) + .newInstance(trackedDuringStart, workerRef); + javaxCls.getMethod("start", Runnable.class).invoke(javaxInst, (Runnable) () -> { + taskStarted.countDown(); + try { + releaseTask.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + RequestGate.exit(reqToken); + assertTrue("tracked dispatch must be active inside keploy$async$start", trackedDuringStart.get()); + assertTrue("async task started", taskStarted.await(5, TimeUnit.SECONDS)); + assertEquals("window must stay open (running == 1) while AsyncContext.start task runs", + 1, RequestGate.running()); + assertFalse("short await while AsyncContext.start task runs must cut", + RequestGate.await(TimeUnit.MILLISECONDS.toNanos(40))); + releaseTask.countDown(); + if (workerRef.get() != null) { + workerRef.get().join(5000); + } + + // 2. Transitive jakarta subclass: normal in-window completion drains cleanly, + // and throwing from start(r) releases permit via dropped()! + RequestGate.open("ac-unit-throw", null); + Object reqToken2 = RequestGate.enter(); + Object jakartaInst = jakartaSubCls.getDeclaredConstructor(AtomicBoolean.class, AtomicReference.class) + .newInstance(new AtomicBoolean(), new AtomicReference()); + jakartaSubCls.getField("throwOnStart").setBoolean(jakartaInst, true); + boolean threw = false; + try { + jakartaSubCls.getMethod("start", Runnable.class).invoke(jakartaInst, (Runnable) () -> { }); + } catch (java.lang.reflect.InvocationTargetException ite) { + threw = ite.getCause() instanceof IllegalStateException; + } + assertTrue("start() failure must propagate", threw); + RequestGate.exit(reqToken2); + assertEquals("dropped() must release permit immediately on exception", 0, RequestGate.running()); + assertTrue("dropped() must let window finish cleanly when AsyncContext.start throws", + RequestGate.await(TimeUnit.MILLISECONDS.toNanos(500))); + + // 3. Outside any window: AsyncContext.start(r) latches asyncExecutors=false! + assertFalse("must not have latched yet", KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + Object outsideInst = jakartaSubCls.getDeclaredConstructor(AtomicBoolean.class, AtomicReference.class) + .newInstance(new AtomicBoolean(), new AtomicReference()); + AtomicReference outsideWorker = new AtomicReference<>(); + jakartaSubCls.getField("workerRef").set(outsideInst, outsideWorker); + jakartaSubCls.getMethod("start", Runnable.class).invoke(outsideInst, (Runnable) () -> { }); + if (outsideWorker.get() != null) { + outsideWorker.get().join(5000); + } + assertTrue("AsyncContext.start outside any window must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); } } + private static byte[] generateMarkerInterface(String internalName) { + ClassWriter cw = new ClassWriter(0); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE, + internalName, null, "java/lang/Object", null); + cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, "start", "(Ljava/lang/Runnable;)V", null, null) + .visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateAsyncContextBase(String internalName, String superName, String[] interfaces) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, + internalName, null, superName, interfaces); + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, superName, "", "()V", false); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(1, 1); + init.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateAsyncContextImpl(String internalName, String superName, String[] interfaces) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, internalName, null, superName, interfaces); + cw.visitField(Opcodes.ACC_PUBLIC, "trackedDuringStart", "Ljava/util/concurrent/atomic/AtomicBoolean;", + null, null).visitEnd(); + cw.visitField(Opcodes.ACC_PUBLIC, "workerRef", "Ljava/util/concurrent/atomic/AtomicReference;", + null, null).visitEnd(); + cw.visitField(Opcodes.ACC_PUBLIC, "throwOnStart", "Z", null, null).visitEnd(); + + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", + "(Ljava/util/concurrent/atomic/AtomicBoolean;Ljava/util/concurrent/atomic/AtomicReference;)V", + null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, superName, "", "()V", false); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitVarInsn(Opcodes.ALOAD, 1); + init.visitFieldInsn(Opcodes.PUTFIELD, internalName, "trackedDuringStart", + "Ljava/util/concurrent/atomic/AtomicBoolean;"); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitVarInsn(Opcodes.ALOAD, 2); + init.visitFieldInsn(Opcodes.PUTFIELD, internalName, "workerRef", + "Ljava/util/concurrent/atomic/AtomicReference;"); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(0, 0); + init.visitEnd(); + + // public void start(Runnable r) { + // trackedDuringStart.set(RequestGate.isTrackedDispatchActive()); + // if (throwOnStart) throw new IllegalStateException("boom"); + // Thread t = new Thread(r, "synthetic-async-ctx"); + // workerRef.set(t); + // t.start(); + // } + MethodVisitor start = cw.visitMethod(Opcodes.ACC_PUBLIC, "start", "(Ljava/lang/Runnable;)V", null, null); + start.visitCode(); + start.visitVarInsn(Opcodes.ALOAD, 0); + start.visitFieldInsn(Opcodes.GETFIELD, internalName, "trackedDuringStart", + "Ljava/util/concurrent/atomic/AtomicBoolean;"); + start.visitMethodInsn(Opcodes.INVOKESTATIC, "io/keploy/dedup/JdkSinkBridgeTest", + "isTrackedDispatchActiveForTest", "()Z", false); + start.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/atomic/AtomicBoolean", + "set", "(Z)V", false); + + org.objectweb.asm.Label noThrow = new org.objectweb.asm.Label(); + start.visitVarInsn(Opcodes.ALOAD, 0); + start.visitFieldInsn(Opcodes.GETFIELD, internalName, "throwOnStart", "Z"); + start.visitJumpInsn(Opcodes.IFEQ, noThrow); + start.visitTypeInsn(Opcodes.NEW, "java/lang/IllegalStateException"); + start.visitInsn(Opcodes.DUP); + start.visitLdcInsn("boom"); + start.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/IllegalStateException", + "", "(Ljava/lang/String;)V", false); + start.visitInsn(Opcodes.ATHROW); + + start.visitLabel(noThrow); + start.visitTypeInsn(Opcodes.NEW, "java/lang/Thread"); + start.visitInsn(Opcodes.DUP); + start.visitVarInsn(Opcodes.ALOAD, 1); + start.visitLdcInsn("synthetic-async-ctx"); + start.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Thread", + "", "(Ljava/lang/Runnable;Ljava/lang/String;)V", false); + start.visitVarInsn(Opcodes.ASTORE, 2); + start.visitVarInsn(Opcodes.ALOAD, 0); + start.visitFieldInsn(Opcodes.GETFIELD, internalName, "workerRef", + "Ljava/util/concurrent/atomic/AtomicReference;"); + start.visitVarInsn(Opcodes.ALOAD, 2); + start.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/atomic/AtomicReference", + "set", "(Ljava/lang/Object;)V", false); + start.visitVarInsn(Opcodes.ALOAD, 2); + start.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Thread", "start", "()V", false); + start.visitInsn(Opcodes.RETURN); + start.visitMaxs(0, 0); + start.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + @Test public void unarmedHandOffOutsideWindowLatchesAsyncExecutorsFalse() { boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index 23349838..4af831f6 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -1,6 +1,9 @@ package org.example.servers; import com.sun.net.httpserver.HttpServer; +import io.undertow.Undertow; +import io.undertow.servlet.Servlets; +import io.undertow.servlet.api.DeploymentManager; import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -86,7 +89,8 @@ public static void main(String[] args) throws Exception { tomcat.setBaseDir(base.getPath()); tomcat.setPort(0); Context context = tomcat.addContext("", base.getPath()); - Tomcat.addServlet(context, "async", new AsyncServlet()); + org.apache.catalina.Wrapper wrapper = Tomcat.addServlet(context, "async", new AsyncServlet()); + wrapper.setAsyncSupported(true); context.addServletMappingDecoded("/*", "async"); tomcat.start(); port = tomcat.getConnector().getLocalPort(); @@ -99,11 +103,29 @@ public static void main(String[] args) throws Exception { } Server jetty = new Server(0); ServletContextHandler context = new ServletContextHandler(); - context.addServlet(new ServletHolder(new AsyncServlet()), "/*"); + ServletHolder holder = new ServletHolder(new AsyncServlet()); + holder.setAsyncSupported(true); + context.addServlet(holder, "/*"); jetty.setHandler(context); jetty.start(); port = ((ServerConnector) jetty.getConnectors()[0]).getLocalPort(); server = jetty::stop; + } else if ("undertow".equals(mode)) { + DeploymentManager deployment = Servlets.defaultContainer().addDeployment(Servlets.deployment() + .setClassLoader(AsyncHonestyApp.class.getClassLoader()) + .setContextPath("/") + .setDeploymentName("honesty") + .addServlet(Servlets.servlet("async", AsyncServlet.class) + .setAsyncSupported(true) + .addMapping("/*"))); + deployment.deploy(); + Undertow undertow = Undertow.builder() + .addHttpListener(0, "127.0.0.1") + .setHandler(deployment.start()) + .build(); + undertow.start(); + port = ((InetSocketAddress) undertow.getListenerInfo().get(0).getAddress()).getPort(); + server = undertow::stop; } else if ("uncounted".equals(mode)) { HttpServer http = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); http.createContext("/clean", exchange -> { @@ -161,8 +183,31 @@ public static final class AsyncServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String path = req.getPathInfo() == null ? "/" : req.getPathInfo(); + String path = req.getPathInfo(); + if (path == null || path.isEmpty()) { + path = req.getRequestURI() == null ? "/" : req.getRequestURI(); + } long ms = req.getParameter("ms") == null ? 0L : Long.parseLong(req.getParameter("ms")); + if ("/async-after-complete".equals(path)) { + final javax.servlet.AsyncContext ctx = req.startAsync(); + final long delay = ms; + ctx.start(() -> { + try { + byte[] ok = "ok".getBytes(StandardCharsets.UTF_8); + HttpServletResponse asyncResp = (HttpServletResponse) ctx.getResponse(); + asyncResp.setContentType("text/plain"); + asyncResp.setContentLength(ok.length); + asyncResp.getOutputStream().write(ok); + asyncResp.flushBuffer(); + } catch (IOException ignored) { + } finally { + ctx.complete(); + } + sleepQuietly(delay); + AsyncTail.ran(); + }); + return; + } if ("/submit-tail".equals(path)) { PLAIN_POOL.submit(() -> { sleepQuietly(ms); From 1a62bef97f89573d6d75c02d2988d8c86c1b3516 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Sat, 28 Nov 2026 19:03:39 +0530 Subject: [PATCH 26/26] test(dedup): add AsyncContext fail-closed loader, Jakarta Tomcat 10, and allowlist behaviour tests Add pre-merge follow-up tests: - JdkSinkBridgeTest#asyncContextHookFailsClosedWhenLoaderCannotSeeRequestGate covering javax and jakarta AsyncContext implementations in a ClassLoader that cannot see RequestGate (verifies hadAsyncHookFailure() fails closed). - ForkedAsyncAndHonestyTest#forkedJakartaTomcat10AsyncContextStartAfterCompleteNeverLeaks exercising real Tomcat 10.1.34 (jakarta.servlet.AsyncContext) staged by the JDK 17+ test profile in both prefix and index modes (80ms W1-FLAGGED + tail and 2000ms IN-WINDOW). - JdkSinkBridgeTest#jvmInternalAndServerAllowlistEntriesHaveExplicitBehaviourRows covering every retained JVM_INTERNAL_* and SERVER_* sink allowlist entry. - Document bounded supertype walk in ServerEntries.isAsyncContextType. Signed-off-by: slayerjain --- keploy-sdk/pom.xml | 15 ++ .../java/io/keploy/dedup/ServerEntries.java | 5 + .../dedup/ForkedAsyncAndHonestyTest.java | 208 ++++++++++++++++++ .../io/keploy/dedup/JdkSinkBridgeTest.java | 201 +++++++++++++++++ 4 files changed, 429 insertions(+) diff --git a/keploy-sdk/pom.xml b/keploy-sdk/pom.xml index 9eafc6d7..12690bdd 100644 --- a/keploy-sdk/pom.xml +++ b/keploy-sdk/pom.xml @@ -355,6 +355,21 @@ + + copy-tomcat10 + generate-test-resources + + copy + + + ${skipTests} + ${project.build.directory}/tomcat10 + + org.apache.tomcattomcat-annotations-api10.1.34 + org.apache.tomcat.embedtomcat-embed-core10.1.34 + + + 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 466110b1..9ab1ae4c 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -1071,6 +1071,11 @@ private static boolean isAsyncContextType(ClassLoader loader, String internalNam ? loader.getResourceAsStream(resource) : ClassLoader.getSystemResourceAsStream(resource)) { if (in == null) { + // Bounded walk: if an intermediate supertype's bytecode is unavailable via + // getResourceAsStream and not yet cached, return false without failing class + // loading. Every allowlisted server (Tomcat/Jetty/Undertow) implements + // AsyncContext directly, and non-allowlisted containers fail closed at the + // JDK thread-start sink anyway. return false; } ClassReader parentReader = new ClassReader(in); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index 44b782b7..4a1e0f7e 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -651,6 +651,214 @@ public void forkedServletAsyncContextStartAfterCompleteNeverLeaksAcrossServers() } } + @Test(timeout = 240000) + public void forkedJakartaTomcat10AsyncContextStartAfterCompleteNeverLeaks() throws Exception { + // Spring Boot 3/4 Jakarta Servlet row: uses tomcat-embed-core 10.1.34 staged by the + // JDK 17+ Maven profile into target/tomcat10 (skipped cleanly on JDK 8/11). + File tomcat10Dir = new File("target/tomcat10"); + File[] jars = tomcat10Dir.isDirectory() + ? tomcat10Dir.listFiles((d, name) -> name.startsWith("tomcat-embed-core-") && name.endsWith(".jar")) + : null; + org.junit.Assume.assumeTrue("Jakarta Tomcat 10 row requires JDK 17+ profile (target/tomcat10)", + jars != null && jars.length > 0); + File tomcat10Jar = jars[0]; + + File srcDir = tmp.newFolder("jakarta-src"); + File outDir = tmp.newFolder("jakarta-classes"); + File pkgDir = new File(srcDir, "org/example/jakarta"); + assertTrue(pkgDir.mkdirs()); + File tailSrc = new File(pkgDir, "JakartaAsyncTail.java"); + Files.write(tailSrc.toPath(), ( + "package org.example.jakarta;\n" + + "public final class JakartaAsyncTail {\n" + + " private static volatile int hits;\n" + + " public static void ran() { hits++; }\n" + + "}\n").getBytes(StandardCharsets.UTF_8)); + File appSrc = new File(pkgDir, "JakartaTomcatAsyncApp.java"); + Files.write(appSrc.toPath(), ( + "package org.example.jakarta;\n" + + "import jakarta.servlet.AsyncContext;\n" + + "import jakarta.servlet.http.HttpServlet;\n" + + "import jakarta.servlet.http.HttpServletRequest;\n" + + "import jakarta.servlet.http.HttpServletResponse;\n" + + "import java.io.File;\n" + + "import java.io.IOException;\n" + + "import java.nio.charset.StandardCharsets;\n" + + "import java.nio.file.Files;\n" + + "import org.apache.catalina.Context;\n" + + "import org.apache.catalina.Wrapper;\n" + + "import org.apache.catalina.startup.Tomcat;\n" + + "public final class JakartaTomcatAsyncApp {\n" + + " public static void main(String[] args) throws Exception {\n" + + " File base = Files.createTempDirectory(\"tomcat10-jk\").toFile();\n" + + " Tomcat tomcat = new Tomcat();\n" + + " tomcat.setBaseDir(base.getPath());\n" + + " tomcat.setPort(0);\n" + + " Context context = tomcat.addContext(\"\", base.getPath());\n" + + " Wrapper w = Tomcat.addServlet(context, \"async\", new HttpServlet() {\n" + + " @Override\n" + + " protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {\n" + + " String path = req.getPathInfo() == null ? \"/\" : req.getPathInfo();\n" + + " long ms = req.getParameter(\"ms\") == null ? 0L : Long.parseLong(req.getParameter(\"ms\"));\n" + + " if (\"/async-after-complete\".equals(path)) {\n" + + " final AsyncContext ctx = req.startAsync();\n" + + " final long delay = ms;\n" + + " ctx.start(() -> {\n" + + " try {\n" + + " byte[] ok = \"ok\".getBytes(StandardCharsets.UTF_8);\n" + + " HttpServletResponse ar = (HttpServletResponse) ctx.getResponse();\n" + + " ar.setContentType(\"text/plain\");\n" + + " ar.setContentLength(ok.length);\n" + + " ar.getOutputStream().write(ok);\n" + + " ar.flushBuffer();\n" + + " } catch (IOException ignored) {\n" + + " } finally {\n" + + " ctx.complete();\n" + + " }\n" + + " try { Thread.sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " return;\n" + + " }\n" + + " byte[] body = \"ok\".getBytes(StandardCharsets.UTF_8);\n" + + " resp.setContentType(\"text/plain\");\n" + + " resp.setContentLength(body.length);\n" + + " resp.getOutputStream().write(body);\n" + + " resp.flushBuffer();\n" + + " }\n" + + " });\n" + + " w.setAsyncSupported(true);\n" + + " context.addServletMappingDecoded(\"/*\", \"async\");\n" + + " tomcat.start();\n" + + " System.out.println(\"PORT \" + tomcat.getConnector().getLocalPort());\n" + + " System.out.flush();\n" + + " while (System.in.read() >= 0) { }\n" + + " tomcat.stop();\n" + + " System.exit(0);\n" + + " }\n" + + "}\n").getBytes(StandardCharsets.UTF_8)); + + javax.tools.JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler(); + assertNotNull("JDK compiler required for Jakarta Tomcat 10 row", compiler); + int rc = compiler.run(null, null, null, "-cp", tomcat10Jar.getAbsolutePath(), + "-d", outDir.getAbsolutePath(), tailSrc.getAbsolutePath(), appSrc.getAbsolutePath()); + assertEquals("compile JakartaTomcatAsyncApp", 0, rc); + + String jakartaTail = "org/example/jakarta/JakartaAsyncTail"; + for (boolean prefixMode : new boolean[] {true, false}) { + String label = "jakarta-tomcat10 mode=" + (prefixMode ? "prefix" : "index"); + // 1. Short endWait=80ms: post-complete runnable outlives END -> W1 windowCut:true + W2 tail. + try (ForkedApp app = startJakartaTomcat10Fork(outDir, tomcat10Jar, "80", prefixMode)) { + JsonObject hello = parseHello(app.initialHello); + assertTrue(label + " must declare windowCut=true: " + app.initialHello, + hello.get("windowCut").getAsBoolean()); + app.runHttpTest("jk/warm", "/clean"); + assertTrue(label + " must keep asyncExecutors=true after /clean: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String cov1 = app.runHttpTest("jk/cut", "/async-after-complete?ms=400"); + assertTrue(label + " W1 must report windowCut:true: " + cov1, + cov1.contains("\"windowCut\":true")); + String cov2 = app.runHttpTest("jk/next", "/clean"); + assertTrue(label + " W2 must carry tail:jk/cut: " + cov2, + cov2.contains("\"tail:jk/cut\"")); + Thread.sleep(600); + String cov3 = app.runHttpTest("jk/drained", "/clean"); + assertFalse(label + " W3 after drain must not be windowCut: " + cov3, cov3.contains("windowCut")); + assertFalse(label + " W3 after drain must not be contaminated: " + cov3, + cov3.contains("contaminated")); + String log = readFile(app.log); + assertTrue(label + " log must confirm jakarta AsyncContextImpl hook: " + log, + log.contains("Keploy dedup counts Servlet AsyncContext.start tasks" + + " (org.apache.catalina.core.AsyncContextImpl)")); + } + // 2. Sufficient endWait=2000ms: AsyncTail lands IN-WINDOW in W1 with zero contamination. + try (ForkedApp app = startJakartaTomcat10Fork(outDir, tomcat10Jar, "2000", prefixMode)) { + String cov1 = app.runHttpTest("jk/inwindow", "/async-after-complete?ms=250"); + assertFalse(label + " sufficient wait must not cut: " + cov1, cov1.contains("windowCut")); + assertFalse(label + " sufficient wait must not contaminate W1: " + cov1, + cov1.contains("contaminated")); + assertTrue(label + " post-complete JakartaAsyncTail must land IN-WINDOW in W1: " + cov1, + cov1.contains("\"" + jakartaTail + "\"")); + String cov2 = app.runHttpTest("jk/clean", "/clean"); + assertFalse(label + " W2 must be clean: " + cov2, cov2.contains("contaminated")); + assertFalse(label + " W2 must not contain JakartaAsyncTail: " + cov2, + cov2.contains("\"" + jakartaTail + "\"")); + } + } + } + + private ForkedApp startJakartaTomcat10Fork(File jakartaClassesDir, File tomcat10Jar, String endWait, + boolean externalJacocoPrefixMode) throws Exception { + 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-jk-" + 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<>(); + cp.add(jakartaClassesDir.getAbsolutePath()); + File[] tomcat10Jars = tomcat10Jar.getParentFile().listFiles((d, name) -> name.endsWith(".jar")); + if (tomcat10Jars != null) { + for (File jar : tomcat10Jars) { + cp.add(jar.getAbsolutePath()); + } + } else { + cp.add(tomcat10Jar.getAbsolutePath()); + } + for (String entry : System.getProperty("java.class.path").split(File.pathSeparator)) { + String base = new File(entry).getName(); + if (base.startsWith("tomcat-embed-") || base.startsWith("tomcat-annotations-") + || base.startsWith("javax.servlet") || base.startsWith("jetty-") + || base.startsWith("undertow-")) { + continue; + } + cp.add(new File(entry).getAbsolutePath()); + } + cmd.add("-cp"); + cmd.add(String.join(File.pathSeparator, cp)); + cmd.add("org.example.jakarta.JakartaTomcatAsyncApp"); + + File log = tmp.newFile("fork-jakarta-tomcat10-" + 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) { + env.put("KEPLOY_JAVA_CLASS_DIRS", jakartaClassesDir.getAbsolutePath()); + } + 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-jk"); + env.put("KEPLOY_DEDUP_POD_NAME", "pod-name-jk"); + env.put("KEPLOY_DEDUP_SESSION_ID", "session-jk"); + + 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; + } + } + @Test(timeout = 420000) public void forkedAppSubPoolsAndReflectiveStartupWorkersFailClosed() throws Exception { // Isolated forks in both prefix and index modes for app/library JDK pool diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java index 04b5e2e8..b40864f5 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java @@ -568,6 +568,207 @@ private static byte[] generateAsyncContextImpl(String internalName, String super return cw.toByteArray(); } + @Test + public void asyncContextHookFailsClosedWhenLoaderCannotSeeRequestGate() { + final ServerEntries transformer = new ServerEntries(true); + final byte[] javaxImpl = generateAsyncContextImpl( + "org/example/isolated/IsolatedJavaxAsyncCtx", "java/lang/Object", + new String[] {"javax/servlet/AsyncContext"}); + final byte[] jakartaImpl = generateAsyncContextImpl( + "org/example/isolated/IsolatedJakartaAsyncCtx", "java/lang/Object", + new String[] {"jakarta/servlet/AsyncContext"}); + ClassLoader isolatedLoader = new ClassLoader(null) { }; + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + try { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + assertFalse("fresh asyncHookFailed must be false", ServerEntries.hadAsyncHookFailure()); + byte[] outJavax = transformer.transform(isolatedLoader, + "org/example/isolated/IsolatedJavaxAsyncCtx", null, null, javaxImpl); + assertEquals("unaccessible loader must leave bytecode untouched", null, outJavax); + assertTrue("javax AsyncContext in loader without RequestGate must set hadAsyncHookFailure()", + ServerEntries.hadAsyncHookFailure()); + + ServerEntries.setHookStatusForTests(false, false, false, false, false); + byte[] outJakarta = transformer.transform(isolatedLoader, + "org/example/isolated/IsolatedJakartaAsyncCtx", null, null, jakartaImpl); + assertEquals("unaccessible loader must leave jakarta bytecode untouched", null, outJakarta); + assertTrue("jakarta AsyncContext in loader without RequestGate must set hadAsyncHookFailure()", + ServerEntries.hadAsyncHookFailure()); + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + } + } + + @Test + public void jvmInternalAndServerAllowlistEntriesHaveExplicitBehaviourRows() throws Exception { + ExecutorService plain = Executors.newSingleThreadExecutor(); + Thread plainThread = new Thread(() -> { }); + Runnable plainTask = () -> { }; + String[] callerOut = new String[1]; + try { + // 1. JVM_INTERNAL_CALLER_CLASSES (exact count + behaviour at Thread/TPE/STPE/Timer sinks). + String[] expectedJvmCallers = { + "java.lang.ApplicationShutdownHooks", + "java.lang.ProcessHandleImpl", + "java.lang.ProcessImpl", + "java.lang.UNIXProcess", + "jdk.internal.ref.CleanerImpl", + "jdk.internal.ref.CleanerFactory", + "sun.misc.Cleaner", + "java.lang.ref.Cleaner", + "java.util.logging.LogManager", + "sun.net.www.http.KeepAliveCache", + "sun.net.www.http.KeepAliveCache$1", + "java.lang.VirtualThread", + "java.util.concurrent.DelayScheduler", + "jdk.internal.misc.Signal", + "sun.misc.Signal", + }; + assertEquals("exact count of JVM_INTERNAL_CALLER_CLASSES", + expectedJvmCallers.length, SinkAllowlist.JVM_INTERNAL_CALLER_CLASSES.size()); + for (String cls : expectedJvmCallers) { + assertFalse("no package wildcards: " + cls, cls.endsWith(".") || cls.endsWith("*")); + assertTrue("behaviour: JVM caller allowed at Thread.start: " + cls, + SinkAllowlist.isAllowlistedThreadStart(plainThread, cls, callerOut)); + assertEquals(cls, callerOut[0]); + assertTrue("behaviour: JVM caller allowed at TPE.execute: " + cls, + SinkAllowlist.isAllowlistedTpeExecute(plain, plainTask, cls, callerOut)); + assertTrue("behaviour: JVM caller allowed at STPE.delayedExecute: " + cls, + SinkAllowlist.isAllowlistedStpeDelayedExecute(plain, plainTask, cls, callerOut)); + assertTrue("behaviour: JVM caller allowed at Timer.sched: " + cls, + SinkAllowlist.isAllowlistedTimerSched(new Object(), plainTask, cls, callerOut)); + } + assertTrue("behaviour: java.lang.VirtualThread allowed at FJP.submit", + SinkAllowlist.isAllowlistedFjpSubmit(ForkJoinPool.commonPool(), plainTask, + "java.lang.VirtualThread", callerOut)); + + // 2. JVM_INTERNAL_THREAD_CLASSES (exact count + zero wildcards). + String[] expectedJvmThreads = { + "java.lang.ref.Reference$ReferenceHandler", + "java.lang.ref.Finalizer$FinalizerThread", + "jdk.internal.ref.CleanerImpl$InnocuousThread", + "jdk.internal.misc.InnocuousThread", + "sun.misc.InnocuousThread", + "jdk.internal.misc.CarrierThread", + "java.util.logging.LogManager$Cleaner", + }; + assertEquals("exact count of JVM_INTERNAL_THREAD_CLASSES", + expectedJvmThreads.length, SinkAllowlist.JVM_INTERNAL_THREAD_CLASSES.size()); + for (String cls : expectedJvmThreads) { + assertTrue("expected JVM thread class: " + cls, + SinkAllowlist.JVM_INTERNAL_THREAD_CLASSES.contains(cls)); + assertFalse("no package wildcards: " + cls, cls.endsWith(".") || cls.endsWith("*")); + } + + // 3. SERVER_THREAD_START_CALLERS (exact count + behaviour at Thread.start). + String[] expectedServerThreadCallers = { + "org.apache.tomcat.util.net.AbstractEndpoint", + "org.apache.tomcat.util.net.NioEndpoint", + "org.apache.tomcat.util.net.Nio2Endpoint", + "org.apache.tomcat.util.net.AprEndpoint", + "org.apache.tomcat.util.threads.ThreadPoolExecutor", + "org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor", + "org.apache.catalina.core.StandardServer", + "org.apache.catalina.core.ContainerBase", + "org.apache.catalina.startup.Catalina", + "org.apache.juli.AsyncFileHandler$LoggerExecutorService", + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", + "org.eclipse.jetty.util.thread.ExecutorThreadPool", + "org.eclipse.jetty.util.thread.TimerScheduler", + "org.xnio.nio.NioXnioWorker", + "org.xnio.XnioWorker", + "org.quartz.simpl.SimpleThreadPool", + "org.quartz.core.QuartzScheduler", + }; + assertEquals("exact count of SERVER_THREAD_START_CALLERS", + expectedServerThreadCallers.length, SinkAllowlist.SERVER_THREAD_START_CALLERS.size()); + for (String cls : expectedServerThreadCallers) { + assertFalse("no package wildcards: " + cls, cls.endsWith(".") || cls.endsWith("*")); + assertTrue("behaviour: server thread caller allowed at Thread.start: " + cls, + SinkAllowlist.isAllowlistedThreadStart(plainThread, cls, callerOut)); + assertEquals(cls, callerOut[0]); + } + + // 4. SERVER_POOL_CALLERS (exact count + behaviour at TPE & STPE). + String[] expectedServerPoolCallers = { + "org.apache.tomcat.util.net.AbstractEndpoint", + "org.apache.tomcat.util.net.NioEndpoint", + "org.apache.tomcat.util.net.Nio2Endpoint", + "org.apache.tomcat.util.net.AprEndpoint", + "org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor", + "org.apache.catalina.core.StandardServer", + "org.apache.catalina.core.ContainerBase", + "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", + "org.eclipse.jetty.util.thread.ExecutorThreadPool", + "org.xnio.XnioWorker", + }; + assertEquals("exact count of SERVER_POOL_CALLERS", + expectedServerPoolCallers.length, SinkAllowlist.SERVER_POOL_CALLERS.size()); + for (String cls : expectedServerPoolCallers) { + assertFalse("no package wildcards: " + cls, cls.endsWith(".") || cls.endsWith("*")); + assertTrue("behaviour: server pool caller allowed at TPE: " + cls, + SinkAllowlist.isAllowlistedTpeExecute(plain, plainTask, cls, callerOut)); + assertTrue("behaviour: server pool caller allowed at STPE: " + cls, + SinkAllowlist.isAllowlistedStpeDelayedExecute(plain, plainTask, cls, callerOut)); + } + + // 5. VirtualThread & TimerScheduler server caller behaviour rows. + assertTrue("behaviour: Tomcat VirtualThreadExecutor allowed at VirtualThread.start", + SinkAllowlist.isAllowlistedVirtualThreadStart(plainThread, + "org.apache.tomcat.util.threads.VirtualThreadExecutor", callerOut)); + assertTrue("behaviour: Tomcat StandardVirtualThreadExecutor allowed at VirtualThread.start", + SinkAllowlist.isAllowlistedVirtualThreadStart(plainThread, + "org.apache.catalina.core.StandardVirtualThreadExecutor", callerOut)); + assertTrue("behaviour: Jetty TimerScheduler allowed at Timer.sched", + SinkAllowlist.isAllowlistedTimerSched(new Object(), plainTask, + "org.eclipse.jetty.util.thread.TimerScheduler", callerOut)); + + // 6. Real server worker Thread, pool, and JobGate-hooked task instances behave as allowlisted. + Thread tomcatTaskThread = new org.apache.tomcat.util.threads.TaskThread( + Thread.currentThread().getThreadGroup(), plainTask, "test-task-thread"); + assertTrue("behaviour: Tomcat TaskThread allowed at Thread.start even from test caller", + SinkAllowlist.isAllowlistedThreadStart(tomcatTaskThread, JdkSinkBridgeTest.class.getName(), + callerOut)); + + org.apache.tomcat.util.threads.ThreadPoolExecutor tomcatPool = + new org.apache.tomcat.util.threads.ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new org.apache.tomcat.util.threads.TaskQueue()); + java.util.concurrent.ScheduledExecutorService delegateSched = Executors.newSingleThreadScheduledExecutor(); + org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor tomcatSched = + new org.apache.tomcat.util.threads.ScheduledThreadPoolExecutor(delegateSched); + try { + assertTrue("behaviour: Tomcat ThreadPoolExecutor allowed at TPE.execute", + SinkAllowlist.isAllowlistedTpeExecute(tomcatPool, plainTask, + JdkSinkBridgeTest.class.getName(), callerOut)); + assertTrue("behaviour: Tomcat ScheduledThreadPoolExecutor allowed at STPE.delayedExecute", + SinkAllowlist.isAllowlistedStpeDelayedExecute(tomcatSched, plainTask, + JdkSinkBridgeTest.class.getName(), callerOut)); + } finally { + tomcatPool.shutdownNow(); + tomcatSched.shutdownNow(); + delegateSched.shutdownNow(); + } + + Runnable schedMethodRunnable = new org.springframework.scheduling.support.ScheduledMethodRunnable( + this, JdkSinkBridgeTest.class.getMethod("unarmedHandOffOutsideWindowLatchesAsyncExecutorsFalse")); + assertTrue("behaviour: JobGate-hooked ScheduledMethodRunnable allowed at TPE & STPE", + SinkAllowlist.isAllowlistedTpeExecute(plain, schedMethodRunnable, + JdkSinkBridgeTest.class.getName(), callerOut)); + assertTrue("behaviour: JobGate-hooked ScheduledMethodRunnable allowed at STPE", + SinkAllowlist.isAllowlistedStpeDelayedExecute(plain, schedMethodRunnable, + JdkSinkBridgeTest.class.getName(), callerOut)); + + // Pin exact sizes of SERVER_WORKER_THREAD_CLASSES, SERVER_POOL_CLASSES, SERVER_TASK_CLASSES. + assertEquals(7, SinkAllowlist.SERVER_WORKER_THREAD_CLASSES.size()); + assertEquals(3, SinkAllowlist.SERVER_POOL_CLASSES.size()); + assertEquals(9, SinkAllowlist.SERVER_TASK_CLASSES.size()); + } finally { + plain.shutdownNow(); + } + } + @Test public void unarmedHandOffOutsideWindowLatchesAsyncExecutorsFalse() { boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get();