From 10e175d4deb4237600ee4e4ef870b97f12225e03 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Mon, 23 Nov 2026 20:03:30 +0000 Subject: [PATCH] :books: Consolidate worker and Integrant schema guidance Keep dispatch, recovery, and cron rules with jobs. Move startup schema diagnostics to a focused memory linked from the backend testing guide. AI-assisted-by: gpt-6.2-sol --- .serena/memories/backend/core.md | 1 + .serena/memories/backend/integrant-schemas.md | 5 +++++ .serena/memories/backend/jobs.md | 4 +++- .serena/memories/backend/subtleties.md | 13 ++----------- .serena/memories/backend/testing.md | 2 +- 5 files changed, 12 insertions(+), 13 deletions(-) create mode 100644 .serena/memories/backend/integrant-schemas.md diff --git a/.serena/memories/backend/core.md b/.serena/memories/backend/core.md index 82433912fb..361a0b7f22 100644 --- a/.serena/memories/backend/core.md +++ b/.serena/memories/backend/core.md @@ -6,6 +6,7 @@ JVM Clojure backend. Start in `app.main` for Integrant wiring, `app.rpc.commands - RPC wrapper order, DB transactions and advisory locks, config, HTTP middleware and metrics: `mem:backend/subtleties`. - RPC concurrency limit declarations, acquisition order and queue diagnosis: `mem:backend/rpc-concurrency`. +- Injected component schemas and startup assertion failures: `mem:backend/integrant-schemas`. - Read-time migrations, fragments and snapshots: `mem:backend/file-data/reads-and-versions`. Partial save and failure handling: `mem:backend/file-data/save`. - Job definitions, submission and lifecycle transaction boundaries, dispatch/recovery, user-facing jobs, and metrics: `mem:backend/jobs`. - File import/export format compatibility, jobs, permissions and cancellation: `mem:backend/binfile`. diff --git a/.serena/memories/backend/integrant-schemas.md b/.serena/memories/backend/integrant-schemas.md new file mode 100644 index 0000000000..de879782d9 --- /dev/null +++ b/.serena/memories/backend/integrant-schemas.md @@ -0,0 +1,5 @@ +# Integrant parameter schemas + +- In a Malli map schema, a bare component key refers to a registered schema of the same name. The owning namespace must register it before the map schema compiles. For a component without a registered type, declare the key and schema explicitly, as in `app.auth.oidc/schema:routes-params`. A present key with a `nil` value and a missing key are different: use `:maybe` for the former and `{:optional true}` for the latter. +- A failure from `ig/assert-key` during system construction is not a test assertion. If the cause is hidden, compile the schema with `app.common.schema/schema` to distinguish an unresolved registry reference from invalid params. `sm/valid?` returns `false` for both; `sm/check`, as used by the worker components, propagates schema errors and explains invalid values. +- Test schema compilation explicitly for components that tests do not start. See `backend-tests.worker-test` and `backend-tests.http-websocket-test`. Keep backend assertions enabled when verifying the boot path; see `mem:backend/testing`. diff --git a/.serena/memories/backend/jobs.md b/.serena/memories/backend/jobs.md index 62acad90a5..66012b17fb 100644 --- a/.serena/memories/backend/jobs.md +++ b/.serena/memories/backend/jobs.md @@ -9,8 +9,10 @@ - A job-def closes over its own dependencies. A handler receives context and business params, never the runner cfg. A job-def must not reference `::jobs/defs` through Integrant: the registry already depends on the definitions. Don't add routing or retry state to public context; it belongs to dispatch or execution, not the job's business contract. - `submit` joins the caller transaction because creation is part of the caller's work. Claim, retry and terminal transitions own their transactions because they report work the caller cannot roll back. A job must commit before an independent claimant can see it. A transition writes its event with the state change; a no-op writes neither event nor metric. Keep job foreign keys deferrable. -- Submit keys include tenant, name, queue and label; rely on the partial unique indexes, not a read-before-write check. `skip-if-active` excludes live exclusive jobs; dedupe discards a conflict with an unstarted job; debounce refreshes that pending row and retains its ID. Opted-in jobs do not conflict with plain jobs just because they share a label. The options that require distinct conflict targets cannot be combined. +- Submit keys include tenant, name, queue and label; rely on the partial unique indexes, not a read-before-write check. `skip-if-active` excludes live exclusive jobs; dedupe discards a conflict with a `new` job; debounce refreshes that pending row and retains its ID. Use an explicit non-blank label for dedupe or debounce. Opted-in jobs do not conflict with plain jobs just because they share a label. Submit accepts at most one of these options. +- Cron claims its `scheduled_task` row with `FOR UPDATE SKIP LOCKED` to coordinate the tick while the transaction is open. The exclusive job insert prevents overlap across ticks and backends; the row lock alone cannot. Worker runners, dispatcher and cron do not start on a read-only pool. - Postgres owns the lifecycle; Redis delivery is not proof of a claim. Dispatch and recovery must stay tenant-scoped. Lost scheduled jobs and expired running jobs are terminal, not requeued; sending them back to `new` can violate dedupe. Long-running work must heartbeat; a beat that finds a terminal or missing job raises an internal interruption, not a retryable failure. Progress can be throttled, so each milestone must make sense without the previous one. +- The runner ignores a delivery whose `scheduled_at` no longer matches the row. A lost-job sweep uses queue depth only after a grace period; an empty queue can also mean that a runner has popped but not yet claimed a job. The age cap catches lost deliveries even behind a backlog. See `app.worker.dispatcher` for these thresholds. - Job events are durable; progress is not a Redis value or mutable column. Dispatcher aborts batch-write terminal events without a Pub/Sub notification; inspect logs or `penpot_jobs_total_ms_count{outcome="aborted"}` for either abort cause. Don't assume a client that missed a WebSocket event can replay the event log through the jobs RPC. - `complete` is the shared result validation boundary for the runner and external completions. The job-def owns the JSON result schema; declare it when UUIDs (including map keys) or other typed values must round-trip. Read job errors and progress through their job decoders rather than generic JSON decoding. diff --git a/.serena/memories/backend/subtleties.md b/.serena/memories/backend/subtleties.md index 22a4517555..ddb71a89d2 100644 --- a/.serena/memories/backend/subtleties.md +++ b/.serena/memories/backend/subtleties.md @@ -28,17 +28,8 @@ ## Workers and cron -- For job lifecycle, handler wiring and metric conventions, see `mem:backend/jobs`. -- `job` carries `tenant` (the instance the job belongs to) and a bare `queue`. Several instances share one database, and the tenant is what keeps an instance from claiming another environment's jobs: every query that acts on one instance's work filters on it (dispatch claim, lost sweep, orphan sweep, cron submit), and the tenant is part of the key of the dedupe and exclusivity indexes of `submit` (the cron no-overlap check is one of those inserts). -- Two submit options resolve their key in the database instead of reading before writing, each through its own partial unique index over (tenant, name, queue, label). `::jobs/skip-if-active` inserts the row as **exclusive** and `job__live_exclusive__uniq` admits a single live row (`new`/`scheduled`/`running`/`retry`). `::jobs/dedupe` inserts it as **deduped** and `job__new_dedupe__uniq` admits a single not-started row (`new`) whatever its `scheduled_at`; a conflicting insert affects no row, the submit returns `nil` and records `penpot_jobs_submit_total{outcome="skipped"}`. The pending row is never deleted nor modified: it runs when it is due, with its own params. `::jobs/debounce` uses the same key and index but resolves the conflict with `ON CONFLICT ... DO UPDATE`, refreshing `scheduled_at` (to `now + delay`), `params` and `modified_at` of the pending row and answering with the id it already had: that is the sliding window of the webhook batches, where the last payload is the one delivered. A refresh is not a new job: the submit records `outcome="refreshed"`, apart from the `created` ones, and the id it reports is the id the statement wrote. Dedupe and debounce are mutually exclusive. Both require an explicit non-blank label and only cover the jobs that asked for the option: a live job that was not submitted with it (a webhook delivery, a notification) does not block a flagged submit, and two plain jobs can share a label. The `exclusive` and `dedupe` columns are what keep that distinction; the label stays a label. -- A single insert carries a single `ON CONFLICT` clause, so `skip-if-active` cannot be combined with `dedupe`/`debounce`: an exclusive job already admits one live row, PostgreSQL admits one conflict target per statement, and the submit raises `:skip-if-active-cannot-be-combined`. -- The dispatcher claims `new`/`retry` jobs atomically, marks them `scheduled` and hands them to their queue; the runner skips a message whose scheduled timestamp no longer matches the database state (a rescheduled or reclaimed job). -- A job handed to a queue (`scheduled`) is marked `aborted` with `app.jobs/lost-error` (`code :lost`) when its queue has nothing waiting (`LLEN`) and it has been `scheduled` longer than the grace (5 min; it also covers the pop-to-claim gap of a message popped right after the hand-off, but not one that waited longer in the queue and is popped while the sweep runs: the round trip can lose that race), or when it has been `scheduled` past the cap (24 h, for a message lost behind a backlog or a queue without a consumer; a daily cron can miss one run). Leftover rows are never re-dispatched, so nothing returns to `new` and the dispatcher cannot violate `job__new_dedupe__uniq` (the thresholds are `lost-grace` and `lost-cap`, and `lost-batch-size` bounds each read in `app.worker.dispatcher`: past-cap rows are aborted without an `LLEN` and grace rows with one, so a younger lost row behind a large legitimate backlog may wait for the cap instead of the grace). `running` jobs untouched past `:jobs-lease` are marked `aborted` with `app.jobs/orphan-error` (`type :internal`, `code :orphan`). `aborted` is a system-side terminal state like `cancelled` (never retried, swept by retention like other terminals, reported with a log line: `warn` for lost, `error` for orphan); long jobs must `heartbeat` per chunk so a healthy backlog is never mistaken for a dead process. The `:progress` report is optional and only feeds the durable log. A beat whose write finds the job no longer active raises an `:interrupt` (`code :job-interrupted`) instead of counting zero: it is the internal stop-the-work signal, not an error, so neither the listener nor the runner logs it as one. -- A missing job-def raises (`:no-job-definition`) instead of completing. Throwing with `ex-data :type ::retry` still controls retry behavior; `:strategy ::noop` retries without incrementing retry count. -- Cron entries claim their `scheduled_task` row with `FOR UPDATE SKIP LOCKED`, disable statement/idle-in-transaction timeouts locally, and submit one exclusive `job` row per entry when no live instance exists. The database's partial unique index decides overlap across backends, not a count. Entries reschedule themselves in `finally` unless interrupted. Worker, dispatcher, and cron components do not start when the DB pool is read-only. -- Integrant params schemas name injected components as bare `::ns/key` entries (pool, metrics, msgbus, job defs), and a bare entry is a malli registry lookup, not `any?`: the owning namespace must `sm/register!` it at load, or the backend crashes at boot with `:malli.core/invalid-schema` instead of asserting. Unit tests never build those keys, so `backend-tests.worker-test` compiles the worker schemas and `backend-tests.http-websocket-test` compiles the revocation-watcher schema to catch it. The assertion only runs with `PENPOT_FLAGS=enable-backend-asserts`, so without it a broken schema reaches production and only crashes at boot. -- Whether a bare entry works has nothing to do with its position or with how many of them there are: it is a registry lookup, so it works only if that exact keyword was `sm/register!`'d. `[:map ::db/pool ::metrics/metrics]` is fine, `[:map :app.aaa/unregistered :app.ccc/unregistered]` throws. When a component is **not** registered as a malli type, spell it as an explicit pair instead of registering a type just to satisfy the lookup — `[:app.nitrate/client {:optional true} [:maybe :map]]` is how `auth.oidc/schema:routes-params` and `loggers.audit.archive-task/schema:audit-log-archive-params` declare it. `{:optional true}` matters because `init-key` yields `nil` when the owning feature flag (`:admin-console`) is off, and a required key would then fail the assert on a perfectly normal boot. -- `sm/valid?` catches every `Throwable` and returns `false`, so an uncompilable schema and a genuinely invalid value both surface as a bare `Assert failed:` with no cause. When an `assert-key` fires with no message, compile the schema by hand to see the real exception. +- Job lifecycle, recovery and cron overlap: `mem:backend/jobs`. +- Startup failures in injected component schemas: `mem:backend/integrant-schemas`. ## Config and HTTP/session middleware diff --git a/.serena/memories/backend/testing.md b/.serena/memories/backend/testing.md index e466515fc6..96e1b30606 100644 --- a/.serena/memories/backend/testing.md +++ b/.serena/memories/backend/testing.md @@ -11,7 +11,7 @@ JVM `clojure.test` (kaocha runner) under `backend/test/backend_tests/`. - **Why the flag matters:** `clojure.core/assert` is elided at compile time when `*assert*` is false, and `app.config` only sets that var from the flags when it loads. The test fixture redefines the flags after that, so they never reach it: without the flag the suite runs with every assertion compiled out, and a test that depends on an assert only means something with it set. `scripts/ci` and `tests-backend.yml` export the flag (GitHub Actions sets it too). When running the suite directly — including a `--focus` run — the command is `PENPOT_FLAGS="enable-backend-asserts" clojure -M:dev:test`. - Coverage: if code is added or modified in `src/`, corresponding tests in `test/backend_tests/` must be added or updated. - Isolated run: `clojure -M:dev:test --focus backend-tests.my-ns-test` for a specific test namespace, or `clojure -M:dev:test --focus backend-tests.my-ns-test/my-test-var` for a specific test var. Keep the `PENPOT_FLAGS="enable-backend-asserts"` prefix on these too; a focused run without it hides assert-dependent failures exactly like a full one. -- A **whole-suite** crash reported as `Execution error ... Assert failed: ...` with no `FAIL in` line is not a test failure: an `ig/assert-key` ran while the test system was being built, which happens outside `clojure.test`, so kaocha reports it as a load/build error and the summary has no counts. Fix the offending schema (see `mem:backend/subtleties`) rather than hunting for a test. +- An `ig/assert-key` failure while building the test system occurs outside `clojure.test`, so Kaocha reports a load/build error rather than a failed assertion in a test. Diagnose the schema or injected params with `mem:backend/integrant-schemas`. - **Log lines are not tested.** A log record is for the operator, not a contract: do not add a test that captures it (`add-watch` on `app.common.logging/log-record`, or `with-redefs` on `enabled?`/`emit-log`) to assert its message, hint or props, and do not keep such a test alive when the line changes. Whatever must be guaranteed belongs in a returned value, an event or a metric, and the test asserts that; a log line may change its wording at any time. - Multiple focus symbols are supported by REPEATING the flag (kaocha accumulates them, last-wins does not apply): `clojure -M:dev:test --focus backend-tests.ns-one --focus backend-tests.ns-two` — preferred over a shell loop of isolated runs. - Regression run: `clojure -M:dev:test` to ensure no regressions in related functional areas.