Skip to content

Migration 0.31x

Use when upgrading from a version older than these releases: 0.319.0, 0.318.0, 0.316.0, 0.314.0, 0.313.0, 0.312.0 and 0.311.0.

Part of the Migration guide.

0.319.0 — counts from bulk_create_values and bulk_upsert

bulk_create_values and bulk_upsert ("update" mode) return 0 when the database reports 0; up to 0.318.x a zero rowcount became len(rows). bulk_upsert(update_columns=[]) raises ValueError pointing to on_conflict="nothing".

What to do

  • Code that treated the result as "always the batch size" now gets the real number.
  • To insert while skipping what already exists, use bulk_upsert(..., on_conflict="nothing") (or returning_ids=True to learn which rows were created).

0.318.0 — log readers, empty log_dir, header IP and the /admin login

Four behavior changes, no signature changes.

  1. Log readers read the backups. GET /logs, /admin/logs and read_log_entries now also read rotated files (info.log.1, info.log.2026-10-20), and total counts the backups. DELETE /logs still only truncates the live file; to delete the backups, use DELETE /logs?delete_backups=true (or clear_log_files(..., delete_backups=True)).
  2. An empty log_dir is an error. make_logs_router(log_dir=""), clear_log_files("") and resolve_log_files("") raise ValueError; before, Path("") resolved to the working directory. read_log_entries("") returns nothing. When file logging is off, do not mount the logs router with settings.LOG_DIR.
  3. The trusted IP header must hold an IP. get_client_ip and get_client_ip_from_scope validate the value with ipaddress; anything else falls back to the connection's address. This affects rate limits, login throttles and auditing. The edge proxy must overwrite the header, not append to it.
  4. /admin/login has an attempt budget. 5 failures per identifier every 900 s by default, in memory; the per-IP budget (20 / 900 s) only turns on with trusted_ip_header. With more than one process, pass login_throttle= / login_ip_throttle= over Redis; False turns it off.

What to do

  • Dashboards or scripts counting /logs lines should expect larger numbers.
  • Mount the logs router conditionally when LOG_DIR can be empty.
  • Check that the proxy writes the real IP into the configured header.

0.316.0 — set-password asks for the factor on an MFA account

tempest user set-password on an account with MFA active (and AUTH_MFA_ENABLED=True) now asks for the code — TOTP or recovery code — and changes the password through UserAuthService.change_password_with_mfa. Without a valid code in three attempts the command exits with code 1 and the password is left unchanged. Up to 0.315.x the command changed the password without asking for the factor.

What to do

  1. A script or CI job that runs set-password without a terminal on an MFA account stops working: nobody is there to type the code.
  2. To recover someone who lost the phone and the recovery codes, run tempest user mfa-reset --email <e> (--yes outside a terminal) and then set-password. See the MFA recipe.
  3. To accept a recovery code the command needs the recovery-code table (--recovery-code-model, default src.db.models:UserRecoveryCodeModel).

0.316.0 — the second item of UserAuthService.signup can be ActivationWithheld

The tuple signup returns now has three shapes for its second item: None (the account was born active), ActivationToken (the link was issued) and the new ActivationWithheld(user_id) (the link was withheld). The third only comes out with AUTH_AUTO_ACTIVATE=false and UserAuthService(refuses_email_link=...) refusing the new account; without the predicate, runtime behaviour is unchanged. The SDK router already handles the new type.

What to do

  1. If you call signup directly and read .url or .token from the second item, check isinstance(activation, ActivationToken) first: with ActivationWithheld the account exists, inactive and without a link. mypy reports union-attr where that check is missing.
  2. Only None authorises issuing the JWT pair right after signup.
  3. If you override signup and forward to super(), adjust the return annotation.

0.314.0 — Python 3.12 is the new minimum

The SDK drops Python 3.11. requires-python moves to >=3.12, and the supported versions become 3.12, 3.13 and 3.14.

If you are on 3.11 you stay on 0.313.x: the installer skips releases whose requires-python excludes the interpreter. Asking for the new version in a 3.11 environment fails before anything is installed. Measured with uv:

error: The requested interpreter resolved to Python 3.11.12, which is incompatible with the project's Python requirement: `>=3.12` (from `project.requires-python`)

What to do

  1. Move the service interpreter to 3.12 or newer (uv python pin 3.13, the Dockerfile base image, the CI runtime).
  2. Set the requires-python of your pyproject.toml to >=3.12. tempest new already generates it that way, with target-version = "py312" for ruff and python_version = "3.12" for mypy.
  3. Run uv lock and uv sync. With the new floor the lock stops carrying the 3.11 split: the SDK's own lock dropped tomli, async-timeout and audioread, and numpy, scipy and librosa went down to one version each.

To stay on 3.11 for now, pin the range: uv add "tempest-fastapi-sdk>=0.313.0,<0.314.0".

0.314.0 — social login of an account with TOTP asks for the second factor

GET /auth/oauth/{provider}/callback and POST /auth/oauth/{provider}/token now mirror /auth/login. When the resolved account has TOTP enrolled (and AUTH_MFA_ENABLED=True), the response carries no pair and no session cookie: it carries mfa_required=true + mfa_token, and the pair only comes out of /auth/mfa/verify, with amr == ["ext", "otp"]. Through 0.313.x the provider was enough, and the account skipped the factor it had enrolled.

What to do

  1. In the social-login client, handle the challenge as in the password login: when mfa_required is true, ask for the code and call POST /auth/mfa/verify with the mfa_token. An account without MFA does not change — the pair stays in the same response, with amr == ["ext"].
  2. If you override UserAuthService.login_with_oauth, move the logic to the new authenticate_oauth (resolves the account, issues nothing). The routes no longer call login_with_oauth, and the router logs a warning when it is built and finds the override. Calling login_with_oauth directly still issues the pair without asking about MFA.
  3. If you override issue_mfa_token, accept the new amr: Sequence[str] | None = PASSWORD_AMR and pass it on to super(). Without it the token carries no first step, and /auth/mfa/verify falls back to the earlier ["pwd", "otp"] — the router logs a warning too.

The pair POST /auth/activate/{token} and POST /auth/password-reset/confirm issue to an account without MFA now carries amr == ["email"] (AMR_EMAIL_LINK) instead of ["pwd"]: neither checks a password. With TOTP enrolled, /auth/mfa/verify on that challenge issues ["email", "otp"]. refresh repeats the origin's amr, so the session stays ["email"] after a rotation.

What to do

  • Code that reads "pwd" in amr as "this session started at a login" now sees "email" on these two paths. If your rule is "any single-factor session", compare against AMR_EMAIL_LINK as well; if it is "the password was checked", the change is the fix you wanted.
  • make_mfa_required_dependency does not change: email is not in MFA_AMR_METHODS, and the gate refuses the pair as it refused ["pwd"].
  • An issue_token_pair override without amr= is still called without the keyword, and the pair carries the override's default (["pwd"] when it delegates to super()), as before.

0.313.0 — a class ending in Enum no longer doubles the type suffix

enum_type_name drops one trailing Enum from the class name before appending _enum. Only enums with that suffix change:

Class Before Now
CandidateSlugEnum candidate_slug_enum_enum candidate_slug_enum
OrderStatus order_status_enum order_status_enum (same)

The database keeps the old name until a migration renames the type, and on PostgreSQL the model now writes the new name in every INSERT, UPDATE and WHERE on the column. Measured on PostgreSQL 16 with asyncpg, before the migration: type "candidate_slug_enum" does not exist on all three.

What to do

  1. Upgrade the SDK and run tempest db revision --autogenerate -m "rename enum types". sync_enum_types detects the renamed type (on PostgreSQL through information_schema, on SQLite through the CHECK name) and writes one op.rename_enum_type per type, with the reverse in downgrade:

    from alembic import op
    
    from tempest_fastapi_sdk.db.enum_migrations import EnumColumnRef
    
    
    def upgrade() -> None:
        """Rename the enum type to the name without the doubled suffix."""
        op.rename_enum_type(
            "candidate_slug_enum_enum",
            "candidate_slug_enum",
            columns=[EnumColumnRef(table="candidates", column="slug")],
        )
    
  2. Apply the migration before the new code serves traffic (the deploy's alembic upgrade head already does). tempest db check fails while the migration is missing, so CI catches the omission.

To keep the old name on a column, pass it explicitly: mapped_column(TempestEnum(CandidateSlugEnum, name="candidate_slug_enum_enum")).

0.313.0 — auth 429s carry their own code

The three throttles of make_auth_router stop answering the generic TOO_MANY_REQUESTS code, the same as any other 429 in the app:

Refusal Before Now
login over the budget, per e-mail or per client TOO_MANY_REQUESTS LOGIN_THROTTLED (LoginThrottledException)
signup over the budget TOO_MANY_REQUESTS SIGNUP_THROTTLED (SignupThrottledException)
wrong MFA code over the budget TOO_MANY_REQUESTS MFA_THROTTLED (MfaThrottledException)

The status stays 429, with Retry-After and details.retry_after_seconds. All three subclass TooManyRequestsException, so except TooManyRequestsException still catches them. What changes is for whoever compares the code: replace code == "TOO_MANY_REQUESTS" with the flow's code. With default_message_catalog(), the detail becomes a specific message (Too many login attempts — wait a moment and try again) instead of Too many requests.

0.313.0 — the refresh token stores the amr, and /mfa/confirm answers 200

The access token now carries the amr claim (how the session was authenticated), and BaseUserRefreshTokenModel gained the amr column (text, nullable) so refresh can repeat it. Because the column is mapped on the base model, migrate the database before upgrading the package if you use refresh_token_model: without it every pair issuance fails — measured with SQLite, POST /auth/signup with auto-activation answered 500 (OperationalError). Without refresh_token_model nothing changes in the database.

What to do

  1. Generate the migration (uv run tempest db revision -m "refresh token amr", or alembic revision --autogenerate) or write it by hand, with your table name:

    import sqlalchemy as sa
    from alembic import op
    
    revision: str = "0313_refresh_token_amr"
    down_revision: str | None = "<the previous revision>"
    
    
    def upgrade() -> None:
        """Add the refresh-token family amr."""
        op.add_column(
            "user_refresh_tokens",
            sa.Column("amr", sa.String(length=64), nullable=True),
        )
    
    
    def downgrade() -> None:
        """Drop the refresh-token family amr."""
        op.drop_column("user_refresh_tokens", "amr")
    
  2. Run uv run tempest db upgrade (or alembic upgrade head) and only then deploy the new version.

Old rows keep NULL: their refresh issues an access token without amr, which make_mfa_required_dependency treats as "no second factor".

Two behavior changes come with it:

  • POST /auth/mfa/confirm answers 200 with a LoginResponseSchema, no longer 204. Confirming revokes every refresh token of the user, and the new pair in the body (or in the cookies, in cookie mode) is what keeps the device signed in. A client that checks status === 204 now checks 200 and stores the new pair.
  • mfa_confirm revokes the sessions by default. A caller of the service that must keep them passes revoke_sessions=False.

POST /auth/password-reset/confirm and POST /auth/activate/{token} now mirror /auth/login: when the account has TOTP enrolled, they do not return the pair — they return mfa_required=true + mfa_token, and the pair only comes out of /auth/mfa/verify, with the MFA amr. The password is replaced either way.

A client that called the confirm (or the activate of a reactivated account) and stored access_token directly must handle the challenge: if mfa_required is true, prompt for the code and call /auth/mfa/verify. An account without MFA is unchanged — it still receives the pair in the response itself. Activating a freshly signed-up account is unchanged too: it never has a factor.

ActivationResponseSchema gained mfa_required / mfa_token, and access_token / refresh_token became optional (str | None), as in LoginResponseSchema. Reading the pair from a fresh-account activation is unchanged.

Password reset now revokes sessions already open, in the same transaction that writes the hash, the way /auth/mfa/confirm and tempest user set-password already did: a DB-backed refresh token issued before the reset can no longer be exchanged for a fresh pair (it answers 401). Access tokens already issued still live until their TTL. A caller of UserAuthService.confirm_password_reset that needs to keep the sessions passes revoke_sessions=False — an old override signature is still called by the router, and delegates to the default that revokes. A stateless refresh token (no refresh_token_model) has no row to revoke and stays valid until it expires.

Two behaviour changes, both measured in the sandbox on 2026-10-10.

An expired Pix is now EXPIRED. An order Mercado Pago returns as canceled / expired is now PaymentStatus.EXPIRED, and the webhook delivers it as PixEventType.CHARGE_EXPIRED. Up to 0.311.0 it came out as CANCELLED / CHARGE_CANCELLED. If your service handled expiry in the cancellation branch, handle both:

from tempest_fastapi_sdk.integrations.payment import PaymentStatusEnum, PixCharge


def is_closed_unpaid(charge: PixCharge) -> bool:
    """Tell whether a Pix charge ended without being paid."""
    return charge.status in {PaymentStatusEnum.CANCELLED, PaymentStatusEnum.EXPIRED}

search_chargebacks requires payment_id. The search answered 400 without that filter, including in the only shape the method accepted (limit / offset), so it never worked. Now:

Before Now
await client.search_chargebacks(limit=10) → always 400 await client.search_chargebacks(payment_id="123") → ChargebackSearchResponse
dict[str, Any] found.paging.total, found.results (items still dict[str, Any])

0.311.0 — Mercado Pago: the Payments API left the SDK

Mercado Pago's dashboard labels the Payments API (/v1/payments) "Esta API será descontinuada em breve" (this API will be discontinued soon), and the SDK now charges through the Orders API. If you used the Payments path, switch like this:

Before Now
client.create_payment(body=PaymentRequest(...)) with Pix MercadoPagoPixProvider(http).create_pix_charge(PixChargeRequest(...))
client.create_payment(...) with a card token MercadoPagoCardProvider(http).create_card_charge(CardChargeRequest(...))
create_pix_payment / get_pix_payment / parse_pix_payment create_pix_charge / get_pix_charge — the QR is on PixCharge.br_code and qr_code_base64
client.get_payment(id) get_pix_charge(order_id) / get_card_charge(order_id), or client.get_order(order_id)
client.update_payment(id, body={"capture": True}) capture_card_charge(order_id)
client.update_payment(id, body={"status": "cancelled"}) cancel_pix_charge(order_id) / cancel_card_charge(order_id)
client.create_refund(id, ...) refund_card_charge(order_id, amount_cents=...)
PixPayment, Payment PixCharge, CardCharge, or the generated Order
the 7 V1/V2 in-store QR and old dynamic QR operations no replacement in this SDK: the spec itself marks them deprecated, and the spec's Orders API only declares type: online

Removed with no direct replacement (the equivalent, where one exists, is the generated Order or the PixCharge / CardCharge contracts):

  • MercadoPagoClient methods: create_payment, search_payments, get_payment, update_payment, cancel_payment, create_refund, list_refunds, get_refund, and the 7 in-store QR ones — create_instore_order_v1, delete_instore_order_v1, create_instore_order_v2, get_instore_order_v2, delete_instore_order_v2, create_dynamic_qr_order, create_qr_tramma_dynamic.
  • Functions and constants: create_pix_payment, get_pix_payment, parse_pix_payment, PAYMENTS_PATH.
  • Models and enums: PixPayment, PixPointOfInteraction, PixTransactionData, Payment, PaymentRequest, PaymentPayer, PaymentPayer2, PaymentCard, PaymentCardCardholder, PaymentItem, PaymentAdditionalInfo, PaymentAdditionalInfoPayer, PaymentAdditionalInfoShipments, PaymentTransactionDetails, PaymentOperationType, PaymentPaymentTypeId, PaymentProcessingMode, PaymentSearchResult, SearchPaymentsRange, PaymentUpdateRequest, PaymentUpdateRequestStatus, CancelPaymentBody, RefundRequest, CreateRefundResponse, CreateRefundResponseSource, GetRefundResponse, GetRefundResponseSource, ListRefundsResponse, ListRefundsResponseSource, and mercado_pago's PaymentStatus. The canonical PaymentStatus, from integrations.payment, stays — it is what the contracts use.

Types that changed:

  • Order.status, Order.status_detail, OrderTransactionPayment.status and OrderTransactionPayment.status_detail go from an enum to Enum | str: the sandbox returned values outside the list. An exhaustive match over the enum needs a branch for the string.
  • get_authenticated_user() returns AuthenticatedUser instead of dict[str, Any]: replace user["id"] with user.id (what is not declared is in user.model_extra).
  • Two enums got names of their own: ListPaymentMethodsResponseItemProcessingModesItem (the list_payment_methods processing mode) and UpdateAdvancedPaymentBodyStatus (the update_advanced_payment body status).

Three differences that need more than a rename:

  1. The id changes shape. An order id is text (ORD…), not a number. If you stored the payment id as an integer, the column becomes text.
  2. The webhook points at another resource. The notification should now name the order — that is what the provider's document describes (order.created / order.updated actions); the live delivery observed on 2026-11-13 carried type=order, and event.event is ORDER since v0.358.0. Replace manual reads of data.id with make_mercado_pago_webhook_delivery_dependency, and tick the Order event in the application's webhook settings.
  3. The credential must come from an "Orders API" application. Measured: a test seller's Checkout Pro application answers 401 Unauthorized use of live credentials to a direct charge. The test accounts and credentials recipe shows the way.