Skip to content

refactor(api): release moderation lookup sessions before external calls - #45896

Open
ShousenZHANG wants to merge 15 commits into
langgenius:mainfrom
ShousenZHANG:refactor/api-moderation-session
Open

ShousenZHANG wants to merge 15 commits into
langgenius:mainfrom
ShousenZHANG:refactor/api-moderation-session

Conversation

@ShousenZHANG

@ShousenZHANG ShousenZHANG commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Part of #45584. The API moderation provider held a database connection while decrypting the extension's API key and waiting for its HTTP response. It now reads a tenant-owned extension through the existing repository. The read session closes before key decryption and HTTP dispatch.

Form validation uses the repository to check that the tenant owns the extension. It requires neither key decryption nor an HTTP request. The input and output paths preserve their existing settings and payload behavior. Each Flask app supplies the moderation runtime through its composition root.

Verification

  • A SQLite pool probe reproduced the original problem and observed the connection being checked in before decryption and before HTTP dispatch after the change. Tests also cover tenant isolation, disabled directions and propagated dependency errors.
  • 477 focused regression tests passed locally. Ruff, import contracts, response contracts, generated billing checks, Pyrefly and repository guards passed.
  • GitHub Actions passed on 31c17008f4a. The Linux test reports include the moderation session-order tests, application initialization and KnowledgeFS registration.

Screenshots

Backend changes only.

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

From Codex

Copilot AI balanced review requested due to automatic review settings November 9, 2026 07:18

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@github-actions github-actions Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Nov 9, 2026
@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 88.05% 88.06% +0.01%
Strict coverage 87.69% 87.70% +0.01%
Typed symbols 98,719 98,823 +104
Untyped symbols 13,451 13,451 0
Modules 4713 4716 +3

@codecov

codecov Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.62%. Comparing base (4cbb38e) to head (31c1700).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #45896      +/-   ##
==========================================
- Coverage   90.62%   90.62%   -0.01%     
==========================================
  Files        6665     6667       +2     
  Lines      415339   415371      +32     
  Branches    83296    83298       +2     
==========================================
+ Hits       376412   376436      +24     
- Misses      32541    32548       +7     
- Partials     6386     6387       +1     
Flag Coverage Δ
api 90.35% <100.00%> (+<0.01%) ⬆️

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.

4 inline suggestions at 6745a908f8, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

Comment thread api/core/moderation/api/api.py Resolved
Comment thread api/core/moderation/api/api.py Resolved
@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
@github-actions github-actions Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Nov 17, 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.

4 inline suggestions at c4c07ad114, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

Comment thread api/services/api_moderation_service.py Resolved
Comment thread api/services/api_moderation_service.py Resolved
@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 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-11-17 07:22:39.527882580 +0000
+++ /tmp/pyrefly_pr.txt	2026-11-17 07:22:23.155794856 +0000
@@ -3734,6 +3734,12 @@
  --> tests/unit_tests/core/evaluation/frameworks/ragas/test_ragas_model_wrapper.py:9:1
 ERROR Cannot find module `langchain_core.prompt_values` [missing-import]
   --> tests/unit_tests/core/evaluation/frameworks/ragas/test_ragas_model_wrapper.py:10:1
+ERROR Cannot redefine existing type alias `RequestHandler` [redefinition]
+  --> tests/unit_tests/core/extension/test_api_based_extension_requestor.py:18:1
+ERROR Cannot redefine existing type alias `InstalledClient` [redefinition]
+  --> tests/unit_tests/core/extension/test_api_based_extension_requestor.py:19:1
+ERROR Cannot redefine existing type alias `InstallClient` [redefinition]
+  --> tests/unit_tests/core/extension/test_api_based_extension_requestor.py:23:1
 ERROR Class member `_ModelInstance.invoke_llm` overrides parent class `ModelInstance` in an inconsistent manner [bad-override]
   --> tests/unit_tests/core/llm_generator/output_parser/test_structured_output.py:68:9
 ERROR Class member `_ModelInstance.invoke_llm` overrides a member in a parent class but is missing an `@override` decorator [missing-override-decorator]

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

CI is failing: API Tests, Run API Tests / API Unit Tests (3.13, shard 2/2), Style Check / Python Style. Please fix it. 5 inline suggestions at 9fd8f7e6f0, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

Comment thread api/services/api_moderation_service.py Resolved
@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 17, 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.

2 inline suggestions at 33d843413b, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong. 2 review threads are still unresolved.

dify-codereview

Comment thread api/core/moderation/factory.py Resolved
@asukaminato0721 asukaminato0721 removed the waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address label Nov 17, 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 80d66a1173, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 2 review threads are still unresolved.

dify-codereview

Comment thread api/services/api_moderation_service.py Resolved
@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
asukaminato0721

This comment was marked as outdated.

@asukaminato0721
asukaminato0721 dismissed stale reviews from themself November 18, 2026 05:47

Nothing left to flag at 80d66a1.

@asukaminato0721 asukaminato0721 added waiting-for-reviewer dify-codereview: checked, nothing left for the author; a reviewer's turn and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 18, 2026
@asukaminato0721 asukaminato0721 removed the waiting-for-reviewer dify-codereview: checked, nothing left for the author; a reviewer's turn label Nov 27, 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.

Please split this into smaller pull requests: it adds 358 lines of non-test code, more than 300. Split it by feature: each pull request carries one functional change together with its tests, so each feature stands on its own and can be reviewed, merged and reverted independently. It will be reviewed once it is under 300. Size counts added non-test lines; tests, lock files and snapshots do not count.

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 27, 2026
asukaminato0721

This comment was marked as outdated.

@asukaminato0721
asukaminato0721 dismissed their stale review November 27, 2026 12:19

Nothing left to flag at 80d66a1.

@asukaminato0721 asukaminato0721 added waiting-for-reviewer dify-codereview: checked, nothing left for the author; a reviewer's turn and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 27, 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.

Please split this into smaller pull requests: it adds 358 lines of non-test code, more than 300. Split it by feature: each pull request carries one functional change together with its tests, so each feature stands on its own and can be reviewed, merged and reverted independently. It will be reviewed once it is under 300. Size counts added non-test lines; tests, lock files and snapshots do not count.

dify-codereview

@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-reviewer dify-codereview: checked, nothing left for the author; a reviewer's turn labels Nov 27, 2026
@github-actions github-actions Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Nov 27, 2026
@ShousenZHANG

Copy link
Copy Markdown
Contributor Author

I split the changes in 31c1700. This PR now covers the tenant-scoped lookup and releases the database connection before decryption or the external request. It adds 194 non-test lines, down from 358, and includes the session-lifetime and tenant-isolation tests. I kept strict configuration and payload validation in a separate local draft.

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

2 inline suggestions at 31c17008f4, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

@dataclass
class Outbound:
events: list[str]
calls: list[tuple[str, str, dict[str, object]]] = field(default_factory=list)

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.

from core.extension.api_based_extension_requestor import APIBasedExtensionPoint, APIBasedExtensionRequestor


def request_inputs(api_endpoint: str, api_key: str, params: dict[str, object]) -> JsonValue:

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.

@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 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XL This PR changes 500-999 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.

3 participants