Nested Subgraph Rendering Fails For 3+ Levels With `Draw_mermaid` And `Xray=True`
When using draw_mermaid with xray=True on a graph with 3 or more levels of nested subgraphs, the generated Mermaid diagram fails to create subgraph boxes, showing flat node IDs with escaped colons instead of a nested hierarchy.
In langchain_core/runnables/graph_mermaid.py, the 'empty subgraphs' section uses the condition 'if ":" not in prefix:' to decide whether to create a subgraph box. This condition incorrectly skips prefixes containing colons, such as 'parent:child', preventing multi-level nested subgraphs from being rendered as boxes.
1. Create three nested StateGraphs: grandchild, child, and parent. Each graph invokes the next lower-level graph from a node. 2. Compile all graphs. 3. Call parent_graph.get_graph(xray=True).draw_mermaid() and observe the output. The expected output should contain nested subgraph boxes for child and grandchild, but instead shows a flat node labelled 'parent\3achild\3agrandchild' with no subgraph containers.
Fixing Code Block
# In langchain_core/runnables/graph_mermaid.py, locate the section handling 'empty subgraphs' (around line 239).
# Replace the condition that skips multi-level prefixes.
# Original code:
# if ":" not in prefix:
# # ... create subgraph box
# Fixed code:
if prefix: # always create a subgraph box when a prefix exists
# create subgraph box using the prefix (including multi-level prefixes like 'parent:child')
# Ensure proper escaping: replace colons with underscores or use Mermaid's escape syntax.
escaped_prefix = prefix.replace(':', '_')
# Insert the existing subgraph creation logic here, using escaped_prefix as the subgraph ID.
# Example (pseudo):
# subgraph_str = f"subgraph {escaped_prefix}["{escaped_prefix}"]\n"
# ... add nodes and edges ...
# subgraph_str += "end\n"
# add to output
The fix removes the erroneous colon check, allowing the 'empty subgraphs' block to process any non-empty prefix. This ensures that multi-level prefixes like 'parent:child' are treated as valid subgraph identifiers, enabling correct rendering of nested subgraph boxes. The prefix is escaped (colon replaced with underscore) to maintain compatibility with Mermaid syntax.
Edge Case Audit
This change affects the rendering of all subgraphs, including those that previously worked correctly. Ensure that the escaping method (colon replaced with underscore) does not conflict with other valid prefixes or produce duplicate IDs. Test with graphs having 2-level nesting and various node names to verify no regression. If issues arise, rollback by restoring the original condition 'if ":" not in prefix:'. Additionally, consider that changing the subgraph ID escaping may alter generated Mermaid diagrams consumed by downstream tools; verify compatibility with your rendering pipeline.