Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion apps/worker/app/services/document_agent/structure/toc_rehome.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,14 +323,26 @@ def _apply_plans(
f"{_LOG_PREFIX} dest parent missing path={dest_parent!r}"
)

new_path: tuple[str, ...] = (*dest_parent, source_path[-1])
# A reused path makes both leaves share one match during range resolution.
if new_path != source_path and (
new_path in overrides or node_at_path(working, new_path) is not None
):
logger.info(
"{} skip occupied destination page={} segment={}",
_LOG_PREFIX,
plan.physical_page,
plan.segment_index,
)
continue

working, detached = _detach_node(working, source_path)
if detached is None:
raise ValueError(
f"{_LOG_PREFIX} detach miss source_path={source_path!r}"
)
target_level = len(dest_parent) + 1
detached = rebase_levels(detached, target_level - detached.level)
new_path = (*dest_parent, detached.title)
working = _insert_under_parent(
nodes=working,
parent_path=dest_parent,
Expand Down
39 changes: 39 additions & 0 deletions apps/worker/tests/contract/test_toc_rehome_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,45 @@ def test_no_prev_leaf_by_page_is_noop_for_that_backjump() -> None:
assert result.events == []


def test_rehome_keeps_the_page_anchor_when_destination_path_is_occupied() -> None:
nodes: list[TitleNode] = [
TitleNode(
title="First section",
level=1,
children=[
TitleNode(title="Overview", level=2, printed_page=6),
TitleNode(title="Details", level=2, printed_page=7),
],
),
TitleNode(
title="Second section",
level=1,
children=[TitleNode(title="Overview", level=2, printed_page=14)],
),
]
anchor_path: tuple[str, ...] = ("First section", "Overview")
source_path: tuple[str, ...] = ("Second section", "Overview")
overrides: dict[tuple[str, ...], TitleMatch] = _overrides(
{anchor_path: 9, ("First section", "Details"): 10, source_path: 9}
)

rehomed = rehome_forest(nodes, overrides)
ranges = resolve_hierarchy_page_ranges(
rehomed.nodes,
page_count=125,
match_overrides=rehomed.match_overrides,
)

assert [item.path_titles for item in ranges] == [
anchor_path,
("First section", "Details"),
source_path,
]
assert ranges[0].start_page <= 9 <= ranges[0].end_page
assert ranges[0].match == overrides[anchor_path]
assert rehomed.match_overrides[source_path] == overrides[source_path]


def test_equal_page_backjump_inserts_after_front_same_page_leaves() -> None:
"""Rehome @116 with one or more front @116 leaves → after that same-page group."""
nodes = [
Expand Down
Loading