Class CancellationChain

java.lang.Object
dev.langchain4j.internal.CancellationChain

public final class CancellationChain extends Object
Propagates cancellation from a single caller-facing "root" future to every downstream future produced while composing an asynchronous, possibly fan-out, pipeline (e.g. the RAG graph: transform → route → retrieve over many queries × retrievers).

CompletableFuture.cancel(boolean) does not propagate to the stages a future was derived from, so in a deep or wide composition each in-flight leaf must be wired back to the root individually (see CompletableFutureUtils.propagateCancellation(CompletableFuture, CompletableFuture)). Doing that by hand at every call site is easy to get wrong — a single missed hop leaks an in-flight call that keeps running after the caller cancelled. This class collapses the wiring to one rule: every future that represents real work enters the pipeline through track(CompletableFuture).

If the root is already cancelled when a later leaf is tracked (cancellation landed mid-pipeline), propagateCancellation fires immediately and cancels that leaf on creation, so dynamically-created fan-out branches are covered without maintaining a separate registry.

Not thread-safe to construct, but track(CompletableFuture) and cancelled() may be called from any thread once constructed; they only read the root and register a completion callback on it.

Since:
1.20.0
  • Constructor Details

    • CancellationChain

      public CancellationChain(CompletableFuture<?> root)
      Parameters:
      root - the caller-facing future whose cancellation should be propagated to every tracked future.
  • Method Details

    • track

      public <T> CompletableFuture<T> track(CompletableFuture<T> future)
      Registers future so it is cancelled whenever the root is cancelled, and returns it unchanged for fluent composition.
      Parameters:
      future - a future representing in-flight work (a leaf I/O call or a composite of such calls).
      Returns:
      the same future.
    • cancelled

      public boolean cancelled()
      Returns:
      true if the root future has been cancelled; useful to short-circuit before starting new work.