๐Ÿ“ฆ EqualifyEverything / equalify-reflow

๐Ÿ“„ test_pipeline_viewer_phases.py ยท 703 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703"""Unit tests for pipeline viewer phase orchestration.

Tests the non-LLM logic of the pipeline viewer service: Phase 1 accumulation,
Phase 2 orchestration, str_replace tool behavior, Phase 3 assembly, and
procedure loading.
"""

from __future__ import annotations

import asyncio
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from src.services.pipeline_viewer import (
    PAGE_AGENT_SEMAPHORE_LIMIT,
    PipelineViewerService,
    _compose_page_prompt,
    _load_fragment,
)
from src.services.pipeline_viewer_models import (
    DocumentChange,
    FootnoteInfo,
    LayoutType,
    OutlineEntry,
    PageAttributes,
    PageCorrectionResult,
    PipelineViewerResult,
    StepResult,
    StructurePageOutput,
    StructureResult,
    HeadingRecommendation,
)


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture
def service():
    """Create a PipelineViewerService instance."""
    return PipelineViewerService()


@pytest.fixture
def base_result():
    """Create a base PipelineViewerResult with v0 data (2 pages)."""
    return PipelineViewerResult(
        filename="test.pdf",
        total_pages=2,
        versions={"v0": "# Page 1\n\nHello world\n\n# Page 2\n\nGoodbye"},
        page_images={"1": "AAAA", "2": "BBBB"},
        page_markdowns={
            "v0": {
                "1": "# Page 1\n\nHello world",
                "2": "# Page 2\n\nGoodbye",
            },
        },
        figures=[],
        steps=[
            StepResult(
                name="docling",
                display_name="Docling Extraction",
                version_before=None,
                version_after="v0",
                elapsed_ms=100,
                changes=[],
                metadata={},
            ),
        ],
        stats={"total_chars": 40},
    )


@pytest.fixture
def sample_structure():
    """Create a StructureResult with outline, page attributes, and footnotes."""
    return StructureResult(
        page_attributes={
            1: PageAttributes(layout=LayoutType.DOUBLE_COLUMN, is_academic=True),
            2: PageAttributes(layout=LayoutType.DOUBLE_COLUMN, is_academic=True),
        },
        outline=[
            OutlineEntry(level=1, text="Title", page=1),
            OutlineEntry(level=2, text="Introduction", page=1),
            OutlineEntry(level=2, text="Methods", page=2),
        ],
        footnotes=[
            FootnoteInfo(number="1", body_text="First footnote.", source_page=1),
        ],
    )


# ---------------------------------------------------------------------------
# Phase 1 โ€” Structure Analysis accumulation
# ---------------------------------------------------------------------------


class TestPhase1Accumulation:
    """Test that Phase 1 accumulates outline, page types, and footnotes.

    _step_structure() uses deferred imports, so we patch at the source
    modules (pydantic_ai.*, src.agents.prompts.*) not the consumer module.
    """

    @pytest.mark.asyncio
    async def test_outline_accumulates_across_pages(self, service, base_result):
        """Outline entries from each page should be appended in order."""
        page1_output = StructurePageOutput(
            page_attributes=PageAttributes(layout=LayoutType.DOUBLE_COLUMN, is_academic=True),
            headings=[
                HeadingRecommendation(
                    text="Title", recommended_level=1, reasoning="doc title"
                ),
            ],
            footnotes=[],
        )
        page2_output = StructurePageOutput(
            page_attributes=PageAttributes(layout=LayoutType.DOUBLE_COLUMN, is_academic=True),
            headings=[
                HeadingRecommendation(
                    text="Methods", recommended_level=2, reasoning="section"
                ),
            ],
            footnotes=[],
        )

        mock_agent = MagicMock()
        mock_run_result = MagicMock()

        call_count = 0

        async def mock_run(messages):
            nonlocal call_count
            call_count += 1
            if call_count == 1:
                mock_run_result.output = page1_output
            else:
                mock_run_result.output = page2_output
            return mock_run_result

        mock_agent.run = mock_run

        with patch(
            "pydantic_ai.Agent", return_value=mock_agent
        ), patch(
            "pydantic_ai.models.bedrock.BedrockConverseModel"
        ), patch(
            "src.agents.prompts.structure_analysis.STRUCTURE_SYSTEM_PROMPT", "test"
        ), patch(
            "src.agents.prompts.structure_analysis.build_structure_user_message",
            return_value="test msg",
        ), patch(
            "pydantic_ai.messages.BinaryContent"
        ):
            structure = await service._step_structure(base_result)

        assert len(structure.outline) == 2
        assert structure.outline[0].text == "Title"
        assert structure.outline[0].page == 1
        assert structure.outline[1].text == "Methods"
        assert structure.outline[1].page == 2

    @pytest.mark.asyncio
    async def test_page_attributes_collected(self, service, base_result):
        """Each page should have its attributes recorded."""
        page_output = StructurePageOutput(
            page_attributes=PageAttributes(layout=LayoutType.SINGLE_COLUMN),
            headings=[],
            footnotes=[],
        )

        mock_agent = MagicMock()
        mock_run_result = MagicMock()
        mock_run_result.output = page_output
        mock_agent.run = AsyncMock(return_value=mock_run_result)

        with patch(
            "pydantic_ai.Agent", return_value=mock_agent
        ), patch(
            "pydantic_ai.models.bedrock.BedrockConverseModel"
        ), patch(
            "src.agents.prompts.structure_analysis.STRUCTURE_SYSTEM_PROMPT", "test"
        ), patch(
            "src.agents.prompts.structure_analysis.build_structure_user_message",
            return_value="test msg",
        ), patch(
            "pydantic_ai.messages.BinaryContent"
        ):
            structure = await service._step_structure(base_result)

        assert structure.page_attributes[1].layout == LayoutType.SINGLE_COLUMN
        assert structure.page_attributes[2].layout == LayoutType.SINGLE_COLUMN

    @pytest.mark.asyncio
    async def test_footnotes_collected_with_source_page(self, service, base_result):
        """Footnotes should be collected with correct source page."""
        page1_output = StructurePageOutput(
            page_attributes=PageAttributes(layout=LayoutType.DOUBLE_COLUMN, is_academic=True),
            headings=[],
            footnotes=[
                FootnoteInfo(number="1", body_text="First note.", source_page=1),
            ],
        )
        page2_output = StructurePageOutput(
            page_attributes=PageAttributes(layout=LayoutType.DOUBLE_COLUMN, is_academic=True),
            headings=[],
            footnotes=[
                FootnoteInfo(number="2", body_text="Second note.", source_page=2),
            ],
        )

        mock_agent = MagicMock()
        mock_run_result = MagicMock()
        call_count = 0

        async def mock_run(messages):
            nonlocal call_count
            call_count += 1
            mock_run_result.output = page1_output if call_count == 1 else page2_output
            return mock_run_result

        mock_agent.run = mock_run

        with patch(
            "pydantic_ai.Agent", return_value=mock_agent
        ), patch(
            "pydantic_ai.models.bedrock.BedrockConverseModel"
        ), patch(
            "src.agents.prompts.structure_analysis.STRUCTURE_SYSTEM_PROMPT", "test"
        ), patch(
            "src.agents.prompts.structure_analysis.build_structure_user_message",
            return_value="test msg",
        ), patch(
            "pydantic_ai.messages.BinaryContent"
        ):
            structure = await service._step_structure(base_result)

        assert len(structure.footnotes) == 2
        assert structure.footnotes[0].number == "1"
        assert structure.footnotes[0].source_page == 1
        assert structure.footnotes[1].number == "2"
        assert structure.footnotes[1].source_page == 2

    @pytest.mark.asyncio
    async def test_agent_failure_skips_page(self, service, base_result):
        """If the agent fails on a page, that page is skipped."""
        mock_agent = MagicMock()
        mock_agent.run = AsyncMock(side_effect=RuntimeError("LLM error"))

        with patch(
            "pydantic_ai.Agent", return_value=mock_agent
        ), patch(
            "pydantic_ai.models.bedrock.BedrockConverseModel"
        ), patch(
            "src.agents.prompts.structure_analysis.STRUCTURE_SYSTEM_PROMPT", "test"
        ), patch(
            "src.agents.prompts.structure_analysis.build_structure_user_message",
            return_value="test msg",
        ), patch(
            "pydantic_ai.messages.BinaryContent"
        ):
            structure = await service._step_structure(base_result)

        # No page attributes should be recorded if all pages failed
        assert len(structure.page_attributes) == 0
        assert len(structure.outline) == 0


# ---------------------------------------------------------------------------
# Phase 2 โ€” Page Content Corrections orchestration
# ---------------------------------------------------------------------------


class TestPhase2Orchestration:
    """Test Phase 2 parallelism, error handling, and change collection."""

    @pytest.mark.asyncio
    async def test_changes_collected_from_all_pages(self, service, base_result, sample_structure):
        """Changes from all pages should be collected."""
        page1_result = PageCorrectionResult(
            page=1,
            corrected_markdown="# Page 1\n\nFixed world",
            changes=[
                DocumentChange(
                    page=1,
                    old_text="Hello world",
                    new_text="Fixed world",
                    reasoning="OCR fix",
                    stage="ocr_error",
                ),
            ],
            issues=[],
        )
        page2_result = PageCorrectionResult(
            page=2,
            corrected_markdown="# Page 2\n\nFixed goodbye",
            changes=[
                DocumentChange(
                    page=2,
                    old_text="Goodbye",
                    new_text="Fixed goodbye",
                    reasoning="OCR fix",
                    stage="ocr_error",
                ),
            ],
            issues=[],
        )

        async def mock_run_page_agent(page_num, **kwargs):
            return page1_result if page_num == 1 else page2_result

        service._run_page_agent = mock_run_page_agent

        await service._step_page_content(base_result, sample_structure)

        step = base_result.steps[-1]
        assert step.name == "page_content"
        assert len(step.changes) == 2
        assert "v1" in base_result.versions

    @pytest.mark.asyncio
    async def test_failed_page_keeps_original_markdown(self, service, base_result, sample_structure):
        """If a page agent raises, the original markdown is preserved."""

        async def mock_run_page_agent(page_num, **kwargs):
            if page_num == 1:
                raise RuntimeError("Page 1 failed")
            return PageCorrectionResult(
                page=2,
                corrected_markdown="# Page 2 corrected",
                changes=[],
                issues=[],
            )

        service._run_page_agent = mock_run_page_agent

        await service._step_page_content(base_result, sample_structure)

        v1_pages = base_result.page_markdowns["v1"]
        # Page 1 should keep original since it failed
        assert v1_pages["1"] == base_result.page_markdowns["v0"]["1"]
        # Page 2 should have corrected markdown
        assert v1_pages["2"] == "# Page 2 corrected"

    @pytest.mark.asyncio
    async def test_hints_passed_to_page_agents(self, service, base_result, sample_structure):
        """Verify page_hints are threaded from _step_page_content to _run_page_agent."""
        received_hints: dict[int, list[str] | None] = {}

        async def mock_run_page_agent(page_num, **kwargs):
            received_hints[page_num] = kwargs.get("context_hints")
            return PageCorrectionResult(
                page=page_num,
                corrected_markdown=base_result.page_markdowns["v0"][str(page_num)],
                changes=[],
                issues=[],
            )

        service._run_page_agent = mock_run_page_agent

        test_hints = {1: ["Hint for page 1"], 2: ["Hint A", "Hint B"]}
        await service._step_page_content(
            base_result, sample_structure, page_hints=test_hints
        )

        assert received_hints[1] == ["Hint for page 1"]
        assert received_hints[2] == ["Hint A", "Hint B"]


# ---------------------------------------------------------------------------
# Phase 2 โ€” str_replace tool behavior
# ---------------------------------------------------------------------------


class TestStrReplaceTool:
    """Test the str_replace tool function directly."""

    def test_successful_replace(self):
        """A unique match should succeed."""
        current_markdown = "Hello world, this is a test."
        changes: list[DocumentChange] = []

        count = current_markdown.count("Hello world")
        assert count == 1

        new_markdown = current_markdown.replace("Hello world", "Hi world", 1)
        changes.append(
            DocumentChange(
                page=1,
                old_text="Hello world",
                new_text="Hi world",
                reasoning="test fix",
                stage="ocr_error",
            )
        )

        assert new_markdown == "Hi world, this is a test."
        assert len(changes) == 1
        assert changes[0].old_text == "Hello world"

    def test_not_found_error(self):
        """When old_text is not in the document, return an error message."""
        current_markdown = "Hello world, this is a test."

        count = current_markdown.count("nonexistent text")
        assert count == 0
        # The tool would return an error message in this case

    def test_multiple_match_error(self):
        """When old_text appears multiple times, return an error message."""
        current_markdown = "Hello world, Hello world again."

        count = current_markdown.count("Hello world")
        assert count == 2
        # The tool would return an error asking for more context


# ---------------------------------------------------------------------------
# Phase 3 โ€” Assembly and boundary logic
# ---------------------------------------------------------------------------


class TestPhase3Assembly:
    """Test Phase 3 assembly and boundary fix orchestration.

    Boundary agent is called with section-aware hints. Tests mock both
    _run_boundary_agent and _run_footnote_agent.
    """

    @pytest.mark.asyncio
    async def test_v2_produced_from_v1(self, service, base_result, sample_structure):
        """v2 should be produced from v1 (or v0 if no v1)."""
        service._run_boundary_agent = AsyncMock(
            return_value=(base_result.versions["v0"], [], [], 0, 0)
        )
        service._run_footnote_agent = AsyncMock(
            return_value=(base_result.versions["v0"], [], [], 0, 0)
        )

        await service._step_boundaries(base_result, sample_structure)

        step = base_result.steps[-1]
        assert step.name == "boundaries"
        assert "v2" in base_result.versions

    @pytest.mark.asyncio
    async def test_deterministic_hyphen_join(self, service, sample_structure):
        """Hyphenated words at page joins should be deterministically joined."""
        result = PipelineViewerResult(
            filename="test.pdf",
            total_pages=2,
            versions={"v1": "The develop-\n\nment of new tools."},
            page_images={},
            page_markdowns={"v1": {"1": "develop-", "2": "ment of new tools."}},
            figures=[],
            steps=[],
            stats={},
        )

        # No footnotes to skip the footnote agent
        no_fn_structure = StructureResult(
            page_attributes={},
            outline=[],
            footnotes=[],
        )

        # Mock boundary agent to pass through without changes
        service._run_boundary_agent = AsyncMock(
            side_effect=lambda doc, *a, **kw: (doc, [], [], 0, 0)
        )

        await service._step_boundaries(result, no_fn_structure)

        assert "development" in result.versions["v2"]
        step = result.steps[-1]
        assert step.metadata["boundary_fixes"] == 1

    @pytest.mark.asyncio
    async def test_footnote_agent_skipped_when_no_footnotes(self, service, base_result):
        """If no footnotes were found in Phase 1, skip footnote agent."""
        no_fn_structure = StructureResult(
            page_attributes={
                1: PageAttributes(layout=LayoutType.DOUBLE_COLUMN, is_academic=True),
                2: PageAttributes(layout=LayoutType.DOUBLE_COLUMN, is_academic=True),
            },
            outline=[],
            footnotes=[],
        )

        service._run_boundary_agent = AsyncMock(
            side_effect=lambda doc, *a, **kw: (doc, [], [], 0, 0)
        )
        service._run_footnote_agent = AsyncMock(return_value=("", [], [], 0, 0))

        await service._step_boundaries(base_result, no_fn_structure)

        service._run_footnote_agent.assert_not_called()

    @pytest.mark.asyncio
    async def test_footnote_changes_metadata(self, service, base_result, sample_structure):
        """Step metadata should count footnote changes."""
        service._run_boundary_agent = AsyncMock(
            side_effect=lambda doc, *a, **kw: (doc, [], [], 0, 0)
        )
        service._run_footnote_agent = AsyncMock(
            return_value=(
                "final doc",
                [
                    DocumentChange(
                        page=0,
                        old_text="work1",
                        new_text="work[^1]",
                        reasoning="footnote marker",
                        stage="footnote",
                    )
                ],
                [],
                0,
                0,
            )
        )

        await service._step_boundaries(base_result, sample_structure)

        step = base_result.steps[-1]
        assert step.metadata["footnotes_relocated"] == 1

    @pytest.mark.asyncio
    async def test_boundary_agent_receives_section_hints(self, service, base_result, sample_structure):
        """When section_map is provided, boundary agent receives hint snippets."""
        from src.services.pipeline_viewer_models import SectionEntry, SectionMap

        section_map = SectionMap(sections=[
            SectionEntry(
                index=0,
                heading_text="Introduction",
                heading_level=2,
                pages=[1, 2],
                markdown="content",
                outline_position=0,
            ),
        ])

        received_snippets = []

        async def mock_boundary_agent(doc, snippets, footnotes):
            received_snippets.extend(snippets)
            return doc, [], [], 0, 0

        service._run_boundary_agent = mock_boundary_agent
        service._run_footnote_agent = AsyncMock(
            return_value=(base_result.versions["v0"], [], [], 0, 0)
        )

        await service._step_boundaries(
            base_result, sample_structure, section_map=section_map
        )

        assert len(received_snippets) == 1
        assert received_snippets[0]["page_before"] == 1
        assert received_snippets[0]["page_after"] == 2
        assert "hints" in received_snippets[0]


# ---------------------------------------------------------------------------
# Cleanup step
# ---------------------------------------------------------------------------


class TestCleanupStep:
    """Test the deterministic cleanup step."""

    @pytest.mark.asyncio
    async def test_collapses_multiple_blank_lines(self, service):
        """3+ blank lines should be collapsed to 2."""
        result = PipelineViewerResult(
            filename="test.pdf",
            total_pages=1,
            versions={"v2": "Hello\n\n\n\nWorld"},
            page_images={},
            page_markdowns={},
            figures=[],
            steps=[],
            stats={},
        )

        await service._step_cleanup(result)

        assert result.versions["v3"] == "Hello\n\nWorld"

    @pytest.mark.asyncio
    async def test_strips_trailing_whitespace(self, service):
        """Trailing whitespace on lines should be removed."""
        result = PipelineViewerResult(
            filename="test.pdf",
            total_pages=1,
            versions={"v2": "Hello   \nWorld  "},
            page_images={},
            page_markdowns={},
            figures=[],
            steps=[],
            stats={},
        )

        await service._step_cleanup(result)

        assert result.versions["v3"] == "Hello\nWorld"


# ---------------------------------------------------------------------------
# Procedure loading
# ---------------------------------------------------------------------------


class TestFragmentComposition:
    """Test _load_fragment and _compose_page_prompt utilities."""

    def test_loads_base_fragment(self):
        """base.md should load successfully."""
        content = _load_fragment("base")
        assert content != ""
        assert "Page Correction Procedure" in content

    def test_loads_layout_fragment(self):
        """Layout fragments should load."""
        content = _load_fragment("layout/double_column")
        assert content != ""
        assert "Double-Column" in content

    def test_loads_content_fragment(self):
        """Content fragments should load."""
        content = _load_fragment("content/academic")
        assert content != ""
        assert "Academic" in content

    def test_loads_quality_fragment(self):
        """Quality fragments should load."""
        content = _load_fragment("quality/scanned")
        assert content != ""
        assert "Scanned" in content

    def test_missing_fragment_returns_empty(self):
        """A nonexistent fragment should return empty string."""
        content = _load_fragment("nonexistent/fragment_12345")
        assert content == ""

    def test_compose_base_only(self):
        """Minimal attributes should include base + layout only."""
        attrs = PageAttributes(layout=LayoutType.SINGLE_COLUMN)
        prompt = _compose_page_prompt(attrs)
        assert "Page Correction Procedure" in prompt
        assert "Single-Column" in prompt
        assert "Academic" not in prompt
        assert "Scanned" not in prompt

    def test_compose_academic_double_column(self):
        """Academic double-column should include base + layout + academic."""
        attrs = PageAttributes(
            layout=LayoutType.DOUBLE_COLUMN,
            is_academic=True,
        )
        prompt = _compose_page_prompt(attrs)
        assert "Page Correction Procedure" in prompt
        assert "Double-Column" in prompt
        assert "Academic" in prompt

    def test_compose_all_flags(self):
        """All flags set should include all fragments."""
        attrs = PageAttributes(
            layout=LayoutType.DOUBLE_COLUMN,
            is_academic=True,
            has_images=True,
            has_tables=True,
            has_equations=True,
            is_scanned=True,
        )
        prompt = _compose_page_prompt(attrs)
        assert "Page Correction Procedure" in prompt
        assert "Double-Column" in prompt
        assert "Academic" in prompt
        assert "Images" in prompt
        assert "Tables" in prompt
        assert "Equations" in prompt
        assert "Scanned" in prompt

    def test_compose_selective_flags(self):
        """Only active flags should contribute fragments."""
        attrs = PageAttributes(
            layout=LayoutType.PRESENTATION,
            has_tables=True,
        )
        prompt = _compose_page_prompt(attrs)
        assert "Presentation" in prompt
        assert "Tables" in prompt
        assert "Academic" not in prompt
        assert "Images" not in prompt
        assert "Equations" not in prompt
        assert "Scanned" not in prompt