Review this generated code before it processes external category trees.
Build an insertion-ordered ID-to-path index, reject cycles or duplicate IDs, and enforce both maximum depth and maximum node count.
Python
def index_categories(root, max_depth=100):
index = {}
visited = set()
path = []
def visit(node, depth=0):
if depth > max_depth:
raise ValueError("category tree is too deep")
if node["id"] in visited:
return
path.append(node["name"])
index[node["id"]] = "/".join(path)
for child in node.get("children", []):
visit(child, depth + 1)
path.pop()
visited.add(node["id"])
visit(root)
return index
generated code is illustrative, not from any one model