You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/10 15:56:33 UTC

(seatunnel) 01/01: [Improve][Connector-V2][File] Validate anydoc Markdown handoff (#11813)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-11813-38385ea1f0fe4fefa3478e08478452adc437f362
in repository https://gitbox.apache.org/repos/asf/seatunnel.git

commit a1135fd445fa4897db6d95472d333c9c0aa47e84
Author: Goutam Adwant <86...@users.noreply.github.com>
AuthorDate: Thu Sep 10 15:43:40 2026 +0000

    [Improve][Connector-V2][File] Validate anydoc Markdown handoff (#11813)
    
    Signed-off-by: Goutam Adwant <wo...@gmail.com>
    Signed-off-by: goutamadwant <wo...@gmail.com>
---
 docs/en/developer/anydoc-document-parser-poc.md    |  75 ++++++++++++++
 docs/zh/developer/anydoc-document-parser-poc.md    |  75 ++++++++++++++
 .../file/source/reader/MarkdownReadStrategy.java   |  60 ++++++++++-
 .../source/reader/MarkdownReadStrategyTest.java    | 112 +++++++++++++++++++++
 .../src/test/resources/anydoc/test_read_excel.md   |   7 ++
 5 files changed, 326 insertions(+), 3 deletions(-)

diff --git a/docs/en/developer/anydoc-document-parser-poc.md b/docs/en/developer/anydoc-document-parser-poc.md
new file mode 100644
index 0000000000..6da595ed86
--- /dev/null
+++ b/docs/en/developer/anydoc-document-parser-poc.md
@@ -0,0 +1,75 @@
+---
+title: Anydoc document parser PoC
+---
+
+# Anydoc document parser PoC
+
+This is a design and compatibility PoC. It does not add a document file format or an anydoc runtime dependency.
+
+**Status:** Open proposal tracked in GH-11801. This file is intentionally not published in the documentation sidebar while the runtime model is unresolved.
+
+## Current boundary
+
+The file connector currently owns two separate document paths:
+
+- `MarkdownReadStrategy` reads Markdown and emits document-element rows.
+- `PdfReadStrategy` reads PDF files through PDFBox and emits a similar row schema.
+
+An anydoc backend would add a conversion step before the existing Markdown row generation:
+
+```text
+source file bytes
+    -> document-to-Markdown backend
+    -> MarkdownReadStrategy
+    -> document-element rows and optional RAG metadata
+```
+
+The PoC adds a package-private Markdown handoff method to `MarkdownReadStrategy`. The handoff receives the original source URI and the SHA-256 hash of the original source bytes explicitly. It must not derive document identity from a temporary Markdown path or treat the converted Markdown hash as the source document hash. Existing Markdown files still use the same read path and schema. A deterministic test feeds Markdown produced by the anydoc CLI from the existing Excel fixture into that [...]
+
+## PoC command
+
+The experiment used the upstream CLI without adding it to SeaTunnel's dependencies. Run this only in an isolated development environment because `npx -y` downloads and executes the named package:
+
+```shell
+npx -y @firecrawl/anydoc@0.1.9 \
+  seatunnel-connectors-v2/connector-file/connector-file-base/src/test/resources/excel/test_read_excel.xlsx \
+  -o anydoc-output.md
+```
+
+The fixture was generated with version `0.1.9`. Its SHA-256 is `e5fc44559f67b2970729b0fb4d4b2d71935790d3073e2abb9001d3b224826fa0`. The result contains a `Sheet1` heading and a GitHub-Flavored Markdown table. The checked-in test fixture preserves that output so unit tests remain local and deterministic.
+
+## Compatibility findings
+
+- Existing `markdown` and `pdf` formats do not need to change.
+- The existing RAG fields can use the original source URI, so document and chunk identifiers remain tied to the source document instead of a temporary Markdown file.
+- The current Flexmark parser does not enable the table extension. Anydoc spreadsheet and CSV tables therefore degrade to one paragraph chunk containing pipe markup. Preserving usable table structure, either by enabling `TablesExtension` compatibly or chunking tables in the converter layer, is a prerequisite for tabular-source support rather than an optional improvement.
+- `MarkdownReadStrategy` already contains `TableBlock` handling, but it is unreachable while `TablesExtension` is disabled. A compatibility decision must define the row shape before activating that code.
+- Text-based documents can be converted. Image-only PDFs still require OCR and must not be presented as supported by a local anydoc backend.
+
+## Runtime choices
+
+### External executable
+
+This is the smallest integration technically, but every worker would need a pinned executable. SeaTunnel would also need contracts for command discovery, timeouts, process termination, temporary files, output limits, stderr handling, concurrency, and unavailable executables.
+
+### WebAssembly
+
+This avoids spawning one process per document, but SeaTunnel currently has no Java WebAssembly runtime boundary. Adding one requires a runtime selection, dependency and distribution review, memory and execution limits, and Linux/macOS/Windows verification.
+
+### Sidecar service
+
+This separates the native runtime from the JVM, but adds a network API, deployment, authentication, retry, and availability contract. It is not equivalent to an optional local parser.
+
+## Decision required before production code
+
+Maintainers need to choose the supported runtime and packaging model before user-facing options or a `DOCUMENT` format are added. The decision should define:
+
+1. whether the first backend is an executable, WebAssembly runtime, or sidecar;
+2. who installs and versions the backend on every worker;
+3. supported operating systems and architectures;
+4. timeout, output-size, resource, concurrency, and cleanup limits;
+5. error categories for unsupported, encrypted, malformed, and image-only files;
+6. whether GFM tables become table elements or are chunked in the converter layer, including the compatibility effect on existing Markdown output;
+7. licensing, NOTICE, binary-distribution, and vulnerability-update responsibilities.
+
+After that decision, the production slice can add a document parser SPI, one optional provider, declarative options, EN/ZH connector documentation, and connector E2E coverage without changing the current PDF and Markdown defaults.
diff --git a/docs/zh/developer/anydoc-document-parser-poc.md b/docs/zh/developer/anydoc-document-parser-poc.md
new file mode 100644
index 0000000000..9483db120e
--- /dev/null
+++ b/docs/zh/developer/anydoc-document-parser-poc.md
@@ -0,0 +1,75 @@
+---
+title: Anydoc 文档解析器 PoC
+---
+
+# Anydoc 文档解析器 PoC
+
+本文是设计与兼容性 PoC,不会新增文档文件格式,也不会引入 anydoc 运行时依赖。
+
+**状态:** 该开放方案由 GH-11801 跟踪。在运行时模型确定前,本文不会加入文档侧边栏发布。
+
+## 当前边界
+
+文件连接器目前有两条独立的文档处理路径:
+
+- `MarkdownReadStrategy` 读取 Markdown 并输出文档元素行。
+- `PdfReadStrategy` 使用 PDFBox 读取 PDF,并输出相近的行结构。
+
+anydoc 后端应在现有 Markdown 行生成之前增加转换步骤:
+
+```text
+源文件字节
+    -> 文档转 Markdown 后端
+    -> MarkdownReadStrategy
+    -> 文档元素行和可选的 RAG 元数据
+```
+
+本 PoC 为 `MarkdownReadStrategy` 增加包级可见的 Markdown 交接方法。交接方法显式接收原始源 URI 和原始源字节的 SHA-256,不能使用临时 Markdown 路径生成文档标识,也不能把转换后 Markdown 的哈希当作原始文档哈希。现有 Markdown 文件仍使用原有读取路径和结构。确定性单元测试使用 anydoc CLI 从已有 Excel 测试文件生成的 Markdown,验证现有元素和 RAG 元数据行为。
+
+## PoC 命令
+
+实验直接使用上游 CLI,不把它加入 SeaTunnel 依赖。由于 `npx -y` 会下载并执行指定软件包,只应在隔离的开发环境中运行:
+
+```shell
+npx -y @firecrawl/anydoc@0.1.9 \
+  seatunnel-connectors-v2/connector-file/connector-file-base/src/test/resources/excel/test_read_excel.xlsx \
+  -o anydoc-output.md
+```
+
+该测试资源使用 `0.1.9` 版本生成,SHA-256 为 `e5fc44559f67b2970729b0fb4d4b2d71935790d3073e2abb9001d3b224826fa0`。输出包含 `Sheet1` 标题和 GitHub-Flavored Markdown 表格。测试资源保存该输出,使单元测试保持本地、确定且不依赖网络。
+
+## 兼容性结论
+
+- 现有 `markdown` 和 `pdf` 格式不需要改变。
+- RAG 字段可以继续使用原始源 URI,因此文档和分块标识不会绑定到临时 Markdown 文件。
+- 当前 Flexmark 解析器未启用表格扩展,因此 anydoc 生成的电子表格和 CSV 表格会退化为一个包含竖线标记的段落分块。要支持表格数据,必须兼容地启用 `TablesExtension`,或在转换层按表格结构分块,这不是可选优化。
+- `MarkdownReadStrategy` 已包含 `TableBlock` 处理代码,但在禁用 `TablesExtension` 时无法到达。启用该代码前必须先确定兼容的行结构。
+- 文本型文档可以转换;纯图片 PDF 仍需要 OCR,不能声明为本地 anydoc 后端支持的格式。
+
+## 运行时选项
+
+### 外部可执行文件
+
+技术实现最小,但每个 worker 都必须安装固定版本的可执行文件。SeaTunnel 还需要定义命令发现、超时、进程终止、临时文件、输出限制、stderr、并发和后端缺失时的行为。
+
+### WebAssembly
+
+可以避免每个文档启动一次进程,但 SeaTunnel 当前没有 Java WebAssembly 运行时边界。引入前需要确定运行时、依赖与分发方式、内存和执行限制,并验证 Linux、macOS 和 Windows。
+
+### Sidecar 服务
+
+可以把原生运行时与 JVM 隔离,但会增加网络 API、部署、认证、重试和可用性约定,不等同于可选的本地解析器。
+
+## 生产实现前需要确认的决策
+
+在新增用户配置或 `DOCUMENT` 格式前,维护者需要确定支持的运行时与打包模型,包括:
+
+1. 首个后端使用外部可执行文件、WebAssembly 还是 sidecar;
+2. 谁负责在每个 worker 上安装并固定后端版本;
+3. 支持的操作系统和处理器架构;
+4. 超时、输出大小、资源、并发和清理限制;
+5. 不支持、加密、损坏和纯图片文件的错误分类;
+6. GFM 表格改为表格元素,还是在转换层进行分块,以及对现有 Markdown 输出的兼容性影响;
+7. 许可证、NOTICE、二进制分发和漏洞更新责任。
+
+完成上述决策后,生产实现可以增加文档解析器 SPI、一个可选 provider、声明式配置、英文和中文连接器文档及 E2E 测试,同时保持现有 PDF 和 Markdown 默认行为不变。
diff --git a/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/source/reader/MarkdownReadStrategy.java b/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/source/reader/MarkdownReadStrategy.java
index c9982a9e55..5d0aeaf055 100644
--- a/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/source/reader/MarkdownReadStrategy.java
+++ b/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/source/reader/MarkdownReadStrategy.java
@@ -26,6 +26,7 @@ import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
 import org.apache.seatunnel.api.table.type.SeaTunnelRow;
 import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
 import org.apache.seatunnel.connectors.seatunnel.file.config.FileBaseSourceOptions;
+import org.apache.seatunnel.connectors.seatunnel.file.exception.FileConnectorErrorCode;
 import org.apache.seatunnel.connectors.seatunnel.file.exception.FileConnectorException;
 import org.apache.seatunnel.connectors.seatunnel.file.source.FileSourceDocumentRouting;
 import org.apache.seatunnel.connectors.seatunnel.file.source.MarkdownKnowledgeSyncMetadata;
@@ -148,9 +149,6 @@ public class MarkdownReadStrategy extends AbstractReadStrategy {
             }
             markdown = IOUtils.toString(contentStream, StandardCharsets.UTF_8);
         }
-        Parser parser = Parser.builder().build();
-        Node document = parser.parse(markdown);
-        String sourceUri = FileSourceDocumentRouting.normalizeSourceUri(path);
         LogicalDocumentMetadata logicalMetadata =
                 documentDigest == null
                         ? null
@@ -158,6 +156,62 @@ public class MarkdownReadStrategy extends AbstractReadStrategy {
                                 logicalSourceUri,
                                 logicalDocumentId,
                                 MarkdownKnowledgeSyncMetadata.toLowerHex(documentDigest.digest()));
+        collectMarkdownRows(markdown, path, logicalMetadata, output);
+    }
+
+    /**
+     * Emits rows from converted Markdown while preserving the identity of the original source.
+     *
+     * <p>{@code sourcePath} and {@code sourceDocumentHash} must describe the original source file,
+     * not an intermediate Markdown file or the converted Markdown bytes.
+     */
+    void collectMarkdownRows(
+            String markdown,
+            String sourcePath,
+            String sourceDocumentHash,
+            Collector<SeaTunnelRow> output) {
+        validateConvertedMarkdown(markdown, sourcePath, sourceDocumentHash);
+        LogicalDocumentMetadata logicalMetadata = null;
+        if (markdownRagMetadataEnabled) {
+            String logicalSourceUri =
+                    MarkdownKnowledgeSyncMetadata.canonicalizeSourceUri(sourcePath);
+            logicalMetadata =
+                    new LogicalDocumentMetadata(
+                            logicalSourceUri,
+                            MarkdownKnowledgeSyncMetadata.buildDocumentId(logicalSourceUri),
+                            sourceDocumentHash);
+        }
+        collectMarkdownRows(markdown, sourcePath, logicalMetadata, output);
+    }
+
+    private void validateConvertedMarkdown(
+            String markdown, String sourcePath, String sourceDocumentHash) {
+        if (sourcePath == null || sourcePath.trim().isEmpty()) {
+            throw new FileConnectorException(
+                    FileConnectorErrorCode.DATA_DESERIALIZE_FAILED,
+                    "Cannot parse converted Markdown without the original source path");
+        }
+        if (markdown == null || markdown.trim().isEmpty()) {
+            throw new FileConnectorException(
+                    FileConnectorErrorCode.DATA_DESERIALIZE_FAILED,
+                    "Converted Markdown is empty for source: " + sourcePath);
+        }
+        if (markdownRagMetadataEnabled
+                && (sourceDocumentHash == null || sourceDocumentHash.trim().isEmpty())) {
+            throw new FileConnectorException(
+                    FileConnectorErrorCode.DATA_DESERIALIZE_FAILED,
+                    "Original document hash is missing for source: " + sourcePath);
+        }
+    }
+
+    private void collectMarkdownRows(
+            String markdown,
+            String sourcePath,
+            LogicalDocumentMetadata logicalMetadata,
+            Collector<SeaTunnelRow> output) {
+        Parser parser = Parser.builder().build();
+        Node document = parser.parse(markdown);
+        String sourceUri = FileSourceDocumentRouting.normalizeSourceUri(sourcePath);
 
         Map<Node, NodeInfo> nodeInfoMap = new IdentityHashMap<>();
         Map<String, Integer> typeCounters = new HashMap<>();
diff --git a/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/source/reader/MarkdownReadStrategyTest.java b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/source/reader/MarkdownReadStrategyTest.java
index f7408aae48..7b71cade1d 100644
--- a/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/source/reader/MarkdownReadStrategyTest.java
+++ b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/source/reader/MarkdownReadStrategyTest.java
@@ -23,7 +23,9 @@ import org.apache.seatunnel.api.table.type.KnowledgeSyncMetadataField;
 import org.apache.seatunnel.api.table.type.SeaTunnelRow;
 import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
 import org.apache.seatunnel.connectors.seatunnel.file.config.HadoopConf;
+import org.apache.seatunnel.connectors.seatunnel.file.exception.FileConnectorException;
 import org.apache.seatunnel.connectors.seatunnel.file.source.FileSourceDocumentRouting;
+import org.apache.seatunnel.connectors.seatunnel.file.source.MarkdownKnowledgeSyncMetadata;
 
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
@@ -42,6 +44,11 @@ import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.FS_DEFAULT_NAME
 
 class MarkdownReadStrategyTest {
 
+    private static final String CONVERTED_SOURCE_PATH = "file:///documents/folder/../report.xlsx";
+    private static final String INTERMEDIATE_MARKDOWN_PATH = "file:///tmp/report.md";
+    private static final String ORIGINAL_SOURCE_HASH =
+            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+
     private static final String[] DEFAULT_FIELD_NAMES = {
         "element_id",
         "element_type",
@@ -207,6 +214,111 @@ class MarkdownReadStrategyTest {
         Assertions.assertNotEquals(firstContentHash, secondCollector.getRows().get(0).getField(12));
     }
 
+    @Test
+    public void testCollectRowsFromConvertedMarkdown() throws Exception {
+        URL resource = this.getClass().getResource("/anydoc/test_read_excel.md");
+        String convertedMarkdown =
+                new String(Files.readAllBytes(Paths.get(resource.toURI())), StandardCharsets.UTF_8);
+        MarkdownReadStrategy markdownReadStrategy =
+                (MarkdownReadStrategy) createRagMetadataMarkdownReadStrategy();
+        TempCollector collector = new TempCollector();
+        TempCollector intermediateCollector = new TempCollector();
+
+        markdownReadStrategy.collectMarkdownRows(
+                convertedMarkdown, CONVERTED_SOURCE_PATH, ORIGINAL_SOURCE_HASH, collector);
+        markdownReadStrategy.collectMarkdownRows(
+                convertedMarkdown,
+                INTERMEDIATE_MARKDOWN_PATH,
+                ORIGINAL_SOURCE_HASH,
+                intermediateCollector);
+
+        // TablesExtension is intentionally disabled today, so the table remains one paragraph.
+        Assertions.assertEquals(2, collector.getRows().size());
+        Assertions.assertEquals("Heading", collector.getRows().get(0).getField(1));
+        Assertions.assertEquals("Sheet1", collector.getRows().get(0).getField(3));
+        Assertions.assertEquals("Paragraph", collector.getRows().get(1).getField(1));
+        Assertions.assertTrue(
+                String.valueOf(collector.getRows().get(1).getField(3)).contains("Cosmos"));
+        String canonicalSourceUri =
+                MarkdownKnowledgeSyncMetadata.canonicalizeSourceUri(CONVERTED_SOURCE_PATH);
+        Assertions.assertEquals(canonicalSourceUri, collector.getRows().get(0).getField(8));
+        Assertions.assertEquals(
+                MarkdownKnowledgeSyncMetadata.buildDocumentId(canonicalSourceUri),
+                collector.getRows().get(0).getField(9));
+        Assertions.assertNotEquals(
+                intermediateCollector.getRows().get(0).getField(9),
+                collector.getRows().get(0).getField(9));
+        Assertions.assertNotEquals(
+                intermediateCollector.getRows().get(0).getField(10),
+                collector.getRows().get(0).getField(10));
+        Assertions.assertEquals(1, collector.getRows().get(0).getField(11));
+        Assertions.assertEquals(2, collector.getRows().get(1).getField(11));
+        for (SeaTunnelRow row : collector.getRows()) {
+            Assertions.assertEquals(
+                    ORIGINAL_SOURCE_HASH,
+                    row.getOptions().get(KnowledgeSyncMetadataField.DOCUMENT_HASH.getName()));
+        }
+    }
+
+    @Test
+    void shouldRejectEmptyConvertedMarkdownWithSourceContext() {
+        MarkdownReadStrategy markdownReadStrategy =
+                (MarkdownReadStrategy) createRagMetadataMarkdownReadStrategy();
+
+        FileConnectorException nullFailure =
+                Assertions.assertThrows(
+                        FileConnectorException.class,
+                        () ->
+                                markdownReadStrategy.collectMarkdownRows(
+                                        null,
+                                        CONVERTED_SOURCE_PATH,
+                                        ORIGINAL_SOURCE_HASH,
+                                        new TempCollector()));
+        FileConnectorException blankFailure =
+                Assertions.assertThrows(
+                        FileConnectorException.class,
+                        () ->
+                                markdownReadStrategy.collectMarkdownRows(
+                                        "  ",
+                                        CONVERTED_SOURCE_PATH,
+                                        ORIGINAL_SOURCE_HASH,
+                                        new TempCollector()));
+
+        Assertions.assertTrue(nullFailure.getMessage().contains(CONVERTED_SOURCE_PATH));
+        Assertions.assertTrue(blankFailure.getMessage().contains(CONVERTED_SOURCE_PATH));
+    }
+
+    @Test
+    void shouldRequireOriginalDocumentHashWhenRagMetadataEnabled() {
+        MarkdownReadStrategy markdownReadStrategy =
+                (MarkdownReadStrategy) createRagMetadataMarkdownReadStrategy();
+
+        FileConnectorException failure =
+                Assertions.assertThrows(
+                        FileConnectorException.class,
+                        () ->
+                                markdownReadStrategy.collectMarkdownRows(
+                                        "# Title",
+                                        CONVERTED_SOURCE_PATH,
+                                        null,
+                                        new TempCollector()));
+
+        Assertions.assertTrue(failure.getMessage().contains(CONVERTED_SOURCE_PATH));
+    }
+
+    @Test
+    void shouldCollectConvertedMarkdownWithoutRagMetadata() {
+        MarkdownReadStrategy markdownReadStrategy =
+                (MarkdownReadStrategy) createMarkdownReadStrategy();
+        TempCollector collector = new TempCollector();
+
+        markdownReadStrategy.collectMarkdownRows("# Title", CONVERTED_SOURCE_PATH, null, collector);
+
+        Assertions.assertEquals(1, collector.getRows().size());
+        Assertions.assertEquals(DEFAULT_FIELD_NAMES.length, collector.getRows().get(0).getArity());
+        Assertions.assertNull(collector.getRows().get(0).getOptionsOrNull());
+    }
+
     @Test
     void shouldEmitExactDocumentAndImmediateChunkHashesInIndependentOptions() throws Exception {
         Path markdownFile = tempDir.resolve("hashes.md");
diff --git a/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/resources/anydoc/test_read_excel.md b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/resources/anydoc/test_read_excel.md
new file mode 100644
index 0000000000..970d4fb7b2
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/resources/anydoc/test_read_excel.md
@@ -0,0 +1,7 @@
+## Sheet1
+
+| c_bytes | c_short | c_int | c_bigint | c_string | c_double | c_float | c_decimal | c_boolean | c_map | c_array | c_date | c_datetime | c_time |
+| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
+| 1 | 22 | 333 | 4444 | Cosmos | 5.555 | 6.666 | 7.78 | FALSE | {"name":"Ivan","age":"26"} | \["Ivan","Dusayi"] | 2024-01-31 | 2024-01-31 16:00:48 | 16:00:48 |
+| 2 |  |  |  | 1 |  |  |  |  |  |  |  |  |  |
+| 3 |  |  |  |  |  |  |  |  |  |  |  |  |  |