xlsongc commented on code in PR #77478:
URL: https://github.com/apache/airflow/pull/77478#discussion_r4736459195


##########
providers/common/ai/src/airflow/providers/common/ai/operators/document_loader.py:
##########
@@ -599,6 +638,7 @@ def _get_docx_table_rows(
             # Merges starting in a row that is left out for being empty still 
continue below it.
             above = current
             if any(cells):

Review Comment:
   Thanks, reproduced. Each table now counts itself, its rows and their cells 
before any of them is walked, with one XPath count in C, and each row also 
counts the empty cells that its padding and `w:gridSpan` add. Counting the 
cells up front also covers a walk that went over every cell before any was 
charged: the column count of a table without `w:tblGrid`, and the `w:gridSpan` 
sum at the start of each row (1M `<w:tc/>` in one row took 0.85 s there). 6M 
`<w:tr/>` now stop at the limit in 0.9 s on my machine, and 1M rows with 
`gridBefore=999` in 0.5 s. Test cases: `empty-tables`, `empty-rows`, 
`cells-in-a-row`, `grid-before-padding` and `grid-span-columns`.



##########
providers/common/ai/src/airflow/providers/common/ai/operators/document_loader.py:
##########
@@ -483,19 +511,24 @@ def _parse_docx_stream(self, stream: BinaryIO, *, 
source_hint: str) -> list[dict
             raise AirflowOptionalProviderFeatureException(e)
 
         doc = Document(stream)
+        budget = _DocxBudget()
         blocks = []
-        for block in doc.iter_inner_content():
-            if isinstance(block, Table):
-                rows = self._get_docx_table_rows_or_none(
-                    block, Table, _Cell, InvalidXmlError, 
source_hint=source_hint
-                )
-                if rows is None:
-                    continue
-                text = "\n".join(f"| {' | '.join(cells)} |" for cells in rows)
-            else:
-                text = block.text
-            if text.strip():
-                blocks.append(text)
+        try:
+            for block in doc.iter_inner_content():
+                if isinstance(block, Table):
+                    rows = self._get_docx_table_rows_or_none(
+                        block, Table, _Cell, InvalidXmlError, budget=budget, 
source_hint=source_hint
+                    )
+                    if rows is None:
+                        continue
+                    text = "\n".join(f"| {' | '.join(cells)} |" for cells in 
rows)
+                else:
+                    text = block.text
+                    budget.charge(len(text))

Review Comment:
   Yes. Each paragraph now counts its `w:r` and `w:hyperlink` children and the 
runs inside its hyperlinks, with a compiled XPath count, before `.text` is 
read, and body and cell paragraphs go through the same method. The limit is now 
on elements (paragraphs, runs, hyperlinks, tables, rows and cells) and stays at 
1,000,000: the largest of about 2,300 real files has 87K, and their output is 
unchanged. The children of a run (`w:t`, `w:tab`, ...) are not counted, because 
`CT_R.text` reads them in one query at about 0.4 us each, against about 9 us 
for a run. The counts are added rather than taken over a union, since libxml2 
merged `w:r | w:hyperlink | w:hyperlink/w:r` in quadratic time: 98 s for 7M 
runs in hyperlinks. 7M `<w:r/>` in one paragraph now stop in 1.0 s, and the 
slowest shape I found just under the limit takes about 11 s on my machine.



##########
providers/common/ai/docs/operators/document_loader.rst:
##########
@@ -95,6 +95,11 @@ including any tables nested in it, would be longer than 
about 1,000,000
 characters. If a skipped table is nested inside a cell, only that table is left
 out.
 
+Reading stops with a warning once the text passes about 10,000,000 characters,
+or the document has more than 1,000,000 paragraphs and table cells, including
+those in tables. The text read up to that point is kept, and the rest of the

Review Comment:
   Done: the paragraph now says that a table reading stops inside is left out 
whole, with the rows already read from it, and that the text of a table skipped 
by the per-table limit still counts toward the 10,000,000.



##########
providers/common/ai/tests/unit/common/ai/operators/test_document_loader.py:
##########
@@ -657,6 +657,70 @@ def 
test_docx_nested_table_text_counts_toward_parent_table_limit(self, caplog):
             "ValueError('the table text exceeds the maximum of 20 characters')"
         ) in caplog.messages
 
+    
@patch("airflow.providers.common.ai.operators.document_loader._DOCX_MAX_CHARS", 
12)
+    
@patch("airflow.providers.common.ai.operators.document_loader._DOCX_MAX_PARAGRAPHS_AND_CELLS",
 5)
+    @pytest.mark.parametrize(
+        ("blocks", "expected", "reason"),
+        [
+            pytest.param(
+                ("aaaa", "bbbb", "cccc", "dddd"),
+                "aaaa\n\nbbbb\n\ncccc",
+                "its text exceeds 12 characters",
+                id="text-over-limit",
+            ),
+            # 4 + 3 + 3 separators + 3 is over the limit in the table's second 
row, and the
+            # paragraph after the table is left out too.
+            pytest.param(
+                ("keep", [["abc"], ["abc"]], "after"),
+                "keep",
+                "its text exceeds 12 characters",
+                id="text-over-limit-inside-table",
+            ),
+            pytest.param(
+                ("", "", "", "", "", "late"),
+                "",
+                "it has more than 5 paragraphs and table cells",
+                id="empty-paragraphs-over-limit",
+            ),
+            pytest.param(
+                ([["a", "b", "c"]],),
+                "",
+                "it has more than 5 paragraphs and table cells",
+                id="cells-and-their-paragraphs-over-limit",
+            ),
+        ],
+    )
+    def test_docx_document_over_limit_stops_with_warning(self, blocks, 
expected, reason, caplog):
+        assert _load_docx_text(_build_docx_bytes(*blocks)) == expected
+        assert f"Stopped reading <bytes:.docx> because {reason}; the rest is 
left out." in caplog.messages
+
+    
@patch("airflow.providers.common.ai.operators.document_loader._DOCX_MAX_CHARS", 
12)
+    def test_docx_repeated_merge_text_counts_toward_document_limit(self):

Review Comment:
   With every row and cell counted before the table is walked, a merge 
continuation no longer charges a cell of its own, only its repeated text, which 
`test_docx_repeated_merge_text_counts_toward_document_limit` pins. For `>`, 
`test_docx_document_at_limit_read_in_full` reads a document exactly at each 
limit in full. I also mutated each condition of the budget one at a time (17 
mutants, including both of yours), and each fails at least one test.



##########
providers/common/ai/src/airflow/providers/common/ai/operators/document_loader.py:
##########
@@ -483,19 +511,24 @@ def _parse_docx_stream(self, stream: BinaryIO, *, 
source_hint: str) -> list[dict
             raise AirflowOptionalProviderFeatureException(e)
 
         doc = Document(stream)
+        budget = _DocxBudget()
         blocks = []
-        for block in doc.iter_inner_content():
-            if isinstance(block, Table):
-                rows = self._get_docx_table_rows_or_none(
-                    block, Table, _Cell, InvalidXmlError, 
source_hint=source_hint
-                )
-                if rows is None:
-                    continue
-                text = "\n".join(f"| {' | '.join(cells)} |" for cells in rows)
-            else:
-                text = block.text
-            if text.strip():
-                blocks.append(text)
+        try:
+            for block in doc.iter_inner_content():
+                if isinstance(block, Table):
+                    rows = self._get_docx_table_rows_or_none(
+                        block, Table, _Cell, InvalidXmlError, budget=budget, 
source_hint=source_hint
+                    )
+                    if rows is None:
+                        continue
+                    text = "\n".join(f"| {' | '.join(cells)} |" for cells in 
rows)
+                else:
+                    text = block.text
+                    budget.charge(len(text))
+                if text.strip():
+                    blocks.append(text)
+        except _DocxLimitReachedError as e:
+            self.log.warning("Stopped reading %s because %s; the rest is left 
out.", source_hint, e)
         text = "\n\n".join(blocks)
         return [{"text": text, "metadata": {}}]

Review Comment:
   Added: a document cut off by either limit now has `metadata["truncated"] = 
True`, and a complete one keeps `{}`. A table skipped by the per-table limits 
does not set it, since the rest of the document is still read and the warning 
names the file; happy to set it there too if you think it should.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to