Skip to content
Open
1 change: 0 additions & 1 deletion api/controllers/console/workspace/model_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,6 @@ class ModelProviderPaymentCheckoutUrlApi(Resource):
def get(self, current_tenant_id: str, current_user: Account, provider: str):
if provider != "anthropic":
raise ValueError(f"provider name {provider} is invalid")
# pyrefly: ignore [deprecated]
link = BillingService.get_model_provider_payment_link(
provider_name=provider,
tenant_id=current_tenant_id,
Expand Down
102 changes: 98 additions & 4 deletions api/dev/generate_billing_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
from typing import Any, Literal

import yaml
from pydantic import BaseModel
from pydantic import BaseModel, ConfigDict, Field, ValidationError

API_ROOT = Path(__file__).resolve().parents[1]
REPO_ROOT = API_ROOT.parent
Expand All @@ -66,6 +66,13 @@
ERROR_REASON_SUFFIX = "ErrorReason"
ERROR_CLASS_SUFFIXES = ("UpstreamError", "UpstreamUnavailableError", "UpstreamInvalidResponseError")

# A proto enum is open: a dify-saas deployment older or newer than this snapshot can send a value the
# committed spec never listed, and a `Literal[...]` would then reject a reply the subject can still
# read. Fields named here render as `str` instead, keyed by (schema, wire property name). Keep the set
# minimal: only add a field whose consumer already handles unknown values, and delete the entry once
# the upstream spec drops the enum.
OPEN_ENUM_FIELDS: frozenset[tuple[str, str]] = frozenset({("CheckAccountInFreezeReply", "freezeType")})


@dataclass(frozen=True)
class AllowedOperation:
Expand Down Expand Up @@ -123,6 +130,53 @@ 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]


class SnapshotComponents(BaseModel):
"""The named schemas under the snapshot's OpenAPI components."""

schemas: SnapshotSchemas


class SnapshotSchemaEnvelope(BaseModel):
"""The portion of the raw snapshot needed by the schema allowlist check."""

components: SnapshotComponents


def parse_snapshot_schemas(snapshot: JsonObject) -> SnapshotSchemas:
"""Parse the schema envelope without changing the raw rendering input.

Raise `GenerationError` when required sections or their schemas have an invalid shape.
"""
try:
return SnapshotSchemaEnvelope.model_validate(snapshot).components.schemas
except ValidationError as error:
raise GenerationError(f"snapshot schemas do not match the expected OpenAPI shape: {error}") from error


def snapshot_path(service: Service) -> Path:
return CLIENT_DIR / f"{service}.openapi.json"

Expand Down Expand Up @@ -347,8 +401,14 @@ def python_type(schema: JsonObject, context: str) -> str:
raise GenerationError(f"{context}: unsupported schema {json.dumps(schema)}; give it a named message type")


def field_type(schema: JsonObject, required: bool, context: str) -> str:
annotation = python_type(schema, context)
def field_type(schema: JsonObject, required: bool, context: str, *, open_enum: bool) -> str:
"""Render a field annotation.

Precondition: `open_enum` is true only for a `(schema, wire name)` in `OPEN_ENUM_FIELDS`.
Postcondition: the declared enum is replaced by `str` when `open_enum`, so an upstream value the
snapshot does not list still validates; nullability and presence rules are unaffected.
"""
annotation = "str" if open_enum else python_type(schema, context)
if schema.get("nullable") or not required:
annotation = f"{annotation} | None"
return annotation
Expand Down Expand Up @@ -406,7 +466,8 @@ def render_model(name: str, schema: JsonObject) -> list[str]:
properties: dict[str, JsonObject] = schema.get("properties", {})
for wire_name, field in properties.items():
attribute = python_name(wire_name)
annotation = field_type(field, wire_name in required, f"{name}.{wire_name}")
open_enum = (name, wire_name) in OPEN_ENUM_FIELDS
annotation = field_type(field, wire_name in required, f"{name}.{wire_name}", open_enum=open_enum)
default = "" if wire_name in required else "None"
if attribute != wire_name:
arguments = ", ".join([*([default] if default else []), f"alias={json.dumps(wire_name)}"])
Expand Down Expand Up @@ -590,7 +651,40 @@ def format_python(source: str, path: Path) -> str:
# --- entry point ----------------------------------------------------------------------------------


def check_open_enum_fields(
snapshots: dict[Service, JsonObject],
*,
open_enum_fields: frozenset[tuple[str, str]] = OPEN_ENUM_FIELDS,
) -> None:
"""Check that every `open_enum_fields` entry still names a string enum field of a snapshot.

Precondition: `snapshots` holds the parsed snapshot JSON; `open_enum_fields` is the allowlist to
verify, defaulting to the module-level one that generation uses.

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.

The allowlist is a parameter so the tests hand in their own instead of patching the module
global, and the snapshots are parsed into `SnapshotSchema` here so the check reads typed fields
rather than probing nested dictionaries.
"""
found: set[tuple[str, str]] = set()
for snapshot in snapshots.values():
schemas = parse_snapshot_schemas(snapshot)
for name, wire_name in open_enum_fields:
schema = schemas.get(name)
property_schema = schema.properties.get(wire_name) if schema is not None else None
if property_schema is not None and property_schema.enum is None:
raise GenerationError(f"OPEN_ENUM_FIELDS lists {name}.{wire_name}, which is no longer an enum")
if property_schema is not None:
found.add((name, wire_name))
if stale := sorted(open_enum_fields - found):
raise GenerationError(f"OPEN_ENUM_FIELDS lists fields missing from the snapshots: {stale}")


def expected_files(snapshots: dict[Service, JsonObject]) -> dict[Path, str]:
check_open_enum_fields(snapshots)
files: dict[Path, str] = {}
for service, snapshot in snapshots.items():
files[snapshot_path(service)] = render_snapshot(snapshot)
Expand Down
2 changes: 1 addition & 1 deletion api/services/billing_client/saas.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions api/services/billing_service.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import logging
from collections.abc import Mapping, Sequence
from typing import Literal
from warnings import deprecated

from pydantic import ValidationError

Expand Down Expand Up @@ -137,10 +136,15 @@ def get_subscription(
)

@classmethod
@deprecated("Only used by the deprecated model-provider checkout endpoint.")
def get_model_provider_payment_link(
cls, provider_name: str, tenant_id: str, account_id: str, prefilled_email: str
) -> billing.GetModelProviderPaymentLinkReply:
"""Payment link for the deprecated model-provider checkout route.

The route keeps the deprecation itself (``console_openapi`` marks the endpoint deprecated); this
forwarding helper does not need a second marker, which would only make callers suppress a warning
about a route they cannot stop using.
"""
return billing.model_provider_get_model_provider_payment_link(
provider_name=provider_name, tenant_id=tenant_id, account_id=account_id, prefilled_email=prefilled_email
)
Expand Down
78 changes: 78 additions & 0 deletions api/tests/unit_tests/dev/test_generate_billing_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,81 @@ 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_schema = generator.parse_snapshot_schemas(snapshots["saas"])["CheckAccountInFreezeReply"]
assert reply_schema.properties["freezeType"].enum is not None
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() -> None:
snapshots: dict[generator.Service, generator.JsonObject] = {
"billing": {"components": {"schemas": {"Reply": {"properties": {"value": {"type": "string"}}}}}}
}

with pytest.raises(generator.GenerationError, match="which is no longer an enum"):
generator.check_open_enum_fields(snapshots, open_enum_fields=frozenset({("Reply", "value")}))


def test_open_enum_entries_must_exist_in_a_snapshot() -> None:
snapshots: dict[generator.Service, generator.JsonObject] = {
"billing": {"components": {"schemas": {"Reply": {"properties": {"value": {"type": "string", "enum": ["a"]}}}}}}
}

with pytest.raises(generator.GenerationError, match="missing from the snapshots"):
generator.check_open_enum_fields(snapshots, open_enum_fields=frozenset({("Reply", "value"), ("Reply", "gone")}))


@pytest.mark.parametrize(
"snapshot",
[
{},
{"components": []},
{"components": {}},
{"components": {"schemas": []}},
{"components": {"schemas": {"Reply": []}}},
{"components": {"schemas": {"Reply": {"properties": {"value": []}}}}},
],
ids=["missing-components", "invalid-components", "missing-schemas", "invalid-schemas", "schema", "property"],
)
def test_generation_rejects_malformed_snapshot_schemas(snapshot: generator.JsonObject) -> None:
with pytest.raises(generator.GenerationError, match="snapshot schemas do not match the expected OpenAPI shape"):
generator.expected_files({"billing": snapshot})


def test_parse_snapshot_schemas_preserves_raw_rendering_input() -> None:
snapshot: generator.JsonObject = {
"paths": {},
"components": {
"schemas": {
"Second": {"properties": {"kind": {"type": "string", "enum": ["x", "y"]}}},
"First": {"$ref": "#/components/schemas/Second"},
}
},
}
original = generator.render_snapshot(snapshot)

schemas = generator.parse_snapshot_schemas(snapshot)

assert list(schemas) == ["Second", "First"]
assert schemas["Second"].properties["kind"].enum == ["x", "y"]
assert generator.render_snapshot(snapshot) == original
1 change: 0 additions & 1 deletion api/tests/unit_tests/pyrefly.toml
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ project-excludes = [
"services/rag_pipeline/test_rag_pipeline_transform_service.py",
"services/retention/workflow_run/test_clear_free_plan_expired_workflow_run_logs.py",
"services/retention/workflow_run/test_restore_archived_workflow_run.py",
"services/test_billing_service.py",
"services/test_clear_free_plan_tenant_expired_logs.py",
"services/knowledge/test_dataset_service.py",
"services/data_source/test_provider_service.py",
Expand Down
Loading