penpot/backend/src/app/storage/gc_touched.clj
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

354 lines
14 KiB
Clojure

;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns app.storage.gc-touched
"This task is part of the garbage collection process of storage
objects and is responsible on analyzing the touched objects and mark
them for deletion if corresponds.
For example: when file_media_object is deleted, the depending
storage_object are marked as touched. This means that some files
that depend on a concrete storage_object are no longer exists and
maybe this storage_object is no longer necessary and can be eligible
for elimination. This task periodically analyzes touched objects and
mark them as freeze (means that has other references and the object
is still valid) or deleted (no more references to this object so is
ready to be deleted)."
(:require
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.exceptions :as ex]
[app.common.logging :as l]
[app.common.schema :as sm]
[app.common.time :as ct]
[app.db :as db]
[app.jobs :as jobs]
[app.metrics :as mtx]
[app.storage :as sto]
[app.storage.impl :as impl]
[integrant.core :as ig]))
(def ^:private sql:has-team-font-variant-refs
"SELECT ((SELECT EXISTS (SELECT 1 FROM team_font_variant WHERE woff1_file_id = ?)) OR
(SELECT EXISTS (SELECT 1 FROM team_font_variant WHERE woff2_file_id = ?)) OR
(SELECT EXISTS (SELECT 1 FROM team_font_variant WHERE otf_file_id = ?)) OR
(SELECT EXISTS (SELECT 1 FROM team_font_variant WHERE ttf_file_id = ?))) AS has_refs")
(defn- has-team-font-variant-refs?
[conn {:keys [id]}]
(-> (db/exec-one! conn [sql:has-team-font-variant-refs id id id id])
(get :has-refs)))
(def ^:private
sql:has-file-media-object-refs
"SELECT ((SELECT EXISTS (SELECT 1 FROM file_media_object WHERE media_id = ?)) OR
(SELECT EXISTS (SELECT 1 FROM file_media_object WHERE thumbnail_id = ?))) AS has_refs")
(defn- has-file-media-object-refs?
[conn {:keys [id]}]
(-> (db/exec-one! conn [sql:has-file-media-object-refs id id])
(get :has-refs)))
(def ^:private sql:has-profile-refs
"SELECT ((SELECT EXISTS (SELECT 1 FROM profile WHERE photo_id = ?)) OR
(SELECT EXISTS (SELECT 1 FROM team WHERE photo_id = ?))) AS has_refs")
(defn- has-profile-refs?
[conn {:keys [id]}]
(-> (db/exec-one! conn [sql:has-profile-refs id id])
(get :has-refs)))
(def ^:private
sql:has-file-object-thumbnail-refs
"SELECT EXISTS (SELECT 1 FROM file_tagged_object_thumbnail WHERE media_id = ?) AS has_refs")
(defn- has-file-object-thumbnails-refs?
[conn {:keys [id]}]
(-> (db/exec-one! conn [sql:has-file-object-thumbnail-refs id])
(get :has-refs)))
(def ^:private sql:has-file-thumbnail-refs
"SELECT EXISTS (SELECT 1 FROM file_thumbnail WHERE media_id = ?) AS has_refs")
(defn- has-file-thumbnails-refs?
[conn {:keys [id]}]
(-> (db/exec-one! conn [sql:has-file-thumbnail-refs id])
(get :has-refs)))
;; Objects in the job-resource bucket are referenced by the resource_id
;; column of job rows (the unified jobs substrate). A live job row of
;; any status keeps the object frozen; once no row references it (the
;; jobs GC deletes expiring/retained rows and marks the object as
;; touched before/at the same time) the object becomes deletable.
(def ^:private sql:has-job-resource-refs
"SELECT EXISTS (SELECT 1 FROM job WHERE resource_id = ?) AS has_refs")
(defn- has-job-resource-refs?
"Checks if ANY job row (any status) references the object. Terminal states
(completed, failed, cancelled, aborted) also freeze the object because the jobs GC
hasn't run yet to clean them up. Once the jobs GC deletes the row, the
object becomes eligible for storage GC."
[conn {:keys [id]}]
(-> (db/exec-one! conn [sql:has-job-resource-refs id])
(get :has-refs)))
(def ^:private
sql:has-upload-session-chunk-refs
"SELECT EXISTS (SELECT 1 FROM upload_session_chunk WHERE object_id = ?) AS has_refs")
(defn- has-upload-session-chunk-refs?
[conn {:keys [id]}]
(-> (db/exec-one! conn [sql:has-upload-session-chunk-refs id])
(get :has-refs)))
(def sql:exists-file-data-refs
"SELECT EXISTS (
SELECT 1 FROM file_data
WHERE storage_object_id = ?
) AS has_refs")
(defn- has-file-data-refs?
[conn sobject]
(-> (db/exec-one! conn [sql:exists-file-data-refs (:id sobject)])
(get :has-refs)))
(def ^:private sql:mark-freeze-in-bulk
"UPDATE storage_object
SET touched_at = NULL
WHERE id = ANY(?::uuid[])")
(defn- mark-freeze-in-bulk
[conn ids]
(let [ids (db/create-array conn "uuid" ids)]
(db/exec-one! conn [sql:mark-freeze-in-bulk ids])))
(def ^:private sql:mark-delete-in-bulk
"UPDATE storage_object
SET deleted_at = ?,
touched_at = NULL
WHERE id = ANY(?::uuid[])")
(defn- mark-delete-in-bulk
[conn ids]
(let [ids (db/create-array conn "uuid" ids)]
(db/exec-one! conn [sql:mark-delete-in-bulk (ct/now) ids])))
(def ^:private sql:defer-in-bulk
"UPDATE storage_object
SET touched_at = ?
WHERE id = ANY(?::uuid[])")
(defn- defer-in-bulk
[conn ids timestamp]
(let [ids (db/create-array conn "uuid" ids)]
(db/exec-one! conn [sql:defer-in-bulk timestamp ids])))
;; NOTE: A getter that retrieves the key which will be used for group
;; ids; previously we have no value, then we introduced the
;; `:reference` prop, and then it is renamed to `:bucket` and now is
;; string instead. This is implemented in this way for backward
;; comaptibilty.
;; NOTE: we use the "file-media-object" as default value for
;; backward compatibility because when we deploy it we can
;; have old backend instances running in the same time as
;; the new one and we can still have storage-objects created
;; without bucket value. And we know that if it does not
;; have value, it means :file-media-object.
(defn- lookup-bucket
[{:keys [id metadata]}]
(or (some-> metadata :bucket)
(do
;; Only reachable when the metadata column is NULL: the decode
;; always sets :bucket on non-nil metadata (0155 also backfills
;; NULL columns). Keep working, but make it visible.
(l/wrn :hint "storage object without bucket metadata, using fallback"
:id (str id))
sto/default-bucket)))
(def ^:private sql:lock-storage-objects
"SELECT id FROM storage_object WHERE id = ANY(?::uuid[]) ORDER BY id FOR UPDATE")
(defn- verify-frozen
"Re-checks, holding the row locks, that the about-to-freeze objects are
still referenced. A concurrent purge (mapping delete plus touch) either
commits before the check and the object moves to deletion, or blocks on
the lock and its touch wins last, so no touch is ever swallowed by a
stale freeze. Ids are locked in order to avoid lock-order inversions
between workers. Returns [still-frozen-ids now-deletable-ids]."
[conn has-refs? bucket objects]
(let [by-id (into {} (map (juxt :id identity)) objects)
ids (db/create-array conn "uuid" (sort (keys by-id)))
locked (into #{} (map :id) (db/exec! conn [sql:lock-storage-objects ids]))]
(reduce (fn [[frozen deletable] {:keys [id] :as object}]
(if (and (contains? locked id) (has-refs? conn object))
[(conj frozen id) deletable]
(do
(l/dbg :id (str id)
:status "delete-after-recheck"
:bucket bucket)
[frozen (conj deletable id)])))
[#{} #{}]
objects)))
(defn- process-objects
[conn has-refs? bucket objects]
(loop [to-freeze #{}
to-delete #{}
objects (seq objects)]
(if-let [{:keys [id] :as object} (first objects)]
(if (has-refs? conn object)
(do
(l/dbg :id (str id)
:status "freeze"
:bucket bucket)
(recur (conj to-freeze object) to-delete (rest objects)))
(do
(l/dbg :id (str id)
:status "delete"
:bucket bucket)
(recur to-freeze (conj to-delete id) (rest objects))))
(let [[frozen deletable] (if (seq to-freeze)
(verify-frozen conn has-refs? bucket to-freeze)
[#{} #{}])
doomed (into to-delete deletable)]
(some->> (seq frozen) (mark-freeze-in-bulk conn))
(some->> (seq doomed) (mark-delete-in-bulk conn))
[(count frozen) (count doomed)]))))
;; NOTE: upload-session chunks are 1:1 with their mapping and never
;; shared, but the scan owns the liveness decision anyway: a referenced
;; chunk freezes, so gc-deleted never meets a live NO ACTION reference.
;; The freeze path re-verifies under row locks (see verify-frozen).
(defn- process-bucket
[conn bucket objects]
(cond
(= bucket "file-media-object") (process-objects conn has-file-media-object-refs? bucket objects)
(= bucket "team-font-variant") (process-objects conn has-team-font-variant-refs? bucket objects)
(= bucket "file-object-thumbnail") (process-objects conn has-file-object-thumbnails-refs? bucket objects)
(= bucket "file-thumbnail") (process-objects conn has-file-thumbnails-refs? bucket objects)
(= bucket "profile") (process-objects conn has-profile-refs? bucket objects)
(= bucket "file-data") (process-objects conn has-file-data-refs? bucket objects)
(= bucket sto/tempfile-bucket) (process-objects conn (constantly false) sto/tempfile-bucket objects)
(= bucket sto/upload-session-bucket) (process-objects conn has-upload-session-chunk-refs? sto/upload-session-bucket objects)
(= bucket sto/job-resource-bucket) (process-objects conn has-job-resource-refs? bucket objects)
(= bucket "organization") (process-objects conn (constantly false) bucket objects)
:else
(ex/raise :type :internal
:code :unexpected-unknown-reference
:hint (dm/fmt "unknown reference '%'" bucket))))
(defn- defer-poison
"Defer corrupt rows by one day in their own transaction, separate from
the healthy-chunk work."
[{:keys [::db/conn]} poison-ids]
(defer-in-bulk conn poison-ids (ct/plus (ct/now) {:days 1})))
(defn process-chunk
[{:keys [::db/conn]} chunk]
(reduce-kv (fn [[nfo ndo] bucket objects]
(let [[nfo' ndo'] (process-bucket conn bucket objects)]
[(+ nfo nfo')
(+ ndo ndo')]))
[0 0]
(d/group-by lookup-bucket identity #{} chunk)))
(def ^:private sql:get-touched-storage-objects
"SELECT so.*
FROM storage_object AS so
WHERE so.touched_at IS NOT NULL
AND so.touched_at <= ?
AND so.status = 'valid'
ORDER BY touched_at ASC
FOR UPDATE
SKIP LOCKED
LIMIT 10")
(defn- try-decode-row
"Decode a touched row, capturing corrupt metadata as poison instead
of aborting the whole chunk. Poison rows are deferred by the caller."
[row]
(try
[:ok (impl/decode-row row)]
;; Exception, not Throwable: JVM Errors (OOM, StackOverflow) must
;; not be swallowed as a deferrable data problem.
(catch Exception cause
(l/err :hint "storage object with corrupt metadata, deferring evaluation"
:id (str (:id row))
:cause cause)
[:poison (:id row)])))
(defn get-chunk
[conn timestamp]
(let [grouped (->> (db/exec! conn [sql:get-touched-storage-objects timestamp])
(map try-decode-row)
(group-by first))]
{:chunk (not-empty (mapv second (:ok grouped)))
:poison (not-empty (mapv second (:poison grouped)))}))
(defn- process-touched
[{:keys [::db/pool ::mtx/metrics ::timestamp] :as cfg}]
(loop [freezed 0
deleted 0]
(let [{:keys [chunk poison]} (get-chunk pool timestamp)]
(when (seq poison)
(mtx/run! metrics :id :storage-gc-poison :inc (count poison))
(db/tx-run! cfg defer-poison poison))
;; Keep draining after a poison-only batch: the deferred rows leave
;; the selection and the next batch may hold healthy objects.
(if (or (seq chunk) (seq poison))
(let [[nfo ndo] (if (seq chunk)
(db/tx-run! cfg process-chunk chunk)
[0 0])]
(jobs/heartbeat cfg)
(recur (long (+ freezed nfo))
(long (+ deleted ndo))))
{:freeze freezed :delete deleted}))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; HANDLER
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare execute-storage-gc-touched)
(defmethod ig/assert-key ::job-def
[_ params]
(assert (db/pool? (::db/pool params)) "expect valid storage")
(assert (mtx/metrics? (::mtx/metrics params)) "expect valid metrics"))
(defmethod ig/expand-key ::job-def
[k v]
{k (merge {::min-age (ct/duration {:hours 2})} v)})
(def schema:storage-gc-touched-params
"Optional :skip-delay processes all touched objects immediately,
bypassing the min-age threshold (repl-driven deletion cascades)."
[:map {:closed true}
[:skip-delay {:optional true} :boolean]])
(defmethod ig/init-key ::job-def
[_ cfg]
{::jobs/name :storage-gc-touched
::jobs/schema schema:storage-gc-touched-params
::jobs/handler
(fn [_context params]
(execute-storage-gc-touched cfg params))
::jobs/decoder (sm/decoder schema:storage-gc-touched-params sm/json-transformer)
::jobs/validator (sm/validator schema:storage-gc-touched-params)})
(defn execute-storage-gc-touched
"Plain job handler: analyze the touched storage objects and freeze or
delete them depending on their references."
([cfg] (execute-storage-gc-touched cfg {}))
([cfg params]
(let [threshold (if (:skip-delay params)
(ct/now)
(ct/minus (ct/now) (::min-age cfg)))]
(process-touched (assoc cfg ::timestamp threshold)))))