def find_border_crossing(subset, path, final_state):
    """
    Find the transition that steps outside the safe L{subset}.

    @param subset: Set of states that are safe.
    @type  subset: C{set} of L{State}

    @param path: Path from starting state to L{final_state}, sequence of state
                 and its outgoing edge.
    @type  path: C{list} of pairs (L{State}, L{Event}

    @param final_state: Final state of the path.
    @type  final_state: L{State}

    @return: C{None} if the path stays within the safe subset, else a triplet
             (from-state, event, dest-state).
    @rtype:  Either C{None} or (L{State}, L{Event}, L{State})

    @precond: Initial state of the path must be in L{subset}
    """
    if len(path) == 0:
        # No path => final_state is also the first state => must be safe
        assert final_state in subset
        return None

    assert path[0][0] in subset

    pred_state, pred_evt = None, None
    for state, evt in path:
        if pred_state is not None and state not in subset:
            # Tests may hold for the second or further entry of the path
            return (pred_state, pred_evt, state)

        pred_state, pred_evt = state, evt

    if final_state in subset:
        return None

    return (pred_state, pred_evt, final_state)