Andrey Antukh e23ca02aa2
✨ Reference the file data storage object with a foreign key (#12769)
* ✨ Reference the file data storage object with a foreign key

The file data pointer lived in `file_data.metadata.storage-ref-id`, a JSON
key. The storage GC parsed it to find live references, and nothing stopped it
from physically deleting an object a live row still pointed at: a failure in
that scan lost the blob.

Migration 0159 moves the pointer to a nullable `storage_object_id` column on
`file_data`, backfills it from the metadata key, removes the key from the
rows it backfills, indexes the column and rebuilds the foreign key to
`storage_object(id)` as `NO ACTION DEFERRABLE INITIALLY IMMEDIATE`.
`INITIALLY IMMEDIATE` is deliberate: the GC catches the violation inside the
chunk transaction, while a deferred check would fire at commit, outside it,
and the sweep would never move past the blocked chunk.

The column is the only source of truth. The `storage-ref-id` entry is gone
from the file metadata schema, and the single point that serializes the
metadata drops it, so no write can resurrect it. `upsert!` does not query
the row: the pointer of the row being replaced travels in its params, and
the object is touched before the row is written. Fragments and snapshots
pass nil because a modified pointer always gets a new id; the offload passes
its own row; `insert-file!` drops it, since an INSERT never replaces a
persisted object.

`update-file!` takes the file map read from the database plus the fields to
change and merges them, so the pointer comes from the read map and no caller
can lose it by building a partial map. A map without `:data` raises
`:missing-file-data`: it is not `assert`, which is compiled out in the
deployed binary. The params cannot override the pointer or retarget the
write with `:id`/`:file-id`.

`bfc/file->response` strips the pointer from every response (`get-file`,
`create-file`, `duplicate-file`, the view-only bundle, the team access
request, the comments read, the library summary, the snapshot read and the
debug download). A `file-data` object is authentication-only, so a leaked id
would let any logged-in profile fetch the blob from `/assets/by-id`.
`get-file-fragment` resolves through the file data backend, so a fragment on
cold storage no longer hands nil to `blob/decode`, and answers only the keys
of its result schema.

The storage GC reference scan, the restore union and `objects-gc` read the
column. The offload reads `SELECT fd.*`, so its rows go through a
`decode-row` that decodes jsonb metadata and drops a JSON null, which the row
schema rejected; a row without a readable object raises
`:missing-storage-object` with the file and row ids. A chunk blocked by the
foreign key (SQLState 23503) is a real anomaly, since the reference scan
should have frozen the object: it stays an error with its own hint and the
chunk is retried on the next run until the reference is fixed.

The release is a coordinated restart, not a rolling deploy, and not
rollback-safe for the rows it writes: the previous code writes and scans the
metadata pointer, so a key it writes misses the backfill and removing it
loses the reference. `operations/2.20.0-file-data-storage-object-id.md`
builds the column, the index and the foreign key online and runs the
backfill with every instance stopped, then marks the step as applied; a
fresh or small instance does the whole job in the migration. The runbook
keeps the validation scan out of the stopped window and adds a lock timeout
and retry to the online statements.

Tests cover the foreign key shape, the backfill and its corrupt and orphan
guards, the rebuild of a missing index and of a wrong, non-deferrable or
deferred constraint, the deletion refused by a live reference, the metadata
cleanup, the offload row normalizations, the touched objects of the unshare
and the restore, the response stripping on every call site and the chunk
blocked by the foreign key. The backend memories and the developer guide
document the pointer, the GC behavior and the two migration paths.

Closes #12768

AI-assisted-by: deepseek-v4.1-flash
AI-assisted-by: inkling-2-small-free

* 🐛 Hold the file row lock across the migration write

`get-file` applies the pending migrations in memory and, when it finds
any, persists the result. That write read the row without a lock and
`update-file!` is an unconditional UPDATE, so a save that committed in
between was overwritten: the saved content, `revn` and `modified-at`
went back, the next save from that client failed with `:revn-conflict`
and the object the save left became an orphan the storage GC cannot
revisit once it is frozen.

The read now runs in a transaction of its own (`get-file` calls
`get-file*` inside `db/tx-run!` and accepts a cfg map only), so the
`file` row lock covers the re-check and the write. `get-file*` reads
the row once (`sql:get-file` plus `resolve-applied-migrations`) and
completes it with `attach-file-data`; only when a migration is pending
it reads the file again under `FOR UPDATE`, re-checks `need-migration?`
on that fresh map and persists it (`migrate-file`). The common case
stays at one row read and one migrations resolution, the migration case
keeps a single decoded copy in the heap, and a row that changed in
between is not overwritten. A migration found on the unlocked read is
applied in memory only, for the next read to persist.

`migrate-file` returns the reattached map when it persists, with the
`:storage-object-id` of the row the write left, and the realized map
when it does not; `:realize?` is what returns the read fully plain.
`fdata/upsert!` answers `{:written ... :storage-object-id ...}` instead
of a boolean, `update-file!` propagates it and the migrating read puts
it back in the map it returns, so a caller that persists again touches
the current object instead of the replaced one. `insert-file!` keeps
nil: an INSERT never replaces a persisted object.

The write also compares the stored pointer with the caller's value
(`IS NOT DISTINCT FROM`) and raises `:stale-file-data-pointer` when it
affects no row. Every writer holds the `file` row lock, so a pointer
that no longer matches is a protocol violation, not a race to retry.
The expected pointer is a separate argument because the storage branch
replaces `:storage-object-id` before the upsert, and the check lives in
`upsert-in-database`: the `legacy-db` branches do not use that SQL and
their count can legitimately be zero.

The save, snapshot and restore-backup reads take `FOR UPDATE` instead
of `FOR SHARE`: they inherit the lock, and the migration branch asks
for the exclusive one in the same transaction, so a shared lock that
upgrades deadlocks two concurrent readers. A data read rejects
`:lock-for-share?` for the same reason; only row-only reads accept it.
`sql:get-file-without-data` is a plain select now, not a CTE, which
makes locking legal without loading the data. Realization has a single
owner: `attach-file-data` only resolves and decodes, and `get-file*`
realizes once per path. The applied migrations no longer travel in the
`get-file-with-summary` response, cache hit and cache miss alike.

`embed-assets` reads each library without `:realize?`, so its
`:components` is an unloaded pointer map; `absorb-assets` walks it with
`vals`, `PointerMap.seq` calls `load!` and that raised with no loader
bound, so every export with `:merge-libraries` of a library with
components failed. The absorb runs under the library's own loader now.

The in-place binfile import (`import-file-and-overwrite*`,
`::overwrite`, `::bfc/file-id`) had no product caller and cannot carry
the previous `storage_object_id`, so overwriting a storage-backed row
would leave its object unreclaimed. `import-files!` rejects a cfg with
`::bfc/file-id` (`:not-supported`) and the helpers only that path used
go with it (`invalidate-thumbnails`, `*reference-file*`, the
`::overwrite` id branch of `index-object` and of `save-file!`, the
`on-conflict-do-nothing?` flag of the media insert).

Tests: a new `file-migration-read-test` pins the single read, the
locked re-read, the concurrent save interleaving, the double migration
and the read-only path; the upsert tests cover the return shape and the
stale pointer; the SQL recorder they share lives in
`backend-tests.helpers`, and the save, snapshot, restore and summary
sequences follow the new reads. The backend memories document the read
contract and the pointer.

AI-assisted-by: deepseek-v4.1-flash

* 🐛 Harden the get-file guard and skip its read-only transaction

The cfg guard of `get-file` was an `assert`, which `app.config` elides
when `:backend-asserts` is off, so a deployed binary accepted a bare
pool or connection while the docstring promised it raises. It throws
`IllegalArgumentException` now, the class the option guards of the same
namespace already use, and the existing test expects it instead of
`AssertionError`.

A read with `:read-only?` applies the pending migrations in memory and
writes nothing, so the transaction the migration write needs only costs
two round trips there. `get-file` runs it with `db/run!` instead: with
a cfg that carries a connection it still joins the caller's
transaction, and only the reads that would have opened their own skip
it. A lock option needs a read-write transaction from the caller,
because PostgreSQL rejects row locks in a read-only one; the docstring
states that.

Tests: the guard test expects the new class; a cfg marked
`::db/read-only` reads a pending migration without persisting it (the
config flag that fills that key is legacy, but the key is set by hand);
and a read-only read is pinned as not opening a transaction while the
same call without the option does. The backend memory documents the
split and the guard.

AI-assisted-by: deepseek-v4.1-flash
2026-11-14 19:27:18 +01:00

6.5 KiB

title, desc
title desc
3.06. Backend Guide Penpot Technical Guide: Backend basics - REPL setup, loading fixtures, database migrations, and clj-kondo linting to speed development workflows.

Backend guide

This guide collects some basic information on the backend application.

REPL

Note: When in development mode, the backend spins up a traditional nREPL socket on port 6064. If you are experimenting locally, you can connect to it using your Clojure editor or with backend/scripts/nrepl, which starts a REPLy client, see here for more information.

In the devenv environment you can execute backend/scripts/repl to open a Clojure interactive shell (REPL) (this is not a socket-based REPL, but a local, in-process console (over stdin/stdout) with some fancy line-editing and colors). Note that the backend must be stopped before executing this script, otherwise it will fail with Port already in use: 9090.

Once there, you can execute (restart) to load and execute the backend process, or to reload it after making changes to the source code.

Then you have access to all backend code. You can import and use any function o read any global variable:

(require '[app.some.namespace :as some])
(some/your-function arg1 arg2)

There is a specific namespace app.srepl with some functions useful to be executed from the repl and perform some tasks manually. Most of them accept a system parameter. There is a global variable with this name, that contains the runtime information and configuration needed for the functions to run.

For example:

(require '[app.srepl.main :as srepl])
(srepl/send-test-email! system "test@example.com")

Fixtures

This is a development feature that allows populating the database with a good amount of content (typically used to test the application or to run performance tweaks on queries).

In order to load fixtures, enter the REPL environment with the backend/scripts/repl script, and then execute (app.cli.fixtures/run {:preset :small}).

You also can execute this as a standalone script with:

clojure -Adev -X:fn-fixtures

NOTE: This is an optional step because the application can start with an empty database.

The above will create several users that can be used to login into the application. All of them follow the pattern:

  • Username: profileN@example.com
  • Password: 123123

Where N is a number from 0 to 5 on the default fixture parameters.

Migrations

The database migrations are located in two directories:

  • src/app/migrations (contains migration scripts in clojure)
  • src/app/migrations/sql (contains the pure SQL migrations)

The SQL migration naming consists in the following:

XXXX-<add|mod|del|drop|[...verb...]>-<table-name>-<any-additional-text>

Examples:

0025-del-generic-tokens-table
0026-mod-profile-table-add-is-active-field

NOTE: if table name has more than one word, we still use - as a separator.

Large tables

A migration runs inside a single transaction, so it cannot use CONCURRENTLY, and a CREATE INDEX in a migration locks the table against writes until the whole run commits.

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 (forgetting NOT condeferred accepts an INITIALLY DEFERRED foreign key, which moves the integrity check to commit) and they duplicate what the runbook can verify by hand.

On a large table, build the column and the index out of band before deploying, with CREATE INDEX CONCURRENTLY on its own (never inside a transaction block). A partitioned table cannot take CREATE INDEX CONCURRENTLY on the parent: build the index on each partition, create the parent index with CREATE INDEX ... ON ONLY, and attach every partition with ALTER INDEX ... ATTACH PARTITION. An interrupted concurrent build leaves the index INVALID: drop it and retry. CREATE INDEX IF NOT EXISTS matches the name, not the definition, so the runbook verifies pg_index.indisvalid, that the index has no predicate or expression, and that every partition is attached.

A validated foreign key is the other expensive DDL: ADD FOREIGN KEY runs as an ALTER TABLE, so it takes ACCESS EXCLUSIVE on the referencing table and SHARE ROW EXCLUSIVE on the referenced one, and it scans the whole referencing table. NOT VALID on a partitioned table is only available since PostgreSQL 18. 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 deferred one fires at commit, outside the catch.

The runbook ends by verifying the end state (column, pending rows, index and constraint shape) and marking the migration step as applied (INSERT INTO migrations (module, step) ...), so the body does not run at startup. The marker is the only thing that skips the migration.

A backfill that removes a key an old reader uses (for example a JSONB pointer that the previous 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.

ADD COLUMN takes a brief ACCESS EXCLUSIVE even when it changes nothing. A migration accepts that lock; a deployment that cannot take it runs the runbook and marks the step as applied.

If you need to have a global overview of the all schema of the database you can extract it using postgresql:

# (in the devenv environment)
pg_dump -h postgres -s  > schema.sql

Linter

There are no watch process for the linter; you will need to execute it manually. We use clj-kondo for linting purposes and the repository already comes with base configuration.

You can run clj-kondo as-is (is included in the devenv image):

cd penpot/backend;
clj-kondo --lint src