Repository navigation
feat(dedup): add v3 honest protocol (HELLO identity & unix caps), fail-closed async executor & CompletableFuture tracking, cut-tail contamination, and lock-free listener attribution - #196
Open
slayerjain wants to merge 19 commits into
Conversation
…er contamination Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…-in ACK_ID, cancel/pool guards Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…O refresh, chained job deadline, unwrapped Futures, complete pool guards Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…hop-1 job budget, Spring 6 scheduler & JPMS module tests Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…ue, race-free tracking test, positive control in JPMS test Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…ls, CF dependents, tail contamination, lock-free gates, unarmed no-op Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…ight, and fail-closed gaps Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…ts, runtime Spring receiver check, delay-aware schedule tail, and S2/S4/S6 fixes Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…duledFuture handles, multi-hop expired jobs, JDK 21 virtual threads, and flag-site tests Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…ation & Dekker LINGERING check, Timer delay/periodic tracking, ScheduledThreadPoolExecutor multi-hop context, and JDK 21 virtual-thread liveness proof Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…handle liveness and delay extension across unit and forked JDK 21 tests Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…use deterministic Thread.join in forked virtual-thread release Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…runtime guard, handle-driven tail & TimerTask cancel, BACKGROUND tail suppression, inline executors, HELLO connect guard, and unix ackId=true Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…l-return tracking (no JDK-internal reflection), 2-arg submit runtime check, active-lingering BACKGROUND suppression, and full Unix/TCP/inline/HELLO tests Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…el() post-call margin, and complete B1/Timer.cancel/DirectExecutorService test coverage Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…raise Timer.cancel() margin to 20ms Signed-off-by: slayerjain <shubhamkjain@outlook.com>
… on noServerEntry, and test open-time BACKGROUND suppression Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…d refs and polish logs/comments Signed-off-by: slayerjain <shubhamkjain@outlook.com>
…d in smoke-javaagent.sh Signed-off-by: slayerjain <shubhamkjain@outlook.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implements the v3 Java coverage-honesty protocol in
keploy-sdkso both Kubernetes auto-replay and local/Docker deduplication can distinguish honest, complete per-test coverage windows from truncated, background-polluted, untracked-async, or legacy-SDK windows without breaking existing released collectors.What Changed
v3
HELLOidentity & live capability declaration + UnixACK proto=3 caps=...(KeployDedupAgent.java,BuildTable.java)HELLO {"proto":3,"sdkVersion":...,"podUid":...,"podName":...,"sessionId":...,"jvmNonce":...,"buildId":...,"windowCut":...,"contaminated":...,"classMismatch":...,"background":...,"ackId":...,"nopResync":...,"asyncExecutors":...,"listenerContamination":...}on TCP connect (guarded with aRuntimeExceptionfallback to a minimal empty-identityHELLOso a deterministic throw can never cause an infinite reconnect loop, and refreshed mid-stream if capabilities change).podUid,podName,sessionIdfromKEPLOY_DEDUP_POD_UID/KEPLOY_DEDUP_POD_NAME/KEPLOY_DEDUP_SESSION_ID, lazily generates a per-JVMjvmNonceUUID once per startup (stable across TCP reconnects, distinct across JVM restarts, zeroSecureRandomstartup cost when disabled), and computes a deterministic non-emptybuildIdwithout blocking connect.windowCutfromtransformerAdded && endWaitMillis > 0 && !hasUncountedServer && !hadServerHookFailure && !observedNoServerEntry(detecting Netty, Reactor Netty, gRPC, Vert.x, Micronaut, and JDKHttpServeras uncounted) so Jetty/Undertow cold-start pods honestly reportwindowCut=truebefore the first request loadsHttpChannel/Connectors. At runtime, any window recording probes whileenteredCount == 0(and no job contamination) latchesobservedNoServerEntry = true(permanently droppingwindowCutandasyncExecutorstofalsefor the rest of the JVM, refreshingHELLObefore thatCOVon TCP and reportingwindowCut=falseon that and subsequent Unix ACKs) and emits"unverified": ["no-server-entry"](omitted when empty, kept separate from"contaminated").asyncExecutors=trueonly whenwindowCutis true,KEPLOY_JAVA_ASYNC_CALLSITESis notoff, app-only targeting is active (notwhole-jarorclasspathfallback), the JPMS guard did not skip app classes, no app-class call-site rewrite failed or hit an isolated class loader, andobservedPreCapturedUntrackedExecutorisfalse(no real untracked executor/async method reference was captured outside an active request window or tracked job; if one is observed,asyncExecutorslatchesfalsepermanently for the JVM and refreshes TCPHELLO/ UnixACKcaps).listenerContaminationfrom transformer attachment, absence of listener hook/visibility failures, and absence of unhooked messaging consumers (Kafka Streams, Reactor Kafka, Spring Cloud / AWS SQS sync & async, Spring Data RedisRedisMessageListenerContainer, Apache Pulsar, GCP Pub/Sub, or direct app calls toKafkaConsumer.poll, RabbitMQChannel.basicConsume, or JMSMessageConsumer.receive/setMessageListener— scanned read-only even whenKEPLOY_JAVA_ASYNC_CALLSITES=off).CommandServerreply toACK proto=3 caps=windowCut=<bool>,contaminated=<bool>,classMismatch=<bool>,background=<bool>,ackId=true,asyncExecutors=<bool>,listenerContamination=<bool>(no spaces incaps=..., < 1024 bytes, compatible with releasedenterprisestrings.Fieldsparsing) andIGNORED proto=3.ACKas the TCP default untilACK_IDis sent, keepsNOP [<token>]resync barriers and opt-in TCPBACKGROUND, suppressesBACKGROUND(and incrementsbackgroundLost/"lost":N) on both TCP and UnixSTARTwhenever opening the new window addedtail:,job-tail:, orarmed-mid-flightor the previous window had active lingering/untracked async work orno-server-entry, isolatesHELLOrefreshes fromCOV/ACKlockstep on bothSTARTandEND, keepsHELLObuildIdstable per connection, and computescoverageIndex.report()off the TCP command thread and outsideCoverageIndex.lockso large apps never stallEND.Cut-tail, untracked-tail, & expired-job contamination (
RequestGate.java,JobGate.java,KeployDedupAgent.java)RequestGatewindows, unclosed prior tests whenSTARTarrives withoutEND, and windows that recorded untracked async hand-offs: blind untracked hand-offs (no trackable handle) retain auntrackedTailWindowNanos(default 2s) tail, while handle-tracked hand-offs (ScheduledFuture,Thread,TimerTask— includingTimerTask.cancel()/Timer.cancel()interception andscheduledExecutionTime()tracking so cancelled 30s timeouts, joined threads, and cancelledTimerTasks never keep subsequent windows tainted) drive tail contamination strictly from handle liveness (failing closed up to 30s if the 64-handle cap overflows). Tracks actively executing work (Window.executing > 0) separately from idle uncompleted permits somaxLingeringNanos(30s) bounds stuck/abandoned futures without ever dropping actively executing tasks; any late-starting task from an old closed window (even aftermaxLingeringNanosexpiry) immediately contaminates the currently open window withtail:<prevTestId>before its first probe runs (and suppressesBACKGROUNDfor the preceding gap), and Dekker post-remove re-checks close theLINGERING.removeTOCTOU race.JobGateruns (pasthandedJobMaxNanos = 30s, including multi-hop self-resubmitting loops and fan-outs via expiredAttributionpropagation on verified executors) while they are still executing, marking every overlapping windowcontaminated: ["job-tail:<name>"]untilexit()actually runs.CompletableFuturedependent stages via deferredJobGaterelease acrosspostComplete()and flags job-originated unknown-executor / untracked-async hand-offs on both the activeJobGatewindow and the followingRequestGatewindow.Fail-closed executor wrapping,
CompletableFuture/CompletionStagetracking, untracked async flagging, and kill switch (OrderedPools.java,RequestGate.java,ServerEntries.java)OrderedPoolsfails CLOSED: wraps only positively verified safe executors (exactThreadPoolExecutor/ScheduledThreadPoolExecutorwith exactAbortPolicyand exact in-order JDK queues, exactForkJoinPool, verified JDKDelegated*/ThreadPerTaskExecutor, and actual Spring executor/adapter hierarchies whose subclasses do not overrideexecute/submit/doExecuteand whose inner pool is allow-listed). Known same-thread inline executors (org.springframework.core.task.SyncTaskExecutorand GuavaDirectExecutor/MoreExecutors.directExecutor()/DirectExecutorService) are allow-listed so they are neither wrapped nor flaggeduntracked-executor. Plain non-Executorsynchronous helpers (e.g.TxHelper.execute(Runnable)orsubmit(Runnable)— both direct calls and bound/unbound method references) are filtered out at runtime (instanceof Executoron the receiver for direct/bound calls orExecutor.class.isAssignableFromon the handle's declaring owner class for unbound method references, andExecutorService/CompletionService/ SpringAsyncTaskExecutorforsubmit*) before checkingarmedand never falsely flagged.ExecutorService/ThreadPoolExecutor/ Spring executor subclasses, priority queues, non-AbortPolicyhandlers) andComparabletasks receive the original task untouched and mark the window (and following tail window)contaminated: ["untracked-executor:<class>"].CompletableFuture.supplyAsync/runAsync/completeAsync,*Asyncinstance stages, and plain dependent stages on incomplete futures (including JDKHttpClient.sendAsync'sMinimalFutureand JDK 9+MinimalStagewithout calling unguardedisDone()) permits until awhenCompleteregistered before returning the future executes (LIFOpostComplete()ensures synchronous dependents complete before permit release, while earlycomplete()during execution still waits for task exit), withReferenceQueuepermit recovery for GC'd abandoned futures.CompletableFutureandCompletionStage(*Asyncand plain dependent stages, plus JDK 9+/12+completeAsync,exceptionallyCompose,exceptionallyAsync,exceptionallyComposeAsyncvia reflection to preserve--release 8compatibility).ScheduledExecutorService.schedule*(weakScheduledFutureliveness tracking + zero-permit context propagation on verified JDKScheduledThreadPoolExecutoracross multi-hop retries and downstream fan-outs without blockingEND), SpringTaskScheduler.schedule*(weakScheduledFutureliveness tracking),java.util.Timer.schedule*/scheduleAtFixedRate*(weakTimerTaskliveness +TimerTask.cancel()/Timer.cancel()tracking for both one-shot and periodic tasks),ExecutorService.invokeAny,Thread.start()including subclasses via runtimeinstanceof Threadcheck and JDK 21Thread.startVirtualThread/Thread.Builder.startwith weakThread.isAlive()/TERMINATEDtracking, non-JDKexecute/submit/submitCompletablecall sites and bound/unbound method references decided at runtime by receiver/owner type (withExecutor/ExecutorService/CompletionService/ SpringAsyncTaskExecutorguards),ForkJoinPool.execute/submit(ForkJoinTask)andForkJoinTask.fork(), GuavaListenableFuture.addListener/Futures.addCallback/transform*/catching*, ReactorMono/Flux/ParallelFlux.subscribe(), customCompletionStage, and other async method references. (CustomScheduledExecutorService, rawThread/ virtual threads,Timer, and SpringTaskSchedulerrun tasks unwrapped so nested hops spawned inside them are not tracked beyond the parent handle's lifetime.)KEPLOY_JAVA_ASYNC_CALLSITES=offkill switch./shaded/,/relocated/,/repackaged/) ONLY in external-JaCoCoappPackagePrefixmode; exact indexed app classes (includingorg/springframework/samples/...such as Spring PetClinic) are rewritten without shaded-package filtering while still protecting core third-party libraries (Netty, OkHttp, gRPC, AWS SDK, etc.) if misconfigured inKEPLOY_JAVA_CLASS_DIRS.App-safety, memory safety, no-op when Keploy is absent, and cached listener attribution (
RequestGate.java,JobGate.java)armed(zero-allocation static sentinel token and zero task wrapping when Keploy is absent, with 1 ms throttled timestamping for unarmed hand-offs); 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 markedcontaminated: ["armed-mid-flight"].synchronizedmonitors inRequestGateandJobGate(virtual-thread safe lock-freeConcurrentHashMapstructures), fixesPENDING_BY_FUTUREself-referencing retention leak (weak values + eager removal on task start and release), recovers permits viaReferenceQueuefor abandoned tasks (getQueue().clear()/purge()) and abandonedCompletableFuturestages, re-acquires permit and re-retains window if a late worker runs a task after pending release, and caches per-container Kafka/AMQP/JMS topic/queue/destination + listener bean attribution.Verification
mvn -B -pl keploy-sdk -am test, JDK 21 with--release 8, commit56f289a4debd25d7e83b2ee66e89caf7adc61944, tree27f08235b8911fac052e758b6d0cc43d7331234e):Tests run: 419, Failures: 0, Errors: 0, Skipped: 0(BUILD SUCCESS,Java8ApiTest2/2 PASS).BACKGROUNDsuppression (RequestGate.openreturningfalseinstead ofnext.hasOpeningTail()on commit88567de): both the TCP and Unix regression tests (lateStartingExpiredLingeringTaskSuppressesBackgroundViaRequestGateOpenOnTcpand...OnUnix) fail as expected (Tests run: 2, Failures: 2, Errors: 0, Skipped: 0).