def topo_sort(graph):
    """Topologically sort nodes given {node: [dependencies]}.

    Returns dependencies first, choosing the alphabetically smallest
    node whose dependencies are all already placed (deterministic).
    Nodes mentioned only as dependencies are treated as having no
    dependencies of their own.
    Raises ValueError if the graph contains a cycle.
    """
    remaining = {node: set(deps) for node, deps in graph.items()}
    for deps in graph.values():
        for dep in deps:
            remaining.setdefault(dep, set())
    result = []
    while remaining:
        ready = sorted(node for node, deps in remaining.items() if not deps)
        if not ready:
            raise ValueError("cycle detected in graph")
        node = ready[0]
        result.append(node)
        del remaining[node]
        for deps in remaining.values():
            deps.discard(node)
    return result
