Skip to content

bug(mpr): inserting a unit whose UnitID already exists overwrites and then deletes the existing unit's file (row kept, file gone) #2036

Backlog

Description

@italo-kalil-cesar

Version

mxcli main at 9128126 (Windows). Found while adding tests for concurrent writers; confirmed at the Go level, not from the CLI.

What happens

Writer.insertUnit (modelsdk/mpr/writer_core.go, MPR v2 branch) writes the unit file first and only then inserts the row:

if err := os.WriteFile(filePath, contents, 0644); err != nil { ... }
// Insert reference to database
_, err := w.reader.db.Exec(`INSERT INTO Unit (UnitID, ...) VALUES (...)`, ...)
if err != nil {
    // Clean up the file we just wrote - otherwise it becomes an orphan
    os.Remove(filePath)
    return err
}

If a unit with that UnitID already exists, the INSERT fails on the primary key, but by then os.WriteFile has already replaced the existing unit's file, and the clean-up removes it. The existing row stays and its file is gone. The comment says the file is "the file we just wrote", but when the unit already existed it is the other unit's file.

Reproduction (Go level)

With one Writer on a copy of testdata/pedapp: insertUnit a new unit; insertUnit the same UnitID again with different contents. Result: the second call returns the primary-key error, SELECT COUNT(*) FROM Unit WHERE UnitID = ? is still 1, and the unit file no longer exists (it was 74 bytes before). The same happens with two writers (two processes) creating one UnitID.

Expected

A failed INSERT leaves the existing unit untouched: check that the row does not exist before writing, or write to a temporary name and rename after the INSERT succeeds, or remove the file only if this call created it.

How likely is it

I do not know how often a real script reaches it. mxcli draws random UnitIDs, so two scripts creating the same ID needs a deterministic ID, a repeated insert of an existing ID by some code path, or an external writer. The consequence when it happens is a row without a file, which is the kind of state mxcli fix hashes reports as drift. Not tested on a real project, not tested in Studio Pro.

What I can do

I have a fix in mind (guard before the write, keeping the orphan clean-up only for a file this call created) with a test that fails today. Tell me if you want it as a PR. A related set of changes for concurrent writers is in the draft #2035 (opt-in, off by default), which also covers this case under its option; this issue is about the default path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions