Skip to content

test(api): bring the knowledge index node tests under strict pyrefly - #46483

Closed
shuxiachai wants to merge 3 commits into
langgenius:mainfrom
shuxiachai:test/knowledge-index-node-strict-pyrefly
Closed

shuxiachai wants to merge 3 commits into
langgenius:mainfrom
shuxiachai:test/knowledge-index-node-strict-pyrefly

Conversation

@shuxiachai

@shuxiachai shuxiachai commented Nov 16, 2026 •

Copy link
Copy Markdown

Summary

#46482

core/workflow/nodes/knowledge_index/test_knowledge_index_node.py leaves project-excludes in api/tests/unit_tests/pyrefly.toml. The events/test___init__.py entry is dropped too: that file already passes strict checking. project-excludes: 154 → 152.

  • mock_index_processor and mock_summary_index_service used to return the real IndexProcessor / SummaryIndex instances, and the tests then reached into .index_and_clean.return_value and similar. Typed as the real classes, those attributes are bound methods, not mocks. The fixtures now return small frozen dataclasses that hold the mocks mocker.patch.object returned. The test bodies keep the same attribute paths and get typed access.
  • test_invoke_with_summary_index_setting passed {"enabled": True} as summary_index_setting, but SummaryIndexSettingDict defines enable. It is now a typed SummaryIndexSettingDict with the correct key. The node forwards the setting unchanged, so the assertions are the same.
  • The remaining changes are annotations on the fixtures, _build_node and the test methods.

No # pyrefly: ignore, no typing.cast, and no new Mock() / MagicMock() constructions.

Verification

  • uv run --directory api --dev pyrefly check --summary=none --use-ignore-files=false --disable-project-excludes-heuristics=true --config=tests/unit_tests/pyrefly.toml → no errors or warnings
  • ./dev/pyrefly-check-local → exit 0
  • pytest api/tests/unit_tests/core/workflow/nodes/knowledge_index/test_knowledge_index_node.py api/tests/unit_tests/events/test___init__.py → 13 passed
  • make lint steps (ruff format and check, response contract lint, import linter, dotenv-linter) → pass
  • CI guards run on the staged change (no new cast, test doubles, spec mock, getattr, session mock, base model, constructor bypass) → pass

Update after review

Following the review, KnowledgeIndexNode takes index_processor and summary_index_service as optional keyword arguments typed by IndexProcessorProtocol and SummaryIndexServiceProtocol; without them it builds IndexProcessor and SummaryIndex, so the node factory is unchanged. The protocols' summary_index_setting now matches the SummaryIndexSettingDict | None that both implementations accept. The tests pass recording implementations of the protocols instead of patching the node module, so the fixture dataclasses that held the patch mocks are gone.

  • Contract: the node's dependencies are the given implementations, or the production ones when omitted; construction performs no I/O.
  • pyrefly (unit-test config) and ./dev/pyrefly-check-local → no errors; pytest on the node, node factory and index processor tests → 99 passed (one existing index processor test needs os.register_at_fork and errors on Windows only); make lint steps and the staged guards → pass.

Screenshots

N/A (backend change)

Checklist

  • This change requires a documentation update, included: Dify Document
  • I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
  • I've verified the change and added or updated tests where meaningful regression risk justifies coverage.
  • I've updated the documentation accordingly.
  • I ran make lint && make type-check (backend) and vp staged (frontend) to appease the lint gods

🤖 Generated with Claude Code

From Claude Code

Remove test_knowledge_index_node.py and the stale events/test___init__.py
entry from the unit-test pyrefly project-excludes. The patching fixtures
now return the mocks created by mocker.patch.object, and the summary
setting in the pass-through test uses the SummaryIndexSettingDict key
`enable`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Nov 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-11-16 05:09:42.591307813 +0000
+++ /tmp/pyrefly_pr.txt	2026-11-16 05:09:25.351102374 +0000
@@ -4857,8 +4857,6 @@
     --> tests/unit_tests/core/workflow/nodes/human_input/test_entities.py:1456:29
 ERROR Class member `_EventQueue.listen` overrides a member in a parent class but is missing an `@override` decorator [missing-override-decorator]
     --> tests/unit_tests/core/workflow/nodes/human_input/test_entities.py:1484:9
-ERROR Argument `dict[str, bool]` is not assignable to parameter `summary_index_setting` with type `SummaryIndexSettingDict | None` in function `core.workflow.nodes.knowledge_index.knowledge_index_node.KnowledgeIndexNode._invoke_knowledge_index` [bad-argument-type]
-   --> tests/unit_tests/core/workflow/nodes/knowledge_index/test_knowledge_index_node.py:638:35
 ERROR `None` is not subscriptable [unsupported-operation]
    --> tests/unit_tests/core/workflow/nodes/knowledge_retrieval/test_knowledge_retrieval_node.py:615:16
 ERROR `None` is not subscriptable [unsupported-operation]

@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 86.43% 86.50% +0.07%
Strict coverage 86.09% 86.16% +0.07%
Typed symbols 93,437 93,514 +77
Untyped symbols 14,730 14,653 -77
Modules 4587 4587 0

@codecov

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.34%. Comparing base (5244c1b) to head (9c8a237).
⚠️ Report is 24 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #46483      +/-   ##
==========================================
- Coverage   90.41%   90.34%   -0.07%     
==========================================
  Files        6334     6363      +29     
  Lines      396678   402436    +5758     
  Branches    79712    80626     +914     
==========================================
+ Hits       358642   363571    +4929     
- Misses      31928    32459     +531     
- Partials     6108     6406     +298     
Flag Coverage Δ
api 89.99% <ø> (-0.12%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@asukaminato0721 asukaminato0721 self-assigned this Nov 16, 2026

@asukaminato0721 asukaminato0721 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

1 inline suggestion at 9c8a2372a1, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong.

dify-codereview

@asukaminato0721 asukaminato0721 added the waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address label Nov 16, 2026
…tching

KnowledgeIndexNode now takes its index processor and summary service as
optional keyword arguments typed by the existing protocols, as
KnowledgeRetrievalV2Node does with its services. Without them it still
builds IndexProcessor and SummaryIndex, so the node factory is unchanged.

Align summary_index_setting in both protocols with
SummaryIndexSettingDict, the type IndexProcessor and SummaryIndex accept;
nothing used the protocols before. The tests pass recording
implementations of both protocols and no longer patch the node module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@asukaminato0721 asukaminato0721 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

1 inline suggestion at 68e0bd3070, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong.

dify-codereview

dataset_id: str
document_id: str
original_document_id: str
chunks: Mapping[str, object]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/): model this data once at the boundary as a pydantic model / dataclass / TypedDict (Model.model_validate(raw)), and pass the typed value on, instead of passing dicts around and re-checking keys and types where they are used. In a test, don't build this as an ad hoc dict[str, object]: define the shape (TypedDict / model) in the production code and import it here.

dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks. The sample chunks are now built from MultimodalGeneralStructureChunk / GeneralChunk in core/rag/models/document.py, the model ParagraphIndexProcessor validates them with, and the node data uses IndexStructureType.PARAGRAPH_INDEX instead of the unsupported "general_structure" (5b9720c).

IndexCall.chunks itself stays Mapping[str, object] on purpose: it records the argument exactly as the node forwarded it, and IndexProcessorProtocol.index_and_clean types that argument as Mapping[str, Any]. The node does not parse chunks. Their model depends on the chunk structure, and each index processor parses them at its own boundary (MultimodalGeneralStructureChunk, ParentChildStructureChunk, QAStructureChunk). Moving that parsing into the node would change production behaviour, which is outside the scope of this PR, so I've left that boundary as it is.

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 18, 2026
The sample chunks were ad hoc dicts, and the node data named a chunk
structure ("general_structure") that IndexProcessorFactory does not
support. Build the chunks from MultimodalGeneralStructureChunk, the
model the paragraph index processor validates them with, and use
IndexStructureType.PARAGRAPH_INDEX.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@asukaminato0721 asukaminato0721 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

1 inline suggestion at 5b9720ca7c, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 1 review thread is still unresolved.

dify-codereview

document_id: str
original_document_id: str
chunks: Mapping[str, object]
batch: object

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please use the precise type here, not object / Any: e.g. -> str, -> Session, Callable[...]; for a parametrized test, the union of the case types (or a type alias for it); for __exit__, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None.

dify-codereview · precise-types (concrete-type) Learned from an earlier review. Reply here if this is wrong.

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 18, 2026
@shuxiachai shuxiachai closed this Nov 25, 2026
@shuxiachai
shuxiachai deleted the test/knowledge-index-node-strict-pyrefly branch November 25, 2026 00:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files. waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants