From a474de4abf44c4a1109e04ec1fac2ed0152f2179 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Thu, 26 Nov 2026 09:22:28 +0100 Subject: [PATCH] :bug: Fix the pointer-map read and write contracts (#13055) * :bug: Fix the pointer-map read and write contracts fdata/objects-map is consolidated, so the server stops negotiating it: get-file and get-file-snapshot no longer convert it for a client that does not declare it. Converting it rewrote the page map, and doing that on a page that is still a pointer produced a fresh fragment id with no row behind it (a read never persists), so the client got a 404 for every page. The save path now reattaches unchanged pages after migrating, like the read path: a save that triggers a pending migration keeps the fragment ids of the pages the migration does not change. A pointer carries its file id in its metadata and the fragment loader resolves with it, so it no longer depends on a per-file binding. That makes libraries lazy (they were materialized in full on first access), removes the file-id argument from the loader macros and the extra arities of realize-pointers, and lets the snapshot preview resolve without the live file id. A pointer without the field raises instead of falling back: the feature has never been enabled in production. Also use with-untracked in the validation and repair sites, cover enable-objects-map with the encode-file tracking binding, document the fragment contract, and delete two dynamic vars that have had no readers since 2024-01-17. AI-assisted-by: deepseek-v4.1-flash * :bug: Fix the pointer-map review findings The snapshot preview no longer materializes the objects map when it has to apply a pending migration: it realizes the pointers only, so an old version and an already-migrated one return the same shape. The preview stays read-only. `wrap` now lets the bound metadata win, so the `:file-id` of the file that writes the fragment row is authoritative, and the ns docstring records that pointer metadata is changed with `vary-meta` (it merges over the current map and keeps the file id) rather than `with-meta`. Also bind the fragment loader in `srepl/main/validate-file-schema`, remove a leftover argument from a test, and add the two missing tests: the public RPC rejects a marked fragment while the internal loader reads it, and the id plus the metadata survive the fressian and transit round-trip. AI-assisted-by: deepseek-v4.1-flash * :bug: Avoid orphan fragments during save migrations Skip pointer tracking only while pending migrations run. Reattach unchanged pointers after tracking resumes; verify stored fragment references in tests. AI-assisted-by: gpt-6-luna * :bug: Prevent save migration tests from masking failures Use one non-migrating file read for post-save IDs and migration state, so a later read cannot mask a missing migration record. AI-assisted-by: gpt-6-luna --- .serena/memories/backend/subtleties.md | 17 ++- backend/src/app/binfile/common.clj | 99 ++++++------ backend/src/app/features/fdata.clj | 61 +++++--- backend/src/app/features/file_snapshots.clj | 4 +- backend/src/app/http/debug.clj | 10 +- backend/src/app/rpc/commands/comments.clj | 2 +- backend/src/app/rpc/commands/files.clj | 34 +++-- .../src/app/rpc/commands/files_snapshot.clj | 39 ++--- .../src/app/rpc/commands/files_thumbnails.clj | 2 +- backend/src/app/rpc/commands/files_update.clj | 44 +++--- backend/src/app/srepl/helpers.clj | 12 +- backend/src/app/srepl/main.clj | 6 +- backend/src/app/tasks/file_gc.clj | 10 +- backend/src/app/util/pointer_map.clj | 31 +++- .../file_pointer_snapshot_test.clj | 143 +++++++++++++++--- .../backend_tests/offload_file_data_test.clj | 17 ++- .../backend_tests/rpc_file_snapshot_test.clj | 34 ++--- backend/test/backend_tests/rpc_file_test.clj | 99 ++++++++++++ .../backend_tests/util_pointer_map_test.clj | 82 ++++++++-- common/src/app/common/features.cljc | 3 - 20 files changed, 542 insertions(+), 207 deletions(-) diff --git a/.serena/memories/backend/subtleties.md b/.serena/memories/backend/subtleties.md index 09b38b010b..cc644a9562 100644 --- a/.serena/memories/backend/subtleties.md +++ b/.serena/memories/backend/subtleties.md @@ -97,15 +97,18 @@ - File data backends for writing are `db` and `storage`; `legacy-db` is a read-only alias for old payloads. The storage backend keeps encoded file data in storage bucket `file-data`; the DB row stores nil data and points at the object with the `storage_object_id` column (FK `NO ACTION DEFERRABLE`). - `fdata/upsert!` touches the storage object the persisted row pointed at before replacing it; the pointer travels in the params (`file->file-data-params` from the read file map, `nil` for a new row, the row for the offload) and the params of `update-file!` cannot override it. `binfile.common/update-file!` merges the read file map with the fields to change, so the pointer survives; `insert-file!` drops it because an INSERT never replaces a persisted object. The column is the only source of truth and the metadata no longer carries `storage-ref-id` (the migration removes it from the backfilled rows and the write path never stores it); the release is a coordinated restart when the storage backend is in use (the previous code cannot read the new rows), while the default `db` backend reads the same data column and tolerates a rolling deploy. Responses built from a file map go through `bfc/file->response`, which strips the pointer and a residual `storage-ref-id` from the metadata. -- 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. +- 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. The pointer metadata carries the `:file-id` of its file (bound by `enable-pointer-map` through `pmap/*metadata*`): fragment rows are keyed by `(file_id, id)` and `PointerMap.load!` hands both to the loader, so a pointer resolves itself instead of relying on a per-file binding. There is no fallback: a pointer without `:file-id` raises `:pointer-without-file-id` (the feature has never been enabled in production, so no old pointers exist). +- `fdata/objects-map` is not negotiated with the client: `get-file` and `get-file-snapshot` never convert it (the flag is in `flags/default` and every frontend decodes `penpot/objects-map/v2`). Converting it rewrites the page map, and on a page that is still a pointer that produces a fresh fragment id with no row behind it (a read never persists), so the client would get a 404 for every page. The client's `:features` is the *enabled* set (`features/get-enabled-features`), not the supported one, so the server cannot tell "does not support" from "not enabled"; only `fdata/pointer-map` is still negotiated, and its fallback (materialize) is safe. +- `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. `encode-file` wraps objects and pointers inside one tracked set that inherits the current one, so a pointer created by the objects wrap is persisted in the same pass. - 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. +- `file-gc` is a monolithic pass on purpose and will be split into smaller collectors in future work: do not optimize it as a side effect of another change. Its liveness scan decodes every unpurged snapshot and each snapshot row loads its own pointer instances, so a fragment shared by N snapshots is read N times (assumed); the live walk reads each fragment once and `reattach-unchanged` keeps the ids. The pass also holds the whole file decoded in heap, because the cleaner rewrites every page map before reattaching it. +- 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 the pages keep `fdata/objects-map` as is (not negotiated, see above; the migration branch realizes the pointers only, never the objects, so both branches return the same shape). 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). +- 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. The save path (`files-update/update-file-data!`) migrates too, because `update-file` reads with `:decode? false` and `get-file*` only migrates when decoding: it captures `original-pointers` before `fmg/migrate-file` and applies `reattach-unchanged` after it, before the changes, so a save that migrates also keeps the fragment id of every page the migration does not change. +- The save migration path (`files-update/update-file-data!`) captures original pointers and attaches the automatic snapshot before applying pending migrations. It binds `fdata/with-untracked` only around `fmg/migrate-file`, then reattaches unchanged pointers after tracking is restored. This prevents discarded intermediate pointers from being persisted as orphan fragments. Do not extend the untracked binding to change application or encoding: `encode-file` wraps and tracks the final pointers that survive the migration and save. +- `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. Maintenance operations (delete, `absorb-library`, restore) need pointers that are marked but not purged yet. The `get-file-fragment` RPC keeps rejecting marked rows: that is the public contract, by design. Do not align the two. +- Bind the fragment loader through `fdata/with-pointers` (reads) or `fdata/with-tracked-pointers` (writes with a loader); neither takes a file id, because the pointer carries its own. Use `fdata/with-tracked` for writes with nothing to load yet (e.g. file creation) and `fdata/with-untracked` for validation passes that must track nothing (`app.rpc.commands.files-update` uses it in its five validation/repair sites). The one direct binding left is `binfile.common/encode-file` (a fresh tracked set inheriting the current one). Any consumer that walks a lazy library needs a loader bound: `get-resolved-file-libraries` returns each library unrealized, with its pages still as pointers. +- 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 (each pointer resolves with its own `:file-id`, so no live file id is needed). - `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. diff --git a/backend/src/app/binfile/common.clj b/backend/src/app/binfile/common.clj index c81de59c90..f599640190 100644 --- a/backend/src/app/binfile/common.clj +++ b/backend/src/app/binfile/common.clj @@ -241,8 +241,8 @@ persists again touches the current object. Without `persist-after-migration?` the realized map is returned, which is what a read-only context can do. `get-file*` realizes the result when the caller asks for it." - [cfg {:keys [id] :as file} {:keys [persist-after-migration?]}] - (fdata/with-tracked-pointers cfg id + [cfg file {:keys [persist-after-migration?]}] + (fdata/with-tracked-pointers cfg (let [libs (delay (get-resolved-file-libraries cfg file)) ;; Capture the pointer layout before realizing: the migration ;; runs on plain data, and unchanged positions must keep their @@ -776,9 +776,9 @@ (if-let [library (get-file cfg library-id :include-deleted? true)] ;; The library is read without `:realize?`, so its ;; `:components` may be a pointer map. Bind the - ;; library's own loader: the absorb walks the - ;; components and would raise without one. - (cond-> (fdata/with-pointers cfg library-id + ;; fragment loader: the absorb walks the components + ;; and would raise without one. + (cond-> (fdata/with-pointers cfg (ctf/absorb-assets data (:data library))) (= library-id (cfo/get-tokens-source data)) (cfo/absorb-tokens-lib (:data library))) @@ -813,46 +813,55 @@ (defn process-file [cfg {:keys [id] :as file}] - (let [libs (delay (get-resolved-file-libraries cfg file))] - (-> file - (update :data (fn [fdata] - (-> fdata - (assoc :id id) - (dissoc :recent-colors)))) - (update :data (fn [fdata] - (-> fdata - (update :pages-index relink-shapes) - (update :components relink-shapes) - (update :media relink-media) - (update :colors relink-colors) - (d/without-nils)))) - (fmg/migrate-file libs) + ;; The libraries are lazy now; a migration that walks them needs a + ;; fragment loader bound, and the pointers resolve with their own file id. + (fdata/with-pointers cfg + (let [libs (delay (get-resolved-file-libraries cfg file))] + (-> file + (update :data (fn [fdata] + (-> fdata + (assoc :id id) + (dissoc :recent-colors)))) + (update :data (fn [fdata] + (-> fdata + (update :pages-index relink-shapes) + (update :components relink-shapes) + (update :media relink-media) + (update :colors relink-colors) + (d/without-nils)))) + (fmg/migrate-file libs) - ;; NOTE: this is necessary because when we just creating a new - ;; file from imported artifact or cloned file there are no - ;; migrations registered on the database, so we need to persist - ;; all of them, not only the applied - (vary-meta dissoc ::fmg/migrated)))) + ;; NOTE: this is necessary because when we just creating a new + ;; file from imported artifact or cloned file there are no + ;; migrations registered on the database, so we need to persist + ;; all of them, not only the applied + (vary-meta dissoc ::fmg/migrated))))) (defn- encode-file [cfg {:keys [id features] :as file}] - (let [file (if (and (contains? features "fdata/objects-map") - (:data file)) - (fdata/enable-objects-map file) - file) + ;; One tracked set for both steps. Wrapping objects can produce a pointer + ;; (a loaded page whose fragment holds plain objects, i.e. a fragment + ;; written before the feature was enabled) and it must be persisted in the + ;; same pass that wraps the pages, not rely on `enable-pointer-map` + ;; tracking it afterwards. + (binding [pmap/*tracked* (pmap/create-tracked :inherit true)] + (let [file (if (and (contains? features "fdata/objects-map") + (:data file)) + (fdata/enable-objects-map file) + file) - file (if (and (contains? features "fdata/pointer-map") - (:data file)) + file (if (and (contains? features "fdata/pointer-map") + (:data file)) + (fdata/enable-pointer-map file) + file)] - (binding [pmap/*tracked* (pmap/create-tracked :inherit true)] - (let [file (fdata/enable-pointer-map file)] - (fdata/persist-pointers! cfg id) - file)) - file)] + (when (and (contains? features "fdata/pointer-map") + (:data file)) + (fdata/persist-pointers! cfg id)) - (-> file - (d/update-when :features into-array) - (d/update-when :data blob/encode)))) + (-> file + (d/update-when :features into-array) + (d/update-when :data blob/encode))))) (defn- file->params [file] @@ -1056,19 +1065,17 @@ all this libraries at the same time on processing file validation or file migration. - This still requires at least one library at time to be loaded while - access to it is performed, but it improves considerable not having - the need of loading all the libraries at the same time." + A library is read lazy: its pages stay as pointers until something + walks them. The pointer carries the file id of its own fragments in + the metadata, so it resolves itself; the consumer must have a + fragment loader bound (`fdata/with-pointers`) while it walks the + data." [{:keys [::db/conn] :as cfg} {:keys [id] :as file}] (let [library-ids (->> (get-file-libraries conn (:id file)) (map :id) (cons (:id file))) - ;; Fragment rows are file-local and callers bind the loader of - ;; the file they work on, so each library realizes its pointers - ;; here, with its own id, before anything walks its data. load-fn (fn [library-id] - (->> (get-file cfg library-id :migrate? false) - (fdata/realize-pointers cfg)))] + (get-file cfg library-id :migrate? false))] (weak/loadable-weak-value-map library-ids load-fn {id file}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; diff --git a/backend/src/app/features/fdata.clj b/backend/src/app/features/fdata.clj index 231c879bb3..c89b93049d 100644 --- a/backend/src/app/features/fdata.clj +++ b/backend/src/app/features/fdata.clj @@ -289,7 +289,15 @@ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn load-pointer - "A database loader pointer helper" + "Load the content of a fragment row. + + Reads rows that a previous `file-gc` pass marked as deleted on purpose: + the mark is a hypothesis about liveness that maintenance operations + refute (a delete, an `absorb-library` or a snapshot restore may still + need a pointer that is marked but not purged yet; only `objects-gc` + removes the row). The public contract is the opposite one: the + `get-file-fragment` RPC serves unmarked rows only, by design. Do not + align the two." [cfg file-id id] ;; Keep the include-marked behavior explicit: `db/get*` only filters ;; rows by `deleted_at` when that column is selected, and a fragment a @@ -332,11 +340,12 @@ :data content}))))) (defmacro with-pointers - "Bind the fragment loader for `file-id` around `body`. All pointer - derefs must happen inside the body; a pointer derefed outside of it - raises because there is no loader bound." - [cfg file-id & body] - `(binding [pmap/*load-fn* (partial load-pointer ~cfg ~file-id)] + "Bind the fragment loader around `body`. All pointer derefs must happen + inside the body; a pointer derefed outside of it raises because there is + no loader bound. The loader resolves each pointer with the file id its + metadata carries, so it is not scoped to one file." + [cfg & body] + `(binding [pmap/*load-fn* (partial load-pointer ~cfg)] ~@body)) (defmacro with-tracked @@ -358,11 +367,11 @@ ~@body)) (defmacro with-tracked-pointers - "Bind a fresh tracked set plus the fragment loader for `file-id` - around `body`. For write paths that create or modify pointers." - [cfg file-id & body] + "Bind a fresh tracked set plus the fragment loader around `body`. For + write paths that create or modify pointers." + [cfg & body] `(binding [pmap/*tracked* (pmap/create-tracked) - pmap/*load-fn* (partial load-pointer ~cfg ~file-id)] + pmap/*load-fn* (partial load-pointer ~cfg)] ~@body)) (defn process-pointers @@ -379,14 +388,11 @@ (defn realize-pointers "Process a file and remove all instances of pointers realizing them to - plain data. Accepts a file map (arity 1) or raw file data with its - file id (arity 2): a snapshot map carries the snapshot id, so always - pass the live file id explicitly." - ([cfg {:keys [id] :as file}] - (update file :data #(realize-pointers cfg id %))) - ([cfg file-id data] - (with-pointers cfg file-id - (process-pointers data deref)))) + plain data. Every pointer resolves its own fragment with the file id in + its metadata, so no file id is needed here and a snapshot map resolves + exactly like the live file." + [cfg {:keys [data] :as file}] + (assoc file :data (with-pointers cfg (process-pointers data deref)))) (defn get-used-pointer-ids "Given a file data map, return all pointer ids used in the data. @@ -400,14 +406,19 @@ (map pmap/get-id))))) (defn enable-pointer-map - "Enable the fdata/pointer-map feature on the file." + "Enable the fdata/pointer-map feature on the file. + + Every pointer created here carries the file id in its metadata, which + is what lets the loader resolve a fragment without knowing which file + it is working on." [file & _opts] - (-> file - (update :data (fn [fdata] - (-> fdata - (update :pages-index d/update-vals pmap/wrap) - (d/update-when :components pmap/wrap)))) - (update :features conj "fdata/pointer-map"))) + (binding [pmap/*metadata* (assoc pmap/*metadata* :file-id (:id file))] + (-> file + (update :data (fn [fdata] + (-> fdata + (update :pages-index d/update-vals pmap/wrap) + (d/update-when :components pmap/wrap)))) + (update :features conj "fdata/pointer-map")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; GENERAL PURPOSE HELPERS diff --git a/backend/src/app/features/file_snapshots.clj b/backend/src/app/features/file_snapshots.clj index 4b1d2de942..ee74e2f49a 100644 --- a/backend/src/app/features/file_snapshots.clj +++ b/backend/src/app/features/file_snapshots.clj @@ -416,7 +416,7 @@ ;; loader stays bound while persisting so any page the encode ;; path does load keeps working (`enable-objects-map` skips the ;; unloaded ones). - (fdata/with-pointers cfg file-id + (fdata/with-pointers cfg (bfc/update-file! cfg file ::bfc/reset-migrations? true)) ;; FIXME: this should be separated functions, we should not have @@ -501,6 +501,6 @@ (map (partial fdata/decode-file-data cfg)) xform)] - (fdata/with-pointers cfg file-id + (fdata/with-pointers cfg (->> (db/plan conn [sql:get-snapshots file-id] {:fetch-size 1}) (transduce xform f init))))) diff --git a/backend/src/app/http/debug.clj b/backend/src/app/http/debug.clj index 768e358176..84f10aac0b 100644 --- a/backend/src/app/http/debug.clj +++ b/backend/src/app/http/debug.clj @@ -24,6 +24,7 @@ [app.common.uuid :as uuid] [app.config :as cf] [app.db :as db] + [app.features.fdata :as fdata] [app.features.file-migrations :as feat.fmig] [app.health :as health] [app.http.session :as session] @@ -786,13 +787,14 @@ (db/tx-run! (assoc cfg ::db/rollback true) (fn [cfg] ;; Validation walks every page and component, so the - ;; file is read realized; the library map is built - ;; from the file (not its id) and its own loader - ;; resolves each library's pointers. + ;; file is read realized. The libraries stay lazy; the + ;; loader is bound while validating because walking a + ;; library derefs its pointers. (let [file (bfc/get-file cfg file-id :realize? true) libs (bfc/get-resolved-file-libraries cfg file)] (if file - (let [errors (cfv/validate-file file libs)] + (let [errors (fdata/with-pointers cfg + (cfv/validate-file file libs))] {::yres/status 200 ::yres/headers {"content-type" "text/plain"} ::yres/body (if (empty? errors) diff --git a/backend/src/app/rpc/commands/comments.clj b/backend/src/app/rpc/commands/comments.clj index 09e24ad8ff..326edd373a 100644 --- a/backend/src/app/rpc/commands/comments.clj +++ b/backend/src/app/rpc/commands/comments.clj @@ -186,7 +186,7 @@ (defn- get-file "A specialized version of get-file for comments module." [cfg file-id page-id] - (feat.fdata/with-pointers cfg file-id + (feat.fdata/with-pointers cfg (let [file (bfc/get-file cfg file-id) data (get file :data)] (-> file diff --git a/backend/src/app/rpc/commands/files.clj b/backend/src/app/rpc/commands/files.clj index 80f22bf07f..1a577c7193 100644 --- a/backend/src/app/rpc/commands/files.clj +++ b/backend/src/app/rpc/commands/files.clj @@ -215,13 +215,12 @@ (feat.fdata/realize-pointers cfg file) file) - ;; This operation is needed for backward comapatibility with - ;; frontends that does not support objects-map mechanism; this - ;; just converts all objects map instaces to plain maps - (if (and (contains? (:features file) "fdata/objects-map") - (not (contains? (:features params) "fdata/objects-map"))) - (feat.fdata/realize-objects cfg file) - file) + ;; `fdata/objects-map` is not negotiated: the feature is + ;; consolidated and every client decodes `ObjectsMap` through its + ;; transit handler. Converting it here rewrites the page map, and + ;; doing that on a page that is still a pointer produces a fresh + ;; fragment id with no row behind it (a read never persists), so + ;; the client would get a 404 for every page. ;; The storage pointer is internal bookkeeping: it never leaves the ;; backend in a response. @@ -243,6 +242,17 @@ [:share-id {:optional true} ::sm/uuid]]) (defn- get-file-fragment + "Read one fragment of a file for the client that holds its pointer. + + This is the public contract for fragments and it serves unmarked rows + only: a row that `file-gc` marked as deleted is rejected with + `:not-found`, even though the internal loader (`fdata/load-pointer`) + still reads it until `objects-gc` purges it. The asymmetry is + deliberate. Marking is computed from the current main data and every + unpurged snapshot, so a client that read the current revision never + holds a pointer to a marked row; the internal loader tolerates them + because maintenance operations (delete, absorb, restore) need pointers + that are marked but not purged yet." [cfg file-id fragment-id] ;; Resolve through the file data backend: a fragment can live on cold ;; storage, and reading its row directly would hand `nil` to `blob/decode`. @@ -446,7 +456,7 @@ (cfeat/check-client-features! (:features params)) (cfeat/check-file-features! (:features file))) - page (feat.fdata/with-pointers cfg file-id + page (feat.fdata/with-pointers cfg (let [page (dm/get-in file [:data :pages-index resolved-page-id])] (if (pmap/pointer-map? page) (deref page) @@ -577,7 +587,7 @@ calculate-from-db (fn [] (let [file (bfc/get-file cfg id) - result (feat.fdata/with-pointers cfg id + result (feat.fdata/with-pointers cfg (calculate-library-summary file))] ;; The storage pointer is internal bookkeeping: this summary is an ;; RPC response and must not expose it. The applied migrations go @@ -709,7 +719,7 @@ (defn- get-file-stats [{:keys [::db/conn] :as cfg} file-id] (let [file (bfc/get-file cfg file-id) - base (feat.fdata/with-pointers cfg file-id + base (feat.fdata/with-pointers cfg (cfs/calc-file-stats (:data file))) lib-cnt (get-file-stats-library-counts conn file-id)] (-> base @@ -798,7 +808,7 @@ (bfc/check-file-exists cfg file-id) (check-read-permissions! cfg profile-id file-id) (let [{:keys [data]} (bfc/get-file cfg file-id)] - (feat.fdata/with-pointers cfg file-id + (feat.fdata/with-pointers cfg (when-let [tokens-lib (cfo/get-tokens-lib data)] (ctob/export-dtcg-json tokens-lib (cfo/get-tokens-status data)))))) @@ -1017,7 +1027,7 @@ (assert (db/connection-map? cfg) "expected cfg with valid connection") - (feat.fdata/with-tracked-pointers cfg file-id + (feat.fdata/with-tracked-pointers cfg (let [file (-> (bfc/get-file cfg file-id :include-deleted? true :lock-for-update? true) diff --git a/backend/src/app/rpc/commands/files_snapshot.clj b/backend/src/app/rpc/commands/files_snapshot.clj index d56691540f..af1287154f 100644 --- a/backend/src/app/rpc/commands/files_snapshot.clj +++ b/backend/src/app/rpc/commands/files_snapshot.clj @@ -56,7 +56,7 @@ ::sm/params schema:get-file-snapshot ::sm/result files/schema:file-with-permissions ::db/transaction true} - [cfg {:keys [::rpc/profile-id file-id id features] :as params}] + [cfg {:keys [::rpc/profile-id file-id id]}] (let [perms (perms/get-file-read-permissions cfg profile-id file-id)] (files/check-read-permissions! perms) (let [snapshot (fsnap/get-snapshot cfg file-id id)] @@ -70,34 +70,35 @@ ;; the snapshot data so the client receives the same shape as a ;; normal get-file response but with historical page/object content. ;; Snapshots may hold pointer-mapped pages shared with the live - ;; file, so materialize them here: the preview UI applies the + ;; file, so the pointers are materialized: the preview UI applies the ;; response straight into state and cannot resolve pointers. - ;; NOTE: the loader binds the live file-id, not the snapshot id. + ;; NOTE: pointers resolve with the file id in their own metadata, so a + ;; snapshot needs no live file id to materialize. + ;; + ;; `fdata/objects-map` is not negotiated here either (see + ;; `get-file`): the feature is consolidated and the client always + ;; decodes `ObjectsMap`, so the pages keep it in both branches. ;; ;; A snapshot taken while a migration was pending stores the old ;; format. Apply the pending migrations in memory, the same pure ;; step a normal read runs, and never persist them: the stored ;; version keeps its data and restoring it re-migrates on the - ;; next read. `decode-snapshot` hands an ordered set, which is + ;; next read. Only the pointers are materialized for the migration; + ;; realizing the objects too would give this branch a different + ;; shape than an already-migrated snapshot. + ;; + ;; `decode-snapshot` hands an ordered set, which is ;; what `need-migration?`/`migrate` require; a stored NULL is ;; regenerated from the snapshot's version. (let [base-file (bfc/get-file cfg file-id :load-data? false) snapshot (assoc snapshot :id file-id) - file (if (fmg/need-migration? snapshot) - (let [file (fdata/realize cfg snapshot)] - (fmg/migrate-file - file - (delay (bfc/get-resolved-file-libraries cfg file)))) - (update snapshot :data - #(fdata/realize-pointers cfg file-id %))) - ;; Works like in `get-file`: a client that does not declare - ;; `fdata/objects-map` gets plain objects. The historical - ;; feature set is deliberately not checked against the - ;; enabled one: a version may predate a feature change. - file (if (and (contains? (:features file) "fdata/objects-map") - (not (contains? features "fdata/objects-map"))) - (fdata/realize-objects cfg file) - file)] + file (fdata/with-pointers cfg + (if (fmg/need-migration? snapshot) + (let [file (fdata/realize-pointers cfg snapshot)] + (fmg/migrate-file + file + (delay (bfc/get-resolved-file-libraries cfg file)))) + (fdata/realize-pointers cfg snapshot)))] (-> base-file (assoc :data (:data file)) (assoc :version (:version file)) diff --git a/backend/src/app/rpc/commands/files_thumbnails.clj b/backend/src/app/rpc/commands/files_thumbnails.clj index 53245d3f7d..e999f05eb3 100644 --- a/backend/src/app/rpc/commands/files_thumbnails.clj +++ b/backend/src/app/rpc/commands/files_thumbnails.clj @@ -167,7 +167,7 @@ objects)))] - (fdata/with-pointers cfg id + (fdata/with-pointers cfg (let [frame (get-thumbnail-frame data) frame-id (:id frame) page-id (or (:page-id frame) diff --git a/backend/src/app/rpc/commands/files_update.clj b/backend/src/app/rpc/commands/files_update.clj index 8dcae7ab7d..e12f63c1e6 100644 --- a/backend/src/app/rpc/commands/files_update.clj +++ b/backend/src/app/rpc/commands/files_update.clj @@ -309,7 +309,7 @@ [{:keys [::db/conn ::timestamp] :as cfg} {:keys [profile-id file team features changes commits session-id skip-validate] :as params}] - (fdata/with-tracked-pointers cfg (:id file) + (fdata/with-tracked-pointers cfg (let [file (assoc file :features (-> features @@ -533,26 +533,34 @@ take-snapshot? (take-snapshot? file) + ;; Captured before anything mutates the data so pages that remain + ;; value-equal can keep their original fragment ids. Nothing is + ;; loaded here. + original + (fdata/original-pointers (:data file)) + ;; Attach the snapshot before migrating: a migration can rebuild a ;; page and give its PointerMap a new id with `modified?` set, and a ;; snapshot taken after that would keep the very pointer the save ;; then rewrites, ending up with post-save content. - ;; - ;; For avoid unnecesary overhead of creating multiple - ;; pointers and handly internally with objects map in their - ;; worst case (when probably all shapes and all pointers - ;; will be readed in any case), we just realize/resolve them - ;; before applying the migration to the file file (cond-> file - ;; need-migration? - ;; (->> (fdata/realize cfg)) - take-snapshot? - (->> (attach-snapshot)) + (->> (attach-snapshot))) - need-migration? - (fmg/migrate-file libs))] + ;; A migration may create modified pointers that reattach-unchanged + ;; discards. Do not track those intermediate pointers; encode-file + ;; tracks the pointers that remain in the final data. + file + (if need-migration? + (fdata/with-untracked + (fmg/migrate-file file libs)) + file) + + file + (if need-migration? + (fdata/reattach-unchanged original file) + file)] (apply update-fn cfg file args))) @@ -595,7 +603,7 @@ "Validates the entities `changes` affect and the schema of the data they modify." [cfg file libs changes skip-validate] - (binding [pmap/*tracked* nil] + (fdata/with-untracked (when (contains? cf/flags :soft-file-validation) (with-validation-timing cfg :soft-validate-affected-ms "soft-validate-affected" (soft-validate-file! file libs changes))) @@ -695,7 +703,7 @@ `changes` touch, before they are applied." [file libs changes skip-validate] (try - (binding [pmap/*tracked* nil] + (fdata/with-untracked (when (and (contains? cf/flags :file-validation) (not skip-validate)) (val/validate-file-affected! file libs changes)) @@ -808,7 +816,7 @@ (let [libs (or libs {})] (try (let [pre-errors - (binding [pmap/*tracked* nil] + (fdata/with-untracked (val/validate-file-affected original libs changes))] (when (empty? pre-errors) @@ -821,7 +829,7 @@ (cfr/repair-file-until-valid original libs (fn [file applied] - (binding [pmap/*tracked* nil] + (fdata/with-untracked (val/validate-file-affected file libs (into applied changes)))) :initial-errors pre-errors)) @@ -840,7 +848,7 @@ (d/without-nils))))) scope (into repair-changes changes)] - (binding [pmap/*tracked* nil] + (fdata/with-untracked (val/validate-file-affected! repaired libs scope) (when (contains? cf/flags :file-schema-validation) diff --git a/backend/src/app/srepl/helpers.clj b/backend/src/app/srepl/helpers.clj index 5f839081b5..b1a5a2a4d9 100644 --- a/backend/src/app/srepl/helpers.clj +++ b/backend/src/app/srepl/helpers.clj @@ -14,6 +14,7 @@ [app.common.files.validate :as cfv] [app.common.time :as ct] [app.db :as db] + [app.features.fdata :as fdata] [app.features.file-snapshots :as fsnap] [app.system :as sys])) @@ -162,10 +163,13 @@ libs (when with-libraries? (bfc/get-resolved-file-libraries system file)) - file' (when file - (if with-libraries? - (update-fn file libs opts) - (update-fn file opts)))] + ;; The libraries stay lazy, so the loader must be bound while the + ;; transformation walks them. + file' (fdata/with-pointers system + (when file + (if with-libraries? + (update-fn file libs opts) + (update-fn file opts))))] (when (and (some? file') (or (fmg/migrated? file) diff --git a/backend/src/app/srepl/main.clj b/backend/src/app/srepl/main.clj index 337f4ef3aa..3b72f53618 100644 --- a/backend/src/app/srepl/main.clj +++ b/backend/src/app/srepl/main.clj @@ -549,7 +549,8 @@ (fn [system] (let [file (bfc/get-file system file-id) libs (bfc/get-resolved-file-libraries system file)] - (cfv/validate-file file libs)))))) + (fdata/with-pointers system + (cfv/validate-file file libs))))))) (defn validate-file-schema "Validate structure, referencial integrity and semantic coherence of @@ -560,7 +561,8 @@ (fn [system] (try (let [file (bfc/get-file system file-id)] - (cfv/validate-file-schema! file) + (fdata/with-pointers system + (cfv/validate-file-schema! file)) (println "OK")) (catch Exception cause (if-let [explain (-> cause ex-data ::sm/explain)] diff --git a/backend/src/app/tasks/file_gc.clj b/backend/src/app/tasks/file_gc.clj index d168bda095..206ea335ad 100644 --- a/backend/src/app/tasks/file_gc.clj +++ b/backend/src/app/tasks/file_gc.clj @@ -267,9 +267,13 @@ (if-let [file (get-file cfg props)] ;; Every fragment load goes through `with-pointers`. Each pointer ;; instance loads its content once (`loaded?`), and the replacement - ;; instances `clean-file` creates already carry their content, so - ;; the pass reads each fragment once without a separate cache. - (feat.fdata/with-pointers cfg file-id + ;; instances `clean-file` creates already carry their content, so the + ;; live file reads each fragment once with no separate cache. The + ;; snapshot scan is not the same: each row decodes its own pointer + ;; instances, so a fragment shared by N snapshots is read N times. + ;; That repeated read is assumed on purpose; this pass is monolithic + ;; and will be split into smaller collectors before optimizing it. + (feat.fdata/with-pointers cfg (let [liveness (collect-snapshot-liveness cfg file-id) original (feat.fdata/original-pointers (:data file)) file (bfl/clean-file file) diff --git a/backend/src/app/util/pointer_map.clj b/backend/src/app/util/pointer_map.clj index 75effbee5a..7c4de22e80 100644 --- a/backend/src/app/util/pointer_map.clj +++ b/backend/src/app/util/pointer_map.clj @@ -22,20 +22,32 @@ be regenerated, and is resposability of the hashmap user to properly garbage collect the unused/unreferenced objects. + The pointers created by `app.features.fdata/enable-pointer-map` carry + the `:file-id` of the file they belong to in their metadata: fragment + rows are keyed by `(file_id, id)`, so a pointer without it cannot be + resolved, and the loader takes both from the pointer instead of + relying on a per-file binding. Change pointer metadata with + `vary-meta`, which merges over the current map and keeps the file id; + `with-meta` replaces the whole metadata and drops it. + For properly work it requires some dynamic vars binded to appropriate values: - *load-fn*: when you instantatiate an object by ID, on first access to the contents of the hash-map will try to load the real data by - calling the function binded to that dynamic var. + calling the function binded to that dynamic var with the pointer's + `:file-id` and its id. - *tracked*: when you instantiate an object or modify it, it is updated on the atom (holding a hashmap) binded to this var; if no binding is available, no tracking is performed. Tracking is needed for finally persist to external storage all modified objects. - " + + - *metadata*: extra metadata attached to every pointer created while + it is binded; it is how the current file id reaches `wrap`." (:require + [app.common.exceptions :as ex] [app.common.fressian :as fres] [app.common.time :as ct] [app.common.transit :as t] @@ -91,7 +103,13 @@ (when-not *load-fn* (throw (UnsupportedOperationException. "load is not supported when *load-fn* is not bind"))) - (when-let [data (*load-fn* id)] + (when-not (:file-id mdata) + (ex/raise :type :internal + :code :pointer-without-file-id + :hint "pointer metadata has no :file-id" + :id id)) + + (when-let [data (*load-fn* (:file-id mdata) id)] (set! odata data)) (set! loaded? true) @@ -133,6 +151,9 @@ (or mdata {})) (withMeta [_ mdata'] + ;; The metadata replaces the previous one, so `with-meta` drops the + ;; `:file-id` and the pointer becomes unresolvable; use `vary-meta` to + ;; change pointer metadata (it merges over the current map). (let [changed? (not= mdata mdata') ;; A fragment row never changes after it is written, so a ;; metadata change is a new pointer (fresh id + tracked), like @@ -244,7 +265,9 @@ (do (some-> *tracked* (swap! assoc (get-id data) data)) data) - (let [mdata (assoc (meta data) :created-at (ct/now)) + ;; The bound metadata wins: the file that wraps the pointer is the one + ;; that writes its fragment row, so its `:file-id` is authoritative. + (let [mdata (assoc (merge (meta data) *metadata*) :created-at (ct/now)) id (uuid/next) pmap (PointerMap. id mdata diff --git a/backend/test/backend_tests/file_pointer_snapshot_test.clj b/backend/test/backend_tests/file_pointer_snapshot_test.clj index 359ab7b85a..a6f82f04a3 100644 --- a/backend/test/backend_tests/file_pointer_snapshot_test.clj +++ b/backend/test/backend_tests/file_pointer_snapshot_test.clj @@ -23,6 +23,7 @@ [app.util.blob :as blob] [app.util.pointer-map :as pmap] [backend-tests.helpers :as th] + [clojure.set :as set] [clojure.test :as t])) (t/use-fixtures :once th/state-init) @@ -253,16 +254,25 @@ (t/deftest pointer-context-contract ;; The invariant the whole backend relies on: a pointer can only be - ;; derefed while a loader is bound; with-pointers binds the loader - ;; for the given file. - (let [pointer (pmap/create (uuid/next) {})] + ;; derefed while a loader is bound; `with-pointers` binds it, and the + ;; loader takes the file from the pointer's own metadata. + (let [file-id (uuid/next) + pointer (pmap/create (uuid/next) {:file-id file-id})] (t/is (thrown? UnsupportedOperationException (deref pointer))) - (fdata/with-pointers th/*system* (uuid/random) + (fdata/with-pointers th/*system* (try (deref pointer) (t/is false "expected a fragment-not-found error") (catch clojure.lang.ExceptionInfo cause - (t/is (= :fragment-not-found (:code (ex-data cause))))))))) + (t/is (= :fragment-not-found (:code (ex-data cause))))))) + (t/testing "a pointer without :file-id fails before asking the loader" + (let [pointer (pmap/create (uuid/next) {})] + (fdata/with-pointers th/*system* + (try + (deref pointer) + (t/is false "expected a pointer-without-file-id error") + (catch clojure.lang.ExceptionInfo cause + (t/is (= :pointer-without-file-id (:code (ex-data cause))))))))))) (t/deftest restore-returns-snapshot-content ;; Snapshot, modify the page so the old fragment is snapshot-only, @@ -666,7 +676,7 @@ (add-rect-changes page-a 45))) (let [ids-before (page-pointer-ids file-id) - page (fdata/with-pointers th/*system* file-id + page (fdata/with-pointers th/*system* (deref (get-in (:data (bfc/get-file th/*system* file-id)) [:pages-index page-a])))] @@ -716,7 +726,7 @@ ;; maps, drop the feature and persist through the same encode path. (db/tx-run! th/*system* (fn [cfg] - (fdata/with-tracked-pointers cfg file-id + (fdata/with-tracked-pointers cfg (let [file (bfc/get-file cfg file-id) file (fdata/disable-objects-map file)] (bfc/update-file! cfg file))))) @@ -888,6 +898,85 @@ (t/is (= ids-after (page-pointer-ids file-id))) (t/is (not (fmg/need-migration? returned))))))) +(t/deftest save-migration-keeps-unchanged-page-fragments + ;; A save that triggers a pending migration keeps the fragment ids of pages + ;; the migration does not change, persists pages changed by the migration, + ;; and does not write fragments for discarded intermediate pointers. + ;; `update-file` reads with `:decode? false`, so the migration runs on save. + (let [profile (th/create-profile* 1) + file (th/create-file* 1 {:profile-id (:id profile) + :project-id (:default-project-id profile) + :is-shared false}) + file-id (:id file) + page-a (uuid/random) + page-b (uuid/random) + page-c (uuid/random) + shape-b (uuid/random)] + + (update-file! :profile-id (:id profile) + :file-id file-id + :revn 0 + :changes [{:type :add-page :name "a" :id page-a} + {:type :add-page :name "b" :id page-b} + {:type :add-page :name "c" :id page-c} + (first (add-rect-change page-a (uuid/random))) + (-> (first (add-rect-change page-b shape-b)) + (update :obj assoc :applied-tokens + {:stroke-width "token"})) + (first (add-rect-change page-c (uuid/random)))]) + + (let [ids-before (page-pointer-ids file-id)] + (t/is (contains? ids-before page-a)) + (t/is (contains? ids-before page-b)) + (t/is (contains? ids-before page-c)) + + ;; Force the 0031 migration on the next save. + (th/db-delete! :file-migration + {:file-id file-id + :name "0031-migrate-stroke-width-token-attr"}) + + (let [fragments-before (live-fragment-ids file-id)] + (update-file! :profile-id (:id profile) + :file-id file-id + :revn 1 + :changes (add-rect-change page-c (uuid/random))) + + (let [main (bfc/get-file th/*system* file-id :migrate? false) + snapshot (first (snapshots-by-revn file-id 1)) + snapshot-data (when snapshot + (:data (fsnap/get-snapshot th/*system* + file-id + (:id snapshot)))) + refs (into (fdata/get-used-pointer-ids (:data main)) + (when snapshot-data + (fdata/get-used-pointer-ids snapshot-data))) + fragments-after (live-fragment-ids file-id) + ids-after (into {} (map (fn [[pid pointer]] + [pid (pmap/get-id pointer)])) + (:pages-index (:data main))) + migrated-page-id (get ids-after page-b)] + + ;; Use the same non-migrating read for both assertions. A normal + ;; read here could apply a migration that the save failed to record. + (t/is (not (fmg/need-migration? main))) + (t/is (= (get ids-before page-a) (get ids-after page-a))) + (t/is (not= (get ids-before page-b) (get ids-after page-b))) + (t/is (not= (get ids-before page-c) (get ids-after page-c))) + (t/is (some? snapshot) "the save should keep its pre-migration snapshot") + + ;; Every newly written fragment must be referenced by the saved + ;; main file or this save's snapshot. An unreferenced migration + ;; pointer would add an id to fragments-after but not refs. + (t/is (= (set/difference fragments-after fragments-before) + (set/difference refs fragments-before))) + + ;; The migration-only change must still be persisted even though + ;; tracking is disabled while the migration runs. + (let [tokens (get-in (fragment-objects file-id migrated-page-id) + [shape-b :applied-tokens])] + (t/is (contains? tokens :stroke-width-top)) + (t/is (not (contains? tokens :stroke-width))))))))) + (t/deftest migration-read-only-keeps-fragments-untouched ;; A read-only migration returns realized data but does not persist: ;; the stored pointers and the pending migration stay as they were. @@ -925,11 +1014,10 @@ {:file-id file-id :name "0031-migrate-stroke-width-token-attr"})))))) -(t/deftest libraries-load-their-pages-with-their-own-loader - ;; Fragment rows are keyed by (file_id, id), and every caller binds the - ;; loader of the file it works on. A library's pages must therefore come - ;; back from the library loader already readable, or the first deref - ;; under the consumer's loader asks the wrong file for the fragment. +(t/deftest libraries-stay-lazy-and-resolve-their-own-fragments + ;; A library is read lazily: its pages stay as pointers until something + ;; walks them, and each pointer resolves itself with the file id in its + ;; metadata (fragment rows are keyed by (file_id, id)). (let [profile (th/create-profile* 1) library (th/create-file* 1 {:profile-id (:id profile) :project-id (:default-project-id profile) @@ -950,16 +1038,27 @@ ;; Precondition: the library stores the page as a fragment pointer. (t/is (contains? (page-pointer-ids (:id library)) lib-page)) - (let [page (db/tx-run! th/*system* - (fn [cfg] - (fdata/with-pointers cfg (:id file) - (let [consumer (bfc/get-file cfg (:id file)) - libs (bfc/get-resolved-file-libraries cfg consumer)] - (-> (get libs (:id library)) - (get-in [:data :pages-index lib-page]) - (fdata/realize-entry))))))] - (t/is (= lib-page (:id page))) - (t/is (contains? (:objects page) uuid/zero))))) + (db/tx-run! th/*system* + (fn [cfg] + (let [loads (atom 0) + load fdata/load-pointer] + (with-redefs [fdata/load-pointer + (fn [cfg file-id id] + (swap! loads inc) + (load cfg file-id id))] + (fdata/with-pointers cfg + (let [consumer (bfc/get-file cfg (:id file)) + libs (bfc/get-resolved-file-libraries cfg consumer) + page (get-in (get libs (:id library)) + [:data :pages-index lib-page])] + ;; Resolving the library does not materialize it. + (t/is (pmap/pointer-map? page)) + (t/is (not (pmap/loaded? page))) + ;; The page resolves with the library's own file id: + ;; exactly one fragment is loaded, not the whole + ;; library. + (t/is (= lib-page (:id @page))) + (t/is (= 1 @loads)))))))))) (t/deftest feature-off-keeps-plain-snapshots-and-gc ;; The feature is disabled by default (`fdata/pointer-map` is not in diff --git a/backend/test/backend_tests/offload_file_data_test.clj b/backend/test/backend_tests/offload_file_data_test.clj index 8f4fad28a9..4ec3d24769 100644 --- a/backend/test/backend_tests/offload_file_data_test.clj +++ b/backend/test/backend_tests/offload_file_data_test.clj @@ -380,6 +380,18 @@ (t/is (nil? (:error out))) (get-in out [:result :data]))) +(defn- get-pointer-realized-data + "The file data a client that declares no feature receives: pointers + materialized and `ObjectsMap` kept as is (objects-map is not negotiated). + + Runs inside a transaction: resolving a cold-storage fragment reuses the + connection." + [file-id] + (db/tx-run! th/*system* + (fn [cfg] + (let [file (fdata/realize-pointers cfg (bfc/get-file cfg file-id))] + (:data file))))) + (t/deftest offloaded-file-reads-identically (let [profile (th/create-profile* 1 {:is-active true}) file (create-file 1 profile) @@ -387,7 +399,7 @@ shape-id (uuid/next)] (add-page-with-rect profile file page-id shape-id) - (let [before-bfc (:data (bfc/get-file th/*system* (:id file) {:realize? true})) + (let [before-bfc (get-pointer-realized-data (:id file)) before-rpc (get-file-data profile (:id file))] (t/is (some? (get-in before-bfc [:pages-index page-id :objects shape-id]))) @@ -398,8 +410,7 @@ (t/is (every? #(= "storage" (:backend %)) (remove :deleted-at (db-rows (:id file)))))) (t/testing "direct read resolves cold storage transparently" - (t/is (= before-bfc - (:data (bfc/get-file th/*system* (:id file) {:realize? true}))))) + (t/is (= before-bfc (get-pointer-realized-data (:id file))))) (t/testing "rpc read resolves cold storage transparently" (t/is (= before-rpc (get-file-data profile (:id file)))))))) diff --git a/backend/test/backend_tests/rpc_file_snapshot_test.clj b/backend/test/backend_tests/rpc_file_snapshot_test.clj index 91178ff14f..edecc7150f 100644 --- a/backend/test/backend_tests/rpc_file_snapshot_test.clj +++ b/backend/test/backend_tests/rpc_file_snapshot_test.clj @@ -694,6 +694,12 @@ (t/is (contains? tokens :stroke-width-top)) (t/is (contains? tokens :stroke-width-bottom))) + ;; The migration branch materializes the pointers only: the objects + ;; keep the `ObjectsMap` structure, like in an already-migrated + ;; snapshot. + (t/is (omap/objects-map? + (get-in out [:result :data :pages-index page-id :objects]))) + ;; The preview declared the migrated set in the payload. (t/is (contains? (set (get-in out [:result :migrations])) "0031-migrate-stroke-width-token-attr"))) @@ -710,10 +716,10 @@ (get-in stored [:data :pages-index page-id :objects shape-id :applied-tokens])))))) -(t/deftest snapshot-preview-realizes-objects-for-clients-without-the-feature - ;; `:features` works like in `get-file`: a client that does not - ;; declare `fdata/objects-map` receives plain objects instead of the - ;; storage structure of the fragment. +(t/deftest snapshot-preview-keeps-objects-map-for-any-client + ;; `fdata/objects-map` is not negotiated: the preview materializes the + ;; pointers but the pages keep the `ObjectsMap` structure, whatever the + ;; client declares. Converting it here would rewrite the page map. (let [profile (th/create-profile* 1) file (th/create-file* 1 {:profile-id (:id profile) :project-id (:default-project-id profile) @@ -741,22 +747,16 @@ ::rpc/profile-id (:id profile) :file-id file-id :label "v1"}))) - preview (fn [features] - (th/command! {::th/type :get-file-snapshot - ::rpc/profile-id (:id profile) - :file-id file-id - :id snapshot-id - :features features})) - with-feature (preview cfeat/supported-features) - without-feature (preview (disj cfeat/supported-features - "fdata/objects-map"))] + without-feature (th/command! {::th/type :get-file-snapshot + ::rpc/profile-id (:id profile) + :file-id file-id + :id snapshot-id + :features (disj cfeat/supported-features + "fdata/objects-map")})] - (t/is (nil? (:error with-feature))) (t/is (nil? (:error without-feature))) (t/is (omap/objects-map? - (get-in with-feature [:result :data :pages-index page-id :objects]))) - (t/is (not (omap/objects-map? - (get-in without-feature [:result :data :pages-index page-id :objects])))))) + (get-in without-feature [:result :data :pages-index page-id :objects]))))) (t/deftest snapshot-preview-migrates-legacy-snapshots-without-migrations ;; Snapshots written before the `migrations` column existed (SQL diff --git a/backend/test/backend_tests/rpc_file_test.clj b/backend/test/backend_tests/rpc_file_test.clj index 3c6a8a46ea..27f9894165 100644 --- a/backend/test/backend_tests/rpc_file_test.clj +++ b/backend/test/backend_tests/rpc_file_test.clj @@ -14,6 +14,7 @@ [app.common.pprint :as pp] [app.common.thumbnails :as thc] [app.common.time :as ct] + [app.common.types.objects-map :as omap] [app.common.types.page :as ctp] [app.common.types.shape :as cts] [app.common.types.tokens-lib :as ctob] @@ -30,6 +31,7 @@ [app.rpc :as-alias rpc] [app.rpc.commands.files :as files] [app.storage :as sto] + [app.util.pointer-map :as pmap] [backend-tests.helpers :as th] [clojure.test :as t] [cuerdas.core :as str] @@ -3265,6 +3267,103 @@ :id slink-id})] (t/is (nil? (:error out))))))) +(t/deftest get-file-keeps-the-stored-pointer-without-objects-map-feature + ;; `fdata/objects-map` is not negotiated. A client that declares + ;; pointer-map but not objects-map makes the server skip both + ;; realizations: the page arrives as its stored pointer, with the very + ;; id persisted in the main blob. Converting the objects of a page that + ;; is still a pointer would give it a fresh id with no row behind it. + (let [profile (th/create-profile* 1 {:is-active true}) + file (th/create-file* 1 {:profile-id (:id profile) + :project-id (:default-project-id profile) + :is-shared false}) + file-id (:id file) + page-id (first (get-in file [:data :pages]))] + + ;; The save unions the client features into the file, so it ends up + ;; with both pointer-map and objects-map and every page wrapped. + (update-file! :profile-id (:id profile) + :file-id file-id + :revn 0 + :changes [{:type :add-page :name "extra" :id (uuid/random)}]) + + (let [before (-> (bfc/get-file th/*system* file-id) + (get-in [:data :pages-index page-id]) + (pmap/get-id)) + out (th/command! {::th/type :get-file + ::rpc/profile-id (:id profile) + :id file-id + :features (disj cfeat/supported-features + "fdata/objects-map")})] + + (t/is (nil? (:error out))) + (let [page (get-in out [:result :data :pages-index page-id])] + (t/is (= before (pmap/get-id page))))))) + +(t/deftest get-file-keeps-objects-map-for-a-client-without-the-features + ;; A client that declares neither feature gets the pages materialized, + ;; but their objects stay as an `ObjectsMap`: the server never converts + ;; that structure any more. + (let [profile (th/create-profile* 1 {:is-active true}) + file (th/create-file* 1 {:profile-id (:id profile) + :project-id (:default-project-id profile) + :is-shared false}) + file-id (:id file) + page-id (first (get-in file [:data :pages]))] + + (update-file! :profile-id (:id profile) + :file-id file-id + :revn 0 + :changes [{:type :add-page :name "extra" :id (uuid/random)}]) + + (let [out (th/command! {::th/type :get-file + ::rpc/profile-id (:id profile) + :id file-id + :features (disj cfeat/supported-features + "fdata/pointer-map" + "fdata/objects-map")})] + + (t/is (nil? (:error out))) + (let [page (get-in out [:result :data :pages-index page-id])] + (t/is (not (pmap/pointer-map? page))) + (t/is (omap/objects-map? (:objects page))))))) + +(t/deftest get-file-fragment-rejects-a-marked-fragment + ;; Public contract: the RPC serves unmarked rows only. The internal + ;; loader still reads a row that a `file-gc` pass marked, because the + ;; mark is a liveness hypothesis that maintenance operations refute and + ;; only `objects-gc` purges the row. + (let [profile (th/create-profile* 1 {:is-active true}) + file (th/create-file* 1 {:profile-id (:id profile) + :project-id (:default-project-id profile)}) + fragment (first (th/db-query :file-data {:file-id (:id file) + :type "fragment"}))] + (t/is (uuid? (:id fragment))) + + ;; Mark it the way a file-gc pass does. + (th/db-update! :file-data + {:deleted-at (ct/now)} + {:file-id (:id file) + :id (:id fragment) + :type "fragment"}) + + (t/testing "the internal loader still reads the marked row" + (let [data (db/tx-run! th/*system* + (fn [cfg] + (fdata/load-pointer cfg (:id file) (:id fragment))))] + (t/is (map? data)) + (t/is (contains? data :objects)))) + + (t/testing "the public RPC rejects it" + (let [out (th/command! {::th/type :get-file-fragment + ::rpc/profile-id (:id profile) + :file-id (:id file) + :fragment-id (:id fragment)}) + err (:error out)] + (t/is (th/ex-info? err)) + (t/is (= :not-found (:type (ex-data err)))) + (t/is (= :object-not-found (:code (ex-data err)))))))) + (t/deftest get-file-fragment-returns-only-public-fields (let [profile (th/create-profile* 1 {:is-active true}) file (th/create-file* 1 {:profile-id (:id profile) diff --git a/backend/test/backend_tests/util_pointer_map_test.clj b/backend/test/backend_tests/util_pointer_map_test.clj index 2b0d98babb..0dc8fe00bb 100644 --- a/backend/test/backend_tests/util_pointer_map_test.clj +++ b/backend/test/backend_tests/util_pointer_map_test.clj @@ -7,18 +7,10 @@ (ns backend-tests.util-pointer-map-test (:require [app.common.fressian :as fres] - [app.common.spec :as us] [app.common.transit :as transit] - [app.common.types.shape :as cts] [app.common.uuid :as uuid] [app.util.pointer-map :as pmap] - [backend-tests.helpers :as th] - [clojure.pprint :refer [pprint]] - [clojure.spec.alpha :as s] - [clojure.test :as t] - [clojure.test.check.clojure-test :refer [defspec]] - [clojure.test.check.generators :as gen] - [clojure.test.check.properties :as props])) + [clojure.test :as t])) (t/deftest basic-operations (t/testing "assoc" @@ -87,7 +79,7 @@ (t/testing "tracking modifying not modified" (binding [pmap/*tracked* (atom {}) pmap/*load-fn* (constantly {})] - (let [obj1 (pmap/create uuid/zero {}) + (let [obj1 (pmap/create uuid/zero {:file-id uuid/zero}) obj2 (assoc obj1 :a 1)] (t/is (pmap/modified? obj2)) (t/is (not (pmap/modified? obj1))) @@ -107,7 +99,7 @@ (t/testing "loading" (binding [pmap/*tracked* (atom {}) pmap/*load-fn* (constantly {:a 1})] - (let [obj1 (pmap/create uuid/zero {})] + (let [obj1 (pmap/create uuid/zero {:file-id uuid/zero})] (t/is (not (pmap/modified? obj1))) (t/is (= 1 (count obj1))) (t/is (= uuid/zero (pmap/get-id obj1))) @@ -122,15 +114,77 @@ (t/testing "with-meta" (binding [pmap/*tracked* (atom {}) pmap/*load-fn* (constantly {})] - (let [obj1 (pmap/create uuid/zero {}) + (let [obj1 (pmap/create uuid/zero {:file-id uuid/zero}) obj2 (with-meta obj1 {:foo :bar}) - obj3 (with-meta obj1 {})] + obj3 (with-meta obj1 {:file-id uuid/zero})] ;; A metadata change is a new pointer: fresh id and tracked, so ;; the fragment row is never rewritten under the same id. (t/is (pmap/modified? obj2)) (t/is (not= (pmap/get-id obj1) (pmap/get-id obj2))) (t/is (contains? @pmap/*tracked* (pmap/get-id obj2))) + ;; `with-meta` replaces the metadata, so the file id is gone: that + ;; is the documented sharp edge of the protocol. + (t/is (nil? (:file-id (meta obj2)))) ;; The same metadata keeps the pointer untouched. (t/is (not (pmap/modified? obj3))) - (t/is (= (pmap/get-id obj1) (pmap/get-id obj3))))))) + (t/is (= (pmap/get-id obj1) (pmap/get-id obj3)))))) + + (t/testing "vary-meta keeps the file id" + (binding [pmap/*tracked* (atom {})] + (let [obj1 (pmap/create uuid/zero {:file-id uuid/zero}) + obj2 (vary-meta obj1 assoc :foo :bar)] + (t/is (= uuid/zero (:file-id (meta obj2)))) + (t/is (= :bar (:foo (meta obj2)))) + (t/is (pmap/modified? obj2)) + (t/is (not= (pmap/get-id obj1) (pmap/get-id obj2))) + (t/is (contains? @pmap/*tracked* (pmap/get-id obj2))))))) + +(t/deftest file-id-metadata + (t/testing "wrap copies the bound metadata" + (binding [pmap/*metadata* {:file-id uuid/zero}] + (let [obj (pmap/wrap {})] + (t/is (= uuid/zero (:file-id (meta obj)))) + (t/is (some? (:created-at (meta obj))))))) + + (t/testing "the loader receives the file id of the pointer" + (let [calls (atom [])] + (binding [pmap/*load-fn* (fn [file-id id] + (swap! calls conj [file-id id]) + {:a 1}) + pmap/*tracked* (atom {})] + (let [obj (pmap/create uuid/zero {:file-id uuid/zero})] + (t/is (= 1 (count obj))) + (t/is (= [[uuid/zero uuid/zero]] @calls)))))) + + (t/testing "a pointer without file id fails before asking the loader" + (binding [pmap/*load-fn* (constantly {})] + (let [obj (pmap/create uuid/zero {})] + (try + (deref obj) + (t/is false "expected a pointer-without-file-id error") + (catch clojure.lang.ExceptionInfo cause + (t/is (= :pointer-without-file-id (:code (ex-data cause)))))))))) + +(t/deftest serialization-roundtrip + ;; The persistence handlers carry the id and the metadata by hand, so + ;; the `:file-id` has to survive both encodings for a pointer to be + ;; resolvable after a read. `:created-at` is stored with millisecond + ;; precision by the handlers, so only its presence is asserted. + (let [obj (binding [pmap/*metadata* {:file-id uuid/zero} + pmap/*tracked* (atom {})] + (pmap/wrap {}))] + + (t/testing "fressian keeps the id and the metadata" + (let [obj' (fres/decode (fres/encode obj))] + (t/is (pmap/pointer-map? obj')) + (t/is (= (pmap/get-id obj) (pmap/get-id obj'))) + (t/is (= uuid/zero (:file-id (meta obj')))) + (t/is (some? (:created-at (meta obj')))))) + + (t/testing "transit keeps the id and the metadata" + (let [ptr (transit/decode (transit/encode obj))] + (t/is (transit/pointer? ptr)) + (t/is (= (pmap/get-id obj) @ptr)) + (t/is (= uuid/zero (:file-id (meta ptr)))) + (t/is (some? (:created-at (meta ptr)))))))) diff --git a/common/src/app/common/features.cljc b/common/src/app/common/features.cljc index 281ed4c9bb..a905ea82e4 100644 --- a/common/src/app/common/features.cljc +++ b/common/src/app/common/features.cljc @@ -38,9 +38,6 @@ (def ^:dynamic *current* #{}) (def ^:dynamic *new* nil) -(def ^:dynamic *wrap-with-objects-map-fn* identity) -(def ^:dynamic *wrap-with-pointer-map-fn* identity) - ;; A set of supported features (def supported-features #{"fdata/objects-map"