Skip to content

test(api): bring the tenant expired logs test under strict pyrefly - #46335

Open
MindOfqc wants to merge 9 commits into
langgenius:mainfrom
MindOfqc:test/pyrefly-tenant-expired-and-app-generator
Open

MindOfqc wants to merge 9 commits into
langgenius:mainfrom
MindOfqc:test/pyrefly-tenant-expired-and-app-generator

Conversation

@MindOfqc

Copy link
Copy Markdown
Contributor

Why

api/tests/unit_tests/services/test_clear_free_plan_tenant_expired_logs.py is still listed in project-excludes, so it is never checked under strict pyrefly.

Summary

Brings the module under strict checking and removes its entry from project-excludes (208 → 207 entries).

Twelve diagnostics are cleared:

  • 2 × bad-override + 2 × missing-override-decorator on the frozen-clock subclass. datetime.now is declared to return the subclass itself, so the helper now returns cls.fromtimestamp(...) of the pinned instant and marks the override. Microseconds and tzinfo survive the round trip, so the value the test freezes is still the same instant.
  • 1 × bad-argument-type → the conversation status uses ConversationStatus.NORMAL instead of the literal "normal". It is a StrEnum whose value is that string, so the persisted value is unchanged.
  • 7 × implicit-any-empty-container → the "no more rows" entries in the batch side_effect lists use list[object]() so their element type is known.

No # pyrefly: ignore, no # type: ignore, no typing.cast, no typing.Any.

Verification

  • Strict pyrefly project check (api/tests/unit_tests, pyrefly 1.5.0-dev.1 with the repo venv interpreter): ERROR 29 with all 29 being the pre-existing missing-import noise. WARN 0. Target file residual 0.
  • pytest on the file → 13 passed.
  • ruff check and ruff format --check clean.

Annotate the free plan tenant cleanup test so it passes the strict pyrefly
project check, then drop its entry from project-excludes.

Twelve diagnostics are cleared. The frozen clock subclass now returns an
instance of itself, matching what `datetime.now` declares, and marks the
override; the value it returns is still the pinned instant. The conversation
status uses the real enum instead of the literal string, three expiring batches
use `list[object]()` so the element type is known, and ruff reports no import
drift. No ignores, no casts, no typing.Any.
@github-actions github-actions Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Nov 14, 2026
@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-11-28 04:11:19.052781240 +0000
+++ /tmp/pyrefly_pr.txt	2026-11-28 04:11:08.916666700 +0000
@@ -5069,22 +5069,6 @@
    --> tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.py:894:16
 ERROR Argument `str` is not assignable to parameter `freeze_type` with type `Literal['', 'email_domain_suspended', 'freeze']` in function `services.billing_client.saas.CheckAccountInFreezeReply.model_construct` [bad-argument-type]
    --> tests/unit_tests/services/test_billing_service.py:373:87
-ERROR Argument `Literal['normal']` is not assignable to parameter `status` with type `ConversationStatus | SQLCoreOperations[ConversationStatus]` in function `models.model.Conversation.__init__` [bad-argument-type]
-   --> tests/unit_tests/services/test_clear_free_plan_tenant_expired_logs.py:117:16
-ERROR Object of class `object` has no attribute `id` [missing-attribute]
-   --> tests/unit_tests/services/test_clear_free_plan_tenant_expired_logs.py:329:39
-ERROR Class member `FixedDateTime.now` overrides parent class `datetime` in an inconsistent manner [bad-override]
-   --> tests/unit_tests/services/test_clear_free_plan_tenant_expired_logs.py:593:13
-ERROR Class member `FixedDateTime.now` overrides a member in a parent class but is missing an `@override` decorator [missing-override-decorator]
-   --> tests/unit_tests/services/test_clear_free_plan_tenant_expired_logs.py:593:13
-ERROR Class member `FixedDateTime.now` overrides parent class `datetime` in an inconsistent manner [bad-override]
-   --> tests/unit_tests/services/test_clear_free_plan_tenant_expired_logs.py:665:13
-ERROR Class member `FixedDateTime.now` overrides a member in a parent class but is missing an `@override` decorator [missing-override-decorator]
-   --> tests/unit_tests/services/test_clear_free_plan_tenant_expired_logs.py:665:13
-ERROR Object of class `object` has no attribute `kw` [missing-attribute]
-   --> tests/unit_tests/services/test_clear_free_plan_tenant_expired_logs.py:762:12
-ERROR Object of class `object` has no attribute `kw` [missing-attribute]
-   --> tests/unit_tests/services/test_clear_free_plan_tenant_expired_logs.py:763:12
 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:92:45
 ERROR Argument `Iterator[dict[str, str | dict[str, str]] | str]` is not assignable to parameter `response` with type `Generator[Mapping[str, Any] | str] | Mapping[str, Any]` in function `services.snippet_generate_service.SnippetGenerateService._filter_virtual_start_events` [bad-argument-type]

@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 88.05% 88.05% 0.00%
Strict coverage 87.69% 87.69% 0.00%
Typed symbols 98,721 98,721 0
Untyped symbols 13,450 13,450 0
Modules 4713 4713 0

@codecov

codecov Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.43%. Comparing base (f2b8315) to head (cc6ff0d).
⚠️ Report is 238 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #46335      +/-   ##
==========================================
+ Coverage   90.31%   90.43%   +0.12%     
==========================================
  Files        6495     6534      +39     
  Lines      408426   412355    +3929     
  Branches    81921    82281     +360     
==========================================
+ Hits       368857   372921    +4064     
+ Misses      33163    33048     -115     
+ Partials     6406     6386      -20     
Flag Coverage Δ
api 90.35% <100.00%> (+0.21%) ⬆️

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.

… sweep

pyrefly could not see `.kw` or `.id` on the `object`-typed placeholders.
Declare the collected session makers as `sessionmaker[Session]` and read
each record id through an explicit local before asserting it is present.
@github-actions github-actions Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Nov 14, 2026
Naming `record.id` fails the strict check because the shared declarative base
declares no such attribute, and `getattr` is blocked by the new-getattr guard.
The identity SQLAlchemy already tracks is the same value the `Session.get`
lookups below use.
@asukaminato0721 asukaminato0721 self-assigned this Nov 15, 2026
The cleanup service widened its rows to 'object' because the cleaned
models share an 'id' primary key without a common declarative base, so
callers had to work around the missing attribute. Publish the shared row
type from the origin code and type the service against it.
The two batch loop tests simulated the repository boundary with MagicMock,
so they asserted call counts on a stand-in instead of proving that the
production repositories really remove the rows they hand back.

Both tests now write expired rows to the SQLite database and call the
real factory, then verify from a fresh session that the rows are gone.
Because a broken delete would otherwise make the loop spin forever, the
repositories are wrapped in a forwarding bound that raises after the
second batch, so a regression fails in seconds with a clear message.

Verified by mutating each delete call to return 0: both mutations fail
the suite in ~10s, and the unmodified tree passes 13 tests.
@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 b6ab64e3e5, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

@MindOfqc

Copy link
Copy Markdown
Contributor Author

Replaced both repository stand-ins with the real repositories.

test_process_tenant_processes_and_persists_all_batches and test_process_tenant_repo_loops_break_on_empty_second_batch now write genuinely expired rows to the SQLite session, let DifyAPIRepositoryFactory build the production repositories, and then assert from a fresh session that the rows are gone. The MagicMock repositories and their side_effect batches are removed.

One thing worth flagging: a broken delete previously made the cleanup loop spin forever, so a regression would hang the suite instead of failing it. Both tests now wrap the real repositories in a forwarding bound that raises after the second batch, which keeps the production path intact while making the failure immediate. I confirmed this by mutating each delete call to return 0: both mutations fail the suite in about ten seconds, and the unmodified tree reports 13 passed.

The bounded wrappers used __getattr__ to delegate everything else, which the
no-new-getattr guard rejects. The wrappers only need the two repository calls
the tests exercise, so both are forwarded explicitly instead.

@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 8206b933ea, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong.

dify-codereview

class ClearFreePlanTenantExpiredLogs:
@staticmethod
def _serialize_record(record: object) -> dict[str, object]:
def _serialize_record(record: MessageRelatedRecord | WorkflowNodeExecutionModel) -> dict[str, object]:

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.

The two factory helpers that build the bounded wrappers still declared an
`object` return type, so the type checker could not see that the tests hand
the real repository calls through typed wrappers.
asukaminato0721

This comment was marked as outdated.

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

This comment was marked as outdated.

@asukaminato0721 asukaminato0721 removed the waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address label Nov 20, 2026
@asukaminato0721 asukaminato0721 added the waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address label Nov 20, 2026
…-app-generator

Resolve import-block conflicts by keeping both sides' imports and letting ruff isort re-sort them; no behavioural change.
@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 22, 2026
@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 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 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.

2 participants