From 3733e5c4a25dc3dcdf743ef20e5a2605f5c64a19 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Mon, 23 Nov 2026 16:43:19 +0000 Subject: [PATCH] :books: Clarify workspace isolation and deployment guidance Document shared Valkey and tenant-scoped jobs without duplicating runtime configuration. Keep durable production constraints and remove release- specific instructions from the infrastructure memories. AI-assisted-by: gpt-6.2-sol --- .serena/memories/devenv/core.md | 128 +++-------------------- .serena/memories/prod-infra/core.md | 70 +++---------- docs/technical-guide/developer/devenv.md | 28 ++--- 3 files changed, 43 insertions(+), 183 deletions(-) diff --git a/.serena/memories/devenv/core.md b/.serena/memories/devenv/core.md index 6949a0b004..5221b8c779 100644 --- a/.serena/memories/devenv/core.md +++ b/.serena/memories/devenv/core.md @@ -1,119 +1,23 @@ -# Devenv startup and configuration +# Devenv -Compose-based dev environment under `docker/devenv/`, driven by `manage.sh`. Parallel instances share infra + Postgres + RustFS; each instance has its own `main` container, Valkey, source checkout, tmux session. The main database (`penpot`) and the S3 bucket (`penpot`) are shared by all instances on purpose; backend-test databases are isolated per instance (`penpot_test` on ws0, `penpot_test_wsN` on wsN) with per-instance Valkey DB numbers (`6+N`, since runtime backends occupy `0..5`). +- Start with `manage.sh` for command parsing and workspace overrides, `docker/devenv/defaults.env` for defaults, and `docker/devenv/docker-compose.{infra,main}.yml` for service and volume definitions. For commands and ports see `docs/technical-guide/developer/devenv.md`. -## Compose project layout +## Workspace isolation -- `penpotdev-infra`: shared `postgres`, `rustfs`, `valkey`, `mailer`, `ldap`. File: `docker-compose.infra.yml`. -- `penpotdev-wsN` (N=0,1,…): per-instance `main` + `redis` (Valkey). File: `docker-compose.main.yml`. ws0 (a.k.a. `main`) binds `$PWD`; ws1+ bind clones at `${PENPOT_WORKSPACES_DIR}/wsN/` (default `${XDG_DATA_HOME:-~/.local/share}/penpot-devenv/workspaces/`, or the former `~/.penpot/penpot_workspaces/` when it already exists), maintained by the developer. -- Optional overlay `docker-compose.opencode.yml`: added by `instance-compose` as an extra `-f` only when `PENPOT_OPENCODE_CONFIG_DIR` is set (i.e. `run-devenv --opencode-config-dir DIR` ran in this process). Bind-mounts the host dir at `/home/penpot/.config/opencode` (`:z`). Flag-only, per-call; not read from ambient env. Parser `parse-opencode-config-dir` absolutizes (`~`, realpath) because compose resolves relative bind sources against the compose file's dir. Only instances brought up with the flag get the mount. -- All projects join external network `penpot_shared`. Created idempotently by `ensure-devenv-network`, never removed by lifecycle commands. +- Workspaces share PostgreSQL, the application database and RustFS bucket, and one Valkey server. Each workspace has its own runtime Valkey database and tenant. Valkey Pub/Sub is not scoped to a logical database; `app.msgbus` prefixes topics with the tenant. Do not infer shared notifications from a shared server or shared application rows. +- Backend tests must use the workspace's `PENPOT_TEST_DATABASE_URI` and `PENPOT_TEST_REDIS_URI`. The PostgreSQL test database and Valkey test database number are separate from runtime data; `instance-test-db-name` and `instance-test-redis-db` in `manage.sh` are the source of truth. Provision the test database explicitly for new workspaces: PostgreSQL init scripts run only on a fresh volume. +- Jobs can be inserted into shared PostgreSQL but are dispatched by tenant. Check effective flags, tenant and Valkey destination when a job sits pending; do not assume a worker in another workspace will pick it up. See `mem:prod-infra/core` and `mem:backend/jobs`. -## Source-of-truth files +## Lifecycle and configuration -- `docker/devenv/defaults.env`: ws0 baseline — container/volume names, runtime env, published host ports, tmux defaults. `manage.sh` aborts if unreadable. -- For ws1+, `instance-env-overrides` computes the per-instance overrides (container/volume names, host ports offset `10000·N`, `PENPOT_PUBLIC_URI`, `PENPOT_REDIS_URI`, `PENPOT_TEST_DATABASE_URI`, `PENPOT_TEST_REDIS_URI`) and `instance-compose` injects them as env vars at compose time — never written to disk, recomputed each call so they can't drift. ws0 uses `defaults.env` as-is. -- Per-instance test databases are created by `ensure-instance-test-database` (called from `start-instance`): `CREATE DATABASE` guarded by a `pg_database` existence check, so it is idempotent. Needed because `postgresql_init.sql` only runs on first volume creation. The backend applies migrations itself on first use, so an empty database is enough. -- `backend/scripts/_env`: backend-internal only — secret keys, `PENPOT_FLAGS` (with `enable-backend-worker` gated on `PENPOT_BACKEND_WORKER`), `JAVA_OPTS`, `setup_s3_bucket()`. Never duplicates `defaults.env`. -- Frontend admin-console is off by default in devenv: `docker-compose.main.yml` sets `PENPOT_DEVENV=true`, which makes `app.config` (`goog-define devenv-mode`) prepend `disable-admin-console` ahead of the user `config.js` flags; flags parse in order and user flags win, so `enable-admin-console` in `frontend/resources/public/js/config.js` re-enables it. Outside devenv (prod builds) the default is unset and the admin-console stays on, matching `flags/default`. The backend `_env` also adds `disable-admin-console` and keeps `enable-nexus` commented out, so both cursor consumers are off in devenv: `cf/audit-persist?` is false and no full audit rows are written (telemetry is disabled there too). Uncomment `enable-nexus` in `_env` when integration testing the consumer. -- Compose files use pure `${VAR}` substitution; missing var = compose fails. +- `infra-compose` and `instance-compose` clear the inherited shell environment, then reinject required values. Compose gives these overrides precedence over `--env-file`; letting sourced defaults leak back into Compose can override the intended workspace values. +- Shared infrastructure stays up until the last workspace stops. Keep named volumes independent of Compose project names; replacing a service or major database version must not silently reuse or erase an incompatible volume. PostgreSQL readiness probes use TCP so the temporary init server does not count as ready. +- `--sync` copies Git metadata and files into the target workspace; it is not a merge. Do not run it over local work you need to keep. The first start seeds a missing workspace; later starts do not sync unless requested. Git selects the files, including tracked paths under ignored directories. Ignored caches survive, and the workspace owns its `config.js` after the initial copy. +- tmux adds conditional windows when it creates a session, not when attaching. The OpenCode config overlay applies at container creation; passing a different path to an attach does not change the mount. MCP uses the workspace's same-origin proxy; see `mem:mcp/core`. +- The backend `_env` can override launcher `JAVA_OPTS`. Frontend devenv flags are applied before user `config.js` flags so the user can override them; backend audit consumers and persistence have their own flags. See `mem:audit-log` for the relationship between consumers and full audit rows. -## Invariants +## Tooling and images -- `infra-compose` / `instance-compose` wrap `docker compose` with `env -i`, then re-inject what compose needs. Stripping is required because `defaults.env` is sourced into manage.sh's shell at startup (stale values would leak); the ws1+ overrides are deliberately re-injected as shell env vars precisely because Compose gives shell precedence over `--env-file`, so they override the `defaults.env` baseline. -- Volume names pinned via `name:` (PENPOT_*_VOLUME), decoupled from the compose project name. Replacement services use new volumes and leave old volumes untouched. PostgreSQL 18 mounts `penpotdev_postgres_data_pg18` at `/var/lib/postgresql`; the old PG16 volume is not migrated automatically. -- Network aliases (`- main`, `- redis`) are not declared in main.yml. Compose's auto-service-alias still registers `redis` on the shared network, so DNS for `redis` is non-deterministic with multiple instances. Backend uses `PENPOT_REDIS_URI=redis://penpot-devenv-wsN-valkey/0` (container_name) instead. -- No cross-project `depends_on`. `manage.sh ensure-infra-up` uses Compose `--wait`; PostgreSQL, RustFS, and Mailpit expose healthchecks. PostgreSQL checks TCP so its temporary init server cannot report ready. -- `JAVA_OPTS` in `manage.sh` is shadowed inside the container by `_env`. The `-e JAVA_OPTS=...` flag only matters for processes that don't source `_env`. -- opencode is not part of the devenv image. `scripts/setup-opencode` installs the `@opencode/cli` global pnpm package into the penpot user's `$PNPM_HOME` (`/home/penpot/.local/share/pnpm`, inside the user-data volume, so it survives a container re-creation); nothing pins the version in the repo, it tracks the `latest` dist-tag at install time. pnpm 12 puts the global packages in `$PNPM_HOME/global` and the bin dir in `$PNPM_HOME/bin`, and aborts with `ERR_PNPM_GLOBAL_BIN_DIR_NOT_IN_PATH` unless that bin dir is on `PATH`; `files/bashrc` and the script both add it. The script exports `PNPM_HOME` itself because non-interactive shells never read `~/.bashrc`. -- `files/entrypoint.sh` chowns penpot's whole `~/.local` and `~/.cache` on every start, because `EXTERNAL_UID` remaps penpot's UID to the host user and build-time ownership then stops matching. That covers pnpm's global dir, store, `package-manager-store` and metadata cache, plus opencode's own state; without it, global installs and pnpm's `packageManager` auto-download fail on permissions. The dotfiles copied from `/root` (`.bashrc`, `.vimrc`, `.tmux.conf`) are chowned in the same pass. `~/.config` stays out on purpose (the opencode overlay bind-mounts a host directory inside it) and so does `/home/penpot` itself, which holds the repo bind mount. - -## Worker policy - -Backend workers run only on ws0. `_env` gates `enable-backend-worker` on `PENPOT_BACKEND_WORKER`; ws1+ inject it as false. Workers are fire-and-forget from the RPC's point of view: `jobs/submit` inserts a row into the shared Postgres `job` table and returns (the legacy `task` table stays dormant) and RPC handlers never wait on completion. A job with an owner profile does publish `:job-event` on that profile's msgbus topic after the commit, on the msgbus of the workspace that executes it; with per-workspace valkey, a job enqueued from ws1 and run on ws0 notifies ws0's bus, not ws1's. The reason for "ws0 only" is avoiding multi-instance worker races (cron dedup is best-effort across instances; `jobs/submit` resolves its dedupe and exclusivity in the database, so the submit itself does not race); details in `mem:prod-infra/core`. - -Each workspace is independent and can be started/stopped in any order. Shared infra (Postgres, RustFS, etc.) is shut down only when no instances remain running. - -## Port layout - -Container-internal ports fixed; host side offset `10000·N`. - -| ws0 | ws1 | wsN | container | role | -|---|---|---|---|---| -| 3449 | 13449 | 3449+10000·N | 3449 | public HTTPS (Caddy; `/mcp/ws` same-origin) | -| 3449/udp | 13449/udp | … | 3449/udp | HTTP/3 | -| 4401 | 14401 | … | 4401 | MCP HTTP stream | -| 4403 | 14403 | … | 4403 | MCP REPL | -| 14181 | 24181 | … | 14281 | Serena MCP | -| 14182 | 24182 | … | 24282 | Serena dashboard | - -Everything else (frontend dev, backend API, exporter, storybook, REPLs, plugin dev, MCP inspector/WebSocket) is in-process or same-origin via Caddy/nginx. Infra publishes RustFS S3 API 9000, RustFS console 9001, and Mailpit UI 1080 on loopback; ldap 10389/10636 remains a singleton without offsets. Mailpit stores its SQLite database in `penpotdev_mailpit_data`. - -## Tmux + MCP routing - -`docker/devenv/files/start-tmux.sh` is session-level idempotent. Reads `PENPOT_TMUX_ATTACH`. If the session exists it attaches or exits; otherwise creates 4 base windows (frontend watch / storybook / exporter / backend) plus `mcp` (when `enable-mcp` in `PENPOT_FLAGS`) and `serena` (when `SERENA_ENABLED=true`). `run-devenv --agentic` always sets both env vars. The legacy `run-devenv` alias doesn't, hence its 4-window-only session. To switch from a legacy session to agentic, `stop-devenv` then `run-devenv --agentic` — the conditional windows are only added at session create time. - -MCP plugin routing is same-origin: frontend uses `/mcp/ws`, per-instance nginx proxies to MCP port 4401 in-container. For the plugin↔MCP server wiring (how the browser plugin discovers the URL, the in-memory connection registry, why DB-mediated routing isn't needed), see `mem:mcp/core`. - -## Workspace orchestration (ws1+) - -Workspace directories are user-maintained at `${PENPOT_WORKSPACES_DIR}/wsN`. `run-devenv --agentic --ws i` syncs only when `--sync` is passed, with one exception: if the workspace directory is missing on first use, sync runs implicitly to seed it. - -`sync-workspace wsN`: -1. `assert-clean-git-state` — refuses on `.git/{rebase-apply,rebase-merge,MERGE_HEAD,CHERRY_PICK_HEAD,index.lock}`. No `--sync-force` escape. -2. `rsync -a --delete $PWD/.git/ $workspace/.git/`. -3. `git ls-files -z --cached --others --exclude-standard` → `rsync --files-from` (Git is the authority on tracked files; rsync's gitignore filter would drop committed files under gitignored parents like `.clj-kondo/config.edn`). -4. Initial-only copy of `frontend/resources/public/js/config.js` (gitignored, but agentic mode needs it). After the first sync the workspace's copy belongs to the developer — subsequent syncs leave it alone. -5. `git switch -C "wsN/"` inside the workspace. - -No `--delete` on the working-tree pass: gitignored caches in the workspace survive. Workspace dir + named volumes survive `compose down`. - -## CLI surface - -- `run-devenv --agentic [--ws main|0|wsN|N] [--sync] [--serena-context CTX] [--opencode-config-dir DIR]`: bring one instance up. Agentic only — MCP and Serena windows are always created. Default target main. Errors out if the target is already running. `--sync` is rejected on main; on ws1+ it's optional (forced only when the workspace dir does not exist yet). `--opencode-config-dir DIR` bind-mounts DIR at `~/.config/opencode` in-container via the optional overlay above; mount applies at container creation, so changing it requires stop + re-run. -- `stop-devenv [--ws main|0|wsN|N] [--all]`: stop instances. Flags mutually exclusive. `--ws N` stops just that workspace. `--ws 0` or no flag stops ws0; shared infra shuts down only if no other instances remain. `--all` stops every ws highest-first then ws0, then infra. -- `run-devenv`: legacy alias, ws0 non-agentic attached. -- `attach-devenv [--ws main|0|wsN|N]`: pure attach. Fails fast if instance/session missing. -- `run-devenv-shell [--instance 0|wsN|N] [cmd...]`: bash in target instance. (`--instance` flag not yet renamed to `--ws`.) -- `start-devenv` / `log-devenv` / `drop-devenv`: legacy paths around ws0 + shared infra. `drop-devenv` never removes volumes. - -`exporter/scripts/run` and `wait-and-start.sh` source `backend/scripts/_env` then `_env.local` if present. - -## Image and dependency pins - -Two Dockerfile trees, both multi-arch (`linux/amd64,linux/arm64`): -`docker/devenv` (dev) and `docker/images` + `docker/imagemagick` (prod). - -- Hand-pinned versions, one source each: - - `docker/devenv/Dockerfile`: `NODE_VERSION` (+ per-arch `NODE_SHA256`), - `PNPM_VERSION` (+ `PNPM_SHA256`), `CADDY_VERSION`, `CLOJURE_VERSION`, - Zulu JDK URL + `ESUM`, `RUSTUP_VERSION`/`RUST_VERSION`/ - `EMSCRIPTEN_VERSION`, `CLJKONDO_VERSION`, `BABASHKA_VERSION`, - `CLJFMT_VERSION`, `PIXI_VERSION`, `GITHUB_CLI_VERSION`, - `AWS_CLI_VERSION` (+ `BINARY_SHA256`), `UV_VERSION`, `SERENA_VERSION`, - `postgresql-client-18`, and the `penpotapp/imagemagick:` - `COPY --from`. - - `docker/images/Dockerfile.backend`: Zulu JDK URL + `ESUM`. The `jlink` - `--add-modules` list must keep `jdk.management` - (`mem:backend/subtleties`). - - `docker/images/Dockerfile.{exporter,mcp,media-processor}`: `ARG - PNPM_VERSION` (+ arch SHAs, same values as devenv). -- Node and pnpm must agree in five places: `.nvmrc`, the devenv tarball pin, - the two `plugins-deploy-*` workflows that set `runtime: node@`, and - the four Dockerfile pins. pnpm procedure: `mem:workflow/updating-pnpm`. -- `dhi.io` base images are pinned `tag@sha256:`; Renovate moves - them (`penpot-renovate[bot]`, commits titled `:arrow_up: Update DHI base - images`). Tag and digest move together: a new tag with the old digest still - pulls the old image, and the digest must be the multi-arch index, not a - per-platform one. -- Every hand-pinned checksum is per architecture; one wrong value breaks half - of the multi-arch build. -- `SERENA_UPDATE_VERSION` in `docker-compose.main.yml` must never be lower than the Dockerfile's `SERENA_VERSION`. Any value makes `start-tmux.sh` install that Serena release on start, overriding the version baked into the image; a stale value silently downgrades Serena (it once replaced 1.7.0 with 1.6.1). If the image already has that version the install is an offline no-op; otherwise it downloads on every start (`run-devenv` recreates the container) and, offline, fails after ~25s and keeps the image version. Bump both together; empty means use the image version. -- Infra images live in `docker-compose.infra.yml`: `rustfs/rustfs` (owns the - S3 data volume), `axllent/mailpit` (SQLite in a volume), `valkey/valkey`, - `postgres:18.6`, `rroemhild/test-openldap`. Keep the volume names stable - when bumping them; replacement services get new volumes and leave the old - data untouched. -- Build locally: `docker build -f docker/devenv/Dockerfile docker/devenv/` - and `cd docker/images && ./build.sh --local`. CI: - `build-docker-devenv.yml`, `build-docker.yml`. +- `scripts/setup-opencode` installs into the persisted user's `PNPM_HOME`, not the image. Non-interactive shells do not load `.bashrc`; keep the script's `PNPM_HOME` and bin-path handling. On UID remap the entrypoint fixes ownership of tool caches and user data, not the host-mounted repo or config. +- `SERENA_UPDATE_VERSION` overrides the image's `SERENA_VERSION` at startup. An older override can silently downgrade Serena; keep them aligned or leave the override empty. +- Check architecture-specific hashes and use the dependency workflows instead of copying pin lists: `mem:workflow/updating-node`, `mem:workflow/updating-pnpm`, `mem:workflow/docker-images`. diff --git a/.serena/memories/prod-infra/core.md b/.serena/memories/prod-infra/core.md index 6b34af2075..7049b8dac4 100644 --- a/.serena/memories/prod-infra/core.md +++ b/.serena/memories/prod-infra/core.md @@ -1,62 +1,18 @@ -# Production infrastructure (services Penpot depends on) +# Production infrastructure -Backend (`app.config`, `PENPOT_*` env vars) is parameterized; deployments choose providers. +- Start at `app.config` for backend service settings and `docker/images/` for deployment defaults. Object storage lifecycle and bucket rules: `mem:backend/storage`. Local service isolation: `mem:devenv/core`. Metrics and read-replica limits: `mem:prod-infra/grafana`. -## Services +## Worker topology and draining -- **PostgreSQL**: durable store: profiles, teams, files, sessions, audit, the jobs work queue, the cron registry and migrations. File data also lives here depending on the file-data backend. One shared DB across all backends. -- **Redis (Valkey-compatible)**: per-backend message bus and cache: collaborative-editing broadcasts and team/profile notifications, the file-summary cache, rate-limit counters and the dispatcher→runner hand-off. `PENPOT_REDIS_URI`. A burst of client-side `RedisCommandTimeoutException` with the exporter healthy is the JVM paused or starved, not Redis: the timeout fires because nothing reads the reply. -- **Object storage**: backends `:s3` and `:fs`. S3 in prod; devenv uses RustFS. Holds uploaded media, file-data when the file-data backend is `storage`, exports. Backend-side details (resolve, dedup, bucket set, object lifecycle, and file-data backends): `mem:backend/storage`. -- **SMTP mailer**: invitations, password resets, email verification (sent via the `:sendmail` worker job). -- **LDAP** (optional auth provider): helpers in `app.auth.*`, gated by `enable-login-with-ldap`. +- PostgreSQL is authoritative for job state and claims. The dispatcher and runners must use the same tenant and Redis/Valkey destination to share a queue; sharing PostgreSQL alone is insufficient. Pub/Sub is separate from the queue: notifications go to the executing backend's configured bus and tenant. Keep heavy job queues separate from queues serving unrelated work. +- `scheduled_task` locking serializes competing cron ticks while the transaction is open; `skip-if-active` rejects duplicate live jobs. Neither promises one execution across all time: a later tick can submit after the prior job becomes terminal, and work can outlive an aborted row. Enforce idempotency or ownership on the data the handler touches. For dedupe, recovery and metric semantics see `mem:backend/jobs`. +- Use `app.srepl.main/set-offline` to drain one instance. `/readyz` stops routing traffic to it without querying PostgreSQL; in-flight requests can finish. Restart brings it online. Draining ingress does not migrate job execution: unclaimed hand-offs and expired running leases are handled by the job abort sweeps. Read-only backends do not start workers. +- Redis timeouts alone do not prove Redis is stalled; a paused or starved JVM can fail to read replies. Check client/process health as well as the service before assigning cause. -## Task queue and worker model +## Production SQL and migrations -Async jobs are enqueued via `jobs/submit` (`app.jobs`), which inserts a row into the shared Postgres `job` table tagged with its tenant and queue. Submission is **fire-and-forget**: RPC handlers never poll and never wait. The completion signal is the job row's status, which the creation commands read back to answer with the state of the job they just created. A job submitted with an owner profile publishes its progress on that profile's msgbus topic after each transaction commits; the binfile commands are the callers that pass the owner. Soft-delete RPCs return immediately after marking the top-level row, leaving the cascade and reaping to workers. - -Workers run on backends with `enable-backend-worker` in `PENPOT_FLAGS`. Each worker-enabled backend has a dispatcher that claims jobs and pushes them to the shared Redis list `penpot.worker.queue::` (`app.worker/queue-key`), and one or more runners per queue that pop from the same list and update the Postgres row. The tenant segment keeps two tenants sharing one Redis apart; a job handed off by one backend can be popped by any backend running that tenant's queue, and the Postgres row is the only claim. The queues are `default`, `webhooks`, `cron` and `binfile`: `binfile` carries the heavy work of a user job, so a long export or import does not block the default runner that serves the delete cascades. - -## Cross-backend safety - -Postgres row locking is the only correctness primitive: job claims, cron firing and the job-handler-internal locks (for example, the file-gc scheduler locks its candidate rows) all rely on it. This makes the work-claim path safe across any number of worker-enabled backends. - -Two known race patterns survive multi-backend operation: - -- **Cron dedup is best-effort.** The lock on `scheduled_task` is released when the task body finishes. If two backends' cron timers fire for the same scheduled instant with a gap larger than the task body's runtime, both execute it. Penpot's cron entries are idempotent; the exception is `:telemetry`, which would double-report. The audit consumers are not served by cron any more: each one is a loop in a thread and takes a session advisory lock for the whole pass, so a double-fire of a cron entry cannot overlap them. -- **`jobs/submit ::dedupe` / `::debounce`** are not affected by it: the row is inserted as deduped and a partial unique index (`status = 'new'`) admits a single not-started row per tenant/name/queue/label. The insert resolves the conflict with `ON CONFLICT DO NOTHING` (skip) or `DO UPDATE` (refresh the schedule and the params of the pending row), so there is no delete before the insert and no cross-backend duplicate. Neither gives "at most one execution": a row that already left `new` (dispatched, running, retrying) does not block the next submit. -- **`jobs/submit ::skip-if-active true`** works the same way one level up: the row is inserted as exclusive and a partial unique index admits a single live row (`new`/`scheduled`/`running`/`retry`) per tenant/name/queue/label, resolved with `ON CONFLICT DO NOTHING`. What it does not give is "at most one execution": the row can go terminal while its work is still running (a retry, an `aborted` orphan), so the work itself must be claimed on the data it touches. - -Penpot in production lives with both: horizontal-scale deployments accept "exactly-once" as "essentially-once for idempotent operations." Devenv parallel instances handle it by running workers only on ws0 (see `mem:devenv/core`). - -## Jobs observability - -Worker-enabled, writable backends publish unified jobs metrics through the normal Prometheus registry. One submit counter splits by `outcome` (`created`, `skipped`, `refreshed`), and the dispatch and retry counters are keyed by job name; terminal outcomes are the `_count` of the total-time histogram (`completed`, `failed`, `cancelled`, `aborted`), which counts the system-side aborts (an expired orphan lease or a job never claimed after being scheduled), so there is no separate terminal or orphan counter. Histograms separate claim wait (how late the claim happened), handler execution and total job age, plus dispatcher batch timing and size. `queue` survives only on the batch size: a batch mixes job names, and every other measurement is keyed by a name that already determines its queue. SQL-backed events are recorded after the outer PostgreSQL transaction commits. There is no gauge and no sampler: the backlog and the age of the oldest pending job are one SQL query when an operator asks. All labels are bounded operational values; job IDs, profile IDs, params and error text are excluded. Read-only backends do not start the workers. - -## Draining one instance - -Each backend has a per-process availability flag (`app.health`, a global atom). While offline, `/readyz` answers `503 OFFLINE` without querying the database, so the load balancer removes that instance from rotation while requests in flight still finish. Operator surface: `app.srepl.main/set-offline` / `set-online`; a restart comes back online. Nothing stays stuck after an instance leaves: a job handed to a queue (`scheduled`) that no worker claims within the lost window is aborted with `:lost`, and a `running` job whose lease expires is aborted with `:orphan`. The in-flight work is abandoned, not resumed, and the sweep never retries it. - -## Touching production data - -Production runs the deployed toolbox, not the devenv one: - -- **No psql meta-commands there.** `scripts/psql` and `\set`, `\if`, `\copy` do not exist in production, so a data script must be **plain SQL**, copy-pasteable into any client. -- **Start from the ids, not from an inventory.** The ids come from the error or the logs. Unbounded queries over tables with tens of millions of rows (`storage_object`, `file_media_object`) do not finish in a reasonable time; bounded to an id list they are index lookups. -- **One query per reference column.** Two columns in one `IN (col_a, col_b)` lose the index and scan the whole table; split them. -- The read-only replica cuts long queries: see `mem:prod-infra/grafana`. -- A migration that builds an index runs inside the migration transaction, so it cannot use `CONCURRENTLY`, and a plain `CREATE INDEX` locks the table against writes for the whole build. On a large table (file saves write to `file_change` on every save) build the index out of band, before deploying, with `CREATE INDEX CONCURRENTLY` on its own (never inside a transaction block); the shipped migration uses `IF NOT EXISTS`, finds it and skips the build (it still takes the `ALTER`s' locks, so the operator registers the step in `migrations`; the consumer-generalization runbook registers it first of all, before the DDL). A concurrent build interrupted midway leaves the index invalid: drop it and retry (check `pg_index` and `pg_index.indisvalid`). The runner applies **every pending step in one transaction**, so pre-applying one migration of a group does not avoid the locks of the others. -- Audit-log rollout: `operations/2.20.0-consumer-generalization.md` owns the procedure for large databases. It pre-registers `0154-add-job-table` and `0159-consumer-generalization` before doing the schema work out of band; otherwise idempotency guards do not prevent migration locks or scans. The old archiver and new consumers do not coordinate, so stop the old archiver and keep the GC explicitly disabled during the mixed-version rollout. The new GC runs by default. Turning consumers off does not stop it: registered cursors still bound cursor-based deletion, and seven-day shadow retention needs no cursor. See `mem:audit-log` for the replay and retention guarantees. -- The 2.20.0 release ships three out-of-band migration procedures; the unified, self-contained runbook for the whole upgrade (phases from pre-flight to the maintenance window) is `operations/2.20.0-unified.md`, indexed in `operations/README.md`. The individual 2.20.0 runbooks stay as the reference per area. -- A partitioned parent cannot take `CREATE INDEX CONCURRENTLY` (`cannot create index on partitioned table ... concurrently`). Build one index per partition with `CONCURRENTLY`, then `CREATE INDEX ... ON ONLY` on the parent and `ALTER INDEX ... ATTACH PARTITION` for each child; the parent index only becomes valid when every partition is attached. -- Write the migration as plain, idempotent SQL: `ADD COLUMN IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, and `DROP CONSTRAINT IF EXISTS` followed by `ADD CONSTRAINT`. Do not encode shape checks as `pg_catalog` introspection: they are easy to get wrong (a missing `NOT condeferred` accepts an `INITIALLY DEFERRED` foreign key) and they duplicate what the runbook verifies by hand. `IF NOT EXISTS` matches the name, not the definition, so the out-of-band procedure verifies the index shape and completeness; an `INVALID` index from an interrupted build also satisfies `IF NOT EXISTS` and the dedupe/exclusivity stops enforcing silently, so the `indisvalid` gate is mandatory. -- The runbook is the contract for a large instance: it pre-registers the migration steps (`INSERT INTO migrations (module, step) ...`) at the start, then builds and verifies the out-of-band work before deployment. The rows make the runner skip the migrations, so the manual runbook must finish every schema change and backfill before 2.20.0 starts. The unified 2.20.0 runbook registers all steps together at the beginning. -- A reference that a GC task resolves must be `DEFERRABLE INITIALLY IMMEDIATE`, never `INITIALLY DEFERRED`: the immediate check fires inside the transaction that catches the violation and retries the chunk; the deferred one fires at commit, outside the catch. A validated foreign key belongs out of band: `ADD FOREIGN KEY` runs as an `ALTER TABLE` and it scans the whole referencing table; `NOT VALID` on a partitioned table only exists since PostgreSQL 18. -- A backfill that removes a key an old reader uses (for example `metadata.storage-ref-id`, which the previous storage GC scans) must run with the old code stopped. Otherwise the old reader loses the reference and can delete a live object, and the rows it writes in the meantime miss the backfill. The 2.20 file-data migration does this atomically per row; the large-instance runbook batches updates, clears the key with the column write, uses a temporary partial index for pending rows, and requires restoring the backup to roll back to the old binary. -- `ADD COLUMN` takes a brief `ACCESS EXCLUSIVE` even when `IF NOT EXISTS` skips it, and `ADD FOREIGN KEY` takes `ACCESS EXCLUSIVE` on the referencing table and `SHARE ROW EXCLUSIVE` on the referenced one. A migration accepts those locks; a deployment that cannot take them runs the runbook and marks the step as applied. - -## See also - -- Devenv composition and the ws0-only worker placement: `mem:devenv/core`. -- Storage backend resolution, dedup, bucket behavior, object lifecycle, and file-data lifecycle: `mem:backend/storage`. -- Storage operation metrics (S3 API calls, logical ops, dedup, asset requests) and the logical-bucket vs physical-target distinction: `mem:backend/storage` (Metrics section). -- Grafana (datasource ids and how to use them, main dashboard, panel conventions and gotchas): `mem:prod-infra/grafana`. +- Use plain SQL for the deployed toolbox, not local `scripts/psql` or psql meta-commands. Start with known IDs and use point lookups on indexed reference columns; split lookups rather than wrapping several indexed columns in an expression that can force a scan. The read replica can cut long queries. +- The migration runner groups pending steps in one transaction; it cannot run `CREATE INDEX CONCURRENTLY`. A plain index build blocks writes, and even skipped DDL can acquire table locks. For large tables plan and verify the out-of-band work before deployment; never mark a migration as applied unless the deployment procedure accounts for all work it would skip. +- `IF NOT EXISTS` matches a name, not the definition, validity or completeness. An interrupted concurrent build can leave an invalid index that satisfies it, silently defeating deduplication or exclusivity. Verify `pg_index.indisvalid` and the index definition before relying on it. On partitioned tables build child indexes concurrently, then attach all of them to the parent index. +- For a reference whose violation a GC task must catch and retry, use `DEFERRABLE INITIALLY IMMEDIATE`: a deferred check can fail at commit outside the catch. Adding a validated foreign key can scan the whole referencing table; check the supported PostgreSQL version before assuming `NOT VALID` works for partitioned tables. +- Stop old readers and writers before removing a reference they still use. Otherwise a GC can delete a live object and concurrent writes can escape the backfill. Write the replacement reference and clear the old one atomically. For audit consumers and retention during mixed-version rollout, see `mem:audit-log`; disabling a consumer does not automatically disable GC. diff --git a/docs/technical-guide/developer/devenv.md b/docs/technical-guide/developer/devenv.md index 9cd8ed6fa3..01210447b2 100644 --- a/docs/technical-guide/developer/devenv.md +++ b/docs/technical-guide/developer/devenv.md @@ -213,20 +213,20 @@ their rendering backend. ### Shared state and workers -All instances share one Penpot database and one RustFS bucket; users, teams, -files, and MCP tokens are visible from every instance. Per-instance Valkey -keeps msgbus Pub/Sub channels (collab broadcasts, team-org notifications, -file-summary cache, rate-limit counters) isolated. +All workspaces share one application database and one RustFS bucket, so +they see the same users, teams, files, and MCP tokens. They also share a +Valkey server, but each workspace uses a separate logical database for +runtime keys. Pub/Sub channels are separated by a workspace-specific tenant +prefix, not by the Valkey database number. -Background workers (`enable-backend-worker`) run only on ws0 — ws1+ overlays -disable it. ws1+ RPC handlers still enqueue jobs into the shared Postgres -`job` table; ws0's dispatcher claims them via `FOR UPDATE SKIP LOCKED` and -runs them against the shared DB and RustFS. Workers are fire-and-forget: -`jobs/submit` inserts a row and returns; RPC handlers never wait on -completion. The "ws0 only" policy avoids multi-instance worker races (cron -dedup is best-effort across instances; the dedupe and exclusivity of -`jobs/submit` are resolved by unique indexes, so the submits themselves do -not race). +Backend tests use a separate PostgreSQL database and Valkey logical database +for each workspace. Use the workspace's `PENPOT_TEST_DATABASE_URI` and +`PENPOT_TEST_REDIS_URI` rather than pointing tests at the runtime databases. + +Jobs are stored in shared PostgreSQL but dispatched by tenant. A worker +enabled in `ws0` does not pick up jobs submitted under another workspace's +tenant. If a job stays pending, check the submitting workspace's effective +worker flags and tenant. Each workspace is independent and can be started and stopped in any order. Shared infrastructure shuts down only when no instances remain running. @@ -239,7 +239,7 @@ into separate compose projects per runtime instance: - `docker/devenv/docker-compose.infra.yml` (Postgres, RustFS, Valkey, mailer, LDAP) runs under the compose project `penpotdev-infra`. -- `docker/devenv/docker-compose.main.yml` (one main container + its Valkey) +- `docker/devenv/docker-compose.main.yml` (one main container) runs once per runtime instance under `penpotdev-ws0`, `penpotdev-ws1`, …. - Both projects join the external Docker network `penpot_shared`, created idempotently by `manage.sh`.