| 384 | |
| 385 | |
| 386 | def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False, built_at_commit: str | None = None, community_labels: dict[int, str] | None = None, original_links: "list[dict] | None" = None) -> bool: |
| 387 | # Drop #3774 accounting before any write. Extract pops these first; every |
| 388 | # other caller of to_json (the documented build_merge persist path) does not. |
| 389 | from graphify.build import take_dedup_remap, take_shrink_accounting |
| 390 | # The guard below reads it; it is removed here so node_link_data cannot |
| 391 | # write it into graph.json (#4940). |
| 392 | dedup_remap = take_dedup_remap(G) |
| 393 | take_shrink_accounting(G) |
| 394 | # Sources build_merge replaced or pruned this run: their old semantic ids |
| 395 | # are not lost. Popped so it is never written into graph.json. |
| 396 | replaced_sources = set(G.graph.pop("_replaced_sources", None) or ()) |
| 397 | # Safety check: refuse to silently shrink an existing graph (#479) |
| 398 | existing_path = Path(output_path) |
| 399 | _prev_hyperedges = None |
| 400 | _prev_hyperedges_loaded = False |
| 401 | if not force and existing_path.exists(): |
| 402 | from graphify.security import check_graph_file_size_cap |
| 403 | try: |
| 404 | check_graph_file_size_cap(existing_path) |
| 405 | except Exception: |
| 406 | # Existing graph.json trips the size cap; reading it to compare would |
| 407 | # be the very DoS the cap guards against. Can't verify — let the new |
| 408 | # graph replace the oversized file. |
| 409 | oversized = True |
| 410 | _prev_hyperedges_loaded = True |
| 411 | else: |
| 412 | oversized = False |
| 413 | if not oversized: |
| 414 | try: |
| 415 | raw = existing_path.read_text(encoding="utf-8") |
| 416 | except Exception: |
| 417 | raw = "" |
| 418 | if not raw.strip(): |
| 419 | # Empty/whitespace existing file (e.g. a freshly touched path): |
| 420 | # no nodes to lose, so any new graph is a growth — proceed. |
| 421 | existing_n = 0 |
| 422 | existing_nodes = [] |
| 423 | _prev_hyperedges_loaded = True |
| 424 | else: |
| 425 | try: |
| 426 | existing_data = json.loads(raw) |
| 427 | del raw |
| 428 | if not isinstance(existing_data, dict): |
| 429 | raise TypeError( |
| 430 | f"expected JSON object, got {type(existing_data).__name__}" |
| 431 | ) |
| 432 | _prev_hyperedges = existing_data.get("hyperedges") |
| 433 | existing_nodes = existing_data.get("nodes", []) |
| 434 | _prev_hyperedges_loaded = True |
| 435 | # Only the node list and hyperedges flag are needed; let the links go now. |
| 436 | del existing_data |
| 437 | if not isinstance(existing_nodes, list): |
| 438 | existing_nodes = [] |
| 439 | existing_n = len(existing_nodes) |
| 440 | except Exception as exc: |
| 441 | # Non-empty but unparseable existing graph (corrupt or a |
| 442 | # mid-write): we cannot verify the new graph is not a silent |
| 443 | # shrink. Fail SAFE — refuse rather than overwrite. A |