Class LeafSelection

java.lang.Object
com.google.genkit.ai.agent.internal.LeafSelection

public final class LeafSelection extends Object
Utility for selecting the leaf snapshot from a collection of snapshots in a session's parent-chain.

A leaf is a snapshot whose snapshotId is not referenced as a parentId by any other snapshot in the list.

  • Method Details

    • selectLeaf

      public static <S> SessionSnapshot<S> selectLeaf(List<SessionSnapshot<S>> snapshots, boolean rejectBranching)
      Selects the leaf snapshot from the given list.

      Selection rules:

      1. Empty list — returns null. An empty input carries no information about a cycle, so returning null (no snapshot found) is the correct behaviour.
      2. Exactly one leaf — returns it directly.
      3. Zero leaves in a non-empty list — the chain is corrupt (cycle). Throws GenkitException with error code FAILED_PRECONDITION.
      4. More than one leaf — if rejectBranching is true, throws GenkitException with error code FAILED_PRECONDITION. Otherwise the most recent leaf is returned (by createdAt parsed as Instant; null createdAt is treated as the epoch / earliest). Ties are broken by snapshotId in natural (lexicographic) ascending order, taking the greater ID.
      Type Parameters:
      S - the type of custom session state
      Parameters:
      snapshots - the full list of snapshots for a session (may be empty)
      rejectBranching - if true, more than one leaf is treated as an error
      Returns:
      the selected leaf snapshot, or null if the input list is empty
      Throws:
      GenkitException - with FAILED_PRECONDITION when the chain contains a cycle or (with rejectBranching=true) multiple leaves