def topo_sort(graph):
    # Universe of nodes: every key plus every referenced dependency.
    nodes = set(graph)
    for deps in graph.values():
        nodes.update(deps)

    result = []
    done = set()
    for _ in nodes:
        ready = sorted(
            node for node in nodes
            if node not in done
            and all(dep in done for dep in graph.get(node, []))
        )
        if not ready:
            raise ValueError("cycle detected")
        node = ready[0]
        result.append(node)
        done.add(node)
    return result
