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")(orreturning_ids=Trueto 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.
- Log readers read the backups.
GET /logs,/admin/logsandread_log_entriesnow also read rotated files (info.log.1,info.log.2026-10-20), andtotalcounts the backups.DELETE /logsstill only truncates the live file; to delete the backups, useDELETE /logs?delete_backups=true(orclear_log_files(..., delete_backups=True)). - An empty
log_diris an error.make_logs_router(log_dir=""),clear_log_files("")andresolve_log_files("")raiseValueError; before,Path("")resolved to the working directory.read_log_entries("")returns nothing. When file logging is off, do not mount the logs router withsettings.LOG_DIR. - The trusted IP header must hold an IP.
get_client_ipandget_client_ip_from_scopevalidate the value withipaddress; 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. /admin/loginhas an attempt budget. 5 failures per identifier every 900 s by default, in memory; the per-IP budget (20 / 900 s) only turns on withtrusted_ip_header. With more than one process, passlogin_throttle=/login_ip_throttle=over Redis;Falseturns it off.
What to do¶
- Dashboards or scripts counting
/logslines should expect larger numbers. - Mount the logs router conditionally when
LOG_DIRcan 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¶
- A script or CI job that runs
set-passwordwithout a terminal on an MFA account stops working: nobody is there to type the code. - To recover someone who lost the phone and the recovery codes, run
tempest user mfa-reset --email <e>(--yesoutside a terminal) and thenset-password. See the MFA recipe. - To accept a recovery code the command needs the recovery-code table
(
--recovery-code-model, defaultsrc.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¶
- If you call
signupdirectly and read.urlor.tokenfrom the second item, checkisinstance(activation, ActivationToken)first: withActivationWithheldthe account exists, inactive and without a link. mypy reportsunion-attrwhere that check is missing. - Only
Noneauthorises issuing the JWT pair right after signup. - If you override
signupand forward tosuper(), 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¶
- Move the service interpreter to 3.12 or newer (
uv python pin 3.13, theDockerfilebase image, the CI runtime). - Set the
requires-pythonof yourpyproject.tomlto>=3.12.tempest newalready generates it that way, withtarget-version = "py312"for ruff andpython_version = "3.12"for mypy. - Run
uv lockanduv sync. With the new floor the lock stops carrying the 3.11 split: the SDK's own lock droppedtomli,async-timeoutandaudioread, andnumpy,scipyandlibrosawent 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¶
- In the social-login client, handle the challenge as in the password login:
when
mfa_requiredistrue, ask for the code and callPOST /auth/mfa/verifywith themfa_token. An account without MFA does not change — the pair stays in the same response, withamr == ["ext"]. - If you override
UserAuthService.login_with_oauth, move the logic to the newauthenticate_oauth(resolves the account, issues nothing). The routes no longer calllogin_with_oauth, and the router logs a warning when it is built and finds the override. Callinglogin_with_oauthdirectly still issues the pair without asking about MFA. - If you override
issue_mfa_token, accept the newamr: Sequence[str] | None = PASSWORD_AMRand pass it on tosuper(). Without it the token carries no first step, and/auth/mfa/verifyfalls back to the earlier["pwd", "otp"]— the router logs a warning too.
0.314.0 — activation and reset links stamp amr=["email"]¶
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 amras "this session started at a login" now sees"email"on these two paths. If your rule is "any single-factor session", compare againstAMR_EMAIL_LINKas well; if it is "the password was checked", the change is the fix you wanted. make_mfa_required_dependencydoes not change:emailis not inMFA_AMR_METHODS, and the gate refuses the pair as it refused["pwd"].- An
issue_token_pairoverride withoutamr=is still called without the keyword, and the pair carries the override's default (["pwd"]when it delegates tosuper()), 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¶
-
Upgrade the SDK and run
tempest db revision --autogenerate -m "rename enum types".sync_enum_typesdetects the renamed type (on PostgreSQL throughinformation_schema, on SQLite through theCHECKname) and writes oneop.rename_enum_typeper type, with the reverse indowngrade: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")], ) -
Apply the migration before the new code serves traffic (the deploy's
alembic upgrade headalready does).tempest db checkfails 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¶
-
Generate the migration (
uv run tempest db revision -m "refresh token amr", oralembic 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") -
Run
uv run tempest db upgrade(oralembic 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/confirmanswers200with aLoginResponseSchema, no longer204. 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 checksstatus === 204now checks200and stores the new pair.mfa_confirmrevokes the sessions by default. A caller of the service that must keep them passesrevoke_sessions=False.
Password reset and link reactivation now ask for the second factor¶
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.
0.312.0 — Mercado Pago: expired Pix and chargeback search¶
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):
MercadoPagoClientmethods: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, andmercado_pago'sPaymentStatus. The canonicalPaymentStatus, fromintegrations.payment, stays — it is what the contracts use.
Types that changed:
Order.status,Order.status_detail,OrderTransactionPayment.statusandOrderTransactionPayment.status_detailgo from an enum toEnum | str: the sandbox returned values outside the list. An exhaustivematchover the enum needs a branch for the string.get_authenticated_user()returnsAuthenticatedUserinstead ofdict[str, Any]: replaceuser["id"]withuser.id(what is not declared is inuser.model_extra).- Two enums got names of their own:
ListPaymentMethodsResponseItemProcessingModesItem(thelist_payment_methodsprocessing mode) andUpdateAdvancedPaymentBodyStatus(theupdate_advanced_paymentbody status).
Three differences that need more than a rename:
- 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. - The webhook points at another resource. The notification should now
name the order — that is what the provider's document describes
(
order.created/order.updatedactions); the live delivery observed on 2026-11-13 carriedtype=order, andevent.eventisORDERsince v0.358.0. Replace manual reads ofdata.idwithmake_mercado_pago_webhook_delivery_dependency, and tick the Order event in the application's webhook settings. - The credential must come from an "Orders API" application. Measured:
a test seller's Checkout Pro application answers
401 Unauthorized use of live credentialsto a direct charge. The test accounts and credentials recipe shows the way.