From 50ee0649a8f4bae69a053295791cd99f02eb5130 Mon Sep 17 00:00:00 2001 From: italo-kalil Date: Wed, 2 Dec 2026 19:19:20 -0400 Subject: [PATCH 1/4] fix(mpr): refuse inserting a UnitID that already has a row before touching its file insertUnit wrote the unit file and only then inserted the row. For a UnitID that already had a row, the write replaced the existing unit's file, the INSERT then failed on the primary key, and the clean-up removed the file it believed it had just written: the row stayed and its file was gone. The UnitID is now checked first and refused with 'unit already exists; nothing was written', and the clean-up after a failed INSERT leaves the file alone when a row for the unit exists (another writer got in between the check and the INSERT). A new UnitID, and a delete followed by an insert of the same ID (create or modify), insert as before. The tests fail without the change: the existing unit's file is gone and the error is the raw constraint error. Co-Authored-By: Claude Sonnet 5.5 --- modelsdk/mpr/writer_core.go | 11 +- .../mpr/writer_insert_existing_unit_test.go | 100 ++++++++++++++++++ modelsdk/mpr/writer_insert_guard.go | 38 +++++++ 3 files changed, 147 insertions(+), 2 deletions(-) create mode 100644 modelsdk/mpr/writer_insert_existing_unit_test.go create mode 100644 modelsdk/mpr/writer_insert_guard.go diff --git a/modelsdk/mpr/writer_core.go b/modelsdk/mpr/writer_core.go index 130107d8e..9fe625c64 100644 --- a/modelsdk/mpr/writer_core.go +++ b/modelsdk/mpr/writer_core.go @@ -600,6 +600,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 @@ -633,8 +639,9 @@ func (w *Writer) insertUnit(unitID, containerID, containmentName, unitType strin VALUES (?, ?, ?, 0, ?, '') `, unitIDBlob, containerIDBlob, containmentName, hash) if err != nil { - // Clean up the file we just wrote — otherwise it becomes an orphan - os.Remove(filePath) + // Clean up the file we just wrote — otherwise it becomes an orphan — + // unless a row for this unit exists now: that row's file is this path. + w.removeFileOfFailedInsert(unitIDBlob, filePath) 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..c1e93e87e --- /dev/null +++ b/modelsdk/mpr/writer_insert_existing_unit_test.go @@ -0,0 +1,100 @@ +// 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, and an orphan file left by a crashed insert (a file +// with no row) is replaced, as before. +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 fallback when the row appears between the check and the INSERT (another +// writer got there first): the INSERT fails, and the file must not be removed, +// because the row that won points at it. +func TestInsertUnit_AFailedInsertDoesNotRemoveTheFileOfARowThatExists(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") + + // The up-front check cannot be skipped from outside, so the clean-up decision + // is called directly: with a row for the unit it must leave the file alone, + // with no row it must remove the orphan. + if !w.unitRowExists(uuidToBlob(existingUnitID)) { + t.Fatal("unitRowExists does not see the seeded row") + } + w.removeFileOfFailedInsert(uuidToBlob(existingUnitID), unitPath) + if _, err := os.Stat(unitPath); err != nil { + t.Errorf("the file of an existing row was removed by the clean-up: %v", err) + } + orphan := unitPath + ".orphan" + if err := os.WriteFile(orphan, []byte("x"), 0644); err != nil { + t.Fatal(err) + } + w.removeFileOfFailedInsert(uuidToBlob("cccccccc-bbbb-cccc-dddd-eeeeeeeeeeee"), orphan) + if _, err := os.Stat(orphan); err == nil { + t.Error("the clean-up kept a file that no row points at") + } +} diff --git a/modelsdk/mpr/writer_insert_guard.go b/modelsdk/mpr/writer_insert_guard.go new file mode 100644 index 000000000..d86093eb8 --- /dev/null +++ b/modelsdk/mpr/writer_insert_guard.go @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: Apache-2.0 + +package mpr + +import ( + "fmt" + "os" +) + +// 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 must be refused before anything is written, +// because the unit file of that row lives at the very path the insert would write. +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 +} + +// removeFileOfFailedInsert removes the file an insert wrote when its INSERT then +// failed, so that it does not stay behind as an orphan. It leaves the file alone +// when a row for the unit exists now: that row (another writer's, which got in +// between the check and the INSERT) points at this path. +func (w *Writer) removeFileOfFailedInsert(unitIDBlob []byte, filePath string) { + if w.unitRowExists(unitIDBlob) { + return + } + os.Remove(filePath) +} From 7de9a52a20252d203173d17691f8f064b1d4bad1 Mon Sep 17 00:00:00 2001 From: italo-kalil Date: Wed, 2 Dec 2026 19:19:21 -0400 Subject: [PATCH 2/4] changelog: note that inserting an existing UnitID keeps the unit file Cites #2036. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 176950439..6faff9ff1 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"), and a failed insert only removes a file that no row points at. Two writers inserting the same ID at the same moment can still reach the INSERT together; that window is closed only by the opt-in optimistic writes proposed in #2035. ## [0.34.0] - 2026-11-27 From 98933ff7e7765e3948fb335b7a6daeef60deab69 Mon Sep 17 00:00:00 2001 From: italo-kalil Date: Wed, 2 Dec 2026 19:40:30 -0400 Subject: [PATCH 3/4] fix(mpr): insert the row before writing the file, so the loser of an insert race never touches it The up-front check refuses a UnitID that already has a row, but two writers can pass it together. insertUnit wrote the file first, so the loser still replaced the winner's file before its INSERT failed. The row is now inserted first, in a transaction (BEGIN; INSERT; write the file; COMMIT): the primary key decides who owns the UnitID, the loser fails at the INSERT with nothing written, and the winner's transaction holds the write lock until its file is on disk. A file that cannot be written rolls the row back, and a crash leaves what the old order left, at worst an orphan file that no row points at. The test that calls the new step for an existing UnitID fails with the old order (the winner's file is gone). Co-Authored-By: Claude Sonnet 5.5 --- modelsdk/mpr/writer_core.go | 31 +++--- .../mpr/writer_insert_existing_unit_test.go | 105 ++++++++++++++---- modelsdk/mpr/writer_insert_guard.go | 62 +++++++++-- 3 files changed, 151 insertions(+), 47 deletions(-) diff --git a/modelsdk/mpr/writer_core.go b/modelsdk/mpr/writer_core.go index 9fe625c64..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. @@ -627,21 +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 — - // unless a row for this unit exists now: that row's file is this path. - w.removeFileOfFailedInsert(unitIDBlob, 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 index c1e93e87e..5d9f74468 100644 --- a/modelsdk/mpr/writer_insert_existing_unit_test.go +++ b/modelsdk/mpr/writer_insert_existing_unit_test.go @@ -50,8 +50,7 @@ func TestInsertUnit_AnExistingUnitIDIsRefusedAndTheUnitIsLeftAlone(t *testing.T) } } -// A new UnitID still inserts, and an orphan file left by a crashed insert (a file -// with no row) is replaced, as before. +// 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")) @@ -70,31 +69,99 @@ func TestInsertUnit_ANewUnitIDStillInserts(t *testing.T) { } } -// The fallback when the row appears between the check and the INSERT (another -// writer got there first): the INSERT fails, and the file must not be removed, -// because the row that won points at it. -func TestInsertUnit_AFailedInsertDoesNotRemoveTheFileOfARowThatExists(t *testing.T) { +// 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) - // The up-front check cannot be skipped from outside, so the clean-up decision - // is called directly: with a row for the unit it must leave the file alone, - // with no row it must remove the orphan. - if !w.unitRowExists(uuidToBlob(existingUnitID)) { - t.Fatal("unitRowExists does not see the seeded row") + 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") } - w.removeFileOfFailedInsert(uuidToBlob(existingUnitID), unitPath) - if _, err := os.Stat(unitPath); err != nil { - t.Errorf("the file of an existing row was removed by the clean-up: %v", err) + got, readErr := os.ReadFile(unitPath) + if readErr != nil { + t.Fatalf("the winner's file is gone: %v", readErr) } - orphan := unitPath + ".orphan" - if err := os.WriteFile(orphan, []byte("x"), 0644); err != nil { + 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) } - w.removeFileOfFailedInsert(uuidToBlob("cccccccc-bbbb-cccc-dddd-eeeeeeeeeeee"), orphan) - if _, err := os.Stat(orphan); err == nil { - t.Error("the clean-up kept a file that no row points at") + 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 index d86093eb8..2653c80ff 100644 --- a/modelsdk/mpr/writer_insert_guard.go +++ b/modelsdk/mpr/writer_insert_guard.go @@ -3,10 +3,23 @@ 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 @@ -17,8 +30,9 @@ func (w *Writer) unitRowExists(unitIDBlob []byte) bool { } // refuseExistingUnit is the up-front check of insertUnit: a UnitID that already -// has a row cannot be inserted, and must be refused before anything is written, -// because the unit file of that row lives at the very path the insert would write. +// 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) @@ -26,13 +40,41 @@ func (w *Writer) refuseExistingUnit(unitID string, unitIDBlob []byte) error { return nil } -// removeFileOfFailedInsert removes the file an insert wrote when its INSERT then -// failed, so that it does not stay behind as an orphan. It leaves the file alone -// when a row for the unit exists now: that row (another writer's, which got in -// between the check and the INSERT) points at this path. -func (w *Writer) removeFileOfFailedInsert(unitIDBlob []byte, filePath string) { - if w.unitRowExists(unitIDBlob) { - return +// 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 } - os.Remove(filePath) + 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 } From e776bd454858c3d60c9a91845325e1ca79d860e3 Mon Sep 17 00:00:00 2001 From: italo-kalil Date: Wed, 2 Dec 2026 19:40:32 -0400 Subject: [PATCH 4/4] changelog: the insert race and the unit without a row Updates the entry for #2036. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6faff9ff1..01d097ff1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -104,7 +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"), and a failed insert only removes a file that no row points at. Two writers inserting the same ID at the same moment can still reach the INSERT together; that window is closed only by the opt-in optimistic writes proposed in #2035. +- **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