```python:inference/core/workflows/execution_engine/v1/executor/execution_data_manager/step_input_assembler.py
from typing import Dict, Set

from inference.core.workflows.execution_engine.v1.executor.execution_data_manager.dynamic_batches_manager import \
    DynamicBatchIndex


def filter_to_valid_prefix_chains(
    per_dim_sets: Dict[int, Set[DynamicBatchIndex]],
    dimensions: Set[int],
) -> Dict[int, Set[DynamicBatchIndex]]:
    """Keep only indices that form a complete parent-child chain across dimensions.

    Given per-dimension sets (e.g. from intersect_masks_per_dimension), retains
    only indices that have a full lineage from the smallest to the largest
    dimension. Used for inter-level intersection.
    """
    sorted_dims = sorted(dimensions)
    by_dim: Dict[int, Set[DynamicBatchIndex]] = {
        dim: per_dim_sets.get(dim, set()) for dim in sorted_dims
    }

    if len(sorted_dims) <= 1:
        return dict(by_dim)

    prev_dim = {sorted_dims[i]: sorted_dims[i - 1] for i in range(1, len(sorted_dims))}

    # Bottom-up: mark indices that have at least one descendant
    has_child: Set[DynamicBatchIndex] = set()
    last_dim = sorted_dims[-1]
    for dim in reversed(sorted_dims):
        is_last_dim = (dim == last_dim)
        dim_indices = by_dim[dim]
        
        for idx in dim_indices:
            if is_last_dim or idx in has_child:
                parent = idx[:-1]
                if parent:
                    has_child.add(parent)

    # Top-down: keep indices only if full prefix chain exists
    valid: Dict[int, Set[DynamicBatchIndex]] = {dim: set() for dim in sorted_dims}
    first_dim = sorted_dims[0]
    
    for dim in sorted_dims:
        is_first_dim = (dim == first_dim)
        is_last_dim = (dim == last_dim)
        dim_indices = by_dim[dim]
        valid_dim = valid[dim]
        
        if is_first_dim:
            # First dimension: only keep if has children
            for idx in dim_indices:
                if idx in has_child:
                    valid_dim.add(idx)
        else:
            # Other dimensions: check parent chain
            valid_parent_dim = valid[prev_dim[dim]]
            
            if is_last_dim:
                # Last dimension: no need to check has_child
                for idx in dim_indices:
                    parent = idx[:-1]
                    if parent in valid_parent_dim:
                        valid_dim.add(idx)
            else:
                # Middle dimensions: check both parent and has_child
                for idx in dim_indices:
                    parent = idx[:-1]
                    if parent in valid_parent_dim and idx in has_child:
                        valid_dim.add(idx)

    return valid
```