← Back to Pull requests

test(api): bring the billing service tests under strict pyrefly #46407

Open
MindOfqc opened this pull request with 252 lines diff across 7 files
View on GitHub
MindOfqc MindOfqc commented on Nov 14, 2026 12:30 UTC
Author

Part of the pyrefly strict-mode migration: this file leaves project-excludes.

api/tests/unit_tests/pyrefly.toml now carries real annotations, and the remaining diagnostics it exposed were fixed rather than suppressed. No pyrefly: ignore / type: ignore / cast / typing.Any was added.

Verification: pyrefly check on tests/unit_tests/pyrefly.toml reports 29 errors (all pre-existing missing-import for optional packages) and 0 warnings with 0 diagnostics left in the target file; pytest passes match the pre-change baseline; ruff check and ruff format --check pass.

Diff: 252 lines (+213 / -39) across 7 files Reviewer: asukaminato0721 Review duration: 25069m
All Vouch review confidence checks passed
Residual risk 0.07 = Change Risk (0.68) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.68 · 252 lines diff across 7 files
0.68
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.93 · 5 substantive comment(s)
0.93
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.331
Sensitive Paths sensitive_paths
0.068
Real PR Conversation Timeline
20 items
github-actions[bot] github-actions[bot] commented on Nov 14, 2026 12:32 UTC
Bot

Pyrefly Diff


<details>
<summary>base → PR</summary>

--- /tmp/pyrefly_base.txt	2026-11-26 14:03:52.266339810 +0000
+++ /tmp/pyrefly_pr.txt	2026-11-26 14:03:41.254266297 +0000
@@ -5067,8 +5067,6 @@
    --> tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.py:760:16
 ERROR `in` is not supported between `Literal['not found']` and `None` [not-iterable]
    --> 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]


</details>

github-actions[bot] github-actions[bot] commented on Nov 14, 2026 12:32 UTC
Bot

Pyrefly Type Coverage

| Metric | Base | PR | Delta |
| --- | ---: | ---: | ---: |
| Type coverage | 87.92% | 87.94% | +0.03% |
| Strict coverage | 87.58% | 87.61% | +0.03% |
| Typed symbols | 97,241 | 97,282 | +41 |
| Untyped symbols | 13,415 | 13,389 | -26 |
| Modules | 4672 | 4672 | 0 |

codecov[bot] codecov[bot] commented on Nov 14, 2026 12:36 UTC
Bot

Codecov Report


:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 90.52%. Comparing base (df05396) to head (cb631cb).
:warning: Report is 4 commits behind head on main.

<details><summary>Additional details and impacted files</summary>

@@            Coverage Diff             @@
##             main   #46407      +/-   ##
==========================================
- Coverage   90.53%   90.52%   -0.01%     
==========================================
  Files        6608     6608              
  Lines      410585   410691     +106     
  Branches    82396    82394       -2     
==========================================
+ Hits       371706   371781      +75     
- Misses      32489    32512      +23     
- Partials     6390     6398       +8     

| Flag | Coverage Δ | |
|---|---|---|
| api | 90.20% <100.00%> (-0.02%) | :arrow_down: |

Flags with carried forward coverage won't be shown. Click here to find out more.
</details>

:umbrella: View full report in Codecov by Harness.
:loudspeaker: Have feedback on the report? Share it here.
<details><summary> :rocket: New features to boost your workflow: </summary>

  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

  • </details>

    asukaminato0721 asukaminato0721 commented on code on Nov 15, 2026 08:53 UTC
    Code Review
    api/tests/unit_tests/services/test_billing_service.py:1
    @@ -17,10 +17,20 @@
     ACCOUNT_ID = "33333333-3333-3333-3333-333333333333"
     
     
    +def _freeze_reply(data: bool, freeze_type: str) -> saas.CheckAccountInFreezeReply:
    +    """Build a freeze reply carrying an arbitrary upstream freeze type.
    +
    +    Billing versions predating the enum send values outside the declared literal set,
    +    so the reply is built without validation: the subject only reads `data` and `freeze_type`.

    can we just fix the origin code?

    asukaminato0721 asukaminato0721 requested changes on Nov 15, 2026 08:53 UTC
    Changes Requested Reviewer

    Requested changes.

    MindOfqc MindOfqc commented on Nov 15, 2026 09:50 UTC
    Author

    Fixed at the origin as suggested — and since saas.py is generated, the fix belongs in the generator.

    CheckAccountInFreezeReply.freeze_type is rendered from a proto enum, but the set is open: a dify-saas deployment older or newer than the committed snapshot can send a member the spec never listed. The only consumer, BillingService.get_email_freeze_type, already handles that with case _, so the literal did not protect anything — it only moved the failure from that fallback into pydantic, and transport.py logs validation failures to Sentry while salvaging with model_construct. So every reply from an older server was both noise and a validation bypass.

    generate_billing_client.py now carries an explicit allowlist of open enum fields, and a check_open_enum_fields pass fails generation if an entry stops naming an enum field or vanishes from the snapshot. saas.py declares str, the snapshot JSON is untouched, and the _freeze_reply helper is gone — the test builds a real model through validation, including the "unexpected" case, which is the point of the change.

    Verified: generate_billing_client.py --check exits 0, git diff --stat saas.py is non-empty, strict pyrefly stays at the 29 missing-import baseline with no new warnings, the production project is unchanged at its 3174/32 baseline, test_billing_service.py passes 30 and the billing suites pass 101, ruff is clean, and all seven check_no_new_* guards exit 0.

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:47 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_billing_client.py:1
    @@ -278,3 +278,47 @@ def test_committed_snapshots_keep_only_the_reasons_of_called_services() -> None:
     
     def test_committed_client_matches_snapshots() -> None:
         assert generator.check(generator.expected_files({s: generator.load_snapshot(s) for s in generator.SERVICES})) == 0
    +
    +
    +def test_open_enum_field_renders_as_str_instead_of_the_declared_enum() -> None:
    +    schema = {"type": "string", "enum": ["", "freeze"]}
    +
    +    assert generator.field_type(schema, True, "Reply.value", open_enum=True) == "str"
    +    assert generator.field_type(schema, True, "Reply.value", open_enum=False) == 'Literal["", "freeze"]'
    +
    +
    +def test_open_enum_field_keeps_nullability_and_presence_rules() -> None:
    +    schema = {"type": "string", "enum": ["", "freeze"], "nullable": True}
    +
    +    assert generator.field_type(schema, True, "Reply.value", open_enum=True) == "str | None"
    +    assert generator.field_type(schema, False, "Reply.value", open_enum=True) == "str | None"
    +
    +
    +def test_committed_snapshots_satisfy_the_open_enum_allowlist() -> None:
    +    snapshots = {service: generator.load_snapshot(service) for service in generator.SERVICES}
    +
    +    generator.check_open_enum_fields(snapshots)
    +
    +    reply = snapshots["saas"]["components"]["schemas"]["CheckAccountInFreezeReply"]
    +    assert "enum" in reply["properties"]["freezeType"]
    +    assert 'freeze_type: str = Field(alias="freezeType")' in generator.render_module("saas", snapshots["saas"])
    +
    +
    +def test_open_enum_entries_must_still_name_an_enum_field(monkeypatch: pytest.MonkeyPatch) -> None:
    +    monkeypatch.setattr(generator, "OPEN_ENUM_FIELDS", frozenset({("Reply", "value")}))

    Rather than patching this in the test, change the production code to take the dependency as a parameter (pass the session / account / service in), so the test hands in a real one and needs no patch.

    <sub>dify-codereview · tests-real-dependencies (inject-dependency) Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=tests-real-dependencies;option=inject-dependency;key=f625a8b44eabc765 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:47 UTC
    Code Review
    api/dev/generate_billing_client.py:1
    @@ -590,7 +604,28 @@ def format_python(source: str, path: Path) -> str:
     # --- entry point ----------------------------------------------------------------------------------
     
     
    +def check_open_enum_fields(snapshots: dict[Service, JsonObject]) -> None:
    +    """Precondition: every `OPEN_ENUM_FIELDS` entry still names a string enum field of a snapshot.
    +
    +    Postcondition: a stale entry fails generation instead of silently doing nothing, which would
    +    quietly narrow the field back to the enum. Entries are dropped only together with the upstream
    +    enum, and that is a deliberate edit here.
    +    """
    +    found: set[tuple[str, str]] = set()
    +    for snapshot in snapshots.values():
    +        schemas = snapshot["components"]["schemas"]

    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.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=dab7a851a5a94507 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:47 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_billing_client.py:1
    @@ -278,3 +278,47 @@ def test_committed_snapshots_keep_only_the_reasons_of_called_services() -> None:
     
     def test_committed_client_matches_snapshots() -> None:
         assert generator.check(generator.expected_files({s: generator.load_snapshot(s) for s in generator.SERVICES})) == 0
    +
    +
    +def test_open_enum_field_renders_as_str_instead_of_the_declared_enum() -> None:
    +    schema = {"type": "string", "enum": ["", "freeze"]}
    +
    +    assert generator.field_type(schema, True, "Reply.value", open_enum=True) == "str"
    +    assert generator.field_type(schema, True, "Reply.value", open_enum=False) == 'Literal["", "freeze"]'
    +
    +
    +def test_open_enum_field_keeps_nullability_and_presence_rules() -> None:
    +    schema = {"type": "string", "enum": ["", "freeze"], "nullable": True}
    +
    +    assert generator.field_type(schema, True, "Reply.value", open_enum=True) == "str | None"
    +    assert generator.field_type(schema, False, "Reply.value", open_enum=True) == "str | None"
    +
    +
    +def test_committed_snapshots_satisfy_the_open_enum_allowlist() -> None:
    +    snapshots = {service: generator.load_snapshot(service) for service in generator.SERVICES}
    +
    +    generator.check_open_enum_fields(snapshots)
    +
    +    reply = snapshots["saas"]["components"]["schemas"]["CheckAccountInFreezeReply"]

    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.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=a3985bb615d08f9d -->

    asukaminato0721 asukaminato0721 commented on Nov 16, 2026 09:47 UTC
    Reviewer

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

    <sub>dify-codereview</sub>
    <!-- dify-review:head=13c3a9611c4003ed1332895a22b621d00569f424 -->

    asukaminato0721 asukaminato0721 commented on Nov 16, 2026 12:13 UTC
    Reviewer

    Nothing to flag at 086e07e11d.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=086e07e11d9395f1c830e47823a943b77315268e -->

    asukaminato0721 asukaminato0721 commented on code on Nov 17, 2026 05:53 UTC
    Code Review
    api/services/billing_client/saas.py:1
    @@ -42,7 +42,7 @@ class AppNetworkAccessGroupBinding(BillingModel):
     
     class CheckAccountInFreezeReply(BillingModel):
         data: bool
    -    freeze_type: Literal["", "freeze", "email_domain_suspended"] = Field(alias="freezeType")
    +    freeze_type: str = Field(alias="freezeType")

    why this changed from literal?

    asukaminato0721 asukaminato0721 requested changes on Nov 17, 2026 05:53 UTC
    Changes Requested Reviewer

    Requested changes.

    MindOfqc MindOfqc commented on code on Nov 17, 2026 06:37 UTC
    Code Review
    api/services/billing_client/saas.py:1
    @@ -42,7 +42,7 @@ class AppNetworkAccessGroupBinding(BillingModel):
     
     class CheckAccountInFreezeReply(BillingModel):
         data: bool
    -    freeze_type: Literal["", "freeze", "email_domain_suspended"] = Field(alias="freezeType")
    +    freeze_type: str = Field(alias="freezeType")

    freezeType is an open proto enum, not a closed one. A dify-saas deployment older or newer than this committed spec snapshot can return a value the spec never listed. With Literal[...], pydantic would reject that reply with a ValidationError even though the consumer can still read and act on it — turning a harmless new enum value into a spurious error in Sentry.

    The consumer of CheckAccountInFreezeReply.freeze_type already matches with a case _ fallback, so widening to str loses no safety. The change is made in the generator (api/dev/generate_billing_client.py), not by hand-editing the generated saas.py (api/AGENTS.md forbids editing generated files): a minimal OPEN_ENUM_FIELDS allowlist keyed by (schema, wire name) renders just this one field as str. The allowlist comment says to keep it minimal and to drop the entry once the upstream spec removes the enum.

    Every other enum field stays Literal — only fields whose consumer already handles unknown values are widened.

    asukaminato0721 asukaminato0721 requested changes on Nov 19, 2026 06:47 UTC
    Changes Requested Reviewer

    This branch has conflicts with main: please rebase onto the latest main. Checked 086e07e11d.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=086e07e11d9395f1c830e47823a943b77315268e;conflict=086e07e11d9395f1c830e47823a943b77315268e -->

    asukaminato0721 asukaminato0721 requested changes on Nov 26, 2026 10:17 UTC
    Changes Requested Reviewer

    This branch has conflicts with main: please rebase onto the latest main. Checked 8ff6a7d255.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=8ff6a7d255bae62ac24bdc415129704999f337ea;conflict=8ff6a7d255bae62ac24bdc415129704999f337ea -->

    asukaminato0721 asukaminato0721 commented on code on Nov 26, 2026 10:46 UTC
    Code Review
    api/dev/generate_billing_client.py:1
    @@ -123,6 +130,43 @@ class GenerationError(Exception):
         pass
     
     
    +class SnapshotProperty(BaseModel):
    +    """One `properties` entry of a snapshot schema, parsed once at the snapshot boundary.
    +
    +    Only `enum` is modelled: it is the sole key the open-enum allowlist reads. Every other OpenAPI
    +    key stays reachable through `extra="allow"`, so the snapshot remains the rendering input while
    +    the check receives a typed value instead of probing dictionary keys.
    +    """
    +
    +    model_config = ConfigDict(extra="allow")
    +
    +    enum: list[str] | None = None
    +
    +
    +class SnapshotSchema(BaseModel):
    +    """One named schema of a snapshot, with `properties` parsed into `SnapshotProperty`."""
    +
    +    model_config = ConfigDict(extra="allow")
    +
    +    properties: dict[str, SnapshotProperty] = Field(default_factory=dict)
    +
    +
    +type SnapshotSchemas = dict[str, SnapshotSchema]
    +
    +
    +def parse_snapshot_schemas(snapshot: JsonObject) -> SnapshotSchemas:
    +    """Postcondition: every named schema of `snapshot` is a `SnapshotSchema`.
    +
    +    Raises `ValidationError` when a properties entry is not an object, which means the upstream spec
    +    changed shape and generation must stop instead of silently skipping the field.
    +    """
    +    raw_schemas: JsonObject = snapshot["components"]["schemas"]

    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.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=ac9d3fa06a7a24cd -->

    asukaminato0721 asukaminato0721 requested changes on Nov 26, 2026 10:46 UTC
    Changes Requested Reviewer

    1 inline suggestion at be40ea9da3, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 1 review thread is still unresolved.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=be40ea9da3fa714b830a2b802df971b9fc9500c7 -->

    MindOfqc MindOfqc commented on code on Nov 26, 2026 14:02 UTC
    Code Review
    api/dev/generate_billing_client.py:1
    @@ -123,6 +130,43 @@ class GenerationError(Exception):
         pass
     
     
    +class SnapshotProperty(BaseModel):
    +    """One `properties` entry of a snapshot schema, parsed once at the snapshot boundary.
    +
    +    Only `enum` is modelled: it is the sole key the open-enum allowlist reads. Every other OpenAPI
    +    key stays reachable through `extra="allow"`, so the snapshot remains the rendering input while
    +    the check receives a typed value instead of probing dictionary keys.
    +    """
    +
    +    model_config = ConfigDict(extra="allow")
    +
    +    enum: list[str] | None = None
    +
    +
    +class SnapshotSchema(BaseModel):
    +    """One named schema of a snapshot, with `properties` parsed into `SnapshotProperty`."""
    +
    +    model_config = ConfigDict(extra="allow")
    +
    +    properties: dict[str, SnapshotProperty] = Field(default_factory=dict)
    +
    +
    +type SnapshotSchemas = dict[str, SnapshotSchema]
    +
    +
    +def parse_snapshot_schemas(snapshot: JsonObject) -> SnapshotSchemas:
    +    """Postcondition: every named schema of `snapshot` is a `SnapshotSchema`.
    +
    +    Raises `ValidationError` when a properties entry is not an object, which means the upstream spec
    +    changed shape and generation must stop instead of silently skipping the field.
    +    """
    +    raw_schemas: JsonObject = snapshot["components"]["schemas"]

    Updated in cb631cbe. The allowlist check now parses components.schemas as a typed envelope using the existing schema and property models. Invalid envelopes raise GenerationError, while rendering still uses the original JSON. All 59 focused tests passed, and --check confirmed the generated files are unchanged.

    Assignees
    MindOfqc MindOfqc
    Labels
    risk: low confidence: 89.8% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 68.1% (HIGH) · Higher = larger blast radius
    68.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.8% · Lower = rushed or shallow review
    89.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.0% · Safe to merge
    7.0%