def _topological_sort(key_less_than_values):
  """Topological sort for monotonicities.

  Args:
    key_less_than_values: A defaultdict from index to a list of indices, such
      that for j in key_less_than_values[i] we must have output(i) <= output(j).

  Returns:
    A topologically sorted list of indices.

  Raises:
    ValueError: If monotonicities are circular.
  """
  all_values = set()
  for values in key_less_than_values.values():
    all_values.update(values)

  q = [k for k in key_less_than_values if k not in all_values]
  if not q:
    raise ValueError(
        "Circular monotonicity constraints: {}".format(key_less_than_values))

  result = []
  seen = set()
  while q:
    v = q[-1]
    seen.add(v)
    expand = [x for x in key_less_than_values[v] if x not in seen]
    if not expand:
      result = [v] + result
      q.pop()
    else:
      q.append(expand[0])

  return result