Skip to content

feat(feishu): batch-import wiki space / directory URLs (#3120) - #3543

Closed
now-ing wants to merge 1 commit into
volcengine:mainfrom
now-ing:feat/feishu-wiki-batch-import-3120-clean
Closed

now-ing wants to merge 1 commit into
volcengine:mainfrom
now-ing:feat/feishu-wiki-batch-import-3120-clean

Conversation

@now-ing

@now-ing now-ing commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

What & why

Closes #3120.

ov add-resource only recognized single Feishu doc URLs (.../wiki/<doc_token> or .../docx/<doc_token>); a wiki space root (.../wiki/settings/<space_id>) or a directory node URL was rejected with "must import a document link", so importing a 90+-doc wiki knowledge base meant one link at a time.

This extends Feishu URL recognition to dispatch three shapes:

URL shape before after
.../wiki/<doc_token> / .../docx/<doc_token> (leaf) single import unchanged
.../wiki/<token> with children (directory node) error recursive expand, async-import each doc
.../wiki/settings/<space_id> (space root) error expand whole space, async-import each doc

How

  • parse/accessors/feishu_accessor.py
    • classify_url() — three-shape dispatch (single_doc / wiki_node / wiki_space_root).
    • list_wiki_subtree() — async recursive walk via the real lark-oapi SDK (wiki.v2.space.list with pagination + wiki.v2.space.get_node to detect directory nodes), bounded by max_depth (5) + max_nodes (500), with obj_token de-dup to prevent cycles and a stale-page-token guard.
    • expand_feishu_url() — flattens a space/directory URL into direct doc URLs (so children don't re-trigger batch dispatch — no infinite recursion).
  • service/resource_service.py — _is_feishu_batch_candidate predicate + _maybe_enqueue_feishu_batch_add_resource: at the ingestion dispatch point, a batch URL is expanded and each child doc is enqueued through the existing single-doc import path; a batch to becomes the parent for all children (each gets its own URI). Single-doc and non-Feishu URLs unchanged. Reuses feishu_watch_auth tokens; no hardcoded credentials. Batch children get watch_interval=0 (watch stays on the outer request).

Recursion is bounded + timeout-guarded; unknown URLs still raise the original error.

Tests — 43 new, all pass (97 incl. existing Feishu suite, no regression)

tests/parse/test_feishu_wiki_batch.py (32) + tests/service/test_feishu_batch_dispatch.py (11), all mock lark-oapi (no real Feishu calls): classify_url three-shape + edge cases, leaf passthrough, directory recursion, space-root whole-tree, pagination (has_more+page_token), max_depth/max_nodes truncation, empty subtree, obj_token de-dup, unknown obj_type skip-but-continue, API failure propagates (no silent degrade), and service-layer dispatch (N child add_resource tasks + summary, single-doc → original path, token passthrough, expand-failure propagation). 43 pass; full Feishu suite 97 pass, 0 regression.

Notes

  • Real lark-oapi wiki.v2 calls are wired (not TODO); SDK method shapes were probed from the real SDK and aligned with mocked tests. No end-to-end real-Feishu test (no creds in test env).
  • Default bounds (depth 5 / 500 nodes) are conservative — easy to expose as config if a tunable is preferred.

This contribution was developed with AI assistance.

Refs #3120

@now-ing
now-ing force-pushed the feat/feishu-wiki-batch-import-3120-clean branch from 7356db1 to 1399810 Compare July 27, 2026 17:16
@now-ing

now-ing commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

A same-model adversarial review (E2E, with a mocked cyclic wiki graph) found that the cycle prevention was incomplete — fixed in the latest push:

  1. Recursion cycle (red line) — seen_tokens (obj_token) only deduped emitted results; the walker re-entered recursion purely on has_child, so a node whose child pointed back at an ancestor (A → B → A) recursed unboundedly → RecursionError once max_depth was large. Added a separate seen_node_tokens set checked at _walk entry: each node_token is expanded at most once. (Default max_depth=5\) hid this, but expand_feishu_url(max_depth=N)` is a public API.)
  2. Page-token cycle — the guard next_page_token == page_token only caught an adjacent duplicate; an alternating A→B→A token cycle (buggy/malicious API) span until max_nodes. Now uses a seen_page_tokens set.

Two regression tests added (test_list_wiki_subtree_breaks_node_token_cycle, test_list_wiki_subtree_breaks_page_token_cycle) that construct a real cyclic graph and assert bounded API calls + no stack overflow. Suite now 45/45 (32 accessor + 11 dispatch + 2 cycle).

@now-ing

now-ing commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up hardening from the adversarial review: the batch import now throttles concurrency (asyncio.Semaphore(8) — _FEISHU_BATCH_CONCURRENCY). Without it, importing a wiki space with hundreds of docs fanned out one Feishu fetch per doc simultaneously, risking API rate-limiting/风控. Now at most 8 child imports are in flight. Suite still 45/45.

@huangruiteng huangruiteng left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for iterating on #3120. I reviewed exact head 858200b4e5464d865afc28a2e235e2dc7398d4ca; these are still blocking:

  1. _maybe_enqueue_feishu_batch_add_resource() uses only len(expanded) == 1 to distinguish a leaf from a batch. A space or directory with exactly one importable document therefore falls through and tries to ingest the original /wiki/settings/<space_id> or directory URL as a single document. The expansion result needs to preserve source kind, with regressions for one-document spaces/directories.

  2. An explicit to is reassigned to batch_parent, but that directory is never created and create_parent is not forwarded. A normal new target such as viking://resources/my_wiki therefore makes each child fail target resolution. Please cover this through the real target/finalization path rather than a mocked add_resource call.

  3. The batch is currently process-local fire-and-forget work: child imports are started with asyncio.create_task, shutdown cancels them, failures are only logged, and the returned response has no durable batch task/per-item state. This does not satisfy the issue contract for partial-failure visibility, idempotent checkpoint/resume, and restart safety. The (url, title) expansion also discards relative hierarchy, so all documents are flattened. Please route the provider-neutral batch manifest through durable queue/task state and preserve relative paths.

  4. The changed files do not pass repository formatting/lint: ruff check reports import ordering, B017, and F841; ruff format --check reports four files requiring formatting.

Validation on this head with an isolated no-credential HOME: 45 new focused tests passed; 27 existing Feishu parser tests passed; git diff --check passed; merge-tree against current origin/main (8391d3a) was clean. The passing tests currently mock away the target-resolution/durability failures above.

now-ing pushed a commit to now-ing/OpenViking that referenced this pull request Jul 28, 2026
…get path (volcengine#3120)

Address PR volcengine#3543 review blocking points:

1. source_kind dispatch — introduce ExpandedDoc (url/title/source_kind/
   rel_path); a one-document space/directory now correctly takes the
   batch path. Previously len(expanded)==1 mis-classified it as a leaf
   and tried to ingest the /wiki/settings/<id> URL as a single doc.

2. Real target/finalization path — the batch parent is created through
   the real FS (mkdir) before fan-out and create_parent is forwarded on
   every child, so viking://resources/my_wiki resolves each child instead
   of failing target resolution. Dispatch tests exercise the real FS, not
   a mocked add_resource.

3. Durable provider-neutral batch manifest — replace process-local
   asyncio.create_task fire-and-forget with batch_manifest_store (atomic
   tmp→bak→rename, mirrors watch storage) + per-child AddResourceMsg /
   TaskTracker (crash-recoverable QueueFS). The response carries batch_id
   + per-item task_id/status; idempotent resume via deterministic batch_id;
   wiki hierarchy preserved via rel_path (no flattening).

4. ruff — fix import ordering, B017, F841; format all changed files.

56 tests pass (wiki_batch 34 + dispatch 8 + manifest store 7 + routing);
ruff check + format clean on all changed files.
@now-ing

now-ing commented Jul 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review — all four blocking points are addressed in b0090e1.

1. source_kind dispatch (was len(expanded) == 1)
expand_feishu_url / list_wiki_subtree now return ExpandedDoc(url, title, source_kind, rel_path) entries. _maybe_enqueue_feishu_batch_add_resource dispatches on source_kind (single_doc_passthrough vs batch_child), not on length, so a space/directory with exactly one importable document correctly takes the batch path instead of falling through to ingest the original /wiki/settings/<id> URL. Regression: test_batch_handles_single_document_space_as_batch.

2. Real target/finalization path
The batch parent is now created through the real FS (viking_fs.mkdir(exist_ok=True)) before fan-out, and create_parent=True is forwarded on every child add_resource, so a normal new target like viking://resources/my_wiki resolves each child through the real resolve_target_uri path instead of failing target resolution. The dispatch tests now use a real in-memory FS (not a mocked add_resource) and assert the parent directory is actually created and the manifest is actually persisted — test_batch_creates_parent_and_persists_manifest.

3. Durable provider-neutral batch manifest + hierarchy
Replaced the process-local asyncio.create_task fire-and-forget with:

  • a durable manifest (openviking/service/batch_manifest_store.py) written atomically (tmp → bak → rename, mirroring watch-task storage) under viking://resources/.batch_imports/<batch_id>.json;
  • per-child ingestion through the real add_resource(wait=False) path, which enqueues a crash-recoverable AddResourceMsg (QueueFS) + a durable TaskTracker record.

The response now carries batch_id + per-item task_id / status / to_uri. The batch id is derived deterministically from the source URL + parent, so re-submission is idempotent (children that already have a task_id are not re-enqueued — test_batch_is_idempotent_on_resubmit); restart safety comes from the persistent manifest + QueueFS recover-stale + TaskTracker store. Partial failures are recorded per-item and visible, not silently logged (test_batch_partial_failure_records_error). The wiki hierarchy is preserved via rel_path — each child imports under <batch_parent>/<rel_path>/<doc_name> rather than being flattened (test_batch_preserves_hierarchy_via_rel_path).

The manifest module/URI are intentionally provider-neutral (batch_imports, not feishu-specific) so other providers can reuse the same durable path later.

4. ruff
Fixed import ordering, B017 (pytest.raises(Exception) → pytest.raises(OpenVikingError, match=...)) and F841 (unused local); ruff format applied to all six changed files. ruff check and ruff format --check are clean on the changed files.

Validation on b0090e1 (isolated, no-credential HOME): 56 tests pass — tests/parse/test_feishu_wiki_batch.py (34), tests/service/test_feishu_batch_dispatch.py (8), tests/service/test_batch_manifest_store.py (7), plus the routing parametrize. ruff check clean; ruff format --check clean on changed files; working tree clean.

now-ing pushed a commit to now-ing/OpenViking that referenced this pull request Jul 29, 2026
…get path (volcengine#3120)

Address PR volcengine#3543 review blocking points:

1. source_kind dispatch — introduce ExpandedDoc (url/title/source_kind/
   rel_path); a one-document space/directory now correctly takes the
   batch path. Previously len(expanded)==1 mis-classified it as a leaf
   and tried to ingest the /wiki/settings/<id> URL as a single doc.

2. Real target/finalization path — the batch parent is created through
   the real FS (mkdir) before fan-out and create_parent is forwarded on
   every child, so viking://resources/my_wiki resolves each child instead
   of failing target resolution. Dispatch tests exercise the real FS, not
   a mocked add_resource.

3. Durable provider-neutral batch manifest — replace process-local
   asyncio.create_task fire-and-forget with batch_manifest_store (atomic
   tmp→bak→rename, mirrors watch storage) + per-child AddResourceMsg /
   TaskTracker (crash-recoverable QueueFS). The response carries batch_id
   + per-item task_id/status; idempotent resume via deterministic batch_id;
   wiki hierarchy preserved via rel_path (no flattening).

4. ruff — fix import ordering, B017, F841; format all changed files.

56 tests pass (wiki_batch 34 + dispatch 8 + manifest store 7 + routing);
ruff check + format clean on all changed files.
@now-ing
now-ing force-pushed the feat/feishu-wiki-batch-import-3120-clean branch from b0090e1 to fdbd452 Compare July 29, 2026 14:43
@now-ing

now-ing commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main. The four blocking points from your review of 858200b are addressed at head fdbd452 (fix(feishu): durable batch manifest + source-kind dispatch + real target path):

  1. source-kind dispatch — expansion preserves source kind (space/directory/leaf) instead of len(expanded)==1, with one-document space/directory regressions.
  2. real target path — explicit to goes through the real target/finalization path (parent created, create_parent forwarded).
  3. durable batch manifest — provider-neutral batch manifest routed through durable queue/task state, relative paths preserved.
  4. lint/format — ruff check / ruff format --check clean.

Ready for re-review. Thanks!

@now-ing
now-ing force-pushed the feat/feishu-wiki-batch-import-3120-clean branch 2 times, most recently from fdbd452 to b9bdff4 Compare August 26, 2026 18:13
@now-ing

now-ing commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (head b9bdff4) and resolved the merge conflicts against the new resource-service source-plan flow: the batch dispatch now runs before _prepare_standard_source_plan, and the wiki expansion block coexists with the new legacy-doc parsing. All review feedback from earlier rounds remains addressed. Ready for re-review.

@viafcccy

viafcccy commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Cross-reference: focused Phase 1 alternative

Thank you for the extensive exploration and iteration in this PR. A separate focused Draft PR, #4592, now proposes the first phase of #3120.

It carries forward several lessons demonstrated here: recognizing Wiki space URLs, paginated traversal, node/page-token cycle protection, bounded document-fetch concurrency, hierarchy preservation, and visible partial failures.

The main boundary is different:

This cross-reference is intended to help maintainers compare the phase boundaries; it is not a request to close this PR. #4592 also uses Relates to #3120 rather than closing the umbrella issue.

交叉说明:更聚焦的第一阶段方案

感谢本 PR 中大量的探索与多轮迭代。现在另有一个聚焦的 Draft PR #4592,用于落地 #3120 的第一阶段。

新方案继承了这里已经验证出的多项经验:识别 Wiki 空间 URL、分页遍历、节点与分页游标循环保护、正文抓取并发限制、层级保留和可见的部分失败信息。

两者主要区别在阶段边界:

这条说明用于帮助维护者比较两种阶段拆分,并不是请求关闭本 PR。#4592 同样使用 Relates to #3120,不会关闭总 Issue。

- expand wiki space/directory URLs into per-document batch imports
- durable batch manifest routed through queue/task state
- cycle prevention (node-token + page-token) and bounded concurrency (8)
@now-ing
now-ing force-pushed the feat/feishu-wiki-batch-import-3120-clean branch from b9bdff4 to 44ea9c4 Compare September 3, 2026 02:39
@now-ing

now-ing commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @viafcccy for the thoughtful cross-reference — and for carrying the hard-won lessons (paginated traversal, node/page-token cycle protection, bounded fetch concurrency, hierarchy preservation, visible partial failures) into a much more focused shape. The Phase 1 boundary reads well: one directory resource through the existing add-resource queue, node_token placement identity, and durability semantics explicitly deferred.

Two small things from this PR's iteration history that may be worth a look when reviewing #4592:

  1. Windows-unsafe trailing characters in title-derived filenames. {title}.md generation can emit names ending in dots/spaces (or reserved suffixes), which Windows silently strips — two distinct titles like "A" and "A." then collide on disk. The node-token suffix protects siblings, but the root doc name has no such guard. Upstream just hardened the same class of problem for memory URIs in fix(uri): preserve file extension when sanitize_segment truncates #4617 (sanitize_segment truncation); reusing that sanitize for the subtree path generator would keep the two path pipelines consistent.

  2. Partial-failure reports should outlive the task result. With hundreds of docs, the skipped/inaccessible-body list can get truncated in transient UI state; persisting a per-import summary field on the task result keeps failures queryable after completion. Cheap to reserve in Phase 1, avoids a schema change later.

On the phase split: this PR's remaining differentiated pieces — durable batch manifest, per-child task state, checkpoint/resume — map cleanly onto the deferred follow-ups under #3120. If maintainers prefer landing #4592 first, I'm happy to close this PR and re-propose the durability layer as a focused Phase 2 built on top of #4592's structure. The 45-case suite here (cycles, single-document spaces, concurrency regressions, resume semantics) is available for reuse either way.

@now-ing

now-ing commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Farewell note for #3543

First of all — thank you @viafcccy and the team for taking this on. Seeing #4592 land the focused Phase 1 (Wiki subtree import with hierarchy) is exactly the outcome we hoped for when we opened this PR. The carried-forward lessons are the right calls, and in a couple of places #4592 does better than our draft:

  • node_token as placement identity solves both cycle prevention and the shared-document case cleanly. We initially deduped emitted results by obj_token, which silently drops a document's second placement; keeping both placements (as feat(feishu): import Wiki subtrees with hierarchy / 保留层级导入飞书 Wiki 子树 #4592 does) is more faithful to what the user sees in Feishu.
  • Discovery-before-fetch (full structure walk, then document bodies) means the fail-fast guarantees (depth 20 / 500 nodes / repeated node_token) are checked before any document-fetch quota is spent. We like that.
  • The char+byte dual path budgets with the identity-marker reservation (_identified_path_segment) are more careful than our naming code, and deterministic names make watch re-imports diff cleanly.

We are closing #3543 to reduce the review queue — the remaining value here is not in the diff but in a few lessons from our implementation that #4592's current scope (one directory resource per subtree) does not need yet, but later phases might:

  1. Durable batch manifest + resume semantics (openviking/service/batch_manifest_store.py in our branch): the batch plan is persisted atomically (write .tmp → rotate .bak → rename, with .bak fallback on corruption) under viking://resources/.batch_imports/<batch_id>.json before any fan-out, so a crash mid-batch leaves a durable record. The batch id is derived deterministically from sha1(source_url|parent_uri), which makes re-submitting the same Wiki URL idempotent: only children that do not yet have a task_id are enqueued again. If a later phase splits subtree imports into per-document tasks or incremental watch refreshes, this is the piece that turns "restart the whole 400-doc walk" into "resume where we stopped".

  2. Fan-out through the real durable queue: each child was enqueued via the actual add_resource(wait=False) path, so it lands in the crash-recoverable QueueFS AddResource queue + TaskTracker, and per-item status is aggregated live from TaskTracker (get_batch_status) instead of being rewritten into the manifest on every transition. Per-child failures were recorded with error strings in the manifest and became retryable by simply re-submitting the same source URL.

  3. source_kind dispatch (single_doc_passthrough vs batch_child on each expanded entry): dispatch keyed on the entry kind rather than len(expanded) == 1, so a space that contains exactly one importable document still takes the batch path (importing the /wiki/settings/<id> URL itself as a doc would fail confusingly), while a leaf /wiki/<token> keeps the unchanged single-doc path. Only relevant if later phases fan out again, but it was a real edge we hit.

  4. Per-child rel_path under a user-specified parent: each child carried its hierarchy-relative directory path so the Wiki tree landed under the user's explicit to/parent rather than the default target. feat(feishu): import Wiki subtrees with hierarchy / 保留层级导入飞书 Wiki 子树 #4592's single-directory model makes this moot for now.

  5. Defensive page-token guard: in _list_wiki_children we tracked seen page_tokens per listing and stopped when the API repeated one, in addition to feat(feishu): import Wiki subtrees with hierarchy / 保留层级导入飞书 Wiki 子树 #4592's has_more-without-token check. A pathological has_more=true + repeated-token + empty-page response otherwise loops forever without ever tripping the repeated-node_token guard.

Our branch feat/feishu-wiki-batch-import-3120-clean (commit b9bdff4a, 6 files: accessor expansion, batch_manifest_store.py, service dispatch, and ~1,500 lines of tests including a full fake-lark wiki API harness) stays available for cherry-picking — the manifest store and its tests (tests/service/test_batch_manifest_store.py, test_feishu_batch_dispatch.py) are fairly self-contained if Phase 2 wants resumability.

We've also left a detailed review on #4592 from our exploration here. Thanks again for carrying this feature home — happy to test any follow-up phase.

@now-ing

now-ing commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Closing this in favor of the focused Phase 1 PR #4592 — see the review comment above for our remaining hardening suggestions (durable manifest, retry/backoff, pagination guards). The branch stays available for cherry-picking, especially the batch manifest store.

@now-ing now-ing closed this Sep 3, 2026
@github-project-automation github-project-automation Bot moved this from Backlog to Done in OpenViking project Sep 3, 2026
@now-ing
now-ing deleted the feat/feishu-wiki-batch-import-3120-clean branch September 6, 2026 02:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

3 participants