Skip to content

refactor(api): decode load balancing credentials with Pydantic - #43999

Merged
asukaminato0721 merged 5 commits into
langgenius:mainfrom
xiaoyuCR7:refactor/load-balancing-credentials-pydantic
Nov 18, 2026
Merged

asukaminato0721 merged 5 commits into
langgenius:mainfrom
xiaoyuCR7:refactor/load-balancing-credentials-pydantic

Conversation

@xiaoyuCR7

Copy link
Copy Markdown
Contributor

Important

  1. Make sure you have read our contribution guidelines
  2. Ensure there is an associated issue
  3. Use the correct syntax to link this PR: Fixes #<issue number>.

Summary

Replace the three duplicated json.loads blocks in ModelLoadBalancingService with one TypeAdapter-backed helper, _decode_encrypted_config.

  • get_load_balancing_configs, get_load_balancing_config and _custom_credentials_validate now share the same decode path.
  • A stored encrypted_config that is valid JSON but not an object (a list, a string, null) used to pass through json.loads and raise AttributeError later. It now decodes to an empty mapping, the same as malformed JSON already did.
  • Added a parametrized unit test for missing, malformed and non-object values. 3 of the 6 cases fail on the previous code.

Verified locally: pytest api/tests/unit_tests/services/test_model_load_balancing_service.py (25 passed), ruff format --check, ruff check, and pyrefly check on the service file. make is unavailable on Windows, so the underlying commands were run directly.

Part of #33092

Screenshots

Before After
N/A (backend-only change) N/A

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

@github-actions github-actions Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Oct 13, 2026
@ghfind-review ghfind-review Bot added the review: low ghfind author score; see https://ghfind.com label Oct 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-10-13 15:15:20.853219544 +0000
+++ /tmp/pyrefly_pr.txt	2026-10-13 15:15:12.465161636 +0000
@@ -2248,6 +2248,10 @@
    --> tests/unit_tests/core/agent/test_fc_agent_runner.py:639:29
 ERROR Missing argument `description` in function `core.agent.plugin_entities.AgentStrategyEntity.__init__` [missing-argument]
    --> tests/unit_tests/core/agent/test_plugin_entities.py:292:32
+ERROR Invalid key for TypedDict `AppParametersDict`, got `Unknown` [bad-typed-dict-key]
+  --> tests/unit_tests/core/app/app_config/common/test_parameters_mapping.py:67:23
+ERROR Invalid key for TypedDict `AppParametersDict`, got `str` [bad-typed-dict-key]
+   --> tests/unit_tests/core/app/app_config/common/test_parameters_mapping.py:130:27
 ERROR Argument `dict[str, dict[str, str]]` is not assignable to parameter `config` with type `AppModelConfigDict` in function `core.app.app_config.easy_ui_based_app.agent.manager.AgentConfigManager.convert` [bad-argument-type]
   --> tests/unit_tests/core/app/app_config/easy_ui_based_app/test_agent_manager.py:28:45
 ERROR Object of class `NoneType` has no attribute `strategy` [missing-attribute]
@@ -2400,6 +2404,18 @@
   --> tests/unit_tests/core/app/app_config/easy_ui_based_app/test_variables_manager.py:68:67
 ERROR Argument `dict[str, list[dict[VariableEntityType, dict[str, str]]]]` is not assignable to parameter `config` with type `AppModelConfigDict` in function `core.app.app_config.easy_ui_based_app.variables.manager.BasicVariablesConfigManager.convert` [bad-argument-type]
   --> tests/unit_tests/core/app/app_config/easy_ui_based_app/test_variables_manager.py:85:67
+ERROR Cannot index into `VariableEntity` [bad-index]
+   --> tests/unit_tests/core/app/app_config/workflow_ui_based_app/test_workflow_ui_based_app_manager.py:119:16
+ERROR Cannot index into `VariableEntity` [bad-index]
+   --> tests/unit_tests/core/app/app_config/workflow_ui_based_app/test_workflow_ui_based_app_manager.py:140:16
+ERROR Cannot index into `VariableEntity` [bad-index]
+   --> tests/unit_tests/core/app/app_config/workflow_ui_based_app/test_workflow_ui_based_app_manager.py:159:16
+ERROR Cannot index into `VariableEntity` [bad-index]
+   --> tests/unit_tests/core/app/app_config/workflow_ui_based_app/test_workflow_ui_based_app_manager.py:178:16
+ERROR Cannot index into `RagPipelineVariableEntity` [bad-index]
+   --> tests/unit_tests/core/app/app_config/workflow_ui_based_app/test_workflow_ui_based_app_manager.py:246:16
+ERROR Cannot index into `RagPipelineVariableEntity` [bad-index]
+   --> tests/unit_tests/core/app/app_config/workflow_ui_based_app/test_workflow_ui_based_app_manager.py:273:16
 ERROR Expected a mapping, got object | None [invalid-argument]
   --> tests/unit_tests/core/app/apps/advanced_chat/test_app_config_manager.py:41:29
 ERROR Argument `SimpleNamespace` is not assignable to parameter `args` with type `LoopNodeRunPayload` in function `core.app.apps.advanced_chat.app_generator.AdvancedChatAppGenerator.single_loop_generate` [bad-argument-type]
@@ -4972,6 +4988,8 @@
    --> tests/unit_tests/core/workflow/nodes/agent_v2/test_dify_tools_builder.py:417:43
 ERROR Argument `object` is not assignable to parameter `output` with type `Decimal | Iterable[Any] | Mapping[str, Any] | bool | bytearray | bytes | float | int | str | None` in function `clients.agent_backend.event_adapter.AgentBackendRunSucceededInternalEvent.__init__` [bad-argument-type]
   --> tests/unit_tests/core/workflow/nodes/agent_v2/test_output_adapter.py:51:16
+ERROR Object of class `FromClause` has no attribute `create` [missing-attribute]
+  --> tests/unit_tests/core/workflow/nodes/agent_v2/test_output_file_rebacker.py:22:5
 ERROR Cannot index into `object` [bad-index]
    --> tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py:235:22
 ERROR Cannot index into `object` [bad-index]
@@ -5948,6 +5966,8 @@
     --> tests/unit_tests/services/test_dataset_service_document.py:1038:16
 ERROR Object of class `NoneType` has no attribute `rules` [missing-attribute]
     --> tests/unit_tests/services/test_dataset_service_document.py:1930:38
+ERROR Argument `SimpleNamespace` is not assignable to parameter `knowledge_config` with type `KnowledgeConfig` in function `services.knowledge.dataset_service.DocumentService.save_document_with_dataset_id` [bad-argument-type]
+   --> tests/unit_tests/services/test_dataset_service_lock_not_owned.py:125:26
 ERROR Argument `str` is not assignable to parameter `type` with type `Literal['basic', 'bearer', 'custom'] | None` in function `services.entities.external_knowledge_entities.external_knowledge_entities.AuthorizationConfig.__init__` [bad-argument-type]
    --> tests/unit_tests/services/test_external_dataset_service.py:116:60
 ERROR Argument `str` is not assignable to parameter `type` with type `Literal['api-key', 'no-auth']` in function `services.entities.external_knowledge_entities.external_knowledge_entities.Authorization.__init__` [bad-argument-type]
@@ -5960,6 +5980,8 @@
     --> tests/unit_tests/services/test_external_dataset_service.py:1551:16
 ERROR `None` is not subscriptable [unsupported-operation]
     --> tests/unit_tests/services/test_external_dataset_service.py:1552:16
+ERROR `str` is not assignable to attribute `plan` with type `CloudPlan` [bad-assignment]
+  --> tests/unit_tests/services/test_feature_service_human_input_email_delivery.py:74:42
 ERROR Argument `Literal['invalid']` is not assignable to parameter `session_factory` with type `Engine | sessionmaker[Unknown] | None` in function `services.file_service.FileService.__init__` [bad-argument-type]
   --> tests/unit_tests/services/test_file_service.py:85:41
 ERROR Unexpected keyword argument `whole_workspace` in function `core.workflow.human_input_adapter.EmailRecipients.__init__` [unexpected-keyword]
@@ -5968,6 +5990,10 @@
    --> tests/unit_tests/services/test_message_service.py:214:31
 ERROR Returned type `MetadataService` is not assignable to declared return type `Iterator[MetadataService]` [bad-return]
   --> tests/unit_tests/services/test_metadata_service_session_boundary.py:54:12
+ERROR Argument `str | None` is not assignable to parameter `s` with type `bytearray | bytes | str` in function `json.loads` [bad-argument-type]
+   --> tests/unit_tests/services/test_model_load_balancing_service.py:394:23
+ERROR `(tenant_id: str) -> service_with_fake_configurations._FakeProviderManager` is not assignable to attribute `_get_provider_manager` with type `(tenant_id: str) -> ProviderManager` [bad-assignment]
+  --> tests/unit_tests/services/test_model_provider_service_sanitization.py:74:33
 ERROR Argument `dict[str, Any]` is not assignable to parameter `utm_info` with type `UtmInfo` in function `services.operation_service.OperationService.record_utm` [bad-argument-type]
    --> tests/unit_tests/services/test_operation_service.py:118:57
 ERROR Argument `Literal['']` is not assignable to parameter `plan` with type `CloudPlan` in function `RagPipelineTaskProxyTestDataFactory.create_mock_features` [bad-argument-type]

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 86.56% 86.56% +0.01%
Strict coverage 86.21% 86.22% +0.01%
Typed symbols 93,718 93,763 +45
Untyped symbols 14,614 14,614 0
Modules 4599 4599 0

@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.25%. Comparing base (4dc4748) to head (6db3a25).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #43999   +/-   ##
=======================================
  Coverage   90.24%   90.25%           
=======================================
  Files        6437     6437           
  Lines      405070   405096   +26     
  Branches    81485    81481    -4     
=======================================
+ Hits       365556   365609   +53     
+ Misses      33104    33089   -15     
+ Partials     6410     6398   -12     
Flag Coverage Δ
api 90.02% <100.00%> (+0.01%) ⬆️
cli 94.30% <ø> (ø)
dify-ui 92.65% <ø> (ø)
web 90.36% <ø> (-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.

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

dify-codereview

@cursor
cursor Bot force-pushed the refactor/load-balancing-credentials-pydantic branch from 1b1da41 to df59a4c Compare November 16, 2026 12:41
@github-actions github-actions Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels 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.

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

dify-codereview

xiaoyuCR7 and others added 3 commits November 16, 2026 13:08
Replace the three duplicated json.loads blocks in ModelLoadBalancingService with one TypeAdapter-backed helper. Stored encrypted_config values that are valid JSON but not an object (a list, a string, null) now decode to an empty mapping instead of raising AttributeError further down.

Part of langgenius#33092
Decode stored encrypted_config once into LoadBalancingCredentials, a strict
provider-defined map of strings and switch booleans, and pass that value
through listing, updates, and validation.

Co-authored-by: Evan <lightraincr7@gmail.com>
Credential checks take a LoadBalancingTokenCipher instead of a patched
validator, and submitted credentials are typed as strings or switch booleans.

Co-authored-by: Evan <lightraincr7@gmail.com>
@cursor
cursor Bot force-pushed the refactor/load-balancing-credentials-pydantic branch from df59a4c to 9b22d9d Compare November 16, 2026 13:08
@github-actions github-actions Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Nov 16, 2026
@autofix-ci
autofix-ci Bot requested a review from crazywoola as a code owner November 16, 2026 13:10
@github-actions github-actions Bot added the web This relates to changes on the web. label 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.

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

dify-codereview

@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: Run Web Tests / Web Browser Tests (2/2), Web Tests. Please fix it. Checked 7d2c074875.

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
Credential validation takes the plugin model assembly and an injected
encrypter cipher, so those tests no longer patch or ignore a runtime type.

Co-authored-by: Evan <lightraincr7@gmail.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.

Nothing to flag at 6db3a256f5.

dify-codereview

@asukaminato0721
asukaminato0721 dismissed stale reviews from themself November 16, 2026 13:33

Nothing left to flag at 6db3a25.

@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 16, 2026
@asukaminato0721
asukaminato0721 added this pull request to the merge queue Nov 18, 2026
Merged via the queue into langgenius:main with commit ce26dd6 Nov 18, 2026
63 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review: low ghfind author score; see https://ghfind.com size:XL This PR changes 500-999 lines, ignoring generated files. waiting-for-reviewer dify-codereview: checked, nothing left for the author; a reviewer's turn web This relates to changes on the web.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants