private ContainedInRecursionContext updateContainedInRecursionContext(
      Object containedInstance,
      ContainedInMetadata containedInMetadata,
      ContainedInRecursionContext containedContext) {
    int maxDepth;
    int depth;

    // Handle @IndexedEmbedded.depth-induced limits

    Integer metadataMaxDepth = containedInMetadata.getMaxDepth();
    if (containedInstance != null && metadataMaxDepth != null) {
      maxDepth = metadataMaxDepth;
    } else {
      maxDepth = containedContext != null ? containedContext.getMaxDepth() : Integer.MAX_VALUE;
    }

    depth = containedContext != null ? containedContext.getDepth() : 0;
    if (depth < Integer.MAX_VALUE) { // Avoid integer overflow
      ++depth;
    }

    /*
     * Handle @IndexedEmbedded.includePaths-induced limits If the context for the contained element has a
     * comprehensive set of included paths, and if the @IndexedEmbedded matching the @ContainedIn we're currently
     * processing also has a comprehensive set of embedded paths, *then* we can compute the resulting set of
     * embedded fields (which is the intersection of those two sets). If this resulting set is empty, we can safely
     * stop the @ContainedIn processing: any changed field wouldn't be included in the Lucene document for
     * "containerInstance" anyway.
     */

    Set<String> comprehensivePaths;
    Set<String> metadataIncludePaths = containedInMetadata.getIncludePaths();

    /*
     * See @IndexedEmbedded.depth: it should be considered as zero if it has its default value and if includePaths
     * contains elements
     */
    if (metadataIncludePaths != null
        && !metadataIncludePaths.isEmpty()
        && metadataMaxDepth != null
        && metadataMaxDepth.equals(Integer.MAX_VALUE)) {
      String metadataPrefix = containedInMetadata.getPrefix();

      /*
       * If the contained context Filter by contained context's included paths if they are comprehensive This
       * allows to detect when a @ContainedIn is irrelevant because the matching @IndexedEmbedded would not
       * capture any property.
       */
      Set<String> containedComprehensivePaths =
          containedContext != null ? containedContext.getComprehensivePaths() : null;

      comprehensivePaths = new HashSet<>();
      for (String includedPath : metadataIncludePaths) {
        /*
         * If the contained context has a comprehensive list of included paths, use it to filter out our own
         * list
         */
        if (containedComprehensivePaths == null
            || containedComprehensivePaths.contains(includedPath)) {
          comprehensivePaths.add(metadataPrefix + includedPath);
        }
      }
    } else {
      comprehensivePaths = null;
    }

    return new ContainedInRecursionContext(maxDepth, depth, comprehensivePaths);
  }