Skip to content

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
mainfrom
feat/r1-java-honest-protocol

Conversation

@slayerjain

Copy link
Copy Markdown
Member

Summary

Implements the v3 Java coverage-honesty protocol in keploy-sdk so 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.

Cross-repo compatibility note:

  • Kubernetes TCP path (k8s-proxy): Existing released k8s-proxy collectors ignore HELLO and continue working unchanged with bare ACK and no unsolicited BACKGROUND frames. Parsing the new v3 HELLO identity/capabilities and COV honesty fields (windowCut, contaminated, unverified, classMismatch) — including failing closed on any non-empty "unverified" — is handled by the paired k8s-proxy collector PR, which must land before this SDK is released. As additional SDK-side safeguards: (1) once any END observes probes recorded with enteredCount == 0 (noServerEntry), the SDK logs once at INFO, permanently latches windowCut=false (and asyncExecutors=false), and refreshes HELLO before emitting that COV so even collectors that gate only on HELLO capabilities never treat uncounted servers as honest; and (2) once any executor or async method reference targeting a real untracked executor/async API (e.g. ((Executor) tpe)::execute, pool::submit, Executor::execute) is captured outside an active request window or tracked job (such as in a Spring bean constructor or static field at startup), the SDK logs once at INFO, permanently latches asyncExecutors=false, and refreshes HELLO / Unix ACK caps (plain non-Executor helpers, allow-listed inline executors, and hooked+verified Spring executors do not trip the latch). Recall trade-off: both latches are permanent for the life of the JVM, so in mixed-server apps (e.g., an app serving both a counted Tomcat port and an uncounted HTTP server) or apps that pre-capture an untracked executor method reference at startup, hard removal stays disabled (soft-mark only) for the rest of that JVM run. Because capabilities can downgrade mid-session (e.g. windowCut: true -> false or asyncExecutors: true -> false), paired k8s-proxy and enterprise parsers must apply the latest capability values (or AND across observed values) rather than freezing the initial handshake.
  • Local/Docker Unix socket path (enterprise): Existing released enterprise parses ACK proto=N ... via strings.Fields checking n >= 2 and ignoring extra tokens, and ignores the unknown "unverified" JSON field. For no-server-entry (uncounted servers such as WebFlux/Netty, gRPC, Vert.x, Micronaut, JDK HttpServer, Armeria, Helidon, Play), this preserves existing dedup behavior on older enterprise collectors while v3 collectors fail closed on any non-empty "unverified". For real contamination (tail:, untracked-*, armed-mid-flight, listener names) carried in "contaminated", older enterprise collectors fail closed per test (NOT_MEASURED), and suppressed background gaps ("lost" > 0) mark background incomplete so no background lines are subtracted for that set. Parsing the new caps=... token (including ackId=true so Unix and TCP share the same IsHonest("java", caps) predicate) to write the # honesty: header in local/Docker dedupData.yaml is handled by the paired enterprise parser update.

What Changed

  1. v3 HELLO identity & live capability declaration + Unix ACK proto=3 caps=... (KeployDedupAgent.java, BuildTable.java)

    • Emits HELLO {"proto":3,"sdkVersion":...,"podUid":...,"podName":...,"sessionId":...,"jvmNonce":...,"buildId":...,"windowCut":...,"contaminated":...,"classMismatch":...,"background":...,"ackId":...,"nopResync":...,"asyncExecutors":...,"listenerContamination":...} on TCP connect (guarded with a RuntimeException fallback to a minimal empty-identity HELLO so a deterministic throw can never cause an infinite reconnect loop, and refreshed mid-stream if capabilities change).
    • Reads podUid, podName, sessionId from KEPLOY_DEDUP_POD_UID / KEPLOY_DEDUP_POD_NAME / KEPLOY_DEDUP_SESSION_ID, lazily generates a per-JVM jvmNonce UUID once per startup (stable across TCP reconnects, distinct across JVM restarts, zero SecureRandom startup cost when disabled), and computes a deterministic non-empty buildId without blocking connect.
    • Computes windowCut from transformerAdded && endWaitMillis > 0 && !hasUncountedServer && !hadServerHookFailure && !observedNoServerEntry (detecting Netty, Reactor Netty, gRPC, Vert.x, Micronaut, and JDK HttpServer as uncounted) so Jetty/Undertow cold-start pods honestly report windowCut=true before the first request loads HttpChannel/Connectors. At runtime, any window recording probes while enteredCount == 0 (and no job contamination) latches observedNoServerEntry = true (permanently dropping windowCut and asyncExecutors to false for the rest of the JVM, refreshing HELLO before that COV on TCP and reporting windowCut=false on that and subsequent Unix ACKs) and emits "unverified": ["no-server-entry"] (omitted when empty, kept separate from "contaminated").
    • Computes asyncExecutors=true only when windowCut is true, KEPLOY_JAVA_ASYNC_CALLSITES is not off, app-only targeting is active (not whole-jar or classpath fallback), the JPMS guard did not skip app classes, no app-class call-site rewrite failed or hit an isolated class loader, and observedPreCapturedUntrackedExecutor is false (no real untracked executor/async method reference was captured outside an active request window or tracked job; if one is observed, asyncExecutors latches false permanently for the JVM and refreshes TCP HELLO / Unix ACK caps).
    • Computes listenerContamination from 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 Redis RedisMessageListenerContainer, Apache Pulsar, GCP Pub/Sub, or direct app calls to KafkaConsumer.poll, RabbitMQ Channel.basicConsume, or JMS MessageConsumer.receive/setMessageListener — scanned read-only even when KEPLOY_JAVA_ASYNC_CALLSITES=off).
    • Updates the Unix CommandServer reply to ACK proto=3 caps=windowCut=<bool>,contaminated=<bool>,classMismatch=<bool>,background=<bool>,ackId=true,asyncExecutors=<bool>,listenerContamination=<bool> (no spaces in caps=..., < 1024 bytes, compatible with released enterprise strings.Fields parsing) and IGNORED proto=3.
    • Keeps bare ACK as the TCP default until ACK_ID is sent, keeps NOP [<token>] resync barriers and opt-in TCP BACKGROUND, suppresses BACKGROUND (and increments backgroundLost / "lost":N) on both TCP and Unix START whenever opening the new window added tail:, job-tail:, or armed-mid-flight or the previous window had active lingering/untracked async work or no-server-entry, isolates HELLO refreshes from COV/ACK lockstep on both START and END, keeps HELLO buildId stable per connection, and computes coverageIndex.report() off the TCP command thread and outside CoverageIndex.lock so large apps never stall END.
  2. Cut-tail, untracked-tail, & expired-job contamination (RequestGate.java, JobGate.java, KeployDedupAgent.java)

    • Retains lingering/cut prior RequestGate windows, unclosed prior tests when START arrives without END, and windows that recorded untracked async hand-offs: blind untracked hand-offs (no trackable handle) retain a untrackedTailWindowNanos (default 2s) tail, while handle-tracked hand-offs (ScheduledFuture, Thread, TimerTask — including TimerTask.cancel() / Timer.cancel() interception and scheduledExecutionTime() tracking so cancelled 30s timeouts, joined threads, and cancelled TimerTasks 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 so maxLingeringNanos (30s) bounds stuck/abandoned futures without ever dropping actively executing tasks; any late-starting task from an old closed window (even after maxLingeringNanos expiry) immediately contaminates the currently open window with tail:<prevTestId> before its first probe runs (and suppresses BACKGROUND for the preceding gap), and Dekker post-remove re-checks close the LINGERING.remove TOCTOU race.
    • Retains expired handed-off JobGate runs (past handedJobMaxNanos = 30s, including multi-hop self-resubmitting loops and fan-outs via expired Attribution propagation on verified executors) while they are still executing, marking every overlapping window contaminated: ["job-tail:<name>"] until exit() actually runs.
    • Tracks job-originated CompletableFuture dependent stages via deferred JobGate release across postComplete() and flags job-originated unknown-executor / untracked-async hand-offs on both the active JobGate window and the following RequestGate window.
  3. Fail-closed executor wrapping, CompletableFuture / CompletionStage tracking, untracked async flagging, and kill switch (OrderedPools.java, RequestGate.java, ServerEntries.java)

    • OrderedPools fails CLOSED: wraps only positively verified safe executors (exact ThreadPoolExecutor / ScheduledThreadPoolExecutor with exact AbortPolicy and exact in-order JDK queues, exact ForkJoinPool, verified JDK Delegated* / ThreadPerTaskExecutor, and actual Spring executor/adapter hierarchies whose subclasses do not override execute/submit/doExecute and whose inner pool is allow-listed). Known same-thread inline executors (org.springframework.core.task.SyncTaskExecutor and Guava DirectExecutor / MoreExecutors.directExecutor() / DirectExecutorService) are allow-listed so they are neither wrapped nor flagged untracked-executor. Plain non-Executor synchronous helpers (e.g. TxHelper.execute(Runnable) or submit(Runnable) — both direct calls and bound/unbound method references) are filtered out at runtime (instanceof Executor on the receiver for direct/bound calls or Executor.class.isAssignableFrom on the handle's declaring owner class for unbound method references, and ExecutorService / CompletionService / Spring AsyncTaskExecutor for submit*) before checking armed and never falsely flagged.
    • Unknown/custom executors (Hazelcast, Ignite, Redisson, striped/coalescing executors, custom ExecutorService / ThreadPoolExecutor / Spring executor subclasses, priority queues, non-AbortPolicy handlers) and Comparable tasks receive the original task untouched and mark the window (and following tail window) contaminated: ["untracked-executor:<class>"].
    • Holds CompletableFuture.supplyAsync / runAsync / completeAsync, *Async instance stages, and plain dependent stages on incomplete futures (including JDK HttpClient.sendAsync's MinimalFuture and JDK 9+ MinimalStage without calling unguarded isDone()) permits until a whenComplete registered before returning the future executes (LIFO postComplete() ensures synchronous dependents complete before permit release, while early complete() during execution still waits for task exit), with ReferenceQueue permit recovery for GC'd abandoned futures.
    • Rewrites CompletableFuture and CompletionStage (*Async and plain dependent stages, plus JDK 9+/12+ completeAsync, exceptionallyCompose, exceptionallyAsync, exceptionallyComposeAsync via reflection to preserve --release 8 compatibility).
    • Contamination & liveness tracking for untracked async submission sites: ScheduledExecutorService.schedule* (weak ScheduledFuture liveness tracking + zero-permit context propagation on verified JDK ScheduledThreadPoolExecutor across multi-hop retries and downstream fan-outs without blocking END), Spring TaskScheduler.schedule* (weak ScheduledFuture liveness tracking), java.util.Timer.schedule* / scheduleAtFixedRate* (weak TimerTask liveness + TimerTask.cancel() / Timer.cancel() tracking for both one-shot and 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() / TERMINATED tracking, non-JDK execute/submit/submitCompletable call sites and bound/unbound method references decided at runtime by receiver/owner type (with Executor / ExecutorService / CompletionService / Spring AsyncTaskExecutor guards), ForkJoinPool.execute/submit(ForkJoinTask) and ForkJoinTask.fork(), Guava ListenableFuture.addListener / Futures.addCallback/transform*/catching*, Reactor Mono/Flux/ParallelFlux .subscribe(), custom CompletionStage, and other async method references. (Custom ScheduledExecutorService, raw Thread / virtual threads, Timer, and Spring TaskScheduler run tasks unwrapped so nested hops spawned inside them are not tracked beyond the parent handle's lifetime.)
    • Adds KEPLOY_JAVA_ASYNC_CALLSITES=off kill switch.
    • Applies shaded/relocated filtering (/shaded/, /relocated/, /repackaged/) ONLY in external-JaCoCo appPackagePrefix mode; exact indexed app classes (including org/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 in KEPLOY_JAVA_CLASS_DIRS.
  4. App-safety, memory safety, no-op when Keploy is absent, and cached listener attribution (RequestGate.java, JobGate.java)

    • Gates runtime request/executor/job tracking behind 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 marked contaminated: ["armed-mid-flight"].
    • Eliminates global synchronized monitors in RequestGate and JobGate (virtual-thread safe lock-free ConcurrentHashMap structures), fixes PENDING_BY_FUTURE self-referencing retention leak (weak values + eager removal on task start and release), recovers permits via ReferenceQueue for abandoned tasks (getQueue().clear()/purge()) and abandoned CompletableFuture stages, 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

  • Full test suite (mvn -B -pl keploy-sdk -am test, JDK 21 with --release 8, commit 56f289a4debd25d7e83b2ee66e89caf7adc61944, tree 27f08235b8911fac052e758b6d0cc43d7331234e): Tests run: 419, Failures: 0, Errors: 0, Skipped: 0 (BUILD SUCCESS, Java8ApiTest 2/2 PASS).
  • Mutation verification for open-time BACKGROUND suppression (RequestGate.open returning false instead of next.hasOpeningTail() on commit 88567de): both the TCP and Unix regression tests (lateStartingExpiredLingeringTaskSuppressesBackgroundViaRequestGateOpenOnTcp and ...OnUnix) fail as expected (Tests run: 2, Failures: 2, Errors: 0, Skipped: 0).
  • CI matrix note: GitHub Actions runs the full suite across JDK 8, 17, and 21 on PR submission.

…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant