Repository navigation
exec: opt-in optimistic unit writes (MXCLI_OPTIMISTIC_WRITES=1) - #2035
Draft
italo-kalil-cesar wants to merge 4 commits into
Draft
italo-kalil-cesar wants to merge 4 commits into
italo-kalil-cesar wants to merge 4 commits into
Conversation
The project write lock keeps two mxcli processes apart, but a writer that does not take it can replace a unit between the moment a script read it and the moment the script writes it back, and the script's write then discards that change with no error (mendixlabs#2015). Writer.SetOptimisticUnitWrites(true) makes the rewrite of an MPR v2 unit a compare-and-swap: BEGIN, UPDATE Unit SET ContentsHash = new WHERE ContentsHash = <hash of the bytes first read>, write a temp file of the writer's own, rename it over the unit, COMMIT. A write over a changed unit fails with a *UnitConflictError and writes nothing; a failed rename rolls the transaction back, and a failed COMMIT puts the old file back. The rename comes before the COMMIT so a kill in between leaves the whole write on disk under a stale hash (settled by `mxcli fix hashes`), not a hash for bytes that are not there. The reader records the hash of the first bytes it returns for each unit (computed from the bytes, not copied from the row) and drops them when it drops its views of the disk, except for a unit whose bytes are held in memory by a deferred run: its write is built on what was read before the hold, and the flush must compare with that. Temp files are unique per process and writer, and ones older than an hour left by a killed writer are swept. Off by default: when off, updateUnit takes the path it always took. MPR v1 is not covered and the option has no effect there. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
TestOptimisticAcrossProcesses re-executes the test binary as two processes that rewrite one unit of a copy of testdata/pedapp, with the option off and on, with and without the project write lock, and counts the writes reported as done that are missing from the final unit. It asserts that the option loses none and that the lock variants lose none; the loss of the unprotected path is logged, not asserted. Opt-in (MPR_RACE_ITERS=100), because it spawns processes and takes minutes. TestCrashedWrite_* make the two states a kill between the unit file and its hash can leave (bytes new / hash old, and the reverse) and check that `fix hashes` finds both, that its repair keeps the write in the first and drops it in the second, and that an optimistic write refuses both until repaired. BenchmarkUnitWrite compares a write with the option off and on. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…t exits 75 The model backend sets Writer.SetOptimisticUnitWrites when the environment variable is 1, so exec, -c and the REPL get it with no new flag; on an MPR v1 project it says that it has no effect. A *UnitConflictError stops an exec with exit code 75 (EX_TEMPFAIL, as for a busy project) and does not roll the script back: the journal restores the whole .mpr as the run found it, which would erase what the other writer committed, so the statements before the failing one stay applied and the message says so. -c exits 75 too. Tests: an in-process exec whose domain model is changed by a second connection between its read and its write is refused with the other change intact and the ContentsHash index consistent. Opt-in with a built binary (MXCLI_OPT_BIN): two piped sessions writing one module without the lock lose entities silently with the option off and report every one with it on; two execs behind the lock are unaffected either way; an exec against a lock-free writer exits 75 and loses none of that writer's commits. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
What it is, that it is opt-in with no flag, what it covers and what it does not (MPR v1, inserts and deletes, Studio Pro not tested), and that a conflict stops exec with exit 75 without rolling back (mendixlabs#2015). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Refs #2015
Opened as a draft on purpose. #2015 has had no answer yet, so whether this direction is wanted is the open question, and the Studio Pro validation below is NOT done. Nothing here changes the default: the option is off unless
MXCLI_OPTIMISTIC_WRITES=1is set.What was wrong
The project write lock (
.mxcli/write.lock, ako#2326) keeps two mxcli processes from writing at once. It does not stop a writer that does not take it (a second tool, a script that bypasses it, Studio Pro) from replacing a unit between the moment a script read that unit and the moment it writes it back. The script's write then discards the other change and reports success.Measured on a copy of
testdata/pedapp(MPR v2), two processes each rewriting the same unit 100 times, no lock (Windows/NTFS, one machine, so treat the numbers as a size, not a constant):About a third of what was reported as done was gone, and the ordinary path also failed with rename errors ("being used by another process") on
<unit>.mxunit.tmp, a path that is the same for every process.What changes
Four commits.
mpr: optimistic unit writes, a compare-and-swap on ContentsHash (opt-in).Writer.SetOptimisticUnitWrites(true)makes the rewrite of an MPR v2 unit: BEGIN;UPDATE Unit SET ContentsHash = <new> WHERE UnitID = ? AND ContentsHash = <hash of the bytes first read>; write a temp file of the writer's own (process id and a counter in the name); keep the old file as a hard link; rename the temp over the unit; COMMIT (the_Transactionbump is in the same transaction). No row changed:*UnitConflictError, nothing written. A failed rename rolls the transaction back; a failed COMMIT puts the old file back. Temp and kept-old files older than an hour (a killed writer) are swept.WriteTransaction.Commit. Killed between them, SQLite discards the uncommitted UPDATE and the unit has the new bytes under the old hash: the whole write is on disk and only the index is stale (fix hasheskeeps it, andexecalready warns about drift). Claiming the row first and renaming afterwards closes the race just as well but leaves the opposite state, a hash for bytes that are not there, whichfix hashescan only settle by dropping the write.updateUnittakes the path it always took; the new code is not reached.mpr: cross-process test and benchmark for optimistic unit writes.exec: MXCLI_OPTIMISTIC_WRITES=1 turns optimistic writes on; a conflict exits 75. The model backend turns the option on when the variable is1(no CLI flag: that is a maintainer decision). A conflict stopsexecwith exit 75 (EX_TEMPFAIL, as for a busy project) and does NOT roll the script back, because the journal restores the whole.mpras the run found it, which would erase what the other writer committed. The statements before the failing one stay applied and the message says so.-cexits 75 too. In the piped/interactive session the refused write is an error line ("did not take effect") and the session goes on, as for any other statement error. This "no rollback" choice is the one I am least sure of.docs: ...: a section in Script Files and the CHANGELOG entry.Error text:
MPR v1: the option has no effect (a v1 unit write is already a single UPDATE and there is no recorded read to compare with); mxcli prints a note once.
Tests
modelsdk/mpr/writer_optimistic_test.go: a control (without the option the second write wins silently); the second writer is refused and the first kept, row hash and directory untouched; the refused writer can write after looking at the disk again; a read after the other write is not stale; a writer's own successive writes are not conflicts; the first read, not the reconcile read, is the base; a never-read unit is not refused (stated limit); a unit deleted by another writer is a conflict; no-conflict result is byte-for-byte what the ordinary path leaves (file and hash); the temp file is not the shared one; stale temp files are swept and fresh ones kept; a rename that fails rolls everything back; a COMMIT that fails (forced with another connection's read lock) puts the old file back; v1 has no effect; a held (deferred) write keeps its base when the session looks at the disk (found by the two-process test below; fails without the fix).writer_optimistic_crash_test.go: the two states a kill can leave (bytes new/hash old, and the reverse):fix hashesfinds both, its repair keeps the write in the first and drops it in the second, and an optimistic write refuses both until repaired.cmd/mxcli/exec_optimistic_conflict_test.go: anexecwhose domain model is changed by a second connection between its read and its write is refused with exit 75, the other change intact, "Not rolled back" in the message, the first statement kept, and a consistent ContentsHash index.MXCLI_OPT_BIN=... go test ./cmd/mxcli -run TestOptimisticBinary -v): two piped sessions (no write lock) writing 40 entities each into one module; twoexecprocesses behind the lock; oneexecagainst a lock-free writer inside the test.TestOptimisticAcrossProcesses(MPR_RACE_ITERS=100): see Proof.Proof
Windows 11 / NTFS, one machine,
modelsdk/mprtest binary re-executed as two processes, 100 attempts each, one unit of a copy oftestdata/pedapp, read-modify-write of one field per attempt. "lost" = writes that returned success but are not in the final unit.A second full run on the same machine gave: option off, no lock 188 done / 42 lost / 12 errors (66 lost / 14 errors with the 5 ms gap); option ON, no lock 107 done / 0 lost / 93 conflicts / 0 errors (105 / 0 / 95 / 0 with the gap); with the lock, 0 lost both ways. The unprotected loss moves between about 40 and 70 of ~190 from run to run; the protected one was 0 in every run. In a few of the lock rows one acquisition of the lock itself failed with "Access is denied" (1 in 200), which is the lock file, not this change (see Not covered).
With the real binary (piped sessions without the lock, 40
create entitystatements each into one module; 8 repetitions): with the option off, 33 to 41 of ~80 entities reported created were missing at the end and only 5 to 17 failures were reported (the rest silent). With it on, every missing entity had a reported failure (missing = reported in 8 of 8 runs). Twoexecprocesses behind the lock: 80 of 80 present, exit 0, with the option off or on.execagainst a lock-free writer committing every few milliseconds: exit 75 in every run, none of that writer's commits lost, ContentsHash index consistent.Cost per unit write,
BenchmarkUnitWrite(300 writes, 3 runs): off 13.8 / 14.8 / 16.3 ms, option on 12.0 / 11.8 / 16.2 ms. Within the noise of the machine; the option is not slower (it commits the hash and the transaction id once instead of twice, which is probably why, not measured separately).Not proven by these numbers: Linux or macOS (the test is portable and was only run on Windows), a larger project, or any behavior of Studio Pro. A refused write can be one that would have been safe: the base is the first read, and a backend that reads the unit again itself (creating an entity does) is refused when the unit changed after the first read. The check is conservative; a refused write is re-run, never lost.
Run locally
No
make, Docker,ghor cgo on the machine; equivalents by hand on Windows:go build ./modelsdk/... ./mdl/backend/... ./cmd/mxcli(after generating the grammar) - ok, at each of the four commits.go vet ./modelsdk/mpr ./cmd/mxcli ./mdl/backend/modelsdk- clean;gofmt -lon the touched directories - empty.go test ./modelsdk/mpr -count=1: the only failures are the 12 that fail identically on a clean main on Windows (TestCacheUnitReads_*,TestUnitStore_*cleanup of an open SQLite file,TestSyncWithDisk_Issue2121; fixed by test(mpr): close the readers the test helpers open, so unit-contents.db can be removed on Windows #2016). All new tests pass,-count=3for the new unit tests.go test ./mdl/backend/modelsdk -run 'Connect|Reconnect|Disconnect|SyncWithDisk|Writer'- ok.go test ./cmd/mxcli -run 'TestExec|TestRunScript|TestOneLiner|TestRunCommandLine|ProjectWriteLock'- ok. The whole./cmd/mxcliand./mdl/executorpackages were not run (too slow on this machine); CI is the real check for those.MPR_RACE_ITERS=100 go test ./modelsdk/mpr -run TestOptimisticAcrossProcesses -v(about 3.5 minutes) andMXCLI_OPT_BIN=<binary> go test ./cmd/mxcli -run TestOptimisticBinary -count=8- pass.make check-conformance,check-findings,check-test-timeouts,lint-go: not run.Studio Pro validation
NOT DONE. Whether Studio Pro notices a unit written this way, keeps
ContentsHashcurrent when it saves (the check cannot see its writes if it does not), or overwrites the unit on its next save is unknown. Writes are still refused while Studio Pro has the project open unless--force. I have a test plan for Studio Pro 10.24.4 (three scenarios: mxcli writing with the project open, Studio Pro saving in a loop while mxcli writes, and the two on-disk states a kill between file and hash can leave) and will report the result here; this stays a draft until then.Agentic testing
Not run.
Not covered
WriteTransaction(used bycodec.Store); a write of a unit the writer never read before (nothing to compare).execkeeps the statements before the failing one instead of rolling back (rolling back would restore the.mprover the other writer's save). A batch runner that shares the journal (feat(exec): apply several MDL scripts in one run (all or nothing, plan first, --skip-failed) #2020's savepoints) needs the same exemption when it lands.<unit>.mxunit.tmp, a name shared by every process. Making it per-writer there would be a change of default behavior; left for a separate decision.execcan print the ContentsHash drift warning for a moment while another optimistic writer is between the rename and the COMMIT of a unit.projectlock.Acquirereturned "Access is denied" once in about 200 acquisitions on Windows under heavy contention (a lock file pending deletion is reported as access denied, not as existing).