🐛 Build each file repair on the data left by the previous ones

repair-file built every repair of a pass from the file data taken before
the pass. Repairs write whole values (a :mod-component with the whole
component, a :set with the whole :shapes vector), so two repairs on the
same component or shape attribute undid each other: the last write won,
the lost fix came back as an error, and each clash cost another pass.

Each repair's changes are now applied before the next repair is built.
A private repair-file* returns the data and the changes; repair-file
returns the changes, which give the same result when applied in order,
and repair-file-until-valid reuses the data instead of applying the
batch again (on the backend a second apply wrote an orphan page fragment).

Repairs now see what earlier repairs of the pass did, so
:ref-shape-not-found does nothing when its shape was removed or its ref
shape resolves again; it would otherwise detach a copy that an earlier
:invalid-main-instance-id repair had already relinked.

Tests stub repair-error, through a multi-arity fn so the JS build can
call it, and cover two clashing errors on one component in either order,
three missing children fixed in one pass, and repairs on removed shapes.

Closes #13239

AI-assisted-by: claude-opus-5-5
This commit is contained in:
Pablo Alba 2026-11-23 14:50:22 +01:00 committed by Pablo Alba
parent 8d0ff7984b
commit b58f7d2996
4 changed files with 209 additions and 72 deletions

View File

@ -22,7 +22,8 @@
- Validation starts at root plus orphan shapes, then validates component records. `validate-file!` raises `:validation :referential-integrity` with collected details. - Validation starts at root plus orphan shapes, then validates component records. `validate-file!` raises `:validation :referential-integrity` with collected details.
- `update-file` validates per save with the change-scoped variants: `validate-file-affected!` (referential, whole touched pages/components) and `validate-file-schema-affected!` (file schema with `:pages-index` reduced to the touched pages; non-page data checked whole). The schema variant maps change types to pages itself (`touched-page-ids`): a new change type that writes a page must be added there, or to `file-level-change-types` if it touches no page; an unknown type makes it check the whole file. The whole-file schema check loads and decodes every page, ~75–80% of a save on multi-page files. - `update-file` validates per save with the change-scoped variants: `validate-file-affected!` (referential, whole touched pages/components) and `validate-file-schema-affected!` (file schema with `:pages-index` reduced to the touched pages; non-page data checked whole). The schema variant maps change types to pages itself (`touched-page-ids`): a new change type that writes a page must be added there, or to `file-level-change-types` if it touches no page; an unknown type makes it check the whole file. The whole-file schema check loads and decodes every page, ~75–80% of a save on multi-page files.
- `repair-file` does not mutate data directly; it reduces validation errors into redo changes using `changes-builder`. Callers must apply or persist those changes. - `repair-file` does not mutate data directly; it reduces validation errors into redo changes using `changes-builder`. Callers must apply or persist those changes.
- `repair-file-until-valid` stops on: no errors; unchanged `:data` after apply (backend page/`PointerMap` `=` is pointer identity); stable error fingerprint `(frequencies (map #(dissoc % :shape) errors))` vs previous pass (check fingerprint before `repair-file`/`process-changes`); or `max-iterations`. Each `repair-error` builds from the original `file-data`, so N `:set`-based errors on one shape take N passes. - `repair-file-until-valid` stops on: no errors; unchanged `:data` after apply (backend page/`PointerMap` `=` is pointer identity); stable error fingerprint `(frequencies (map #(dissoc % :shape) errors))` vs previous pass (check fingerprint before `repair-file*`); or `max-iterations`.
- `repair-file` applies each repair's changes before building the next, so repairs of one pass see each other's writes: two whole-value writes (`:mod-component`, a `:set` of `:shapes`) on one component or shape no longer undo each other. `repair-file-until-valid` reuses that data (private `repair-file*`), never re-applying the batch: on the backend a second apply makes a second tracked `PointerMap` per touched page and an orphan fragment row. The `pcb` builders read the shape/component from the current data, but the error's `:shape` is still the validation snapshot, and some methods decide from it (`:shapes` in `:duplicate-slot`/`:variant-container-bad-name`, `:parent-id` in `:parent-not-variant`/`:child-not-in-parent`, `:shape-ref` in `:ref-shape-not-found`). A repair whose choice is destructive must first check that its error still holds in the current data: `:ref-shape-not-found` resolves the ref shape again and does nothing when found, or it would detach a copy that an earlier `:invalid-main-instance-id` repair already relinked. A shape removed by an earlier repair may still get a `:mod-obj` (when the update-fn returns a map for `nil`), which `process-operations` skips. Tests stub `cfr/repair-error` to drive `repair-file-until-valid`.
- `:ref-shape-not-found` repair: when the copy root's local component has a `:main-instance-id` that resolves to no shape but a `:main-instance` shape of that component sits on its `:main-instance-page`, it emits `mod-component` pointing the id back to that main (keeps the copy linked; a repair scoped to the copy's page never sees the main's `:invalid-main-instance-id`). Otherwise near-main reassign, else detach the copy subtree. - `:ref-shape-not-found` repair: when the copy root's local component has a `:main-instance-id` that resolves to no shape but a `:main-instance` shape of that component sits on its `:main-instance-page`, it emits `mod-component` pointing the id back to that main (keeps the copy linked; a repair scoped to the copy's page never sees the main's `:invalid-main-instance-id`). Otherwise near-main reassign, else detach the copy subtree.
- `:missing-slot` fires only for a REAL swap: a copy sub-head whose `shape-ref` is no longer a child of the near main parent. A pure positional mismatch (ref still a sibling elsewhere) is a reorder — valid, realigned by the async component sync; do not "repair" it by assigning swap slots (a slot freezes the child out of normal sync). `fix-missing-swap-slots` (migration 0019) follows the same membership rule. - `:missing-slot` fires only for a REAL swap: a copy sub-head whose `shape-ref` is no longer a child of the near main parent. A pure positional mismatch (ref still a sibling elsewhere) is a reorder — valid, realigned by the async component sync; do not "repair" it by assigning swap slots (a slot freezes the child out of normal sync). `fix-missing-swap-slots` (migration 0019) follows the same membership rule.

View File

@ -309,13 +309,15 @@
broken (break-frame ctx) broken (break-frame ctx)
calls (atom 0) calls (atom 0)
before (repair-count :unrepaired) before (repair-count :unrepaired)
out (with-redefs [cfr/repair-file (fn [_ _ _] out (with-redefs [cfr/repair-error (fn [_ _ _ _]
(swap! calls inc) (swap! calls inc)
[])] {:redo-changes []})]
(update-file (:id profile) file-id (:revn broken) (update-file (:id profile) file-id (:revn broken)
[(set-attr page-id shape-b :name "renamed")]))] [(set-attr page-id shape-b :name "renamed")]))]
(t/is (not (th/success? out))) (t/is (not (th/success? out)))
(t/is (= :referential-integrity (:code (ex-data (:error out))))) (t/is (= :referential-integrity (:code (ex-data (:error out)))))
;; `calls` counts repairs, one per error; `break-frame` yields a
;; single error, so one call means one pass.
(t/is (= 1 @calls)) (t/is (= 1 @calls))
(t/is (= 1.0 (- (repair-count :unrepaired) before))))))) (t/is (= 1.0 (- (repair-count :unrepaired) before)))))))

View File

@ -297,37 +297,49 @@
(defmethod repair-error :ref-shape-not-found (defmethod repair-error :ref-shape-not-found
[_ {:keys [shape page-id] :as error} file-data libraries] [_ {:keys [shape page-id] :as error} file-data libraries]
(let [lost-main (let [page (ctpl/get-page file-data page-id)] (let [;; An earlier repair of the same pass may have removed the shape, or
(find-lost-main file-data (ctn/get-component-shape (:objects page) shape))) ;; fixed the reference (e.g. pointed the component back to its main).
current (let [page (ctpl/get-page file-data page-id)]
(get (:objects page) (:id shape)))
matching-shape (let [page (ctpl/get-page file-data page-id) ref-shape (when (some? current)
root-shape (ctn/get-component-shape (:objects page) shape) (ctf/find-ref-shape {:id (:id file-data) :data file-data}
component-file (if (= (:component-file root-shape) (:id file-data)) (ctpl/get-page file-data page-id) libraries current
file-data :include-deleted? true))
(-> (get libraries (:component-file root-shape)) :data))
component (when component-file
(ctkl/get-component component-file (:component-id root-shape) true))
component-shapes (ctf/get-component-shapes file-data component)]
;; Check if the shape points to the remote main. If so, reassign to the near main. lost-main (when (some? current)
(if-let [near-shape-1 (d/seek #(= (:shape-ref %) (:shape-ref shape)) component-shapes)] (let [page (ctpl/get-page file-data page-id)]
near-shape-1 (find-lost-main file-data (ctn/get-component-shape (:objects page) shape))))
;; Check if it points to any random shape in the page. If so, try to find a matchng
;; shape in the near main component. matching-shape (when (some? current)
(when-let [random-shape (ctn/get-shape page (:shape-ref shape))] (let [page (ctpl/get-page file-data page-id)
(if-let [near-shape-2 (d/seek #(= (:id %) (:shape-ref random-shape)) component-shapes)] root-shape (ctn/get-component-shape (:objects page) shape)
near-shape-2 component-file (if (= (:component-file root-shape) (:id file-data))
;; If not, check if it's a fostered copy and find a direct main. file-data
(let [head-shape (ctn/get-head-shape (:objects page) shape) (-> (get libraries (:component-file root-shape)) :data))
component-file (if (= (:component-file head-shape) (:id file-data)) component (when component-file
file-data (ctkl/get-component component-file (:component-id root-shape) true))
(-> (get libraries (:component-file head-shape)) :data)) component-shapes (ctf/get-component-shapes file-data component)]
component (when component-file
(ctkl/get-component component-file (:component-id head-shape) true)) ;; Check if the shape points to the remote main. If so, reassign to the near main.
component-shapes (ctf/get-component-shapes file-data component)] (if-let [near-shape-1 (d/seek #(= (:shape-ref %) (:shape-ref shape)) component-shapes)]
(if-let [near-shape-3 (d/seek #(= (:id %) (:shape-ref random-shape)) component-shapes)] near-shape-1
near-shape-3 ;; Check if it points to any random shape in the page. If so, try to find a matchng
nil)))))) ;; shape in the near main component.
(when-let [random-shape (ctn/get-shape page (:shape-ref shape))]
(if-let [near-shape-2 (d/seek #(= (:id %) (:shape-ref random-shape)) component-shapes)]
near-shape-2
;; If not, check if it's a fostered copy and find a direct main.
(let [head-shape (ctn/get-head-shape (:objects page) shape)
component-file (if (= (:component-file head-shape) (:id file-data))
file-data
(-> (get libraries (:component-file head-shape)) :data))
component (when component-file
(ctkl/get-component component-file (:component-id head-shape) true))
component-shapes (ctf/get-component-shapes file-data component)]
(if-let [near-shape-3 (d/seek #(= (:id %) (:shape-ref random-shape)) component-shapes)]
near-shape-3
nil)))))))
reassign-shape reassign-shape
(fn [shape] (fn [shape]
(log/debug :hint " -> reassign shape-ref to" :shape-ref (:id matching-shape)) (log/debug :hint " -> reassign shape-ref to" :shape-ref (:id matching-shape))
@ -343,6 +355,11 @@
;; and link to it. If not, detach the shape. ;; and link to it. If not, detach the shape.
(log/debug :hint "repairing shape :ref-shape-not-found" :id (:id shape) :name (:name shape) :page-id page-id) (log/debug :hint "repairing shape :ref-shape-not-found" :id (:id shape) :name (:name shape) :page-id page-id)
(cond (cond
(or (nil? current) (some? ref-shape))
(do
(log/debug :hint " -> shape removed or ref shape found, nothing to repair")
(pcb/empty-changes nil page-id))
(some? lost-main) (some? lost-main)
(do (do
(log/debug :hint " -> assign main-instance-id" :main-instance-id (:id lost-main)) (log/debug :hint " -> assign main-instance-id" :main-instance-id (:id lost-main))
@ -881,19 +898,29 @@
(log/error :hint "Unknown error code, don't know how to repair" :code (:code error)) (log/error :hint "Unknown error code, don't know how to repair" :code (:code error))
file) file)
(defn repair-file (defn- repair-file*
[{:keys [data id] :as file} libraries errors] "Repair `errors` in `file`. Return `{:data data' :changes redo-changes}`.
Each repair is built on the data left by the previous ones, so two
repairs that write the same component or shape attribute do not undo
each other. The `:shape` of each error is still the one taken by the
validation."
[{:keys [data id]} libraries errors]
(log/debug :hint "repairing file" :id (str id) :errors (count errors)) (log/debug :hint "repairing file" :id (str id) :errors (count errors))
(let [{:keys [redo-changes]} (reduce (fn [{:keys [data] :as result} error]
(reduce (fn [changes error] (let [{:keys [redo-changes]} (repair-error (:code error) error data libraries)]
(pcb/concat-changes changes (cond-> result
(repair-error (:code error) (seq redo-changes)
error (-> (assoc :data (cfc/process-changes data redo-changes))
data (update :changes into redo-changes)))))
libraries))) {:data data :changes []}
(pcb/empty-changes nil) errors))
errors)]
redo-changes)) (defn repair-file
"Return the redo changes that repair `errors` in `file`. Applied in
order to the file data, they give the repaired data."
[file libraries errors]
(:changes (repair-file* file libraries errors)))
(defn- error-fingerprint (defn- error-fingerprint
[errors] [errors]
@ -937,8 +964,7 @@
:errors (not-empty errors)} :errors (not-empty errors)}
:else :else
(let [batch (repair-file file libraries errors) (let [{data' :data batch :changes} (repair-file* file libraries errors)]
data' (cfc/process-changes (:data file) batch)]
(if (= data' (:data file)) (if (= data' (:data file))
{:file file {:file file
:changes applied :changes applied

View File

@ -168,6 +168,101 @@
(t/is (= "Value2, ValueB" (:variant-name root2')))))) (t/is (= "Value2, ValueB" (:variant-name root2'))))))
(t/deftest repair-two-errors-on-one-variant-component-in-one-pass
(t/testing "the properties fix and the variant id fix of the same component both survive one repair pass"
(let [file (-> (thf/sample-file :file1 :page-label :page1)
(thv/add-variant :variant1 :component1 :root1 :component2 :root2)
;; The first child of the container is root2, so component2 sets the
;; property names. Component1 has an extra property and a variant id
;; that does not point to the container.
(thc/update-component :component1 {:variant-id (uuid/next)
:variant-properties [{:name "Property 1" :value "Value1"}
{:name "Extra" :value "x"}]})
(ths/update-shape :root1 :variant-name "Value1, x"))
errors (cfv/validate-file file {})
changes (cfr/repair-file file {} errors)
file' (thf/apply-changes file {:redo-changes changes} :validate? false)
errors' (cfv/validate-file file' {})
comp1' (thc/get-component file' :component1)]
(t/is (= [:invalid-variant-properties :variant-component-bad-id] (mapv :code errors)))
(t/is (nil? errors'))
(t/is (= (thi/id :variant1) (:variant-id comp1')))
(t/is (= [{:name "Property 1" :value "Value1"}] (:variant-properties comp1'))))))
(t/deftest repair-two-errors-on-one-component-in-any-order
(let [stray-id (uuid/next)
file (-> (thf/sample-file :file1 :page-label :page1)
(thv/add-variant :variant1 :component1 :root1 :component2 :root2)
(thc/update-component :component1 {:variant-id (uuid/next)
:objects {stray-id {:id stray-id :type :rect :name "Stray"}}}))
errors (cfv/validate-file file {})]
(t/is (= [:variant-component-bad-id :non-deleted-component-cannot-have-objects]
(mapv :code errors)))
;; Both repairs rewrite the whole component: whichever runs last must
;; keep the fix of the other one.
(doseq [errors [errors (reverse errors)]]
(t/testing (str "both fixes survive with the errors in order " (mapv :code errors))
(let [changes (cfr/repair-file file {} errors)
file' (thf/apply-changes file {:redo-changes changes} :validate? false)
comp1' (thc/get-component file' :component1)]
(t/is (nil? (cfv/validate-file file' {})))
(t/is (not (contains? comp1' :objects)))
(t/is (= (thi/id :variant1) (:variant-id comp1'))))))))
(t/deftest repair-errors-on-shapes-removed-by-an-earlier-repair
(t/testing "repairs on shapes that an earlier repair of the same pass removed change nothing"
(let [file (-> (thf/sample-file :file1 :page-label :page1)
(thv/add-variant :variant1 :component1 :root1 :component2 :root2)
;; A variant that is not a main: its repair removes it with its children
(ths/add-sample-shape :stray :type :frame :parent-label :variant1
:variant-id (thi/id :variant1) :variant-name "Value3")
(ths/add-sample-shape :inner :parent-label :stray)
(ths/update-shape :inner :frame-id (uuid/next)))
errors (cfv/validate-file file {})
removed #{(thi/id :stray) (thi/id :inner)}
later (->> errors
(drop-while #(not= :variant-not-main (:code %)))
(rest))
changes (cfr/repair-file file {} errors)
file' (thf/apply-changes file {:redo-changes changes} :validate? false)
errors' (cfv/validate-file file' {})]
(t/is (some #(= :frame-not-found (:code %)) later))
(t/is (every? #(contains? removed (:shape-id %)) later))
(t/is (nil? errors'))
(t/is (nil? (ths/get-shape file' :stray)))
(t/is (nil? (ths/get-shape file' :inner)))
(t/is (not-any? removed (:shapes (ths/get-shape file' :variant1))))))
;; Guards against a crash, not a lost fix: without the removed-shape check
;; in the :ref-shape-not-found repair, its lookups throw on the removed
;; root1. Removing the variant's main here is the behaviour #13257 tracks;
;; revisit this fixture when that issue changes it.
(t/testing ":ref-shape-not-found on a shape that an earlier repair of the same pass removed"
(let [file (-> (thf/sample-file :file1 :page-label :page1)
(thv/add-variant :variant1 :component1 :root1 :component2 :root2)
(ths/update-shape :root1 :main-instance nil))
errors (cfv/validate-file file {})
result (cfr/repair-file-until-valid
file {}
(fn [file _] (cfv/validate-file file {})))]
(t/is (= [[:variant-not-main (thi/id :root1)]
[:invalid-main-instance (thi/id :root1)]
[:ref-shape-not-found (thi/id :root1)]]
(mapv (juxt :code :shape-id) errors)))
(t/is (= 1 (:iterations result)))
(t/is (nil? (:errors result))))))
(t/deftest repair-variant-not-main (t/deftest repair-variant-not-main
(t/testing "detect and repair a non-main-instance shape inside a variant container" (t/testing "detect and repair a non-main-instance shape inside a variant container"
(let [file (-> (thf/sample-file :file1 :page-label :page1) (let [file (-> (thf/sample-file :file1 :page-label :page1)
@ -379,6 +474,15 @@
(t/is (= uuid/zero (:parent-id shape2'))) (t/is (= uuid/zero (:parent-id shape2')))
(t/is (= #{(thi/id :shape1) (thi/id :shape2)} (set (:shapes root'))))))) (t/is (= #{(thi/id :shape1) (thi/id :shape2)} (set (:shapes root')))))))
(defn- stub-repair-error
"Stand-in for `cfr/repair-error` that returns `(f)` as the redo changes.
Multi-arity on purpose: the JS build calls the multimethod through its
`cljs$core$IFn$_invoke$arity$4` property, which a single-arity fn lacks."
[f]
(fn
([_ _ _ _] {:redo-changes (f)})
([_ _ _ _ & _] {:redo-changes (f)})))
(defn- broken-frame-file (defn- broken-frame-file
[] []
(-> (thf/sample-file :file1 :page-label :page1) (-> (thf/sample-file :file1 :page-label :page1)
@ -436,7 +540,7 @@
(t/testing "an empty repair batch stops after one iteration" (t/testing "an empty repair batch stops after one iteration"
(let [file (broken-frame-file) (let [file (broken-frame-file)
errors (cfv/validate-file file {})] errors (cfv/validate-file file {})]
(with-redefs [cfr/repair-file (fn [_ _ _] [])] (with-redefs [cfr/repair-error (stub-repair-error (constantly []))]
(let [result (cfr/repair-file-until-valid (let [result (cfr/repair-file-until-valid
file {} file {}
(fn [file _] (cfv/validate-file file {})))] (fn [file _] (cfv/validate-file file {})))]
@ -445,8 +549,8 @@
(t/is (= (mapv :code errors) (mapv :code (:errors result))))))))) (t/is (= (mapv :code errors) (mapv :code (:errors result)))))))))
(t/deftest repair-file-until-valid-repairs-several-errors-on-one-shape (t/deftest repair-file-until-valid-repairs-several-errors-on-one-shape
(t/testing "three missing children of one frame are all removed although (t/testing "three missing children of one frame are all removed in one pass,
every pass reports the same [code shape-id]" although the three errors write the same :shapes attribute"
(let [file (-> (thf/sample-file :file1 :page-label :page1) (let [file (-> (thf/sample-file :file1 :page-label :page1)
(ths/add-sample-shape :frame1 :type :frame) (ths/add-sample-shape :frame1 :type :frame)
(ths/update-shape :frame1 :shapes [(uuid/next) (uuid/next) (uuid/next)])) (ths/update-shape :frame1 :shapes [(uuid/next) (uuid/next) (uuid/next)]))
@ -457,6 +561,7 @@
frame1' (ths/get-shape (:file result) :frame1 :page-label :page1)] frame1' (ths/get-shape (:file result) :frame1 :page-label :page1)]
(t/is (= [:child-not-found :child-not-found :child-not-found] (mapv :code errors))) (t/is (= [:child-not-found :child-not-found :child-not-found] (mapv :code errors)))
(t/is (= #{(thi/id :frame1)} (into #{} (map :shape-id) errors))) (t/is (= #{(thi/id :frame1)} (into #{} (map :shape-id) errors)))
(t/is (= 1 (:iterations result)))
(t/is (nil? (:errors result))) (t/is (nil? (:errors result)))
(t/is (nil? (cfv/validate-file (:file result) {}))) (t/is (nil? (cfv/validate-file (:file result) {})))
(t/is (= [] (:shapes frame1')))))) (t/is (= [] (:shapes frame1'))))))
@ -467,12 +572,13 @@
shape-id (thi/id :shape1) shape-id (thi/id :shape1)
page-id (thi/id :page1) page-id (thi/id :page1)
cur-name (:name (ths/get-shape file :shape1 :page-label :page1))] cur-name (:name (ths/get-shape file :shape1 :page-label :page1))]
(with-redefs [cfr/repair-file (with-redefs [cfr/repair-error
(fn [_ _ _] (stub-repair-error
[{:type :mod-obj (fn []
:id shape-id [{:type :mod-obj
:page-id page-id :id shape-id
:operations [{:type :set :attr :name :val cur-name}]}])] :page-id page-id
:operations [{:type :set :attr :name :val cur-name}]}]))]
(let [result (cfr/repair-file-until-valid (let [result (cfr/repair-file-until-valid
file {} file {}
(fn [_ _] [{:code :frame-not-found :shape-id shape-id}]) (fn [_ _] [{:code :frame-not-found :shape-id shape-id}])
@ -491,14 +597,15 @@
:shape-id shape-id :shape-id shape-id
:hint "stuck" :hint "stuck"
:args {:x 1}}] :args {:x 1}}]
(with-redefs [cfr/repair-file (with-redefs [cfr/repair-error
(fn [_ _ _] (stub-repair-error
[{:type :mod-obj (fn []
:id shape-id [{:type :mod-obj
:page-id page-id :id shape-id
:operations [{:type :set :page-id page-id
:attr :name :operations [{:type :set
:val (str "pass-" (swap! pass inc))}]}])] :attr :name
:val (str "pass-" (swap! pass inc))}]}]))]
(let [result (cfr/repair-file-until-valid (let [result (cfr/repair-file-until-valid
file {} file {}
(fn [_ _] [sticky]) (fn [_ _] [sticky])
@ -513,14 +620,15 @@
pass (atom 0) pass (atom 0)
shape-id (thi/id :shape1) shape-id (thi/id :shape1)
page-id (thi/id :page1)] page-id (thi/id :page1)]
(with-redefs [cfr/repair-file (with-redefs [cfr/repair-error
(fn [_ _ _] (stub-repair-error
[{:type :mod-obj (fn []
:id shape-id [{:type :mod-obj
:page-id page-id :id shape-id
:operations [{:type :set :page-id page-id
:attr :name :operations [{:type :set
:val (str "pass-" (swap! pass inc))}]}])] :attr :name
:val (str "pass-" (swap! pass inc))}]}]))]
(let [result (cfr/repair-file-until-valid (let [result (cfr/repair-file-until-valid
file {} file {}
(fn [_ _] (fn [_ _]