From 21771c10ebe5f61275253c53dda842766d80a41a Mon Sep 17 00:00:00 2001 From: suguanYang Date: Sat, 28 Nov 2026 08:47:45 -0700 Subject: [PATCH] Project heading tree levels in linear time Repeated ID searches in the heading tree projection starved the worker heartbeat on dense Markdown. Collect the first depth-first level per ID once and apply the levels in a single DataFrame write. --- .../document_parser/structure/heading_tree.py | 89 +++++++------------ .../unit/test_heading_tree_projection.py | 80 +++++++++++++++++ 2 files changed, 113 insertions(+), 56 deletions(-) create mode 100644 apps/worker/tests/unit/test_heading_tree_projection.py diff --git a/apps/worker/app/services/document_parser/structure/heading_tree.py b/apps/worker/app/services/document_parser/structure/heading_tree.py index 05f5919c7..5a74847d3 100644 --- a/apps/worker/app/services/document_parser/structure/heading_tree.py +++ b/apps/worker/app/services/document_parser/structure/heading_tree.py @@ -1,5 +1,7 @@ from __future__ import annotations +from typing import cast + import pandas as pd from loguru import logger @@ -46,39 +48,28 @@ def tree_to_dataframe( node_to_id: dict[tuple[str, str], int], original_df: pd.DataFrame, ) -> pd.DataFrame: - preserved_headings = _extract_headings_from_tree(tree, node_to_id) - preserved_ids = {heading["id"] for heading in preserved_headings} + levels_by_id: dict[int, int] = {} + _collect_levels_by_id(tree, node_to_id, levels_by_id) - updated_df = original_df.copy() - removed_count = 0 - level_changed_count = 0 + original_levels: pd.Series = cast(pd.Series, original_df["level"]) + numeric_levels: pd.Series = original_levels.map( + lambda level: -1 if level == "nan" else int(level) + ) + heading_rows: pd.Series = numeric_levels.ge(0) + heading_ids: pd.Series = cast(pd.Series, original_df.loc[heading_rows, "id"]).map(int) + preserved_levels: pd.Series = heading_ids.map(levels_by_id) + projected_levels: pd.Series = preserved_levels.fillna(-1).astype(int) - for index, row in original_df.iterrows(): - row_id = int(row["id"]) - old_level = int(row["level"]) if row["level"] not in [-2, "nan", -1] else -1 + updated_df: pd.DataFrame = original_df.copy() + updated_df.loc[heading_rows, "level"] = projected_levels - if old_level <= -1: - continue - - if row_id in preserved_ids: - new_level = next( - ( - heading["level"] - for heading in preserved_headings - if heading["id"] == row_id - ), - old_level, - ) - updated_df.at[index, "level"] = new_level - if new_level != old_level: - level_changed_count += 1 - else: - updated_df.at[index, "level"] = -1 - removed_count += 1 + removed_count: int = int(preserved_levels.isna().sum()) + changed_levels: pd.Series = projected_levels.ne(numeric_levels.loc[heading_rows]) + level_changed_count: int = int((preserved_levels.notna() & changed_levels).sum()) logger.debug( f"Tree changed: removed headings={removed_count}, " - f"level changed={level_changed_count}, preserved headings={len(preserved_ids)}" + f"level changed={level_changed_count}, preserved headings={len(levels_by_id)}" ) return updated_df @@ -87,44 +78,30 @@ def remove_isolated_nodes(tree: dict[str, dict]) -> dict[str, dict]: return _remove_isolated_nodes_recursive(tree) -def _extract_headings_from_tree( +def _collect_levels_by_id( node_dict: dict[str, dict], node_to_id: dict[tuple[str, str], int], + levels_by_id: dict[int, int], *, current_level: int = 1, parent_path: str = "", -) -> list[dict[str, object]]: - results: list[dict[str, object]] = [] +) -> None: for tree_node_key, children in node_dict.items(): - node_key = (tree_node_key, parent_path) - row_id = node_to_id.get(node_key, -1) + row_id: int = node_to_id.get((tree_node_key, parent_path), -1) + if row_id < 0: + continue - if row_id >= 0: - original_heading = ( - tree_node_key.split("#")[0] if "#" in tree_node_key else tree_node_key - ) - results.append( - { - "id": row_id, - "heading": original_heading, - "level": current_level, - "tree_key": tree_node_key, - "parent_path": parent_path, - } + # Preserve the first depth-first match when a row appears in multiple nodes. + levels_by_id.setdefault(row_id, current_level) + if isinstance(children, dict) and children: + _collect_levels_by_id( + children, + node_to_id, + levels_by_id, + current_level=current_level + 1, + parent_path=append_document_path(parent_path, tree_node_key), ) - if isinstance(children, dict) and children: - current_path = append_document_path(parent_path, tree_node_key) - results.extend( - _extract_headings_from_tree( - children, - node_to_id, - current_level=current_level + 1, - parent_path=current_path, - ) - ) - return results - def _remove_isolated_nodes_recursive( node_dict: dict[str, dict], diff --git a/apps/worker/tests/unit/test_heading_tree_projection.py b/apps/worker/tests/unit/test_heading_tree_projection.py new file mode 100644 index 000000000..a960bb100 --- /dev/null +++ b/apps/worker/tests/unit/test_heading_tree_projection.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from typing import ClassVar + +import pandas as pd + +from app.services.document_parser.structure.heading_tree import ( + remove_isolated_nodes, + tree_to_dataframe, +) + + +class _MeasuredHeadingId(int): + equality_checks: ClassVar[int] = 0 + __hash__ = int.__hash__ + + def __eq__(self, other: object) -> bool: + type(self).equality_checks += 1 + return super().__eq__(other) + + +def test_tree_projection_does_not_rescan_headings_for_each_row() -> None: + heading_count: int = 512 + tree: dict[str, dict[str, object]] = { + f"Heading {index}": {} for index in range(heading_count) + } + node_to_id: dict[tuple[str, str], int] = { + (heading, ""): _MeasuredHeadingId(index) + for index, heading in enumerate(tree) + } + original: pd.DataFrame = pd.DataFrame( + {"id": range(heading_count), "level": [2] * heading_count} + ) + + _MeasuredHeadingId.equality_checks = 0 + projected: pd.DataFrame = tree_to_dataframe(tree, node_to_id, original) + + assert projected["level"].tolist() == [1] * heading_count + assert _MeasuredHeadingId.equality_checks <= 10 * heading_count + + +def test_tree_projection_preserves_rows_and_uses_first_matching_node() -> None: + tree: dict[str, dict[str, object]] = { + "Parent": {"First child": {}, "Second child": {}}, + "Standalone": {"Removed child": {}}, + "Duplicate ID": {}, + } + node_to_id: dict[tuple[str, str], int] = { + ("Parent", ""): 100, + ("First child", "Parent"): 101, + ("Second child", "Parent"): 102, + ("Standalone", ""): 103, + ("Removed child", "Standalone"): 104, + ("Duplicate ID", ""): 101, + } + original: pd.DataFrame = pd.DataFrame( + { + "id": [100, 101, 102, 103, 104, 105, 106], + "level": [3, 4, 4, 2, 3, -1, -2], + "heading": [ + "Parent", + "First child", + "Second child", + "Standalone", + "Removed child", + "Body", + "Rule candidate", + ], + }, + index=[4, 6, 7, 10, 13, 16, 18], + ) + expected: pd.DataFrame = original.copy() + expected["level"] = [1, 2, 2, 1, -1, -1, -2] + + projected: pd.DataFrame = tree_to_dataframe( + remove_isolated_nodes(tree), node_to_id, original + ) + + pd.testing.assert_frame_equal(projected, expected) + assert original["level"].tolist() == [3, 4, 4, 2, 3, -1, -2]