Skip to content

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

Open
anneheartrecord wants to merge 1 commit into
langgenius:mainfrom
anneheartrecord:refactor/snippet-model-session-param
Open

refactor(models): pass session into CustomizedSnippet accessors#40379
anneheartrecord wants to merge 1 commit into
langgenius:mainfrom
anneheartrecord:refactor/snippet-model-session-param

Conversation

@anneheartrecord

Copy link
Copy Markdown

Summary

Part of #40372 — this one takes api/models/snippet.py. It does not touch api/models/model.py, so it doesn't overlap #40370.

CustomizedSnippet reached for the Flask-global db.session inside five properties:
graph_dict, tags, created_by_account, author_name, updated_by_account. Those are now
get_*(*, session: Session) methods, matching the accessors already extracted in models/dataset.py
and models/workflow.py.

Since the response models validate by attribute, the session is bound at the request boundary with a
SnippetResponseSource adapter in fields/snippet_fields.py — same shape as _WorkflowResponseSource
in controllers/console/app/workflow.py and _SessionResponseSource in fields/conversation_fields.py.
All four snippet response sites in controllers/console/workspace/snippets.py go through it.

input_fields_list and version_str are pure and stay properties.

Two things worth calling out for review:

  • The PATCH handler now serializes inside the session block, and its except ValueError is narrowed
    to the update itself. pydantic.ValidationError subclasses ValueError, so leaving dump_response
    inside that except would report an already-committed write back to the client as a 400. There's a
    regression test for this.
  • tests/unit_tests/models/test_snippet.py no longer needs to monkeypatch db.session to inject the
    SQLite session — that hack was the symptom this refactor removes. I also dropped the
    @pytest.mark.parametrize("sqlite_session", [...], indirect=True) decorators there, which the
    sqlite_session fixture docstring asks to remove on review ("Legacy indirect model parameters remain
    accepted by pytest but are ignored").

No user-visible behavior change: response payload shapes and values are identical.

Screenshots

Not applicable — backend refactor with no API surface change.

Checklist

  • This change requires a documentation update, included: no docs change needed (no API surface change)
  • 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 cd web && pnpm exec vp staged (frontend) to appease the lint gods

ruff format/ruff check, lint-imports, lint_response_contracts.py and pyrefly are clean;
829 tests pass across tests/unit_tests/{models,fields,controllers/console/workspace,controllers/console/snippets}
and test_snippet_service.py. Frontend untouched.

From Claude Code

The snippet model reached for the Flask-global `db.session` inside five
properties, which hides the session boundary from callers and forces tests
to monkeypatch `db.session` to swap in a SQLite session.

Convert them to `get_*(*, session: Session)` methods, matching the accessors
already extracted in `models/dataset.py` and `models/workflow.py`, and bind
the session at the request boundary with a `SnippetResponseSource` adapter so
the response models keep validating by attribute — the same shape as
`_WorkflowResponseSource` and `_SessionResponseSource`.

`input_fields_list` and `version_str` are pure and stay properties.

The PATCH handler now serializes inside the session block, with `except
ValueError` narrowed to the update itself; `ValidationError` subclasses
`ValueError`, so leaving serialization inside it would report an already
committed write as a 400.
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. refactor labels Aug 9, 2026
@github-actions

github-actions Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-08-09 14:12:26.465843049 +0000
+++ /tmp/pyrefly_pr.txt	2026-08-09 14:12:13.133828972 +0000
@@ -2138,6 +2138,8 @@
    --> tests/unit_tests/controllers/console/workspace/test_endpoint.py:453:46
 ERROR Missing argument `endpoint_id` in function `controllers.console.workspace.endpoint.EndpointIdPayload.__init__` [missing-argument]
    --> tests/unit_tests/controllers/console/workspace/test_endpoint.py:495:46
+ERROR Cannot set item in `dict[str, SnippetType | bool | datetime | int | list[Unknown] | str | None]` [unsupported-operation]
+  --> tests/unit_tests/controllers/console/workspace/test_snippets.py:74:22
 ERROR Argument `list[FromClause]` is not assignable to parameter `tables` with type `Sequence[Table] | None` in function `sqlalchemy.sql.schema.MetaData.create_all` [bad-argument-type]
   --> tests/unit_tests/controllers/console/workspace/test_workspace.py:54:54
 ERROR `SimpleNamespace` is not assignable to attribute `db` with type `SQLAlchemy` [bad-assignment]

@github-actions

github-actions Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 58.26% 58.28% +0.02%
Strict coverage 57.84% 57.85% +0.02%
Typed symbols 38,287 38,311 +24
Untyped symbols 27,627 27,627 0
Modules 3144 3144 0

raise NotFound("Snippet not found")

return dump_response(SnippetResponse, snippet), 200
return dump_response(SnippetResponse, SnippetResponseSource(snippet, session=db.session())), 200

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.

you may try with_session to inject

self._session = session

def __getattr__(self, name: str) -> object:
return getattr(self._snippet, name) # guard-ignore: no-new-getattr -- delegates model fields

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.

no reflection plz

user = _account("account-1")
snippet = _snippet()
updated_snippet = _snippet(get_graph_dict="not-a-dict")
session = SimpleNamespace(merge=Mock(return_value=snippet), commit=Mock())

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.

read conftest

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

Labels

refactor size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants