mirror of
https://github.com/penpot/penpot.git
synced 2026-11-26 21:00:32 +00:00
📚 Separate backend file read and save guidance
Keep migration and version lifetimes separate from partial save behavior. Route readers to the focused notes from the existing persistence entries. AI-assisted-by: gpt-6.2-sol
This commit is contained in:
parent
24315afa47
commit
570a5e67bc
@ -5,4 +5,5 @@
|
||||
- Revalidate permissions when jobs run, not just when submitting: access can be revoked while queued. Import runs inside a transaction so an interruption cannot leave half a file. The job adapter stops on the heartbeat interrupt and checks again after the final tap; do not publish success if cancellation fell between the last tap and return. An upload not adopted by a job must be released; adopted import packages and temporary copies must be released on terminal outcomes.
|
||||
- Keep the progress stage vocabulary shared across formats. Each tap carries its outer scopes, with no dependency on an earlier tap; throttling can drop intermediate events. Do not put source IDs or names into public progress. Normalize format-specific return shapes in the adapter rather than making the caller know the format.
|
||||
- A v1 package can list a file twice (legacy export included libraries without deduping). Consume both objects of every entry to keep the stream aligned, but import and report the first occurrence only.
|
||||
- v1/v3 import and v3 export's file read run inside long transactions. They extend the idle-in-transaction timeout without disabling it or extending the statement timeout; keep both limits distinct. See `app.binfile.common/transaction-idle-timeout-ms`.
|
||||
- v1/v3 import links must refer to files in the package and reject self-links and dependency cycles, using the same check as the live link command. Keep iteration deterministic so the first edge wins consistently.
|
||||
|
||||
@ -4,7 +4,8 @@ JVM Clojure backend. Start in `app.main` for Integrant wiring, `app.rpc.commands
|
||||
|
||||
## Focused memories
|
||||
|
||||
- RPC wrapper order, DB transactions and advisory locks, config and HTTP middleware, metrics, and file data persistence: `mem:backend/subtleties`.
|
||||
- RPC wrapper order, DB transactions and advisory locks, config, HTTP middleware and metrics: `mem:backend/subtleties`.
|
||||
- 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`.
|
||||
- Storage bucket rules, object lifecycle, deduplication, access and GC: `mem:backend/storage`.
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
# File-data storage and persistence boundaries
|
||||
|
||||
- Start at `app.features.fdata` for payloads, `app.binfile.common` for the file-map boundary, and `app.tasks.offload-file-data` for moving data to object storage. For fragment lifetimes, save application and snapshots, see `mem:backend/subtleties`.
|
||||
- Start at `app.features.fdata` for payloads, `app.binfile.common` for the file-map boundary, and `app.tasks.offload-file-data` for moving data to object storage. For fragment and version lifetimes see `mem:backend/file-data/reads-and-versions`.
|
||||
- `file_data.storage_object_id` is the authoritative reference; metadata is not a fallback. `legacy-db` reads old payloads only; startup normalizes that configured write backend to `db`. If an old binary still reads or writes a metadata pointer, it cannot safely coexist with writes that remove it. See `mem:prod-infra/core` for the general deployment constraint.
|
||||
- Carry the old pointer from the persisted row through updates under the file-row lock. `fdata/upsert!` touches it so the GC can reclaim the replaced blob, and rejects a stale expected pointer rather than leaking the object it would overwrite. `binfile.common/update-file!` preserves the old pointer from its read map and returns the pointer actually persisted; inserts must not inherit the source pointer. Strip both the column and any residual metadata pointer from file responses: direct object authentication does not verify file permissions.
|
||||
- Offload and the other writers serialize on the file row. Offload moves live DB rows in one transaction per file; later writes still use the configured default backend, not the offloaded row's backend. If a write aborts after the upload is valid, touched GC checks the blob's references; unfinished uploads use pending GC. Batch deletion must touch the old object and restore must clear the deletion mark on live references. See `mem:backend/storage`.
|
||||
- The foreign key must be `DEFERRABLE INITIALLY IMMEDIATE`: a referenced blob must not be removed, and a violation must reach the GC's chunk error handler rather than appear at commit outside it. The reference scan uses the indexed column, not metadata. See `mem:prod-infra/core`.
|
||||
- `file_change` and `file_data` have matching partition bounds; include `file_id` in lookups and group bulk purges by it so PostgreSQL can prune partitions. Advance `file_change.updated_at` on application writes: it is the watermark for delta copies. The legacy copy is not cleaned up automatically.
|
||||
- Snapshot metadata and revision deltas live in `file_change`; current snapshot payloads live in `file_data`. Queries still distinguish snapshots by label, not by the legacy `data` column or the reserved `kind` column. See `mem:backend/subtleties` for snapshot queries and restore behavior.
|
||||
|
||||
8
.serena/memories/backend/file-data/reads-and-versions.md
Normal file
8
.serena/memories/backend/file-data/reads-and-versions.md
Normal file
@ -0,0 +1,8 @@
|
||||
# File reads, fragments and versions
|
||||
|
||||
- Start at `app.binfile.common/get-file` for reads, `app.features.fdata` for fragments, and `app.features.file-snapshots` and `app.rpc.commands.files-snapshot` for versions. For blob ownership see `mem:backend/file-data-storage`; for save acceptance see `mem:backend/file-data/save`.
|
||||
- Keep the common read path to one file-row read plus migration resolution. If a migration may need persistence, re-read with `FOR UPDATE` and recheck on the fresh row so migration cannot overwrite a concurrent save. Read-only migration is in memory. A data read cannot request `FOR SHARE`: upgrading competing shared locks to `FOR UPDATE` can deadlock. See the `get-file` docstring for the option contract and `mem:common/file-migrations` for migration IDs and ETags.
|
||||
- Fragment rows are immutable once written. Reattach unchanged pointers when persisting migrated data so unchanged pages keep their IDs. Do not materialize untouched pages just to wrap objects maps; a migration explicitly enabling `fdata/objects-map` must rewrite the pages instead. Use `fdata/realize` when the caller needs complete in-memory data.
|
||||
- Snapshots share fragment rows with the live file. `file-gc` marks a fragment only when neither the live file nor any unpurged snapshot references it. Snapshot creation holds the exclusive file-row lock through insertion to serialize with saves and GC. Snapshot reads resolve fragments by live file ID. The internal loader can still read marked fragments until `objects-gc` purges them; the public fragment RPC cannot.
|
||||
- A save captures its automatic snapshot before applying pending migrations. Preview migrates a version in memory using the live libraries without rewriting the historical payload; restoring a pre-migration version leaves the next read to migrate it. Manual snapshot creation and restore backup read with migration enabled. Keep applied migrations as an ordered set; for old snapshots without that set, preview and restore use different baselines and can disagree.
|
||||
- Snapshot metadata lives in `file_change`, with its payload in `file_data`. Use `label IS NOT NULL` to select versions, not the legacy payload or `kind` columns. Keep version quota predicates aligned with the partial index `file_change__user_snapshots__idx`. Revisions are temporary and exist only in `file_change`: they are born dated for deletion. Restore unmarks durable snapshots, never revisions, since no later pass assigns a revision a new deletion date. The audit `:file-change-id` points to the revision, not the snapshot; see `mem:audit-log`.
|
||||
7
.serena/memories/backend/file-data/save.md
Normal file
7
.serena/memories/backend/file-data/save.md
Normal file
@ -0,0 +1,7 @@
|
||||
# File save acceptance
|
||||
|
||||
- Start at `app.rpc.commands.files-update`; for client handling and retry see `mem:frontend/workspace-state-persistence-subtleties`, and for version and fragment lifetime see `mem:backend/file-data/reads-and-versions`.
|
||||
- Partial acceptance requires `:changes-with-metadata` with a `:commit-id` on every group. Flat changes or groups without IDs remain all-or-nothing. Try the entire batch first: a later commit may repair an earlier one. On a change failure, `apply-commits` searches for an accepted prefix and returns HTTP 200 with a `:rejected` suffix. `:preexisting-damage` means the data touched by the first rejected commit already failed validation on the base before that commit.
|
||||
- Persist and broadcast only the accepted prefix. A fully rejected save does not write a revision, change `revn`, or broadcast file changes. Database, I/O, interruption and missing-fragment errors fail the request rather than reject a commit. `app.http.errors` distinguishes transient failures the client can retry from permanent errors; do not classify every I/O error as transient.
|
||||
- Each `apply-prefix` attempt starts from the original file, resets pointer tracking to its baseline and clears media-reference state. Keep only the accepted attempt's tracked pointers and references. A pointer already marked modified can retain its ID across edits, so leaking failed tracking can persist the rejected version under an accepted ID.
|
||||
- Prefer the `fdata/with-*` wrappers for pointer loading and tracking. The save path toggles tracking within the same atom for validation and repair; do not replace that with a fresh tracking scope. Under schema validation, decode affected objects on the shared base before attempts so derived maps inherit the cache. Validation timings describe the first attempt; the bisection has its own retry timing. For controlled save failures, see `:debug-save-faults` in `app.rpc.commands.files-update`.
|
||||
@ -95,23 +95,6 @@
|
||||
|
||||
## File data persistence
|
||||
|
||||
- Blob reference ownership, offload and partition-aware storage lookups: `mem:backend/file-data-storage`.
|
||||
- Pointer-map fragments are persisted separately as type `fragment`, and only modified pointer maps are written. A pointer keeps its id while nothing changes; content (`assoc`/`without`) and metadata (`with-meta`) changes produce a fresh id, so a fragment row is never rewritten after it is written. Re-assoc with an identical value returns the same map in array and hash maps alike, so a save keeps the fragment id of every page it does not change.
|
||||
- `enable-objects-map` skips unloaded pointer pages: their fragment was already wrapped when it was written, and loading it only to wrap it again costs one page read per untouched page on every save. A page with a plain fragment is wrapped when it is first loaded or edited; a data migration that enables `fdata/objects-map` must rewrite the data itself.
|
||||
- Snapshots share fragment rows with the live file (they are stored with pointers, not materialized). `file-gc` marks every fragment referenced neither by the current main file nor by an unpurged snapshot; the file is read unrealized and unchanged pages keep their ids via reattach, so a pass over an unchanged file writes no new fragments.
|
||||
- A save attaches its automatic snapshot before applying pending file migrations: the snapshot keeps the pre-migration pointers, data and migration set, and restoring it leaves the next read to migrate the file. This also holds for files without the feature. The preview (`get-file-snapshot`) applies the pending migrations in memory with the live file's libraries and never persists them: the stored version keeps its data, the payload carries the snapshot's `:migrations` (an ordered set) and `fdata/objects-map` is realized for clients that do not declare it. The historical feature set is deliberately not checked against the enabled one: a version may predate a feature change. The window is narrow: the `get-file` RPC reads with `migrate?` on and its ETag hashes `available-migrations`, so a post-deploy read cannot be a 304 from the pre-deploy state and migrates before any save in the normal flow; the pre-migration snapshot only appears when the save is the first request to touch the file after the deploy (an open tab that saves without re-reading, or a non-UI writer). `create-file-snapshot` and the restore backup read with `migrate?` on, so those versions are stored already migrated.
|
||||
- `:migrations` is always a `d/ordered-set`: `file-migrations/resolve-applied-migrations` builds one, `fmg/migrate` re-wraps the union after applying, and `file-snapshots/decode-snapshot` converts the `file_change` pgarray (as a plain vector, `set/difference` and `contains?` would compare indexes instead of names). A snapshot with NULL `:migrations` and an old `:version` predates the `file_change.migrations` column (SQL migration 0140): the preview regenerates the set from the stored version and applies that full chain, while `restore!` uses a fixed 67 baseline, so preview and restore can disagree for very old snapshots.
|
||||
- The migration read path (`binfile.common/get-file*`) reads the `file` row once (`sql:get-file`, with its data columns; with the storage backend the blob lives in the object, not in the column) plus an explicit `resolve-applied-migrations`, because a row read does not resolve them. A read with no pending migration is completed by `attach-file-data` on that map: one row read and one migrations resolution. Only when a migration is pending is the row re-read under `FOR UPDATE` on the `file` row, where `need-migration?` is re-checked on the fresh map and the migrated file persisted (`binfile.common/migrate-file`); that re-read resolves the migrations again, and `migrate-file` once more after persisting, to return the applied set. The migration path holds two raw copies of the blob (the first read and the locked re-read) but a single decoded one: the alternative, a row-only probe before the read, avoided the first raw copy at the cost of an extra row read on every open, and was removed. `get-file` runs the read inside `db/tx-run!` (joining the caller's transaction when the cfg carries a connection) so the persist commits with the read; a read-only read (`:read-only?`) takes no lock and writes nothing, so it runs on a plain connection (`db/run!`) instead of opening a transaction of its own, and with a cfg that already carries a connection it still joins the caller's. It accepts a cfg map only and throws an `IllegalArgumentException` otherwise (`assert` is elided without `:backend-asserts`); a data read rejects `:lock-for-share?` (only row-only reads accept it), because the migration branch re-reads with `FOR UPDATE`, and a lock option needs a read-write transaction from the caller because PostgreSQL rejects row locks in a read-only transaction. A row-only read (`load-data?` false) resolves the applied migrations by default too (`:load-migrations?`), because the row can be completed later and the caller may need them; a caller that does not want them passes `:load-migrations? false`. Persisting is an optimization of the read (the read already returns migrated data): a row that changed between the first read and the locked read is not overwritten, and a pending migration discovered on the unlocked read is applied in memory only (the next read persists it under the lock). This was the only writer of the file row outside the lock protocol (save, library absorption, restore, `file-gc` and offload already take it); without it, a save that committed in between was overwritten by the stale map (lost content, `revn` moving back so the next save fails with `:revn-conflict`, and the object the save left as a frozen orphan). `migrate-file` captures `fdata/original-pointers` before realizing, reattaches unchanged positions after applying the migrations, and persists the reattached file; it returns that reattached map when it persists (the pages the migration does not change keep their pointers and fragment ids) and the realized map when it does not, so a read is plain only when the caller asks with `:realize?`, and a migration that adds `fdata/objects-map` skips the reattach so the pages get wrapped.
|
||||
- `fdata/load-pointer` reads rows that a previous `file-gc` pass marked on purpose (explicit `::db/remove-deleted false`): the fragment is only gone once `objects-gc` purges it. The `get-file-fragment` RPC keeps rejecting marked rows.
|
||||
- Bind the fragment loader through `fdata/with-pointers` (reads), `fdata/with-tracked-pointers` (writes with a loader) or `fdata/with-tracked` (writes with nothing to load yet, e.g. file creation), and `fdata/with-untracked` (validation passes that must track nothing) instead of hand-rolled `binding` forms. Two direct bindings remain on purpose: the fine-grained tracked toggles of `app.rpc.commands.files-update` (validation/repair turn tracking off, restore the existing atom and read it before repairing), and `binfile.common/encode-file` (a fresh tracked set inheriting the current one). Converge them only if atom-scoped macros (`with-tracking`, `with-inherited-tracking`) are added; today the extra indirection buys nothing.
|
||||
- Snapshot creation takes `FOR UPDATE` on the file row: both `create-file-snapshot` and the backup read of `restore-file-snapshot` hold it from the read to the insert, so they serialize with a `file-gc` pass (`FOR UPDATE ... SKIP LOCKED`) and with a concurrent save, and never pin fragments the pass is about to mark. The lock is exclusive and not `FOR SHARE` because the migration-on-read path may re-read the same row with `FOR UPDATE`: a shared lock that asks for the exclusive one deadlocks two concurrent readers (one creating a snapshot, the other saving, both seeing a pending migration). `get-file-snapshot` realizes the snapshot pointers with the live file id (fragment rows are keyed by file, not by snapshot).
|
||||
- `fdata/realize` combines pointer realization and object-map realization. Use it before operations that need complete in-memory file data instead of pointer placeholders.
|
||||
- A `file_data` row is one of three classes, told apart by `type`: `main` is the file's current state and carries `id = file_id`; `snapshot` is a point-in-time copy whose `id` is the one its `file_change` row shares; `fragment` is a piece of the pointer-map, referenced from the file's data.
|
||||
- Their lifecycles differ: `main` and `snapshot` live with the file (dated when it is deleted, undated when it is restored), while a `fragment` carries no date and is collected by `file_gc` once the file stops referencing it. Neither is a session buffer, so do not read a `fragment` as an ephemeral revision.
|
||||
- File snapshots (versions) keep their metadata row in `file_change` and their payload in `file_data` (`type = 'snapshot'`). With the `db` backend `file_change.data` stays NULL: that column is only read by the `legacy-db` backend (it is no longer written), plus the rows written before the 2025-07 file storage refactor.
|
||||
- Tell a snapshot apart by `label IS NOT NULL` (with `created_by` / `deleted_at` as needed), never by `file_change.data IS NOT NULL`: the label holds with every file data backend, and the payload column stopped meaning "this is a snapshot" when the payload moved out. Queries that identify versions must use the label. `0157-migrate-legacy-file-data` moved the labelled leftovers to `file_data` and deleted the unlabelled payload rows, so from 2.19 on the label is the only marker there is.
|
||||
- The version quota counts of `app.rpc.quotes` (`sql:get-snapshots-per-file`, `sql:get-snapshots-per-team`) are served by the partial index `file_change__user_snapshots__idx`, whose predicate mirrors their where clause; changing one without the other drops the index only scan and the count walks the whole table again.
|
||||
- Revisions live only in `file_change` and have no `file_data` counterpart. They are born already scheduled for deletion one hour later (`app.rpc.commands.files-update`) and the snapshot paths cannot reach one, because they resolve their row through a `label IS NOT NULL` filter. The revision row created by a save travels to the audit event in `:file-change-id` (a consumer reads it with `::db/remove-deleted false`, because the row is born with its `deleted_at` in the future); a save writes two rows, the revision (no `label`) and the snapshot of the previous state (with one).
|
||||
- A deletion date is assigned once and never moved: `restore-files` (`app.rpc.commands.files`) unmarks only durable history, which is `label IS NOT NULL` (the unlabelled rows that still carry a legacy payload are removed by `0157-migrate-legacy-file-data`, so restore leaves them dated), the `:file` method of `app.tasks.delete-object` dates only rows that have no date yet, and `objects-gc` collects only rows that carry one. Unmarking a revision leaves it invisible to `objects-gc` for ever, because nothing sets that date again.
|
||||
- Binfile v1/v3 import and the v3 export `get-file` step run inside one long transaction. They raise `idle_in_transaction_session_timeout` to 30 min (`app.binfile.common/transaction-idle-timeout-ms`) instead of disabling it, so a connection left idle while the ZIP is decoded or the file data is realized is bounded; `statement_timeout` stays at 300 s.
|
||||
- `update-file` with `:changes-with-metadata` groups that all carry `:commit-id` is partial: fast path applies and validates everything once; on a change failure it bisects the commits for the longest prefix that applies and validates (each attempt applies a prefix from the original data and runs referential integrity + file schema; ~log2 K attempts, none for a single commit, the first attempt's error reused), keeping that prefix (a commit that repairs an earlier one can keep both) and answering 200 with `:rejected {:commit-ids :failed-commit-id :error}`, plus `:preexisting-damage true` when the data the first rejected commit touches already fails validation without it (`preexisting-damage?`: one more referential + schema check of its pages/components on the base file, the accepted prefix or the original; the frontend then says the page data is damaged). Only accepted changes reach `file_change`, persistence and the msgbus; a fully rejected request writes and broadcasts nothing (revn unchanged). Flat `:changes` or groups without ids stay all-or-nothing. Before each attempt (`apply-prefix`, which returns `{:file :tracked :refs}` or the cause) `pmap/*tracked*` and the `cpc/*state*` atom are reset to their pre-attempt values (at the end `apply-commits` sets those of the kept prefix): a pointer map already `modified?` keeps its id when changed again, so the failed version would be persisted. DB/IO/interrupt errors and `:not-found` fragments (`change-failure?`) fail the whole request, never reject a commit. A rejection whose ex-info has no `:type` reports `:internal :unexpected-error`. `app.http.errors` answers 503 (`:server-error` + code) for transient SQLSTATEs (classes 08/53, 57P01–3, 40001, 40P01), `SQLTransientException`, `InterruptedException` and only the `IOException`s that pass on their own (`transient-io-exception?`: `SocketException`, `InterruptedIOException` incl. socket timeouts, `UnknownHostException`, `HttpTimeoutException`), which the client's save retries (and GETs retry by themselves); any other `IOException` (EOF from a corrupt blob, Jackson parse errors, missing files) stays 500 `:io-exception`, as do other SQL errors. With the `:debug-save-faults` flag, a `:set-plugin-data` file change in namespace `:penpot-debug` keyed `save-fault:<kind>` raises that fault in `apply-changes` (used by `debug.failNextSave`/`commitInvalidChange`). With a schema check running (hard schema validation without skip-validate, or soft) and 2+ commits, the touched pages' objects are decoded on the original file first (`decode-objects`; referential validation alone reads few objects, so no pre-decode then): objects-map caches decoded values per instance and a derived map copies the cache, so otherwise every attempt re-decodes the page (~260 ms at 10k shapes). Validation step timings (`with-validation-timing`, upstream `penpot_rpc_update_file_validation_timing` + the `update-file` debug log) come from the first attempt only (retries run with a cfg without metrics and timings); the whole bisection is one `retry` step sample, and the rejection log carries `:attempts`/`:elapsed`.
|
||||
- Read-time migrations, fragments, snapshots and restore: `mem:backend/file-data/reads-and-versions`.
|
||||
- Partial save acceptance and failure handling: `mem:backend/file-data/save`.
|
||||
- Blob references, offload and partition-aware storage lookups: `mem:backend/file-data-storage`.
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
|
||||
## Ordering and partial saves
|
||||
|
||||
- A flush moves only its own commits out of the buffer; edits arriving mid-flush remain. Batch by file and version and keep per-commit metadata through `update-file`; flattening the changes would remove the server's partial-rejection boundary. See `mem:backend/subtleties` for the server contract.
|
||||
- A flush moves only its own commits out of the buffer; edits arriving mid-flush remain. Batch by file and version and keep per-commit metadata through `update-file`; flattening the changes would remove the server's partial-rejection boundary. See `mem:backend/file-data/save` for the server contract.
|
||||
- A `:rejected` response can already have saved part of the batch. Roll back rejected groups before acknowledging the saved entry. Within each affected file revert from the first rejected or grouped commit onward, following any newly affected groups across files; unrelated groups in other files stay. If a reverted group was already partly saved, enqueue compensation, including for unloaded files. Undo pending edits before re-applying intervening peer changes and keeping valid local redo; absolute undo values applied in isolation can overwrite later peer edits.
|
||||
- Rebase is not a normal commit, so dependent consumers cannot rely on commit watchers. Notify rollback only once the rebased or reloaded data is in state; comments persist through their own RPC, library sync needs a landed save before marking success, and thumbnails must not upload stale pre-rollback output. Invalidate stale path or text editor drafts before they can commit again on exit. Follow `apply-rollback-plan` and `notify-rolled-back` for these entry points.
|
||||
- A save whose reply mentions an unseen peer or repair revision waits for its WebSocket change before settlement; do not apply repair changes from the HTTP reply or resend a waiting head. If the wait expires, settle and reload. Preserve the server order so the peer change sits below the rebased local edits.
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user