Skip to content

Saleor Core: the high performance, composable, headless commerce API.

[port] docs: harden AGENTS.md and add Saleor review skills (#19505) (#19523)

Lukasz Ostrowski0aae2a4d1ec8
diff --git a/.claude/skills/saleor-graphql-api-change/SKILL.md b/.claude/skills/saleor-graphql-api-change/SKILL.md
new file mode 100644
index 0000000000..d81ef2e220
--- /dev/null
+++ b/.claude/skills/saleor-graphql-api-change/SKILL.md
@@ -0,0 +1,84 @@
+---
+name: saleor-graphql-api-change
+description: Checklist for adding, changing, deprecating, or removing anything in the Saleor GraphQL schema — fields, mutations, inputs, enums, or webhook event types. Use whenever a change touches the public GraphQL API so it passes review the first time.
+---
+
+# Changing the Saleor GraphQL API
+
+Human reviewers repeatedly send changes back for the same schema mistakes. Work through this
+checklist for any change to a GraphQL field, mutation, input, enum, or webhook event type.
+
+## Versioning
+
+- Find the version this branch is cut from: check the latest git tag (e.g. `3.22`). Annotate every
+ **new** field/mutation/argument with `ADDED_IN_{VERSION}` for the release it actually ships in — not
+ the current `main` version. If the change is backported, use the backport's version.
+- After any schema change, **regenerate `schema.graphql`** and commit it. A stale schema file fails CI
+ and review.
+
+## Deprecating a field / enum value
+
+- **Deprecate through the real mechanism so the schema emits an `@deprecated` directive** — never by
+ writing "DEPRECATED" text into the `description`:
+ - Fields/arguments: `deprecation_reason=DEPRECATED_IN_3X_FIELD` (or the input variant).
+ - Enum values: `from_enum(SomeEnum, deprecation_reason=<callback>)`.
+- Deprecation wording must be precise ("This event **type** will be removed", not "This event").
+- When you deprecate/remove a mutation, update related field descriptions to point users at the
+ replacement.
+
+## Removing a field (breaking change)
+
+- **Never remove a field that wasn't deprecated in a prior released version.** The order is:
+ deprecate → ship a release → remove in a later version. Confirm the deprecation actually shipped.
+- **Provide an off-ramp before removing** a field users depend on (a replacement field, metadata, etc.).
+- Removing a public field requires a CHANGELOG entry and a **tracked follow-up issue** for the eventual
+ DB column drop (see `saleor-migrations` for staged destructive changes).
+- For breaking *behavior* (not just schema) changes, stage enforcement across releases —
+ warn/silently-ignore first, crash later — so upgraders aren't broken instantly.
+
+## Descriptions
+
+- State **concrete values** (the actual configured limit, not "the number is limited").
+- Keep descriptions **in sync with the field's real type and nullability**.
+- Describe **what the field is**, not how a specific client should interpret it, and omit internal
+ jargon ("atomically", "signed delta").
+
+## Design & consistency
+
+- Prefer a **generic enum value plus a distinguishing flag** over an app/integration-specific enum
+ member (`GIFT_CARD` + a brand field, not `SALEOR_GIFT_CARD`). Don't shape the shared API around one
+ integration, and don't bake provider-specific length assumptions into shared field limits.
+- Mutation return types should be implicitly `required=False`, consistent with existing mutations
+ (`OrderSettingsUpdate`, `ShopAddressUpdate`), to avoid non-nullable-field crashes.
+- Pass the **type class** to `get_node_or_error(only_type=PageType)`, not the string `"PageType"`
+ (gives real typing, drops a `cast`).
+- Name new sort/filter enum fields to match the type's existing field names (`createdAt`/`modifiedAt`).
+- Don't use `default_value=[]` on Graphene inputs (graphene treats it as a shared literal) — leave it
+ optional and default inside the mutation body.
+- Don't put any mutable values inside `default_value` Graphene input fields, nor in any
+ other defaults (such as function signatures) where this memory pointer or value
+ could get mutated (thus potentially leading to unexpected behaviors).
+- Guard restricted fields with `PermissionsField`, and add a **separate authorization test per
+ permission-gated field**.
+- Ensure `class Meta` always defines the `permissions` property unless you are explicitly
+ told that you shouldn't.
+
+## Webhook event types
+
+- Add the new event to `WEBHOOK_EVENT_DESCRIPTION` with a description **and** an `ADDED_IN_{VERSION}`
+ clause.
+- Introduce a **specific error code** for a distinct, actionable failure mode instead of overloading a
+ generic `INVALID`.
+- Mark high-fan-out events (can reach thousands of objects) with `is_deferred_payload` so payload
+ building stays short in the scheduling task; reuse `CustomJsonEncoder` and existing dataloaders.
+- Provide a minimal static fallback payload (e.g. `{"id": "Variant:<ID>"}`).
+
+## Before requesting review
+
+- Have you regenerated `schema.graphql`, and are the `ADDED_IN`/`DEPRECATED_IN` annotations correct
+ for the release this change actually ships in?
+- Do the deprecations show up as `@deprecated` directives in the generated schema, rather than only as
+ prose in a description?
+- Is every new or changed input/output contract covered by a unit test, including any nullability
+ changes?
+- Follow the `saleor-pr-checklist` skill for the general PR gate before opening the PR.
diff --git a/.claude/skills/saleor-migrations/SKILL.md b/.claude/skills/saleor-migrations/SKILL.md
new file mode 100644
index 0000000000..2a8a9e4c3b
--- /dev/null
+++ b/.claude/skills/saleor-migrations/SKILL.md
@@ -0,0 +1,69 @@
+---
+name: saleor-migrations
+description: Rules for writing safe Django migrations in Saleor that don't lock tables or break zero-downtime deploys. Use whenever creating or editing a migration (schema or data), including field removals and index/constraint changes.
+---
+
+# Writing Saleor migrations
+
+Saleor deploys with zero downtime across many pods against a shared Postgres. A migration that takes a
+long table lock stalls every pod. Follow these rules.
+
+## Keep locks short: split migrations
+
+- **One model per migration, and one field change per migration.** Each schema operation holds a lock
+ on the table for its duration; batching several into one migration multiplies the locked time.
+- The only valid reason to combine is separating a schema migration from its data migration.
+- Always separate schema changes and data migration.
+- Don't add a migration that re-alters a column an earlier migration already changed — check the
+ existing migration history first.
+- Give migrations descriptive names that reflect the actual operation
+ (`0070_add_payment_gift_card_brand`, not `0070_alter_payment_partial_add_db_default` for something
+ else).
+
+## Indexes and constraints: create concurrently
+
+- **Add unique constraints/indexes concurrently** using the established non-blocking pattern (see e.g.
+ `page` migration `0030_slug_translation_unique_constraint`) — a plain `AddConstraint` /
+ `AddIndex` takes a blocking `ACCESS EXCLUSIVE` lock and can stall writes across all pods.
+- Enforce value invariants (e.g. non-negative balance) with a DB `CheckConstraint`, not just
+ application logic.
+
+## Removing a field: stage it
+
+Removing a NOT NULL / defaulted column in one step can fail mid-deploy while old and new pods coexist.
+Stage it across releases:
+
+1. Add a `db_default` so the DB can write the column without the ORM.
+2. Remove the field from the ORM model (column still present).
+3. **Drop the column in a later version**, tracked by an explicit follow-up issue.
+
+Keep any legacy enum values / code retained only for migration safety tracked as a removal task with a
+"remove in X.Y" note.
+
+## Data migrations
+
+- A data migration must be **all-or-nothing**: process everything or nothing. Don't abort partway on a
+ fixed depth/count cap and leave a partial migration.
+- **`post_migrate` sender must be the migration's own app config** — a common copy-paste bug is
+ `registry.get_app_config("product")` inside an `account`/`order` migration.
+- Use a module/task **constant** (like `BATCH_SIZE`) for internal tuning knobs, not an env var nobody
+ will set.
+- When cleaning up (e.g. removing a permission), address **all** models that hold the value
+ (App, AppExtension, AppInstallation, …), or document why one is handled elsewhere.
+- Watch for per-iteration DB queries (`O(N)` vs `O(1)`); batch related lookups.
+
+## Cross-branch ports
+
+- Keep a ported migration's **filename identical** to its counterpart on the other branch, and add a
+ merge migration where histories diverge.
+- Keep a ported migration's **filename identical** to its counterpart on the other branch, and add a
+ merge migration where histories diverge using `./manage.py makemigrations --merge`.
+## Before requesting review
+
+- Confirm each migration touches a single model and a single field, and that any index or constraint
+ is created concurrently rather than with a blocking operation.
+- Confirm every destructive column change is staged across releases (add `db_default`, then remove the
+ field from the ORM, then drop the column in a later version).
+- Confirm each `post_migrate` handler passes its own app config as the sender, and that every data
+ migration is all-or-nothing rather than aborting partway.
+- Run the migration locally with `manage.py migrate` and confirm it applies cleanly.
diff --git a/.claude/skills/saleor-pr-checklist/SKILL.md b/.claude/skills/saleor-pr-checklist/SKILL.md
new file mode 100644
index 0000000000..e8690f119f
--- /dev/null
+++ b/.claude/skills/saleor-pr-checklist/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: saleor-pr-checklist
+description: Final self-review gate before opening or updating a Saleor pull request — CHANGELOG placement, pre-commit, schema regen, and a pass over the review standards that reviewers most often enforce. Use when finishing a change and about to request review.
+---
+
+# Saleor PR checklist
+
+Run this before opening or updating a PR. It catches the process/hygiene issues and the recurring
+review comments that otherwise cost a round trip. (For schema-specific and migration-specific work,
+also use `saleor-graphql-api-change` and `saleor-migrations`.)
+
+## Process gate
+
+- **Run pre-commit** and fix everything it flags (formatting, lint, mypy). PRs regularly bounce for
+ this alone.
+- **Ensure new/changed tests pass locally** before requesting review (see AGENTS.md
+ for how to run tests).
+- Remove debug/test scaffolding (stray `str(...)` casts, prints, unused imports).
+- If you touched the GraphQL schema, **regenerate `schema.graphql`**.
+- For dependency changes, use the pinned `uv` version and change only the target dependency so
+ `uv.lock` doesn't churn.
+
+## CHANGELOG
+
+- Add an entry **under the correct section/heading** — don't blind-append to the end of the file.
+- **Never add or edit a CHANGELOG entry for an already-released version.** Released fixes surface via
+ the release description; a re-added entry is noise. (This is a frequent porting mistake.)
+- Keep the changelog diff scoped to your change — don't drop unrelated entries. Proofread the prose.
+- Add a migration-guide entry for any behavior change that could be breaking for some API consumers,
+ even one intended as a feature.
+
+## Self-review against the standards reviewers enforce
+
+Skim your own diff for the top recurring review comments (all detailed in AGENTS.md):
+
+- **Tests:** exact-value assertions (no `> 0` / `assert not errors`); negative tests assert the side
+ effect didn't happen; no asserting a value the test just set; design tests so a shared input can't
+ mutate the expected value, rather than papering over it with an expensive `copy.deepcopy`; real
+ fixtures over mocked internals; the fix has a regression test reproducing the *real* bug.
+- **Layering:** business logic in the domain layer, not the mutation; no `graphql`-layer imports from
+ non-GraphQL code; validate at the point of production.
+- **DB / scaling:** no N+1 in loops; bulk `update`/`delete`; only-needed columns; `on_commit` for task
+ scheduling; no blocking in request threads.
+- **Naming:** no cryptic abbreviations; positive booleans; `legacy_` prefix on deprecated-behavior flags.
+- **Error handling:** specific exceptions (not bare `Exception`); retryable vs terminal distinguished;
+ precise, field-attributed messages.
+- **Dead code / types:** delete code a refactor made dead; fix types at the source instead of `cast()`.
+
+## PR description
+
+- Explain *why*, and for anything non-obvious (a deprecation path, a deferred cleanup, a concurrency
+ decision) state it explicitly so a reviewer doesn't have to ask.
+- Link tracked follow-up issues for any deferred work (column drops, legacy removals).
diff --git a/.gitignore b/.gitignore
index 5a42f0852d..352fb82aa4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,10 @@
!.gitignore
!.vscode
!.semgrep/
+
+# Track only .claude/skills/; keep the rest of .claude/ (local settings, state) ignored.
+.claude
+!.claude/skills/
*.log
*.pot
*.pyc
diff --git a/AGENTS.md b/AGENTS.md
index c323030f8f..9fb3b6e70f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,30 @@
# Saleor
+## Deployment model (read this first)
+
+Saleor is deployed for **horizontal scale-out: many identical Kubernetes pods** (web + Celery
+workers) run concurrently behind a load balancer, against a **shared Postgres (with read replicas)
+and shared Redis/broker**. Any given request or task may land on any pod, and the same code runs in
+many processes at once. Write code with that in mind:
+
+- **No in-process/local state as source of truth.** Never rely on module globals, in-memory caches,
+ or a value set by a previous request being present on the next one — the next call hits a different
+ pod. Shared state lives in Postgres and Valkey or Redis.
+- **Assume every operation runs concurrently with itself.** Use atomic DB operations
+ (`F()`, `update_or_create`, `select_for_update`) instead of check-then-act — see *Concurrency and
+ Thread Safety* below.
+- **Never block a request/worker thread.** No `time.sleep()` and no unbounded `while True` retry loops
+ in request-handling code — a blocked thread wastes a finite pod worker slot. Use bounded retries and
+ background tasks.
+- **Schedule background work after the transaction commits.** Use `on_commit` / `call_event` (not a
+ bare `.delay()` inside an open transaction) so a task can't run on another pod before the row it
+ needs is committed.
+- **Protect the shared database.** It is the scaling bottleneck: avoid N+1 queries and per-row writes
+ in loops (bulk instead), keep `select_for_update` transactions short, fetch only the columns you
+ need, and don't add per-request queries to hot paths — reuse dataloaders.
+- **Make tasks idempotent and safe to retry** — the broker may deliver a task more than once, and pods
+ can be killed/rescheduled mid-run.
+
## Graphql
### API versioning
@@ -75,6 +100,83 @@ database/cache or collide with another worktree's stack.
```
- When a mutation input is optional/nullable, test the explicit `null` value in addition to omitting the field — they are distinct inputs and can be handled differently.
+### Assert precisely (the #1 source of review comments)
+
+- **Assert exact values and counts, never bounds or mere absence.** No `len(x) > 0`, `>= 1`,
+ `assert not errors`, or `call_count >= 1` — assert the exact count, enum, or object so unexpected
+ extra results are caught. When one error is expected, assert *exactly one*, its full message, and
+ its `path`/field.
+- **On negative / permission-denied tests, also assert the side effect did NOT happen** — balance
+ unchanged, `SomeEvent.objects.exists() is False`, the object left unmutated. An error assertion
+ alone doesn't prove the action was blocked.
+- **Never assert a value the test itself just set and saved** — that verifies the ORM, not the code
+ under test. Set state *or* assert it, not both.
+- **Never assert a mutable input against itself after passing it to code that may mutate it** — the
+ comparison can never fail. Design the test so the expected value is independent of the input (build
+ it from literals/a separate fixture). Reach for `copy.deepcopy` only as a last resort when there is a
+ real mutation risk and no cleaner option — it is expensive (it pickles) and does not scale to a large
+ suite.
+- **Prefer real fixtures/tokens over mocking internals.** Generate a genuinely valid/invalid token
+ (e.g. via the real `create_access_token*` factories or pyjwt) rather than mocking `get_decoded_token`
+ to return a canned payload — otherwise real breakage isn't caught.
+- **A fix must ship with a regression test that reproduces the *actual* reported bug** end-to-end and
+ targets the field/path that actually failed — not just the new helper's happy path.
+- **Encode preconditions as assertions, not comments** (`assert flag is True` before exercising it),
+ so the test fails fast if a default changes.
+- Use `Model.objects.get()` when exactly one row is expected (it asserts uniqueness) instead of
+ `.first()` + a not-None check, and `qs.exists()` instead of `qs.count() == 0`.
+- Don't hardcode a "nonexistent" primary key (e.g. `99999`) — `--reuse-db` can reassign it. Use a
+ negative id such as `-1`; Postgres has no unsigned integer types, so it can never match a real row
+ (and it avoids the extra `max(pk)` query).
+- Use reserved test domains (`example.com`, `*.test`) for any URL in a test, never a real one.
+- For IPs, use network addresses so they cannot reach an actual server, e.g., `8.8.8.0` or `1.1.1.0`
+- Parametrize near-identical test bodies; keep each test minimal (drop unrelated setup); name tests
+ for the exact behavior asserted (no double negatives).
+
+# Code structure and layering
+
+- **Keep business logic in the domain layer; GraphQL mutations do input validation and orchestration
+ only.** How a token is built/stripped, how a balance changes, etc. belongs in the domain module, not
+ in the mutation.
+- **Non-GraphQL code must never import from the `graphql` layer.** If a domain-layer task or model
+ needs a helper, move that helper into the domain module and import it *from* the GraphQL layer —
+ never the reverse.
+- **Validate at the point data is produced (fail-fast)**, and clean a sub-entity inside the same clean
+ step that owns its parent — don't split one entity's cleaning across separate stages.
+- **Pass the narrow value a function actually needs** (a single flag or an already-fetched setting),
+ not a broad `info` / `SiteSettings` context object it has to dig into. A wide parameter hides the
+ real dependency and forces callers to re-thread context.
+- **Prefer typed structures (`dataclass`/`NamedTuple`) over ad-hoc `dict` grab-bags**, and keep a
+ function's return shape homogeneous (don't mix heterogeneous entities in one list).
+- Extract branchy or long logic into a named helper instead of narrating a ~100-line function with
+ comments. Run short-circuit / global checks first, before fetching data.
+- Remove code a refactor made dead (unused validators, unreachable guards added only to satisfy mypy).
+ Fix the type at its source instead of adding a `cast()` around a wrong upstream annotation.
+
+# Naming
+
+- No cryptic abbreviations (`gc_brand` → `gift_card_brand`); align a new field's name to the analogous
+ existing field.
+- **Use positive boolean names** — `delivery_changed`, not `not delivery_unchanged`.
+- **Prefix any flag or field that gates deprecated behavior with `legacy_`** so the deprecation is
+ obvious from the name alone.
+- Name things for what they return/mean and the correct domain, not an incidental call site, and don't
+ bake a format assumption into a name (`last_digits` when a code may contain letters → `last_chars`).
+
+# Error handling
+
+- **Catch the specific exception, never a bare `Exception` or `DatabaseError`.** Catch the whole
+ provider family when needed (`BotoCoreError` *and* `ClientError`; `GoogleAPIError` for 4xx *and*
+ 5xx) and the narrowest DB exception that fits (`OperationalError`, not the base class).
+- **Distinguish retryable failures (network errors, HTTP 5xx) from terminal ones (4xx, bad data,
+ `ValueError`)** — never retry what can't self-recover; return/abort terminal cases immediately so
+ invalid work drains fast. Check an HTTP response's status code before reading its body, and always
+ pass an explicit timeout to outbound network calls.
+- Error messages must state the actual cause ("not found" vs "wrong type"), be attributed to the
+ specific line/field for list inputs, and use generic (non-field) errors for config/store-level
+ failures. Propagate the original caught message rather than rewriting it.
+- Validate referenced GraphQL IDs and return a clean error — don't let a bad/nonexistent id surface a
+ cryptic "Cannot return null for non-nullable field" crash.
# Webhooks and Events
@@ -172,6 +274,41 @@ with traced_atomic_transaction():
obj2.save()
```
+## Schedule background work after commit
+
+Never schedule a Celery task with a bare `.delay()` inside an open transaction — the task can start on
+another pod before the transaction commits and fail on data it can't see yet. Schedule via `on_commit`
+(or `call_event`, which does this for webhook events) so the task only fires after the commit:
+
+```python
+from django.db.transaction import on_commit
+
+with traced_atomic_transaction():
+ obj.save()
+ on_commit(lambda: my_task.delay(obj.pk))
+```
+
+Wrap multi-write / read-modify-write operations in a transaction so they are all-or-nothing, and emit
+a state-change event inside the same transaction as the change.
+
+## Never block a request/worker thread
+
+No `time.sleep()` and no unbounded `while True` retry loops in request-handling or worker code — a
+blocked thread wastes one of the pod's finite worker slots. Use bounded `for attempt in range(n)`
+retries and offload waiting to background tasks.
+
+## Other concurrency rules
+
+- **Scope `allow_writer()` to the exact statement that needs it** (`with allow_writer(): ...`), not the
+ whole task/function.
+- **Re-establish the DB/writer context inside every Promise `.then()` callback** — it runs after the
+ previous context has exited (like async), so a writer/context opened before `.then()` is gone inside it.
+- **Never gate a blocking `Queue.get()` on a separate `empty()`/non-empty check** across threads — the
+ last item can be drained between the check and the get, hanging the consumer. Use a non-blocking get
+ or a sentinel.
+- Route heavyweight fan-out tasks (large downloads, thousands of objects) to a dedicated, bounded queue
+ so a single bulk mutation can't starve workers or OOM a pod.
+
## Summary of Patterns Used in Saleor
| Pattern | Module Example | When to Use |
@@ -180,6 +317,7 @@ with traced_atomic_transaction():
| `select_for_update` | `saleor/payment/lock_objects.py` | Complex read-modify-write |
| `update_or_create` | `saleor/graphql/attribute/utils/type_handlers.py` | Upsert operations |
| `traced_atomic_transaction` | `saleor/core/tracing.py` | Multi-operation atomicity |
+| `on_commit` task scheduling | Any mutation that dispatches a task | Fire task only after commit |
# Data Migrations
@@ -331,3 +469,36 @@ Single-context: one `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agent
if giftcard.active is True:
deactivated_ids.append(giftcard.pk)
```
+
+# Database access
+
+The shared Postgres is the scaling bottleneck — every pod hits it. Keep queries cheap and few.
+
+- **No per-row query in a loop (N+1).** Build a dict keyed by the join fields for O(1) lookups, or do a
+ single aggregate / `filter(...).exists()` across all rows.
+- **Bulk `queryset.update()` / `.delete()`** instead of saving/deleting per row, and **`.iterator()`**
+ instead of `list()` on an unbounded queryset.
+- **Fetch only the columns you need** (`.values(...)` / `.values_list("pk", flat=True)`), not full
+ model instances, when that's all you use.
+- Use `qs.exists()` over `qs.count() == 0`.
+- **Don't add per-request DB queries to hot paths** (auth, resolvers) — reuse dataloaders. Don't bypass
+ a dataloader to "get the latest" value; the data is replica-delayed anyway, so the extra query buys
+ no real consistency.
+- Keep `select_for_update` transactions short (no `list()` of unbounded sets or per-row queries while
+ holding the lock). Don't persist rows purely for debugging/observability — log instead (writes
+ replicate to every read replica).
+
+# Data minimization
+
+- **Don't denormalize user PII** (email, etc.) into other tables or event params — store only the
+ reference id. Register any new user-referencing/PII field with the anonymizer app, and ensure PII is
+ deleted with the user (`on_delete=PROTECT` + deactivate, not `SET_NULL` that leaves orphaned data).
+
+# File Uploads & File Downloads
+
+- **Treat any downloaded file or URL as untrusted**: `Content-Type` headers are spoofable (confirm the
+ real type from magic bytes), enforce an allowed-format allowlist (reject SVG and other
+ executable/vector formats), enforce a maximum size, and check the HTTP status before reading the body.
+- Verify the file extension matches the detected file type
+
+See saleor/graphql/core/validators/file.py for how to properly validate files.