refactor(models): pass session into CustomizedSnippet accessors - #40379
Open
anneheartrecord wants to merge 1 commit into
Open
refactor(models): pass session into CustomizedSnippet accessors#40379anneheartrecord wants to merge 1 commit into
anneheartrecord wants to merge 1 commit into
Conversation
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.
anneheartrecord
requested review from
QuantumGhost and
laipz8200
as code owners
August 9, 2026 13:35
Contributor
Pyrefly Diffbase → 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]
|
asukaminato0721
enabled auto-merge
August 9, 2026 14:13
Contributor
Pyrefly Type Coverage
|
| raise NotFound("Snippet not found") | ||
|
|
||
| return dump_response(SnippetResponse, snippet), 200 | ||
| return dump_response(SnippetResponse, SnippetResponseSource(snippet, session=db.session())), 200 |
Contributor
There was a problem hiding this comment.
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 |
| user = _account("account-1") | ||
| snippet = _snippet() | ||
| updated_snippet = _snippet(get_graph_dict="not-a-dict") | ||
| session = SimpleNamespace(merge=Mock(return_value=snippet), commit=Mock()) |
asukaminato0721
requested changes
Aug 9, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Part of #40372 — this one takes
api/models/snippet.py. It does not touchapi/models/model.py, so it doesn't overlap #40370.CustomizedSnippetreached for the Flask-globaldb.sessioninside five properties:graph_dict,tags,created_by_account,author_name,updated_by_account. Those are nowget_*(*, session: Session)methods, matching the accessors already extracted inmodels/dataset.pyand
models/workflow.py.Since the response models validate by attribute, the session is bound at the request boundary with a
SnippetResponseSourceadapter infields/snippet_fields.py— same shape as_WorkflowResponseSourcein
controllers/console/app/workflow.pyand_SessionResponseSourceinfields/conversation_fields.py.All four snippet response sites in
controllers/console/workspace/snippets.pygo through it.input_fields_listandversion_strare pure and stay properties.Two things worth calling out for review:
except ValueErroris narrowedto the update itself.
pydantic.ValidationErrorsubclassesValueError, so leavingdump_responseinside that
exceptwould report an already-committed write back to the client as a 400. There's aregression test for this.
tests/unit_tests/models/test_snippet.pyno longer needs to monkeypatchdb.sessionto inject theSQLite session — that hack was the symptom this refactor removes. I also dropped the
@pytest.mark.parametrize("sqlite_session", [...], indirect=True)decorators there, which thesqlite_sessionfixture docstring asks to remove on review ("Legacy indirect model parameters remainaccepted 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
make lint && make type-check(backend) andcd web && pnpm exec vp staged(frontend) to appease the lint godsruff format/ruff check,lint-imports,lint_response_contracts.pyandpyreflyare 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