Skip to content

refactor(models): pass session into CustomizedSnippet accessors - #41531

Closed
moneycat957 wants to merge 3 commits into
langgenius:mainfrom
moneycat957:refactor/snippet-session-accessors
Closed

moneycat957 wants to merge 3 commits into
langgenius:mainfrom
moneycat957:refactor/snippet-session-accessors

Conversation

@moneycat957

Copy link
Copy Markdown

Important

  1. Read CONTRIBUTING.md.
  2. Associated issue: rewrite property to accept session: Session as parameter #40372 (claimed the snippet.py slice in this comment).

Summary

Part of #40372.

Follow-up to #40370 and #41370: converts the CustomizedSnippet accessors in
api/models/snippet.py that reach for the global db.session internally into plain
methods taking session: Session explicitly, per the pattern established in those PRs:

  • CustomizedSnippet.graph_dict — was @property doing db.session.get(Workflow, ...);
    now def graph_dict(self, session: Session) -> dict[str, Any].
  • CustomizedSnippet.tags — was @property doing db.session.scalars(...);
    now def tags(self, session: Session) -> Sequence[Tag].
  • CustomizedSnippet.created_by_account — same conversion;
    now def created_by_account(self, session: Session) -> Account | None.
  • CustomizedSnippet.updated_by_account — same conversion;
    now def updated_by_account(self, session: Session) -> Account | None.
  • CustomizedSnippet.author_name — delegates to created_by_account, so it threads the
    caller's session through; now def author_name(self, session: Session) -> str | None.

input_fields_list and version_str touch no database and remain @property.
The now-unused from .engine import db import is dropped — snippet.py no longer
references the global session at all.

No production callers needed updating: the only references to these accessor names
elsewhere in the codebase belong to other models.

Tests

api/tests/unit_tests/models/test_snippet.py previously needed a snippet_session
fixture that monkeypatched snippet_module.db.session onto the SQLite session, purely
to work around the accessors reaching for the global session. That fixture is now
obsolete and has been removed; the existing tests take sqlite_session directly and
pass it into each accessor.

Adds TestCustomizedSnippetSessionAccessors::test_accessors_return_none_when_related_rows_are_absent,
covering the case where created_by / updated_by hold ids with no matching row — a
distinct path from the existing "no id at all" test, since it exercises session.get()
returning None rather than the falsy-id short circuit. It also asserts the empty-result
paths for graph_dict and tags.

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 added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • 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

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-09-21 09:47:17.034329989 +0000
+++ /tmp/pyrefly_pr.txt	2026-09-21 09:47:04.749222829 +0000
@@ -6348,6 +6348,8 @@
    --> tests/unit_tests/models/test_provider_models.py:794:24
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.ProviderModelCredential.__init__` [bad-argument-type]
    --> tests/unit_tests/models/test_provider_models.py:818:24
+ERROR Could not find name `snippet_module` [unknown-name]
+   --> tests/unit_tests/models/test_snippet.py:102:24
 ERROR Argument `Literal['oauth2']` is not assignable to parameter `credential_type` with type `CredentialType | SQLCoreOperations[CredentialType]` in function `models.tools.BuiltinToolProvider.__init__` [bad-argument-type]
    --> tests/unit_tests/models/test_tool_models.py:141:29
 ERROR Argument `None` is not assignable to parameter `value` with type `SQLCoreOperations[str] | str` in function `sqlalchemy.orm.base.Mapped.__set__` [bad-argument-type]

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 84.48% 84.48% -0.00%
Strict coverage 84.14% 84.14% -0.00%
Typed symbols 88,547 88,546 -1
Untyped symbols 16,327 16,328 +1
Modules 4434 4434 0

@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

@moneycat957
moneycat957 marked this pull request as draft August 31, 2026 15:26
auto-merge was automatically disabled August 31, 2026 15:26

Pull request was converted to draft

@moneycat957

Copy link
Copy Markdown
Author

Thanks for the review. The CI failure points at something bigger than a broken test, so
I'd rather flag it than push a green-CI patch.

Root cause of the failing checks

tests/unit_tests/fields/test_snippet_fields.py:34 monkeypatches models.snippet.db:

monkeypatch.setattr(snippet_module.db, "session", sqlite_session)

This PR drops the now-unused from .engine import db import from models/snippet.py, so
that attribute no longer exists. That's what both Run Type Checks
(No attribute 'db' in module 'models.snippet' [missing-attribute]) and
API Unit Tests (3.12) are reporting. I missed this file — I only updated
tests/unit_tests/models/test_snippet.py.

But fixing that test is not sufficient

That test exists because fields/snippet_fields.py consumes these accessors through
Pydantic's from_attributes (ResponseModel sets from_attributes=True):

class SnippetListItemResponse(ResponseModel):
    tags: list[SnippetTagResponse]
    author_name: str | None

class SnippetResponse(ResponseModel):
    graph:      dict[str, Any] = Field(validation_alias="graph_dict")
    tags:       list[SnippetTagResponse]
    created_by: SimpleAccountResponse | None = Field(validation_alias="created_by_account")
    updated_by: SimpleAccountResponse | None = Field(validation_alias="updated_by_account")

All five accessors this PR converts are read by attribute name during response validation.
Once they are methods rather than properties, Pydantic receives the bound method object.
controllers/console/workspace/snippets.py calls dump_response(SnippetResponse, snippet)
directly on the ORM instance at three sites (lines 180, 203, 252), with no session in scope.

Reproduced on this branch:

snippet.author_name
-> <bound method CustomizedSnippet.author_name of <models.snippet.CustomizedSnippet ...>>

dump_response(SnippetListItemResponse, snippet)
-> ValidationError: 2 validation errors for SnippetListItemResponse
   tags:        Input should be a valid list   [input_type=method]
   author_name: Input should be a valid string [input_type=method]

So as it stands this PR would 500 the customized-snippet console endpoints. I've converted
it to draft so it doesn't get merged while we decide.

How would you like to proceed?

(a) Keep the model change and move response construction off from_attributes.
The controller (or SnippetService) would build the response explicitly with a session it
already owns, e.g. author_name=snippet.author_name(session). This is the change that
actually completes the refactor, but it reaches into fields/snippet_fields.py,
controllers/console/workspace/snippets.py and possibly services/snippet_service.py —
well beyond the slice I claimed, so I don't want to do it unilaterally.

(b) Drop snippet.py from #40372's scope for now.
Unlike the ChildChunk / WorkflowAppLog slices, every accessor on CustomizedSnippet is
load-bearing for response serialization, so there's no subset that can be converted in
isolation. If you'd rather land the serialization refactor first and revisit the session
threading afterwards, I'll close this PR and note the finding on #40372 so nobody else
claims the slice and hits the same wall.

I'm happy to do (a) in this PR if you confirm the direction — including whether you'd
prefer the explicit construction to live in the controller or in SnippetService. Just
didn't want to expand the diff by 3 files without asking.

@moneycat957

Copy link
Copy Markdown
Author

Following up on my own question — I went looking for precedent in the tree and found the
answer, so I'd like to propose option (a) concretely rather than leave this open.

api/fields/ already has an established pattern for exactly this problem:
DatasetDetailResponseSource in dataset_fields.py, and ConversationResponseSource /
MessageResponseSource / _SessionResponseSource / _FeedbackResponseSource /
_AnnotationResponseSource in conversation_fields.py. Each holds the ORM object plus a
Session, exposes the session-dependent fields as properties that delegate to
get_*(session=...) on the model, and falls through to the model for everything else via
__getattr__. Response validation then runs against the wrapper instead of the raw model,
so the model accessors are free to take an explicit session.

snippet_fields.py has no such wrapper, which is why converting the CustomizedSnippet
accessors broke serialization here — I skipped a step that the Dataset and Conversation
paths had already taken.

Proposed plan for this PR, mirroring DatasetDetailResponseSource:

  1. Add get_graph_dict, get_tags, get_created_by_account, get_updated_by_account and
    get_author_name, each taking session: Session, to CustomizedSnippet, keeping the
    existing @property accessors in place for now.
  2. Add SnippetResponseSource (plus a snippet_response_source(snippet, *, session)
    factory) to fields/snippet_fields.py, following the DatasetDetailResponseSource
    shape.
  3. Update the three dump_response(SnippetResponse | SnippetListItemResponse, snippet)
    call sites in controllers/console/workspace/snippets.py to wrap the model with a
    session first.
  4. Remove the legacy @property accessors, leaving the session-aware methods as the only
    path — the step this PR originally jumped straight to.

That is more than the snippet.py slice I claimed on #40372, so I'd rather confirm before
expanding the diff: is this the direction you want, and would you prefer it all in this PR,
or steps 1–3 in a separate PR with this one rebased on top to do step 4?

@asukaminato0721
asukaminato0721 marked this pull request as ready for review September 21, 2026 09:46

@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

Co-authored-by: Asuka Minato <i@asukaminato.eu.org>
@github-actions github-actions Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Nov 9, 2026
@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 89.25%. Comparing base (9a0961a) to head (ea2af13).
⚠️ Report is 1487 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #41531      +/-   ##
==========================================
+ Coverage   87.58%   89.25%   +1.66%     
==========================================
  Files        5471     6011     +540     
  Lines      318391   368048   +49657     
  Branches    63816    68331    +4515     
==========================================
+ Hits       278871   328495   +49624     
+ Misses      34129    33452     -677     
- Partials     5391     6101     +710     
Flag Coverage Δ
api 89.92% <ø> (+2.65%) ⬆️

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

@41tair

41tair commented Nov 11, 2026

Copy link
Copy Markdown
Member

Fixed in #40379.

@41tair 41tair closed this Nov 11, 2026
auto-merge was automatically disabled November 11, 2026 11:49

Pull request was closed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants