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


##########
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:
   When the limit is hit inside a table, the rows already read from that table 
are dropped too, since the error unwinds past every enclosing table 
(`text-over-limit-inside-table` expects just `keep`). A document laid out 
inside one outer table then comes back empty. Text from tables skipped for the 
per-table limit also still counts toward the 10,000,000. Could this paragraph 
say both?



##########
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:
   `block.text` walks every `w:r` and `w:hyperlink` in Python, so one paragraph 
of millions of empty `<w:r/>` is charged once with 0 characters. In breeze at 
this head, a single paragraph of 7M `<w:r/>` (97 KB zip, 42 MB of XML) took 
about 110 s with no warning, slower than the 7M empty paragraphs this PR 
bounds. Should the runs count toward the limit, before `.text` is read? The 
cell paragraphs at line 672 have the same gap (1M runs in one cell paragraph 
took 18 s).



##########
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:
   An empty `<w:tr/>` row never gets charged, since it has no cells and doesn't 
pass `any(cells)`. Same for rows with only `w:gridBefore` padding, and for 
empty tables. I tried one table with 6M `<w:tr/>` (98 KB zip, ~42 MB of XML, 
under the 50 MB cap from #77475): 34 s and no warning. 1M rows with 
`gridBefore=999` also took 34 s. Can each row charge one unit, with padding 
counted as cells? Otherwise `<w:tr/>` in place of `<w:p/>` gets around the 
1,000,000 limit.



##########
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:
   A document cut off here comes back as the same `{"text": ..., "metadata": 
{}}` as a complete one, so a downstream embedding step indexes the partial text 
as the whole file, and in directory mode only the log says which file was cut. 
Would a `metadata["truncated"] = True` be worth adding?



##########
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:
   Nothing pins the cell count for a merge continuation: changing the charge at 
line 621 to `paragraphs_and_cells=0`, or `>` to `>=` in `charge`, keeps every 
test green. A 5-row merged column with `_DOCX_MAX_PARAGRAPHS_AND_CELLS` patched 
to 5, plus a case with exactly 5 paragraphs that expects the last one kept, 
would catch both.



-- 
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