diff --git a/CHANGELOG.md b/CHANGELOG.md index 176950439..01d097ff1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -104,6 +104,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **A mapping value can convert between the JSON member's type and the attribute's** (ako/mxcli#2714, upstream mendixlabs/mxcli#2001) — an import mapping binding a JSON integer to a String attribute stored the value with the attribute's type, and `mx check` reported CE5015. Recent builds refused the mapping at `check` instead (MDL127), calling it an exact-type rule. A value now stores the member's type where the mapping converts, as Studio Pro does. `check` accepts what the build accepts, measured over every pairing: on import, any value into a String attribute and an integer into a Decimal; on export, a String attribute into any member and an Integer or Long into a decimal. Other pairings are still refused, now naming CE6099 (import) or CE0227 (export). Re-running `create or modify` repairs a mapping written before. - **`create or modify microflow` can turn a local variable into a parameter of the same name** (ako/mxcli#2726, upstream mendixlabs/mxcli#2002) — moving a list to the caller meant adding the parameter `$SaleList` and removing the `create list` that declared it. That was refused (MDL-V1-REBUILD) with "drop $SaleList: $SaleList is still used by: add $NewSale to $SaleList", although the new parameter supplies the variable. The change is now spliced into the stored flow. A reader left with no variable at all is still refused. - **SEC012 tells a microflow from a snippet of the same name** (ako/mxcli#2730, upstream mendixlabs/mxcli#2004) — a Marketplace module can hold a microflow and a snippet both named `Lib.Overview`. A menu item calling the microflow was taken for the snippet, without the check that the role may execute the microflow. `lint` then reported CE2729 on every attribute the snippet shows, for roles that cannot reach it, where `mx check` reported nothing. The reachability walk now keys each document by its kind as well as its name. `show references` adds the target's type when a name belongs to more than one kind of document. +- **Inserting a unit whose ID already exists no longer destroys the existing unit's file** (#2036) — `insertUnit` wrote the unit file before it inserted the row, so a `UnitID` that already had a row overwrote the file of that unit, then failed on the primary key, and the clean-up deleted the file: the row stayed and its file was gone. A `UnitID` that already has a row is now refused before anything is written ("unit … already exists; nothing was written"). Two writers inserting the same ID at the same moment are held by the primary key as well: the row is now inserted first, in a transaction that holds SQLite's write lock, and the unit file is written before the COMMIT, so the loser fails at the INSERT without having touched the file, and a file that cannot be written rolls the row back. A crash leaves what the old order left (at worst an orphan file). A write of a unit that has no row (`WriteTransaction.WriteUnit`) is also refused now: it used to change nothing in the table and still rename a file into place. ## [0.34.0] - 2026-11-27 diff --git a/modelsdk/mpr/writer_core.go b/modelsdk/mpr/writer_core.go index 130107d8e..0838f8885 100644 --- a/modelsdk/mpr/writer_core.go +++ b/modelsdk/mpr/writer_core.go @@ -302,18 +302,24 @@ func (wt *WriteTransaction) WriteUnit(unitID string, contents []byte) error { }) // Update hash in DB - _, err := wt.tx.Exec(` + res, err := wt.tx.Exec(` UPDATE Unit SET ContentsHash = ? WHERE UnitID = ? `, contentsHashOf(contents), unitIDBlob) - return err + if err != nil { + return err + } + return requireUnitRow(res, unitID) } // V1: contents live in the row, and so does their hash. Studio Pro fills // ContentsHash on every v1 unit too (ako/mxcli#1159), so it moves with them. - _, err = wt.tx.Exec(` + res, err := wt.tx.Exec(` UPDATE Unit SET Contents = ?, ContentsHash = ? WHERE UnitID = ? `, contents, contentsHashOf(contents), unitIDBlob) - return err + if err != nil { + return err + } + return requireUnitRow(res, unitID) } // Commit commits the transaction. @@ -600,6 +606,12 @@ func (w *Writer) insertUnit(unitID, containerID, containmentName, unitType strin return fmt.Errorf("invalid container ID (not a valid UUID): %q", containerID) } + // A UnitID that already has a row is refused before the unit file is touched: + // the file at that path is the existing unit's. + if err := w.refuseExistingUnit(unitID, unitIDBlob); err != nil { + return err + } + contents, normErr := w.normalizeForStorage(unitID, contents) if normErr != nil { return normErr @@ -621,20 +633,10 @@ func (w *Writer) insertUnit(unitID, containerID, containmentName, unitType strin return fmt.Errorf("failed to create directory %s: %w", dir, err) } - // Write content file - if err := os.WriteFile(filePath, contents, 0644); err != nil { - return fmt.Errorf("failed to write unit file: %w", err) - } - - // Insert reference to database + // The row is inserted, and the file written, under one transaction that + // already holds the row: see writeNewUnitV2. hash := contentsHashOf(contents) - _, err := w.reader.db.Exec(` - INSERT INTO Unit (UnitID, ContainerID, ContainmentName, TreeConflict, ContentsHash, ContentsConflicts) - VALUES (?, ?, ?, 0, ?, '') - `, unitIDBlob, containerIDBlob, containmentName, hash) - if err != nil { - // Clean up the file we just wrote — otherwise it becomes an orphan - os.Remove(filePath) + if err := w.writeNewUnitV2(unitIDBlob, containerIDBlob, containmentName, filePath, contents, hash); err != nil { return err } w.reader.noteUnitWritten(unitIDBlob, containerIDBlob, containmentName, contents, hash, true) diff --git a/modelsdk/mpr/writer_insert_existing_unit_test.go b/modelsdk/mpr/writer_insert_existing_unit_test.go new file mode 100644 index 000000000..5d9f74468 --- /dev/null +++ b/modelsdk/mpr/writer_insert_existing_unit_test.go @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: Apache-2.0 + +package mpr + +import ( + "os" + "strings" + "testing" +) + +// insertUnit wrote the unit file before it inserted the row, and when the INSERT +// failed it removed "the file it had just written". With a UnitID that already +// had a row the INSERT fails on the primary key, but by then the existing unit's +// file had been overwritten, and the clean-up then deleted it: the row stayed and +// its file was gone. A failed insert has to leave the existing unit alone. + +const ( + existingUnitID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" + existingContainer = "22222222-2222-2222-2222-222222222222" +) + +func TestInsertUnit_AnExistingUnitIDIsRefusedAndTheUnitIsLeftAlone(t *testing.T) { + first := unitDoc(t, "First") + w, unitPath := newV2WriterForCommitTest(t, existingUnitID, first) + seedTransactionTable(t, w, "the-original-transaction") + seedUnitRow(t, w, existingUnitID, existingContainer, "Documents") + hashBefore := storedHash(t, w, existingUnitID) + txBefore := transactionID(t, w) + + err := w.insertUnit(existingUnitID, existingContainer, "Documents", "Projects$Folder", unitDoc(t, "Second")) + if err == nil { + t.Fatal("inserting a UnitID that already has a row succeeded") + } + if !strings.Contains(err.Error(), "already exists") { + t.Errorf("error = %q, want it to say the unit already exists", err) + } + + got, readErr := os.ReadFile(unitPath) + if readErr != nil { + t.Fatalf("the existing unit's file is gone after a refused insert: %v", readErr) + } + if string(got) != string(first) { + t.Errorf("the existing unit's file was overwritten by a refused insert (%d bytes before, %d after)", len(first), len(got)) + } + if h := storedHash(t, w, existingUnitID); h != hashBefore { + t.Errorf("ContentsHash of the existing unit changed: %q -> %q", hashBefore, h) + } + if tx := transactionID(t, w); tx != txBefore { + t.Errorf("a refused insert moved the transaction id: %q -> %q", txBefore, tx) + } +} + +// A new UnitID still inserts: row and file are both there afterwards. +func TestInsertUnit_ANewUnitIDStillInserts(t *testing.T) { + const otherID = "bbbbbbbb-bbbb-cccc-dddd-eeeeeeeeeeee" + w, _ := newV2WriterForCommitTest(t, existingUnitID, unitDoc(t, "First")) + seedTransactionTable(t, w, "the-original-transaction") + seedUnitRow(t, w, existingUnitID, existingContainer, "Documents") + + if err := w.insertUnit(otherID, existingContainer, "Documents", "Projects$Folder", unitDoc(t, "Other")); err != nil { + t.Fatalf("insert of a new UnitID: %v", err) + } + if _, err := os.Stat(unitFilePath(w.reader.contentsDir, uuidToBlob(otherID))); err != nil { + t.Errorf("the new unit's file is missing: %v", err) + } + var n int + if err := w.reader.db.QueryRow(`SELECT COUNT(*) FROM Unit WHERE UnitID = ?`, uuidToBlob(otherID)).Scan(&n); err != nil || n != 1 { + t.Errorf("rows for the new unit = %d (err %v), want 1", n, err) + } +} + +// The race the up-front check cannot close: two writers pass it together. The +// loser of the INSERT must not have touched the file. writeNewUnitV2 is called +// directly for a UnitID whose row exists, as the loser's call would be. +func TestWriteNewUnitV2_TheLoserOfTheInsertNeverTouchesTheFile(t *testing.T) { + first := unitDoc(t, "First") + w, unitPath := newV2WriterForCommitTest(t, existingUnitID, first) + seedTransactionTable(t, w, "the-original-transaction") + seedUnitRow(t, w, existingUnitID, existingContainer, "Documents") + hashBefore := storedHash(t, w, existingUnitID) + + second := unitDoc(t, "Second") + err := w.writeNewUnitV2(uuidToBlob(existingUnitID), uuidToBlob(existingContainer), "Documents", unitPath, second, hashOf(second)) + if err == nil { + t.Fatal("the second INSERT of one UnitID succeeded") + } + got, readErr := os.ReadFile(unitPath) + if readErr != nil { + t.Fatalf("the winner's file is gone: %v", readErr) + } + if string(got) != string(first) { + t.Errorf("the loser of the INSERT overwrote the winner's file (%d bytes before, %d after)", len(first), len(got)) + } + if h := storedHash(t, w, existingUnitID); h != hashBefore { + t.Errorf("the winner's ContentsHash changed: %q -> %q", hashBefore, h) + } +} + +// A file that cannot be written rolls the row back: no row without its file. +func TestWriteNewUnitV2_AFileThatCannotBeWrittenLeavesNoRow(t *testing.T) { + const otherID = "bbbbbbbb-bbbb-cccc-dddd-eeeeeeeeeeee" + w, _ := newV2WriterForCommitTest(t, existingUnitID, unitDoc(t, "First")) + seedTransactionTable(t, w, "the-original-transaction") + + // A directory where the file should go makes WriteFile fail. + blocked := unitFilePath(w.reader.contentsDir, uuidToBlob(otherID)) + if err := os.MkdirAll(blocked, 0755); err != nil { + t.Fatal(err) + } + doc := unitDoc(t, "Other") + err := w.writeNewUnitV2(uuidToBlob(otherID), uuidToBlob(existingContainer), "Documents", blocked, doc, hashOf(doc)) + if err == nil || !strings.Contains(err.Error(), "failed to write unit file") { + t.Fatalf("error = %v, want a failed-to-write error", err) + } + var n int + if qerr := w.reader.db.QueryRow(`SELECT COUNT(*) FROM Unit WHERE UnitID = ?`, uuidToBlob(otherID)).Scan(&n); qerr != nil || n != 0 { + t.Errorf("rows for the unit whose file could not be written = %d (err %v), want 0", n, qerr) + } +} + +// WriteTransaction.WriteUnit updates the row of a unit. For a unit with no row the +// UPDATE changed nothing and the write was still reported, with the unit file +// renamed into place at commit: a file no row points at. +func TestWriteUnit_AUnitWithNoRowIsRefusedAndNoFileIsLeftBehind(t *testing.T) { + const ghostID = "cccccccc-bbbb-cccc-dddd-eeeeeeeeeeee" + w, _ := newV2WriterForCommitTest(t, existingUnitID, unitDoc(t, "First")) + seedTransactionTable(t, w, "the-original-transaction") + + wt, err := w.BeginWriteTransaction() + if err != nil { + t.Fatal(err) + } + err = wt.WriteUnit(ghostID, unitDoc(t, "Ghost")) + if err == nil || !strings.Contains(err.Error(), "has no row") { + _ = wt.Rollback() + t.Fatalf("WriteUnit of a unit with no row: error = %v, want a has-no-row error", err) + } + if rerr := wt.Rollback(); rerr != nil { + t.Fatalf("rollback: %v", rerr) + } + if _, serr := os.Stat(unitFilePath(w.reader.contentsDir, uuidToBlob(ghostID))); serr == nil { + t.Error("a unit file was left behind for a unit with no row") + } +} + +// A unit that has a row is written as before. +func TestWriteUnit_AUnitWithARowStillWrites(t *testing.T) { + w, unitPath := newV2WriterForCommitTest(t, existingUnitID, unitDoc(t, "First")) + seedTransactionTable(t, w, "the-original-transaction") + next := unitDoc(t, "Next") + + wt, err := w.BeginWriteTransaction() + if err != nil { + t.Fatal(err) + } + if err := wt.WriteUnit(existingUnitID, next); err != nil { + _ = wt.Rollback() + t.Fatalf("WriteUnit of a unit with a row: %v", err) + } + if err := wt.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } + got, rerr := os.ReadFile(unitPath) + if rerr != nil || string(got) == string(unitDoc(t, "First")) { + t.Errorf("the unit file was not rewritten (err %v)", rerr) + } +} diff --git a/modelsdk/mpr/writer_insert_guard.go b/modelsdk/mpr/writer_insert_guard.go new file mode 100644 index 000000000..2653c80ff --- /dev/null +++ b/modelsdk/mpr/writer_insert_guard.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 + +package mpr + +import ( + "database/sql" + "fmt" + "os" +) + +// requireUnitRow turns an UPDATE of a unit that matched no row into an error. +// WriteTransaction.WriteUnit updates the row of a unit it was given; for a unit +// with no row the UPDATE changed nothing, silently, while the unit file was +// still renamed into place at commit: a file no row points at, reported as +// written. +func requireUnitRow(res sql.Result, unitID string) error { + if n, err := res.RowsAffected(); err == nil && n == 0 { + return fmt.Errorf("unit %s has no row in the Unit table; nothing was written", unitID) + } + return nil +} + +// unitRowExists reports whether the Unit table already has a row for the unit. +func (w *Writer) unitRowExists(unitIDBlob []byte) bool { + var n int + if err := w.reader.db.QueryRow(`SELECT COUNT(*) FROM Unit WHERE UnitID = ?`, unitIDBlob).Scan(&n); err != nil { + return false + } + return n > 0 +} + +// refuseExistingUnit is the up-front check of insertUnit: a UnitID that already +// has a row cannot be inserted, and is refused before anything is written, with +// a message that says so. writeNewUnitV2 is what holds when two writers pass +// this check together. +func (w *Writer) refuseExistingUnit(unitID string, unitIDBlob []byte) error { + if w.unitRowExists(unitIDBlob) { + return fmt.Errorf("unit %s already exists; nothing was written", unitID) + } + return nil +} + +// writeNewUnitV2 inserts the row of a new MPR v2 unit and writes its file as one +// step: BEGIN; INSERT; write the file; COMMIT. +// +// The INSERT comes before the write because the primary key is what says whether +// the UnitID is free. A writer that loses the race fails here, with nothing +// written, so it can no longer overwrite (and then delete) the file of the unit +// that won. Once the INSERT has succeeded this transaction holds SQLite's write +// lock, so no other writer can claim the UnitID, or write the file at this path, +// until the COMMIT. +// +// A crash leaves what the old order left: before the COMMIT the row is rolled +// back and at worst the file is an orphan that no row points at (which an insert +// of the same UnitID replaces); there is never a row whose file was not written. +func (w *Writer) writeNewUnitV2(unitIDBlob, containerIDBlob []byte, containmentName, filePath string, contents []byte, hash string) error { + tx, err := w.reader.db.Begin() + if err != nil { + return err + } + if _, err := tx.Exec(` + INSERT INTO Unit (UnitID, ContainerID, ContainmentName, TreeConflict, ContentsHash, ContentsConflicts) + VALUES (?, ?, ?, 0, ?, '') + `, unitIDBlob, containerIDBlob, containmentName, hash); err != nil { + _ = tx.Rollback() + return err + } + if err := os.WriteFile(filePath, contents, 0644); err != nil { + // No row points at this path (the INSERT is ours and uncommitted), so + // whatever was written is an orphan. Remove it while the lock is held. + os.Remove(filePath) + _ = tx.Rollback() + return fmt.Errorf("failed to write unit file: %w", err) + } + if err := tx.Commit(); err != nil { + os.Remove(filePath) + return err + } + return nil +}