diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 9219a32..be4908c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -228,6 +228,15 @@ jobs: make ${{ matrix.make }} dist/loadable echo 'set -e; cd /data/local/tmp; export TMPDIR=/data/local/tmp; ./loadable ./multiwriter.so; echo EXIT_CODE=0' > dist/commands.sh + # The runner has /dev/kvm but not for the runner's user: without it the action runs the emulator with -accel off, which the emulator refuses since version 37 ("Software CPU + # emulation (-accel off) is not supported"). With KVM the emulator is accelerated (the setup that the action documents). + - name: android emulator - enable KVM + if: matrix.test == 'emulator' + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + - name: android emulator - run if: matrix.test == 'emulator' uses: reactivecircus/android-emulator-runner@v2.34.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index ce75a9a..d5cf14c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,29 @@ All notable changes of sqlite-multiwriter are recorded here, newest first. The version is `MW_VERSION` in `src/multiwriter.h`; a version that is not released yet is pushed to `main` and released by the CI. The format of the files on disk (`-mwlock`, `-mwidx`, `-mw.N`, `-mw`) is the same in the versions listed here. +## 0.7.0 - 2026-11-27 + +### Changed +- **Speculative snapshots of the writers** (one process). A write transaction (its first statement writes, or `BEGIN IMMEDIATE`/`EXCLUSIVE`) reads at the newest *installed* commit instead of the newest durable one, and is still acknowledged only when its own record is durable (the log is durable as a prefix, so never without the commits it read). Commits that depend on each other, above all inserts with the rowid that SQLite picks (each one takes the key after the last one it sees), used to follow each other one fsync at a time: with 24 writers and an fsync of about 3 ms, 333 tx/s, p99 694 ms, 545 retries per 100 tx; now 2,547 tx/s, p99 20 ms, 7 retries (the workload of the external comparison "SQLite vs WAL vs Turso MVCC vs sqlite-multiwriter", `bench/events_bench.c`, `MW_FULLFSYNC=1` on this Mac). A transaction that does not write reads only durable commits as before; one that read speculatively and ends without a commit waits until what it read is durable; a commit whose record could not be written is taken back and the transactions that read it are refused (`SQLITE_BUSY_SNAPSHOT`). URI `mw_spec=0` turns it off for a connection, `MW_NO_SPEC=1` for the process (the default stays on). The processes mode is unchanged. +- The rebase: its helper reads speculatively too (at least what the transaction it replays read), and the publication gate that it closes after a lost replay waits until every assigned commit is installed, not durable (waiting for their fsync held every publisher: `samepage` with the rebase, 64 threads on Linux, 15.5k -> 20.6k tx/s against 17.6k before this change). +- Hot spots (one process): with speculative snapshots the turn is taken after the first refusal (it was after 16) and given back as soon as the commit is installed or conflicts (it was at the end of the transaction, after the fsync). Retries per 100 tx of the appends above: 131-143 -> 7 with a fast fsync, 105-111 -> 13-18 with `synchronous=OFF`, and the p99.9 latency 60-175 ms -> 2-56 ms. +- `mw_bench`, threads, `synchronous=FULL`, 4/16/64 writers: `hot` +9%..+160%, `groups`, `samepage`, `cols`, `insert-autoinc`, `crdtinsert` without the rebase +13%..+500%, with it mostly higher too; `bulk`, `independent`, `mixed` unchanged (within ±5%). Lower: `samepage` with the rebase at 4-16 writers on macOS (-9..-11%: more commits take the fast path, one fsync each, instead of the batched replays). On Linux (Docker, fsync about 0.3 ms) the contended workloads go from 1-4k to 17-34k tx/s (the engine without the change collapses under contention), the appends of the comparison with 24 writers from 1,820 to 7,625 tx/s; with no durable fsync (tmpfs, `synchronous=OFF`) they are 3-7% slower from 8 writers up, with a p99 4-5 times lower. + +### Fixed +- **Processes mode: a commit could be acknowledged without an fsync of the log.** A committer that becomes the leader of the group sync and finds its own record made durable already (by the leader before it, which finished between its look and its turn) syncs nothing, but it still moved the durable point to the end of the log as it read it, after the others had installed more records: those were acknowledged with nothing synced, and a power failure could lose them. It now moves the durable point only after its own `msync` and `fsync`. Found by `mw_syncwindow` in the CI (linux-x86_64, about 1 run in 20 on a Linux of 4 CPUs, also before 0.7); its new scenario 3 (`MW_TEST_SYNC_PRELEAD_US`: a delay before a committer tries to be the leader) shows it in every run: 459-531 of 800 commits acknowledged without a sync with the old code, 0 now. +- A data race that ThreadSanitizer built with gcc reported in `mw_log_rewrite_prepare` against `lane_publish` (the tests `mw_rebasewr` and `mw_rebasefkstress`, about 7 runs in 8 on Linux arm64): gcc read the flags `mp_req`, `mp` and `has_log` with one 8-byte load that took in the atomic counter `inflight` next to them. The atomics that follow plain fields of the database (`inflight`, `open_done`) start a word of their own. The CI builds with clang, which reads the flags one by one, and did not see it. + +- Test `mw_multiproc`, scenario 4: the process to kill was killed 150 ms after it was started, and on a slow machine (ThreadSanitizer in a Linux container: 1 run in 15) it had not committed anything yet (`killed > 0` failed). It is killed once it has acknowledged 50 commits (through a pipe, at most a minute), as `mw_procs` does since 0.6.3. Under ThreadSanitizer the test also needs `llvm-symbolizer`: without it the race of SQLite on `randomnessPid` in the children is not matched by `test/tsan.supp`, and the children exit with 66. + +- The build has no warnings with gcc 12 (Linux), clang (macOS, Linux) and MinGW-w64: lines with several `if` on one line (`multiwriter_shidx.c`, `multiwriter_shared.c`, `mw_reloc`) are split; `install_impl` of the shared index refuses a negative count of pages (gcc could not exclude that its allocations wrap) and the repair of a commit that a publisher left half installed initialises its arrays; in the tests, a buffer of `mw_diskfull` that could truncate a command, values that `mw_ioerr` printed uninitialised, a counter that `mw_sharedwindow` did not use, variables of `mw_serial` used only outside Windows. +- CI: the job of the Android x86_64 emulator gives the runner's user access to `/dev/kvm`. Without it the emulator ran with `-accel off`, which the emulator refuses since version 37 (the action installs the latest): the emulator never started and the job timed out. +- Test `mw_relocprep`, scenario 1: it must exercise the rewrite of a prepared relocation, which needs threads that overlap; under ThreadSanitizer on a runner of 4 CPUs one run had 5 relocations and none rewritten. The scenario runs again, up to three times, until a rewrite happens (the data are checked every time). +- `mw_multiproc` printed its lines more than once under ThreadSanitizer: each child wrote again what the parent had printed and not yet flushed. The parent flushes before it forks. + +### Added +- `bench/events_bench.c` (`make bench`): the workload of the external comparison (100 inserts of 64 bytes per transaction with SQLite's rowid and an index, 4 readers, `busy_timeout=5000`, retries counted in the latency). +- Test `mw_spec`: a reader does not see a commit whose fsync is held, a writer does and is acknowledged after it; a commit taken back refuses the writer that read it; dependent appends share the fsyncs. + ## 0.6.5 - 2026-10-31 ### Fixed diff --git a/Makefile b/Makefile index 98b183b..7e0c916 100644 --- a/Makefile +++ b/Makefile @@ -90,6 +90,9 @@ $(DIST)/mw_admitcap$(EXE): $(BUILD)/t_mw_admitcap.o $(filter-out $(BUILD)/multiw $(DIST)/mw_holesync$(EXE): $(BUILD)/t_mw_holesync.o $(filter-out $(BUILD)/multiwriter_log.o,$(LIB_OBJ)) $(BUILD)/inject_fsync.o @mkdir -p $(DIST) $(CC) $^ -o $@ $(LDFLAGS) +$(DIST)/mw_spec$(EXE): $(BUILD)/t_mw_spec.o $(filter-out $(BUILD)/multiwriter_log.o,$(LIB_OBJ)) $(BUILD)/inject_fsync.o + @mkdir -p $(DIST) + $(CC) $^ -o $@ $(LDFLAGS) $(DIST)/mw_stagednormal$(EXE): $(BUILD)/t_mw_stagednormal.o $(filter-out $(BUILD)/multiwriter_log.o,$(LIB_OBJ)) $(BUILD)/inject_log.o @mkdir -p $(DIST) $(CC) $^ -o $@ $(LDFLAGS) @@ -119,7 +122,7 @@ TSAN_TESTS := mw_admitcap mw_appendfail mw_attachsync mw_autoextfail mw_closesta mw_fastcommit mw_format mw_fullfsync mw_gc mw_holesync mw_identity mw_lanes mw_lanetrim mw_logopen mw_logrewrite mw_logswap mw_mapfail mw_mpstale mw_multiproc \ mw_multiproc_crash mw_multiproc_liveness mw_openfail mw_openflags mw_openlocks mw_openrace mw_openrepair mw_oslayer mw_ownepoch mw_procs mw_profile mw_readdeps \ mw_rebase mw_rebasecases mw_rebasefk mw_rebasefkstress mw_rebaseneg mw_rebasenoop mw_rebasepolicy mw_rebaseskew mw_rebasewr mw_recoverread mw_reloc mw_relocprep \ - mw_repairinstall mw_rollback mw_rollbackrace mw_routes mw_rowdiffoom mw_rowid mw_selfcommit mw_shared mw_sharedwindow mw_shidx mw_sizering mw_slotstuck mw_stacked \ + mw_repairinstall mw_rollback mw_rollbackrace mw_routes mw_rowdiffoom mw_rowid mw_selfcommit mw_shared mw_sharedwindow mw_shidx mw_sizering mw_slotstuck mw_spec mw_stacked \ mw_stagedlog mw_stagednormal mw_stalewal mw_store mw_strictany mw_structural mw_syfail mw_syncpragma mw_syncwindow mw_tailscan mw_tempbarrier mw_tempddl mw_ticketring \ mw_trimfail mw_vfs_trace mw_walstatfail mw_warm mw_writeskew .PHONY: test-tsan @@ -141,6 +144,13 @@ $(BUILD)/b_mw_bench.o: bench/mw_bench.c $(HEADERS) $(DIST)/mw_bench$(EXE): $(BUILD)/b_mw_bench.o $(LIB_OBJ) @mkdir -p $(DIST) $(CC) $^ -o $@ $(LDFLAGS) +bench: $(DIST)/events_bench$(EXE) +$(BUILD)/b_events_bench.o: bench/events_bench.c $(HEADERS) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -c $< -o $@ +$(DIST)/events_bench$(EXE): $(BUILD)/b_events_bench.o $(LIB_OBJ) + @mkdir -p $(DIST) + $(CC) $^ -o $@ $(LDFLAGS) include mk/extension.mk include mk/package.mk diff --git a/README.md b/README.md index 7ed97f4..e3e728b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # sqlite-multiwriter -**With 16 threads writing one database, 49,277 transactions per second against 8,630 for SQLite (5.7x), and the slowest 1 in 1000 commits takes 2.08 ms instead of 157 ms.** +**With 16 threads writing one database, 51,558 transactions per second against 8,910 for SQLite (5.8x), and the slowest 1 in 1000 commits takes 1.93 ms instead of 138 ms.** **With 16 processes, 25,987 against 8,636 (3.0x), and 1.54 ms against 233 ms.** SQLite is the most widely used database in the world, and it has one well-known limit: a database accepts only one writer at a time. With many threads, or many processes (several agents working on the @@ -20,13 +20,13 @@ write the same database at once. Every commit is durable, and the file remains a | 16 writers | SQLite tx/s | multiwriter tx/s | Gain | Retries per 100 tx | Slowest 1 in 1000 commits | |---|---:|---:|---:|---:|---:| -| Threads, each inserting its own rows | 8,630 | **49,277** | 5.7x | 189 → **0.2** | 157 → **2.08** ms | -| Threads, own rows on shared pages (with rebase) | 13,562 | **55,098** | 4.1x | 35 → **0** | 584 → **0.93** ms | +| Threads, each inserting its own rows | 8,910 | **51,558** | 5.8x | 156 → **0.0** | 138 → **1.93** ms | +| Threads, own rows on shared pages (with rebase) | 9,788 | **71,788** | 7.3x | 29 → **0** | 760 → **0.87** ms | | Processes, each inserting its own rows | 8,636 | **25,987** | 3.0x | 189 → **0.1** | 233 → **1.54** ms | | Processes, own rows on shared pages (with rebase) | 13,225 | **51,472** | 3.9x | 30 → **0** | 664 → **16.6** ms | -| Threads, all on the same 4 rows | 13,277 | **29,976** | 2.3x | 24 → **17** | 609 → **122** ms | +| Threads, all on the same 4 rows | 10,189 | **73,234** | 7.2x | 30 → **6.1** | 717 → **0.86** ms | -One writer is not slower than SQLite (15,959 against 13,746 tx/s). When writers change the same rows they really conflict: the gain is smaller and the retries stay. +One writer is not slower than SQLite (16,216 against 14,455 tx/s). When writers change the same rows they really conflict: some retries stay, but since 0.7 a connection that lost takes a turn and runs its next transactions on fresh state (rows with threads measured with 0.7.0 on 2026-11-27, rows with processes with 0.6 on 2026-10-09: the processes mode did not change). ## How it works @@ -44,6 +44,22 @@ each other. If another commit got there first on the same page, the transaction loser: it takes the row changes of its transaction and applies them again on top of the latest state, then commits. The application sees no error. A transaction that really conflicts (the same row changed by both) is still refused. The rebase is limited to simple transactions: `INSERT`s and `UPDATE`/`DELETE`s of a row by its key. See Limits. +**Commits that depend on each other** (new in 0.7, `mw_spec`, on by default). A commit is acknowledged only when it is on disk, and it used to become visible to the other connections only then too. That +made a chain of commits that each need the previous one (inserts with the rowid that SQLite picks: each one takes the key after the last one it sees) pay one fsync each, whatever the number of writers. Now +a transaction that writes reads the newest commits that are *installed*, even if their fsync is still running, so a whole chain shares one group fsync: + + before: T1 installed -- fsync -- visible, OK + T2 reads T1 -- installed -- fsync -- OK one fsync per commit + now: T1 installed -- fsync ------------ OK + T2 reads T1 -- installed -- the fsync that covers T1 and T2 -- OK many commits per fsync + +What stays the same: a commit is acknowledged only when it is durable, and the log is durable in order, so a commit is never acknowledged before the ones it read; a transaction that only reads sees only +durable commits; a transaction that read speculatively and ends without writing waits until what it read is durable. The one difference: if the machine crashes before the fsync, a write transaction that +had read the lost commits (and was not acknowledged, since it came after them) may have shown their rows to the application before failing. If a commit cannot be written, it is taken back and the +transactions that read it fail with `SQLITE_BUSY_SNAPSHOT` and are run again. This is what the processes mode (`mw_mp=1`) always did. `mw_spec=0` on a connection, or `MW_NO_SPEC=1` for the whole process, +restores the old behaviour. With it, a connection that lost a conflict takes a turn after its first refusal (it was after 16) and gives it back as soon as its commit is installed: fewer retries and much +shorter tails under contention. + Isolation is snapshot isolation plus validation of the pages a transaction read: if another commit rewrote one of them after the snapshot, the commit is refused, which rules out the usual write skew (`docs/design.md`, "What is guaranteed"). It is tested, not proved serializable. The application must retry a transaction that fails with `SQLITE_BUSY_SNAPSHOT`, the whole transaction. ## Two ways to use it @@ -64,7 +80,7 @@ Every release has the extension for each platform ([releases](https://github.com allows extensions, then open the database with the VFS: .load ./multiwriter -- the sqlite3 shell (multiwriter.so, .dylib or .dll) - SELECT mw_version(); -- 0.6.5 + SELECT mw_version(); -- 0.7.0 From C: @@ -100,16 +116,17 @@ Options (URI parameters, read when the database is opened): |---|---| | `mw` | `1`: the engine, and the default when the URI has `vfs=multiwriter`; `0`: off for that database; any other value fails the open | | `mw_rebase=1` | replay a commit that lost only on shared pages instead of refusing it | +| `mw_spec` | `1` (default): the write transactions read commits that are installed and not yet durable, and commits that depend on each other share one fsync (see How it works); `0`: they read only durable commits, as before 0.7 | | `mw_profile=small` | smaller caches (8 MB of pages, 16 MB of log before compaction), for a phone or a small server | | `mw_log_max_mb` | size of the log before it is compacted into the database | | `mw_fullfsync=1` | `F_FULLFSYNC` for the log and the compaction on macOS | | `mw_readcheck=0` | do not validate the pages a transaction read: fewer retries, but write skew becomes possible | -The complete list is in `docs/design.md`. +Environment variables: `MW_NO_SPEC=1` makes `mw_spec=0` the default for the process; `MW_SHORT_STARVE=n` sets after how many refusals in a row a connection takes the turn of a hot spot (1 with `mw_spec`, 16 without). The complete list is in `docs/design.md`. ### Against stock SQLite, threads -Apple M5 Pro (18 cores, 64 GB, SSD, APFS), SQLite 3.53.4 in WAL mode, `synchronous=FULL`, 8-second runs on a fresh database. "Retries" is how many times, per 100 committed transactions, the application had to +Apple M5 Pro (18 cores, 64 GB, SSD, APFS), SQLite 3.53.4 in WAL mode, `synchronous=FULL`, 8-second runs on a fresh database, version 0.7.0 (2026-11-27). "Retries" is how many times, per 100 committed transactions, the application had to run a transaction again after `SQLITE_BUSY`; the engine refuses a commit that conflicts and the application runs it again, up to 1000 times. Best result of each row in bold. More scenarios and the rows written: `docs/benchmarks.md`. To repeat the runs: `make bench`, then `VARIANTS=mw,mwr,sqlite WORKLOAD=bulk python3 bench/compare_sqlite.py threads out.jsonl 8 1 4 16 64` (`WORKLOAD` is `bulk`, `groups` or `hot`). @@ -117,42 +134,58 @@ run a transaction again after `SQLITE_BUSY`; the engine refuses a commit that co | Threads | SQLite tx/s | retries | multiwriter tx/s | retries | with rebase tx/s | retries | |---:|---:|---:|---:|---:|---:|---:| -| 1 | 13,746 | **0** | **15,959** | **0** | 15,687 | **0** | -| 4 | 9,307 | 128 | **33,258** | **0.0** | 32,898 | **0.0** | -| 16 | 8,630 | 189 | **49,277** | **0.2** | 48,275 | **0.2** | -| 64 | 8,128 | 398 | **45,906** | 1.1 | 45,689 | **1.0** | +| 1 | 14,455 | **0** | **16,216** | **0** | 15,708 | **0** | +| 4 | 9,368 | 108 | **35,539** | **0.0** | 34,444 | **0.0** | +| 16 | 8,910 | 156 | 51,558 | **0.0** | **51,989** | **0.0** | +| 64 | 8,015 | 348 | **47,613** | **0.1** | 45,420 | **0.1** | **Each thread updates its own row, rows share pages** (one row per transaction) | Threads | SQLite tx/s | retries | multiwriter tx/s | retries | with rebase tx/s | retries | |---:|---:|---:|---:|---:|---:|---:| -| 1 | 13,401 | **0** | 34,911 | **0** | **35,885** | **0** | -| 4 | 13,632 | 4.6 | **49,173** | 0.6 | 36,628 | **0** | -| 16 | 13,562 | 35 | 37,789 * | 8.2 | **55,098** | **0** | -| 64 | 13,623 | 132 | **40,012** | 64 | 39,500 | **0** | - -\* a few transactions gave up after 1000 retries. +| 1 | 9,146 | **0** | 31,089 | **0** | **34,439** | **0** | +| 4 | 9,591 | 5.9 | **57,733** | 2.1 | 57,376 | **0** | +| 16 | 9,788 | 29 | **74,440** | 5.2 | 71,788 | **0** | +| 64 | 10,733 | 119 | **60,778** | 5.3 | 58,018 | **0** | **Every thread updates the same 4 rows** (`a = a + 1`): a real conflict, which no engine can merge | Threads | SQLite tx/s | retries | multiwriter tx/s | retries | with rebase tx/s | retries | |---:|---:|---:|---:|---:|---:|---:| -| 1 | 13,770 | **0** | **37,196** | **0** | 32,939 | **0** | -| 4 | 14,248 | 6.7 | **36,895** | **2.5** | 27,225 | 7.6 | -| 16 | 13,277 | 24 | **29,976** | **17** | 28,014 | 34 | -| 64 | 14,057 | 101 | **32,186** | **81** | 26,782 | 142 | +| 1 | 10,056 | **0** | 33,659 | **0** | **35,044** | **0** | +| 4 | 10,143 | 5.7 | 42,882 | 5.9 | **51,020** | **5.5** | +| 16 | 10,189 | 30 | **73,234** | **6.1** | 72,177 | 6.2 | +| 64 | 9,333 | 125 | **61,685** | **5.9** | 60,037 | 6.0 | **Commit latency** (milliseconds, each thread inserting its own rows): time from the start of a transaction to its commit, retries included | Threads | SQLite p50 | p99 | p99.9 | multiwriter p50 | p99 | p99.9 | |---:|---:|---:|---:|---:|---:|---:| -| 1 | 0.07 | 0.09 | 1.26 | **0.06** | **0.08** | **0.13** | -| 4 | 0.21 | 1.54 | 55.8 | **0.11** | **0.24** | **0.69** | -| 16 | **0.23** | 53.9 | 157 | 0.28 | **1.15** | **2.08** | -| 64 | **0.26** | 146 | 271 | 1.18 | **3.97** | **31.4** | +| 1 | 0.06 | 0.08 | 1.17 | **0.06** | **0.08** | **0.11** | +| 4 | 0.21 | 1.57 | 52.0 | **0.10** | **0.19** | **0.66** | +| 16 | **0.22** | 54.4 | 138 | 0.27 | **0.93** | **1.93** | +| 64 | **0.26** | 141 | 253 | 1.14 | **3.39** | **38.4** | SQLite's median can be lower with many writers: a writer that finds the database busy fails at once and the application retries, and the cost shows in the 99.9th percentile. When writers fight over the -same rows the gain is about 2x and the rebase does not help. +same rows the rebase does not help (they really conflict); what keeps their throughput up since 0.7 is the turn: a connection that lost runs its next transactions one after the other on fresh state, and gives +the turn back as soon as its commit is installed, without waiting for the fsync. + +### Commits that depend on each other + +The workload of the external comparison ["SQLite vs WAL vs Turso MVCC vs sqlite-multiwriter"](https://esbencarlsen.substack.com/p/sqlite-vs-wal-vs-turso-mvcc-vs-sqlite), in C (`bench/events_bench.c`, `make bench`): 100 inserts of 64 bytes per +transaction with the rowid that SQLite picks and an index on the writer, 4 readers at the same time, `busy_timeout=5000`, latency with the retries. Every commit takes the key after the last one it sees, so two +concurrent commits always conflict and each needs the one before: before 0.7 such a chain paid one fsync per commit. 24 writers, before (0.6.5) and after (0.7.0, `mw_spec` on): + +| Where | fsync | tx/s | p99 | p99.9 | retries per 100 tx | +|---|---|---:|---:|---:|---:| +| macOS, `MW_FULLFSYNC=1` | ~3 ms | 333 → **2,547** | 694 → **20** ms | 1,043 → **23** ms | 545 → **7.1** | +| macOS, `synchronous=FULL` | fast | 7,978 → **10,180** | 56 → **11** ms | 117 → **56** ms | 143 → **6.8** | +| Linux (Docker, ext4 on the VM's disk) | ~0.3 ms | 1,820 → **7,625** | 145 → **8.6** ms | 247 → **37** ms | 239 → **7.1** | +| Linux, tmpfs | none | **9,935** → 9,262 | 64 → **14** ms | 161 → **22** ms | 113 → **15** | +| Linux, `synchronous=OFF` | none | **9,660** → 9,145 | 62 → **13** ms | 147 → **20** ms | 121 → **13** | + +With a durable fsync the chain now shares one group fsync (8 writers: 314 → 1,075 tx/s, 16: 329 → 1,800 with the fsync of 3 ms). Without one the appends stay serial (each needs the one before): the gain is in +the tails and the retries, and the throughput is 3-7% lower from 8 writers up (`MW_SHORT_STARVE=16` gives the old behaviour of the turn). ## Multi-process @@ -222,7 +255,7 @@ Build one yourself: `make extension [PLATFORM=macos|ios|ios-sim|mac-catalyst|and ## Build and test git clone https://github.com/sqliteai/sqlite-multiwriter && cd sqlite-multiwriter - make test # the test suite (about 50 programs, a few minutes) + make test # the test suite (about 95 programs, a few minutes) make test-mp # the transaction tests with processes (mw_mp=1) make test-io # errors of the file system and a full disk (minutes) make bench # dist/mw_bench; bench/compare_sqlite.py: against stock SQLite @@ -241,6 +274,7 @@ What to know before relying on it (details and measurements in `docs/design.md`) - `PRAGMA data_version` changes with every transaction (also of the connection itself). **Isolation and retries** +- A write transaction may read commits that are installed and not yet durable (`mw_spec`, default on): it is never acknowledged before them, but if the machine crashes before their fsync, rows it showed the application may be gone. `mw_spec=0` turns it off. - Snapshot isolation with first-committer-wins on pages, plus validation of the pages read, which refuses the classic write skew (two transactions that each read what the other writes). It is still possible in three cases: `mw_readcheck=0` (the validation is off), the reads of page 1 (the header of the file: not validated), and transactions on attached databases (not atomic across the files). Serializability is tested, not proved. To protect an invariant that a transaction only reads, make both transactions write a shared row with a real change (`UPDATE guard SET n = n + 1`): they then conflict whatever they read. The application must retry a transaction that fails with `SQLITE_BUSY_SNAPSHOT` (the whole transaction). - A schema change waits up to 2 s for the write transactions of the other connections to end, then goes ahead; a transaction that overlapped it fails on the schema cookie with `SQLITE_BUSY_SNAPSHOT` when it tries to write, and is retried (as a stock WAL reader that tries to write after a commit). A change of the temporary schema does not wait. - Throughput of one database is bounded by the publication of a commit (about 40 us in the processes mode) and by true conflicts: many writers on the same row serialise, and the rebase does not help them. diff --git a/bench/events_bench.c b/bench/events_bench.c new file mode 100644 index 0000000..8f181e4 --- /dev/null +++ b/bench/events_bench.c @@ -0,0 +1,176 @@ +// The workload of the external comparison "SQLite vs WAL vs Turso MVCC vs sqlite-multiwriter" (sqlite-writer-bench), +// in C: W writer threads, one connection each, insert 100 rows of a 64-byte payload per transaction into one table +// with an INTEGER PRIMARY KEY that SQLite assigns (the rowid is not given) and an index on writer_id; 4 reader threads +// run MAX(id) and an indexed lookup with a pause of 1 ms. Every connection: journal_mode=WAL, busy_timeout=5000, +// temp_store=MEMORY, the synchronous of the run. A refused transaction (SQLITE_BUSY, SQLITE_LOCKED, their extended codes) +// is rolled back and run again; its latency includes the retries. +// +// events_bench [--mode mw|wal|delete] [--writers N] [--readers N] [--duration S] [--sync full|normal|off] +// [--rebase 0|1] [--dir D] [--rows R] +// Prints a line of numbers and a JSON line. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "sqlite3.h" +#include "multiwriter.h" + +static const char *g_mode = "mw", *g_sync = "full", *g_dir = "."; +static int g_writers = 8, g_readers = 4, g_duration = 10, g_rebase = 1, g_rows = 100; +static char g_path[512]; +static sqlite3 *g_keep; // the connection of the schema, open for the whole run: the statistics are read from it +static atomic_int g_stop; +static atomic_uint_fast64_t g_tx, g_retries, g_errors, g_reads; + +static uint64_t now_ns (void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; } +static void die (const char *m, sqlite3 *db) { fprintf(stderr, "events_bench: %s: %s\n", m, db ? sqlite3_errmsg(db) : ""); exit(2); } + +static sqlite3 *open_conn (void) { + char uri[700]; sqlite3 *db; + if (!strcmp(g_mode, "mw")) snprintf(uri, sizeof uri, "file:%s?vfs=multiwriter&mw_rebase=%d", g_path, g_rebase); + else snprintf(uri, sizeof uri, "file:%s", g_path); + if (sqlite3_open_v2(uri, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, NULL) != SQLITE_OK) die("open", db); + sqlite3_extended_result_codes(db, 1); + char sql[200]; + snprintf(sql, sizeof sql, "PRAGMA journal_mode=%s", !strcmp(g_mode, "delete") ? "DELETE" : "WAL"); + if (sqlite3_exec(db, sql, NULL, NULL, NULL) != SQLITE_OK) die(sql, db); + snprintf(sql, sizeof sql, "PRAGMA synchronous=%s", g_sync); + if (sqlite3_exec(db, sql, NULL, NULL, NULL) != SQLITE_OK) die(sql, db); + if (sqlite3_exec(db, "PRAGMA busy_timeout=5000; PRAGMA temp_store=MEMORY", NULL, NULL, NULL) != SQLITE_OK) die("pragmas", db); + return db; +} + +static bool retryable (int rc) { int p = rc & 0xff; return p == SQLITE_BUSY || p == SQLITE_LOCKED; } + +typedef struct { int id; uint64_t *lat; size_t n, cap; } writer_t; + +static void *writer (void *arg) { + writer_t *w = arg; + sqlite3 *db = open_conn(); + sqlite3_stmt *ins; + if (sqlite3_prepare_v2(db, "INSERT INTO events(writer_id, seq, payload, created_at) VALUES (?1, ?2, ?3, ?4)", -1, &ins, NULL) != SQLITE_OK) die("prepare", db); + unsigned char payload[64]; for (int i = 0; i < 64; i++) payload[i] = (unsigned char)(i * 37 + w->id); + const char *begin = !strcmp(g_mode, "mw") ? "BEGIN" : "BEGIN IMMEDIATE"; + int64_t seq = 0; + while (!atomic_load(&g_stop)) { + uint64_t t0 = now_ns(); int retries = 0; bool ok = false; + for (int attempt = 0; attempt <= 1000 && !ok; attempt++) { + sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL); + int rc = sqlite3_exec(db, begin, NULL, NULL, NULL); + for (int r = 0; rc == SQLITE_OK && r < g_rows; r++) { + sqlite3_bind_int(ins, 1, w->id); sqlite3_bind_int64(ins, 2, seq++); + sqlite3_bind_blob(ins, 3, payload, sizeof payload, SQLITE_STATIC); + sqlite3_bind_text(ins, 4, "2026-10-09T18:06:04.0000000+00:00", -1, SQLITE_STATIC); + rc = sqlite3_step(ins); sqlite3_reset(ins); + if (rc == SQLITE_DONE) rc = SQLITE_OK; + } + if (rc == SQLITE_OK) rc = sqlite3_exec(db, "COMMIT", NULL, NULL, NULL); + if (rc == SQLITE_OK) { ok = true; break; } + if (!retryable(rc)) { fprintf(stderr, "write error %d: %s\n", rc, sqlite3_errmsg(db)); break; } + retries++; + } + if (!ok) { sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL); atomic_fetch_add(&g_errors, 1); } + atomic_fetch_add(&g_retries, (uint64_t)retries); + if (ok && !atomic_load(&g_stop)) { + atomic_fetch_add(&g_tx, 1); + if (w->n == w->cap) { w->cap = w->cap ? w->cap * 2 : 4096; w->lat = realloc(w->lat, w->cap * sizeof *w->lat); } + w->lat[w->n++] = now_ns() - t0; + } + } + sqlite3_finalize(ins); + sqlite3_close(db); + return NULL; +} + +static void *reader (void *arg) { + int nw = g_writers > 0 ? g_writers : 1; + sqlite3 *db = open_conn(); + sqlite3_stmt *mx, *rg; + if (sqlite3_prepare_v2(db, "SELECT MAX(id) FROM events", -1, &mx, NULL) != SQLITE_OK) die("prepare", db); + if (sqlite3_prepare_v2(db, "SELECT seq, length(payload) FROM events WHERE writer_id = ?1 ORDER BY seq DESC LIMIT 16", -1, &rg, NULL) != SQLITE_OK) die("prepare", db); + int flip = 0; + while (!atomic_load(&g_stop)) { + int rc; + if ((flip++ & 1) == 0) { while ((rc = sqlite3_step(mx)) == SQLITE_ROW) {} sqlite3_reset(mx); } + else { sqlite3_bind_int(rg, 1, flip % nw); while ((rc = sqlite3_step(rg)) == SQLITE_ROW) {} sqlite3_reset(rg); } + if (rc == SQLITE_DONE) atomic_fetch_add(&g_reads, 1); + usleep(1000); + } + sqlite3_finalize(mx); sqlite3_finalize(rg); + sqlite3_close(db); + return NULL; +} + +static int cmp_u64 (const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } +static double pct (uint64_t *v, size_t n, double p) { if (!n) return 0; size_t i = (size_t)(p * (double)(n - 1) + 0.5); return (double)v[i] / 1e6; } + +int main (int argc, char **argv) { + for (int i = 1; i < argc; i++) { + #define ARG(s) (!strcmp(argv[i], s) && i + 1 < argc) + if ARG("--mode") g_mode = argv[++i]; + else if ARG("--writers") g_writers = atoi(argv[++i]); + else if ARG("--readers") g_readers = atoi(argv[++i]); + else if ARG("--duration") g_duration = atoi(argv[++i]); + else if ARG("--sync") g_sync = argv[++i]; + else if ARG("--rebase") g_rebase = atoi(argv[++i]); + else if ARG("--dir") g_dir = argv[++i]; + else if ARG("--rows") g_rows = atoi(argv[++i]); + else { fprintf(stderr, "usage: see the head of bench/events_bench.c\n"); return 2; } + } + snprintf(g_path, sizeof g_path, "%s/events_bench_%d.db", g_dir, (int)getpid()); + { + sqlite3 *db = open_conn(); + if (sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS events (id INTEGER PRIMARY KEY, writer_id INTEGER NOT NULL, seq INTEGER NOT NULL, payload BLOB NOT NULL, created_at TEXT NOT NULL);" + "CREATE INDEX IF NOT EXISTS idx_events_writer ON events(writer_id);", NULL, NULL, NULL) != SQLITE_OK) die("schema", db); + g_keep = db; + } + pthread_t *th = calloc((size_t)(g_writers + g_readers), sizeof *th); + writer_t *ws = calloc((size_t)g_writers, sizeof *ws); + uint64_t t0 = now_ns(); + for (int i = 0; i < g_writers; i++) { ws[i].id = i; pthread_create(&th[i], NULL, writer, &ws[i]); } + for (int i = 0; i < g_readers; i++) pthread_create(&th[g_writers + i], NULL, reader, NULL); + sleep((unsigned)g_duration); + atomic_store(&g_stop, 1); + double secs = (double)(now_ns() - t0) / 1e9; + for (int i = 0; i < g_writers + g_readers; i++) pthread_join(th[i], NULL); + + size_t n = 0; for (int i = 0; i < g_writers; i++) n += ws[i].n; + uint64_t *all = malloc((n ? n : 1) * sizeof *all); size_t k = 0; + for (int i = 0; i < g_writers; i++) { memcpy(all + k, ws[i].lat, ws[i].n * sizeof *all); k += ws[i].n; free(ws[i].lat); } + qsort(all, n, sizeof *all, cmp_u64); + + // validation: every committed row is there exactly once, the file is sound + sqlite3 *db = open_conn(); + sqlite3_stmt *st; int64_t rows = -1, dup = -1; char ic[200] = "?"; + sqlite3_prepare_v2(db, "SELECT count(*), count(*) - count(DISTINCT writer_id || ':' || seq) FROM events", -1, &st, NULL); + if (sqlite3_step(st) == SQLITE_ROW) { rows = sqlite3_column_int64(st, 0); dup = sqlite3_column_int64(st, 1); } + sqlite3_finalize(st); + sqlite3_prepare_v2(db, "PRAGMA integrity_check", -1, &st, NULL); + if (sqlite3_step(st) == SQLITE_ROW) snprintf(ic, sizeof ic, "%s", (const char *)sqlite3_column_text(st, 0)); + sqlite3_finalize(st); + mw_db_stats s; memset(&s, 0, sizeof s); + if (!strcmp(g_mode, "mw")) sqlite3_file_control(g_keep, "main", MW_FCNTL_DBSTATS, &s); + sqlite3_close(db); sqlite3_close(g_keep); + uint64_t tx = atomic_load(&g_tx); + bool valid = !strcmp(ic, "ok") && dup == 0 && rows >= (int64_t)(tx * (uint64_t)g_rows); + printf("%-6s W=%-3d sync=%-4s tx/s %8.0f reads/s %7.0f p50 %7.2f p99 %8.2f p99.9 %8.2f max %8.2f ms retries/100tx %5.1f errors %llu rebases %llu unrebasable %llu conflicts %llu syncs %llu hot %llu %s\n", + g_mode, g_writers, g_sync, (double)tx / secs, (double)atomic_load(&g_reads) / secs, + pct(all, n, .50), pct(all, n, .99), pct(all, n, .999), n ? (double)all[n - 1] / 1e6 : 0, + tx ? 100.0 * (double)atomic_load(&g_retries) / (double)tx : 0, (unsigned long long)atomic_load(&g_errors), + (unsigned long long)s.rebases, (unsigned long long)s.unrebasable, (unsigned long long)s.page_conflicts, (unsigned long long)s.log_syncs, (unsigned long long)s.hot_serialised, + valid ? "valid" : "INVALID"); + printf("JSON {\"mode\":\"%s\",\"writers\":%d,\"sync\":\"%s\",\"tx_per_s\":%.1f,\"reads_per_s\":%.1f,\"p50_ms\":%.3f,\"p99_ms\":%.3f,\"p999_ms\":%.3f,\"max_ms\":%.3f,\"retries_per_100\":%.2f,\"valid\":%d}\n", + g_mode, g_writers, g_sync, (double)tx / secs, (double)atomic_load(&g_reads) / secs, pct(all, n, .50), pct(all, n, .99), pct(all, n, .999), n ? (double)all[n - 1] / 1e6 : 0, + tx ? 100.0 * (double)atomic_load(&g_retries) / (double)tx : 0, valid); + char p2[600]; + unlink(g_path); + const char *sfx[] = { "-wal", "-shm", "-mw", "-journal" }; + for (int i = 0; i < 4; i++) { snprintf(p2, sizeof p2, "%s%s", g_path, sfx[i]); unlink(p2); } + free(all); free(ws); free(th); + return valid ? 0 : 1; +} diff --git a/docs/design.md b/docs/design.md index cb178c8..0b29034 100644 --- a/docs/design.md +++ b/docs/design.md @@ -28,6 +28,14 @@ Open a database through the VFS with `file:db?vfs=multiwriter` (threads of one p - **Snapshot.** The first read of a transaction takes the newest *visible* epoch. Every commit takes the next epoch and becomes visible only after the one before it (readers see a prefix of the commits, never a hole). A page read at a snapshot is the newest version with an epoch not above it, else the page of the real file. Versions are kept while an active snapshot can still see them (`oldest_active_snapshot`), and dropped by the garbage collector that the committing threads run every few dozens of commits. +- **Speculative snapshot of a writer** (one process). A transaction whose first statement writes (or `BEGIN IMMEDIATE`/`EXCLUSIVE`; the statement hook tells the lane) takes its snapshot at the newest *installed* epoch + (`spec_epoch`: every epoch up to it has its versions in the store) instead of the newest visible one, so it may read commits whose record is not durable yet. Its own commit has a later epoch, the log is durable as a + prefix, and it is acknowledged only when its record is durable: it cannot be acknowledged without the commits it read. Without it, commits that depend on each other (inserts with the rowid that SQLite picks: each + one takes the key after the last one it sees) can only follow each other one fsync at a time (measured: 310 tx/s at every number of writers with an fsync of 3 ms); with it they share the group fsync. What is not + weakened: a transaction that does not write reads only durable commits; one that took a speculative snapshot and ends without a commit (a write statement that changed nothing, a `ROLLBACK`) waits, when it ends, + until what it read is durable; a commit whose record cannot be written is taken back (its epoch and versions) and `spec_gen` is bumped, and a speculative transaction of an older generation is refused at its + commit (`SQLITE_BUSY_SNAPSHOT`) and fails its reads (`SQLITE_IOERR_READ`); the recovery in place bumps it too. Only the commits of a failed fsync were ever readable this way, and they fail with the database, as in the + processes mode. URI `mw_spec=0` turns it off for a connection (the helper of its rebase follows it), `MW_NO_SPEC=1` makes that the default of the process. Test `mw_spec`. - **Commit.** Under the locks of the pages it wrote, a commit is validated: (1) the schema cookie is the one the transaction began with; (2) no page that it *read and did not write* has a newer version (a read of an interior b-tree page is forgiven if the path that the transaction took through it is unchanged: *routing*); (3) no page that it wrote has a newer version than its snapshot. Then its record (pages) goes to the log, its versions are installed, and it becomes visible when the log is durable (group commit). A commit that fails (2) or the cookie is refused; one that fails (3) may be saved: @@ -35,7 +43,8 @@ Open a database through the VFS with `file:db?vfs=multiwriter` (threads of one p merged, and the commit is published again, inside the same hold of the locks; - **merge of interior pages** (`multiwriter_btree.c`): both commits rewrote an interior table page (typically the parent of leaves both split): the page is merged three-way with the newest version; - **rebase** (below), if `mw_rebase=1`. - Otherwise the commit is refused and the lane's transaction ends; hot spots are served by a turn (a connection that lost serialises its next few transactions). + Otherwise the commit is refused and the lane's transaction ends; hot spots are served by a turn (a connection that lost serialises its next few transactions). With speculative snapshots (one process) the turn is taken after the + first refusal and given back as soon as the commit is installed or conflicts (the next holder reads it at once, it does not wait for the fsync, nor for the replay of a holder that lost); without them (`MW_NO_SPEC=1`), and in the processes mode, after 16 refusals in a row and at the end of the transaction. - **What is guaranteed.** Snapshot isolation with first-committer-wins at the level of pages, plus the validation of the pages read: no lost update, no write over a row that was deleted meanwhile, no UNIQUE value held by two rows, and a read-only transaction sees one consistent prefix of the commits. A transaction that read a page that another commit rewrote after its snapshot is refused (`SQLITE_BUSY_SNAPSHOT`). That is what stops write skew: in the pair "T1 reads A and writes B, T2 reads B and writes A" the second to commit read a page that the first rewrote, also when A and B are on different pages, when the page caches are warm, with the rebase, when a @@ -64,7 +73,7 @@ a commit conflicts, not at every commit. 2. **The replay** (`multiwriter_rebase.c`), on a helper connection of the lane (`mw_norebase=1`: never recursive; triggers off; foreign keys as the application's connection has them; same `synchronous`), in one transaction at the latest snapshot: the schema cookie is the one the transaction had; for every row that was changed or deleted the row is *exactly what the transaction saw* (the whole row, with `COLLATE BINARY IS`, so the type affinities and collations of the columns do not hide a difference); the deletes, then the updates, then the inserts are run (a key that one frees and another takes); a row that was inserted must not be there, and the constraints (UNIQUE, CHECK, NOT NULL, the key) are evaluated by SQLite on the rows as - they are now. Any of these that fails is a **true conflict**: the transaction is refused (`SQLITE_BUSY_SNAPSHOT`) and the application runs it again, as without the rebase. If the helper's commit loses a race (a commit that was assigned an epoch but is not yet visible has already installed its pages, so the snapshot of the replay is always older than the page heads) the publication gate is closed after the **first** lost attempt (`MW_REBASE_GATE_AFTER 1`), so that the next attempt runs against a frozen state. The replays are serialised and **batched** (a group replay): the connections whose commit conflicted queue a request (their decoded changes), the first becomes the leader and replays everything that is queued (up to 64) in ONE transaction of its helper, in the order the requests came, a savepoint for each (a request that is a true conflict is rolled back alone, the others see the rows as the ones before them left them), and the successful ones commit together at one epoch (`mw_tx_info.commit_order`: their order in it; the result is a serial execution in that order). One commit and one install of the pages for the group instead of a lost race and a commit for each. In the processes mode the batches are serialised across all the processes by an `fcntl` lock. The decoding of the pages is not serialised: every connection decodes its own. + they are now. Any of these that fails is a **true conflict**: the transaction is refused (`SQLITE_BUSY_SNAPSHOT`) and the application runs it again, as without the rebase. If the helper's commit loses a race (a commit that was assigned an epoch but is not yet visible has already installed its pages, so the snapshot of the replay is always older than the page heads) the publication gate is closed after the **first** lost attempt (`MW_REBASE_GATE_AFTER 1`), so that the next attempt runs against a frozen state (with speculative snapshots the helper reads what is installed, at least what the transaction it replays read, and the gate waits until every assigned commit is installed, not until it is durable). The replays are serialised and **batched** (a group replay): the connections whose commit conflicted queue a request (their decoded changes), the first becomes the leader and replays everything that is queued (up to 64) in ONE transaction of its helper, in the order the requests came, a savepoint for each (a request that is a true conflict is rolled back alone, the others see the rows as the ones before them left them), and the successful ones commit together at one epoch (`mw_tx_info.commit_order`: their order in it; the result is a serial execution in that order). One commit and one install of the pages for the group instead of a lost race and a commit for each. In the processes mode the batches are serialised across all the processes by an `fcntl` lock. The decoding of the pages is not serialised: every connection decodes its own. The `UPDATE` of a replay sets only the columns that changed (naming an unchanged indexed column rewrites its index, which refuses the transactions that only read that page). A connection whose replay was refused skips the replay of its next 1, 3, 7... conflicts (the true conflicts of a hot row would fail again at the cost of the decoding; `mw_rebase_backoff=0` turns it off, for the tests), and a conflict that was rebased does not make the connection take the hot-spot turn. 3. **What the result is.** The state that a serial execution of the two commits could have produced: the replay has the epoch of the helper's commit, and every row that the transaction touched is, in that order, what it was when it read it. @@ -125,7 +134,7 @@ copies of a relocation are made before the lock too. The group fsync is shared b ## Durability and recovery -- A commit is durable when its record is in the log and the log is synced; it is visible after that (one process) or before (several processes: an acknowledged commit is never lost, and a failed fsync fails every commit that is not durable yet, +- A commit is durable when its record is in the log and the log is synced; it is visible after that (one process; a write transaction may read it before, see "Speculative snapshot of a writer") or before (several processes: an acknowledged commit is never lost, and a failed fsync fails every commit that is not durable yet, in every process, until the log is closed by all). - Recovery replays the valid prefix of the log (a record is valid as a whole: its checksum covers the pages), cuts a torn tail durably (`fsync` of the file and of the directory), refuses a header that does not check out with records behind it (`SQLITE_CORRUPT`) and a read that fails (it is not the end of the log). @@ -193,11 +202,11 @@ the relocation prepared before the lock, the rebase (`mw_rebase`: what is replay ## Parameters (URI and environment) -URI parameters (read at open): `mw` (0 off, 2 lanes: the engine), `mw_mp` (0 one process, 1 processes: the shared mode), **`mw_rebase`** (1: the rebase), `mw_fullfsync`, `mw_profile` (`small`: the cache of pages of the +URI parameters (read at open): `mw` (0 off, 2 lanes: the engine), `mw_mp` (0 one process, 1 processes: the shared mode), **`mw_rebase`** (1: the rebase), **`mw_spec`** (1, the default: speculative snapshots of the writers; 0: off), `mw_fullfsync`, `mw_profile` (`small`: the cache of pages of the real file at 8 MB, a log of 16 MB before it is compacted), `mw_base_cache_mb`, `mw_log_max_mb`, `mw_gc` (commits between two collections of versions), `mw_hot_credit`, `mw_readcheck` (0: no validation of the pages read: fewer retries, write skew becomes possible), and, for tests and measurements, `mw_noreloc`, `mw_noroute`, `mw_nomerge`, `mw_norebase` (marks a connection that never rebases: the helper), `mw_rebase_backoff` (0: replay every conflict), `mw_prep_delay_us` (waits between the preparation of a relocation and the publication lock). -Environment: `MW_FULLFSYNC`, `MW_PROFILE`, `MW_SEG_MB` (size of a segment of the shared log), `MW_IDX_ENTRIES`, `MW_SIDECAR_DIR` (where the shared maps go: `/dev/shm` on Linux), `MW_SPIN_US`, `MW_POOL_BATCH`, `MW_ENOSPC_WAIT_MS`; +Environment: `MW_FULLFSYNC`, `MW_PROFILE`, `MW_NO_SPEC` (`mw_spec=0` by default), `MW_SHORT_STARVE` (refusals in a row before a short transaction takes the hot-spot turn), `MW_SEG_MB` (size of a segment of the shared log), `MW_IDX_ENTRIES`, `MW_SIDECAR_DIR` (where the shared maps go: `/dev/shm` on Linux), `MW_SPIN_US`, `MW_POOL_BATCH`, `MW_ENOSPC_WAIT_MS`; diagnostics: `MW_DEBUG`, `MW_TIMING` (time spent in each stage of a commit), `MW_IO_TRACE`, `MW_COMPACT_TRACE`, `MW_PAGE_TRACE`. Measurement only (`make EXPERIMENTS=1`): `MW_EXP_*`. ## Security of the files @@ -218,6 +227,23 @@ The code is under the Apache License 2.0 (`LICENSE`, `NOTICE`). `third_party/sql ## Measurements +**The appends of the external comparison** (`bench/events_bench.c`: 100 inserts of 64 bytes per transaction with the rowid that SQLite picks, an index on the writer, 4 readers, `busy_timeout=5000`, a refused transaction is run again and its latency counts the retries; this Mac, 6 s per point, 2026-11-27). Every commit takes the rowid after the last one it sees, so every two concurrent commits are a true conflict and every commit depends on the one before. Before the speculative snapshots and the cheaper turn / after: + +| profile | writers | tx/s | p99 ms | p99.9 ms | retries per 100 tx | +|---|---:|---:|---:|---:|---:| +| fsync of ~3 ms (`MW_FULLFSYNC=1`) | 1 | 303 / 316 | 4.2 / 4.1 | 9.7 / 7.8 | 0 / 0 | +| | 8 | 314 / 1,075 | 410 / 14.9 | 679 / 18.6 | 674 / 7.5 | +| | 24 | 333 / 2,547 | 694 / 20.0 | 1,043 / 22.8 | 545 / 7.1 | +| fast fsync (`synchronous=FULL`) | 8 | 8,880 / 11,058 | 22.3 / 3.7 | 101 / 6.4 | 130 / 6.7 | +| | 24 | 7,978 / 10,180 | 55.8 / 11.1 | 117 / 56.3 | 143 / 6.8 | +| `synchronous=OFF` | 8 | 11,599 / 11,764 | 19.1 / 8.0 | 86 / 15.0 | 108 / 17.9 | +| | 24 | 11,330 / 11,372 | 59.4 / 16.8 | 175 / 27.3 | 111 / 15.2 | + +Linux (Debian 12 in a Docker container on the same Mac, arm64, 18 CPUs, a virtual disk whose fsync takes about 0.3 ms), 24 writers: disk with `synchronous=FULL` 1,820 / 7,625 tx/s, p99 145 / 8.6 ms, 239 / 7 retries per 100 tx; +tmpfs with `synchronous=FULL` 9,935 / 9,262 tx/s, p99 64 / 14 ms; disk with `synchronous=OFF` 9,660 / 9,145 tx/s, p99 62 / 13 ms. Without a durable fsync the appends stay serial (each needs the one before): the gain there is the +latency and the retries, not the throughput, which is 3-7% lower from 8 writers up (the turn after the first refusal; `MW_SHORT_STARVE=16` gives the old behaviour). + + The tables for the readers are in `docs/benchmarks.md` (2026-10-07, this Mac, 18 cores, SQLite 3.53.4, `synchronous=FULL`, one run of 8 s per point; `bench/results/simple_*_2026-10-07.jsonl`, made by `bench/compare_sqlite.py` and `bench/make_report.py`). For this engine a retry is a commit that was refused and that the application ran again; the replays that the rebase lost to other commits and repeated inside the engine are the "lost replays per merged commit". "Gave up" is a transaction that did not commit after 1000 retries. The workloads (`bench/mw_bench.c`): **bulk** = 100-row inserts on disjoint keys; **groups** = each agent updates its own row, four groups whose rows share a page; **same page** = each agent its own row, all on one page; **hot rows** = `UPDATE a = a + 1` on 4 rows (true conflicts); diff --git a/src/multiwriter.h b/src/multiwriter.h index ce60ebd..fb6a77d 100644 --- a/src/multiwriter.h +++ b/src/multiwriter.h @@ -23,10 +23,10 @@ extern "C" { #endif // The version of the extension: the single place it is written (the Makefile, the packages and the release read it from here). -#define MW_VERSION "0.6.5" +#define MW_VERSION "0.7.0" #define MW_VERSION_MAJOR 0 -#define MW_VERSION_MINOR 6 -#define MW_VERSION_PATCH 5 +#define MW_VERSION_MINOR 7 +#define MW_VERSION_PATCH 0 #define MW_VERSION_NUMBER (MW_VERSION_MAJOR * 1000000 + MW_VERSION_MINOR * 1000 + MW_VERSION_PATCH) #if defined(MW_LOADABLE) && defined(_WIN32) #define MW_API __declspec(dllexport) // the loadable extension exports its entry points and nothing else @@ -99,6 +99,7 @@ typedef struct { #define MW_FCNTL_DDL_RELEASE_IDLE 0x4d57000f // internal: a statement ended; the schema barrier it raised is given back if no snapshot of the main file is open #define MW_FCNTL_STMT 0x4d570011 // internal: mw_stmt_note * (a statement of a mw_rebase=1 connection starts or ends) +#define MW_FCNTL_WRITE_INTENT 0x4d570012 // internal: int * (1: a statement that writes is starting, 0: it ended) typedef struct { int ending; int autocommit; sqlite3_stmt *stmt; } mw_stmt_note; #define MW_FCNTL_DDL_BEGIN 0x4d570009 // internal: a schema-changing statement is about to run (exclusive schema barrier) #define MW_FCNTL_LANE_PTR 0x4d57000b // internal: void ** (the connection's lane) diff --git a/src/multiwriter_internal.h b/src/multiwriter_internal.h index 7bea090..cb5f5e1 100644 --- a/src/multiwriter_internal.h +++ b/src/multiwriter_internal.h @@ -177,6 +177,8 @@ struct mw_lane { uint32_t *rs_list; int rs_n, rs_cap; bool norebase; // this connection is itself a rebase helper: never rebase recursively + bool spec_on; // speculative snapshots for this connection's write transactions (URI mw_spec, default 1; MW_NO_SPEC=1 turns the default off): see mw_lane_snapshot_begin + bool rb_helper; // it is the helper of the rebase (not only a connection that asked not to rebase): it reads speculatively, and its reads reach no application bool rebase_on; // URI mw_rebase=1: a commit that conflicts on pages only is replayed at the latest snapshot (multiwriter_rebase.c) bool rb_nobackoff; // URI mw_rebase_backoff=0 (tests): replay every conflict, whatever happened to the last ones sqlite3_stmt *rd_cur; // the statement that is running (mw_rebase=1 connections; set by the statement hook), and what the transaction did before it: @@ -218,6 +220,9 @@ struct mw_lane { int sync_level; // PRAGMA synchronous as observed on this connection (default FULL = 2) int retry_credit; // >0: the lane recently conflicted; its next transactions are serialised (hot spots); decays per successful commit bool holds_hot; // this lane's current snapshot holds db->hot_mu + bool write_intent; // the statement that is starting writes (or is BEGIN IMMEDIATE/EXCLUSIVE): a snapshot taken now may be speculative + bool spec; // the current snapshot is above the visible epoch: it includes commits that are installed and not yet durable + uint64_t spec_gen; // db->spec_gen when that snapshot was taken bool ddl_active; // this lane owns the schema barrier (released when its transaction ends) _Atomic bool write_locked; // WAL write lock held inside the current snapshot bool snapshot_held; // registered in db->lanes as an active snapshot @@ -254,6 +259,8 @@ struct mw_lane { #define MW_VIS_SLOTS 256 struct mw_vis_slot { pthread_mutex_t mu; pthread_cond_t cv; _Atomic int waiters; _Atomic uint64_t ready; }; +#define MW_SPEC_RING 1024 +#define MW_SPEC_SCAN 256 /* the longest run of installed epochs a speculative snapshot looks at */ struct mw_db { char *path; int mode; // 1 = lane tracking on the stock WAL, 2 = private lanes @@ -343,10 +350,12 @@ struct mw_db { // multi-process mode (mw_mp=1) bool mp_req, mp; // requested at open / active bool has_log; // a log file exists (set once when it is opened, before any commit): read by publishers instead of the logfd that a rewrite replaces - _Atomic int inflight; // commits inside lane_publish (the recovery of a failed log waits for them to leave) + // (the atomics that follow plain fields start a word of their own: gcc reads mp_req, mp and has_log together with one 8-byte load, which took in the atomic that came next, a data race for + // ThreadSanitizer built with gcc, in mw_log_rewrite_prepare against lane_publish) + _Alignas(8) _Atomic int inflight; // commits inside lane_publish (the recovery of a failed log waits for them to leave) _Atomic int recovering; // a recovery in place is running mw_store *retired[8]; int nretired; // stores replaced by a recovery: readers that were inside them may still look (freed with the database) - _Atomic bool open_done; // the first connection finished opening (a database whose open failed has nothing to flush) + _Alignas(8) _Atomic bool open_done; // the first connection finished opening (a database whose open failed has nothing to flush) _Atomic int mp_nprocs; // processes registered on this database, as last counted by the admission control bool compact_claimed; // this process holds the compaction claim (shared mode) struct mw_seglog *sl; // the segmented log (shared mode) @@ -362,6 +371,9 @@ struct mw_db { pthread_mutex_t mp_mu; // serialises publication inside this process _Atomic int failed; // sticky I/O failure: no further commits _Atomic uint64_t next_epoch; // last *assigned* epoch (>= epoch; the difference is in-flight commits) + _Atomic uint64_t spec_inst[MW_SPEC_RING]; // one process: slot e % MW_SPEC_RING holds e once the versions of epoch e are installed (visible or not yet durable); a speculative snapshot is the + // contiguous run of them above the visible epoch. No committer waits for another: one that is late leaves a gap, and the snapshots stop below it + _Atomic uint64_t spec_gen; // bumped whenever installed epochs are taken back (a commit whose record failed, a recovery): a speculative snapshot of an older generation must not commit _Atomic uint64_t n_pages_published, n_log_sync_ns; _Atomic uint64_t n_compactions, n_compaction_ns, n_compacted_pages, n_log_syncs; int fd_real; // real database file (compaction), -1 when closed @@ -612,6 +624,13 @@ int mw_shared_compact (mw_db *db, mw_compact_result *out); bool mw_shared_compact_claim (mw_db *db, bool by_size); // election: one process (the first to claim) runs the next background compaction uint64_t mw_snap_for (const mw_validate *v, uint32_t pgno); // the epoch a page is validated against (pages.c) static inline uint64_t mw_db_visible_epoch (mw_db *db) { return db->mp_req ? mw_shared_visible_epoch(db) : atomic_load(&db->epoch); } +// Speculative snapshots (one process): a write transaction reads at the newest *installed* epoch, not at the newest durable one, so that a chain of commits that depend on each other +// (appends to one table: each takes the rowid after the previous one) shares one group fsync instead of paying one each. Per connection: URI mw_spec=0 turns it off; MW_NO_SPEC=1 makes 0 the default. +bool mw_spec_on (void); +void mw_lane_turn_release (mw_lane *lane); +void mw_lane_spec_settle (mw_lane *lane); +void mw_spec_forget (mw_db *db); +uint64_t mw_spec_top (mw_db *db); // The log size at which compaction is requested. Many processes (> 16): 8 MB instead of the configured size: measured 8 MB vs 32 MB, 32 processes 10.2k -> 11.2k, // 64: 7.3k -> 8.2k tx/s (the mapping's working set stays in the caches), but 8 processes -8%. diff --git a/src/multiwriter_lane.c b/src/multiwriter_lane.c index 859ee48..d00e71b 100644 --- a/src/multiwriter_lane.c +++ b/src/multiwriter_lane.c @@ -277,6 +277,9 @@ static bool lane_can_rebase (mw_lane *lane, const uint8_t *pg1, uint32_t snapsho // Publishes the captured write set as one atomic commit at a new epoch. // Consecutive refusals after which a long transaction takes the turn (MW_LONG_STARVE). +// Refusals in a row before a short transaction takes the turn (MW_SHORT_STARVE). With speculative snapshots the turn is given back when the commit is installed, so the next holder does not wait for +// the fsync and the turn costs little: it is taken at the first refusal (appends with the rowid that SQLite picks: 145 -> 7 retries per 100 tx with 24 writers). Without them, and in the processes mode, after 16. +static int short_starve (const mw_lane *lane) { static _Atomic int c = MW_KNOB_UNSET; int v = mw_knob_int(&c, "MW_SHORT_STARVE", 0); return v > 0 ? v : lane->spec_on && !lane->db->mp ? 1 : 16; } // (the processes mode keeps the turn to the end of the transaction: 16) static int long_starve (void) { static _Atomic int c = MW_KNOB_UNSET; return mw_knob_int(&c, "MW_LONG_STARVE", 2); } static int lane_publish_inner (mw_lane *lane); @@ -375,6 +378,7 @@ static int lane_publish_inner (mw_lane *lane) { atomic_fetch_add(&db->schema_generation, 1); } } else if (rc == MW_CONFLICT) { + if (!db->mp && lane->spec_on) mw_lane_turn_release(lane); // (its attempt on fresh state is made; the relocation or the replay that follows does not need the others to wait, and a replay waits for its own fsync) // 1. Was the conflict only that other commits extended the file? Then the transaction's new pages are renumbered above the new end and it commits. uint64_t tr0 = MW_T0(); int rr = lane->noreloc ? MW_RELOC_NA : mw_lane_relocate(lane, &v, lane->ws_pgnos, imgs, lane->ws_n, lane->ws_dbsize, snap_size, lane->sync_level >= 2, &epoch); @@ -407,7 +411,7 @@ static int lane_publish_inner (mw_lane *lane) { // Serialising pays off where a conflict is expensive: a tracked (rebasable) transaction that loses costs a whole rebase. An untracked one just runs // its statement again, and waiting for a turn costs more than the occasional retry (measured: 8-32 concurrent bulk / append writers, 1.3-1.5x faster without). lane->consec_aborts++; - const bool starving = lane->consec_aborts >= (long_tx ? long_starve() : 16); // (a long transaction that lost twice in a row takes the turn and keeps it for hot_credit*16 transactions: FIFO queue, bounded tail) + const bool starving = lane->consec_aborts >= (long_tx ? long_starve() : short_starve(lane)); // (a long transaction that lost twice in a row takes the turn and keeps it for hot_credit*16 transactions: FIFO queue, bounded tail) if (!lane->norebase && rc != MW_CONFLICT_SCHEMA && rc != MW_CONFLICT_READ && (starving)) { lane->retry_credit = long_tx ? lane->hot_credit * 16 : lane->hot_credit; if (mw_timing_on) { extern _Atomic uint64_t mw_grants[2]; atomic_fetch_add(&mw_grants[lane->rebase_on ? 0 : 1], 1); } @@ -628,6 +632,7 @@ static int lm_read (sqlite3_file *pf, void *buf, int n, sqlite3_int64 off) { mw_ev(MW_EV_READ, (mw_file *)pf, off, n, 2); mw_store *st = lane->db->store; uint64_t snap = lane_snapshot(lane); + if (lane->spec && atomic_load(&lane->db->spec_gen) != lane->spec_gen) return SQLITE_IOERR_READ; // (commits that this snapshot includes were taken back: what is left of it is not one state) uint8_t *dst = buf; int remaining = n; sqlite3_int64 o = off; @@ -710,6 +715,7 @@ static int lm_file_control (sqlite3_file *pf, int op, void *arg) { } if (op == MW_FCNTL_DBSTATS) { mw_lane_fill_stats(lane, (mw_db_stats *)arg); return SQLITE_OK; } if (op == MW_FCNTL_STMT) { mw_lane_stmt_note(lane, (mw_stmt_note *)arg); return SQLITE_OK; } + if (op == MW_FCNTL_WRITE_INTENT) { lane->write_intent = *(int *)arg != 0 && !lane->snapshot_held; return SQLITE_OK; } if (op == MW_FCNTL_DDL_BEGIN) { mw_lane_ddl_begin(lane); return SQLITE_OK; } if (op == MW_FCNTL_DDL_RELEASE_IDLE) { if (lane->ddl_active && !lane->snapshot_held) mw_lane_ddl_end(lane); return SQLITE_OK; } if (op == MW_FCNTL_COMPACT) { mw_compact_result *r = (mw_compact_result *)arg; return mw_db_compact(lane->db, r); } diff --git a/src/multiwriter_log.c b/src/multiwriter_log.c index ea25dcc..5163317 100644 --- a/src/multiwriter_log.c +++ b/src/multiwriter_log.c @@ -14,7 +14,8 @@ // 2. outside any lock the record is written; with synchronous>=FULL it is fsynced (group commit); // 3. only then does the epoch become visible, and only after the previous epoch did. // A commit is therefore never visible before its record is persisted according to the requested -// synchronous level. Recovery replays the longest prefix of valid, epoch-contiguous records past +// synchronous level. (A write transaction may read it before, speculatively: it is acknowledged only when +// its own record, which comes later in the log, is persisted; see mw_spec_on.) Recovery replays the longest prefix of valid, epoch-contiguous records past // base_epoch (the compacted epoch), ignoring a torn tail. // // The log file is flock()ed for the lifetime of the database: a second Multi-Writer process opening @@ -395,6 +396,7 @@ int mw_db_recover (mw_db *db) { free(db->p1_cache); db->p1_cache = NULL; db->p1_cache_epoch = 0; pthread_mutex_lock(&nst->seq_mu); __atomic_store_n(&db->log_off, E, __ATOMIC_RELAXED); + mw_spec_forget(db); // (the speculative snapshots above V read commits that are gone: refused, see spec_gen) atomic_store(&db->next_epoch, V); pthread_mutex_unlock(&nst->seq_mu); pthread_mutex_lock(&db->log_mu); diff --git a/src/multiwriter_pages.c b/src/multiwriter_pages.c index f6a6ea9..f7221d7 100644 --- a/src/multiwriter_pages.c +++ b/src/multiwriter_pages.c @@ -224,6 +224,12 @@ void mw_gate_close (mw_db *db, mw_lane *owner) { while (atomic_load(&db->gate_active) > 0) { sched_yield(); if (!warned && now_ns() - tg0 > 3000000000ull && mw_debug_on()) { warned = true; fprintf(stderr, "gate_close: stuck waiting for publishers (active=%d)\n", atomic_load(&db->gate_active)); } } // let in-flight publishers finish // ... and let every epoch already assigned become visible, so the next snapshot is the final state // shared mode: commits are visible in one step under the publication lock; the local epoch counters do not follow other processes' + // With speculative snapshots the replay reads what is installed: every epoch assigned must be installed, not durable (waiting for their fsync held every publisher for it) + if (!db->mp && !db->mp_req && owner && owner->spec_on) { + while (mw_spec_top(db) < atomic_load(&db->next_epoch) && atomic_load(&db->epoch) != atomic_load(&db->next_epoch) && !atomic_load(&db->failed)) sched_yield(); + atomic_fetch_add(&db->n_gate_closures, 1); + return; + } while (!db->mp_req && atomic_load(&db->epoch) != atomic_load(&db->next_epoch) && !atomic_load(&db->failed)) { sched_yield(); if (!warned && now_ns() - tg0 > 3000000000ull && mw_debug_on()) { warned = true; fprintf(stderr, "gate_close: stuck waiting for epoch %llu to become visible (next_epoch %llu)\n", (unsigned long long)atomic_load(&db->epoch), (unsigned long long)atomic_load(&db->next_epoch)); } } atomic_fetch_add(&db->n_gate_closures, 1); } @@ -385,6 +391,9 @@ static int publish_impl (mw_db *db, mw_lane *lane, const mw_validate *v, const u uint64_t tsq0 = MW_T0(); if (db->has_log) mw_log_decide_mode(db, sync); mw_spinlock(&st->seq_mu); + if (lane && lane->spec && atomic_load(&db->spec_gen) != lane->spec_gen) { // (commits that the speculative snapshot includes were taken back: under seq_mu, where they are taken back) + pthread_mutex_unlock(&st->seq_mu); pub_release(db, st, &locked); atomic_fetch_add(&db->n_read_conflicts, 1); rc = MW_CONFLICT_READ; goto fail_free; + } uint64_t epoch = atomic_load(&db->next_epoch) + 1; if (st->nsizes == st->sizes_cap) { int cap = st->sizes_cap ? st->sizes_cap * 2 : 64; @@ -419,6 +428,10 @@ static int publish_impl (mw_db *db, mw_lane *lane, const mw_validate *v, const u for (int i = 0; i < n; i++) if (pgnos[i] == 1 && db->p1_cache) { memcpy(db->p1_cache, copies[i], (size_t)st->pgsz); atomic_store_explicit(&db->p1_cache_epoch, epoch, memory_order_release); break; } } pub_release(db, st, &locked); + if (!db->mp) { + atomic_store_explicit(&db->spec_inst[epoch % MW_SPEC_RING], epoch, memory_order_release); // installed: a speculative snapshot may include it (once the epochs before it are installed too) + if (lane && lane->holds_hot && lane->spec_on) mw_lane_turn_release(lane); + } if (lane && lane->holds_reloc) MW_T1(MW_ST_H_INSTALL, tin0); if (lane && lane->holds_reloc) { lane->holds_reloc = false; MW_T1(MW_ST_RELOCHOLD, lane->reloc_t0); pthread_mutex_unlock(&db->reloc_mu); } // (a relocation: the next one may go, our pages are installed) if (n > 16) { free(copies); free(chains); } @@ -441,6 +454,8 @@ static int publish_impl (mw_db *db, mw_lane *lane, const mw_validate *v, const u bool latest = atomic_load(&db->next_epoch) == epoch && MW_LOG_OFF(db) == log_off + mw_log_record_size(db, n, 0); if (latest) { st->nsizes--; + atomic_store(&db->spec_inst[epoch % MW_SPEC_RING], 0); // (its mark first, then the generation: a snapshot that read the new generation cannot include it) + atomic_fetch_add(&db->spec_gen, 1); atomic_store(&db->next_epoch, epoch - 1); __atomic_store_n(&db->log_off, log_off, __ATOMIC_RELAXED); } else { diff --git a/src/multiwriter_rebase.c b/src/multiwriter_rebase.c index 07719f2..0cbef99 100644 --- a/src/multiwriter_rebase.c +++ b/src/multiwriter_rebase.c @@ -45,7 +45,7 @@ void mw_lane_rebase_free (mw_lane *lane) { } // Percent-escape the characters that would end a URI path. -static char *uri_for (const char *path, bool mp) { +static char *uri_for (const char *path, bool mp, bool spec) { size_t n = strlen(path); char *esc = sqlite3_malloc64(n * 3 + 1), *o = esc; if (!esc) return NULL; @@ -54,13 +54,13 @@ static char *uri_for (const char *path, bool mp) { else *o++ = path[i]; } *o = 0; - char *uri = sqlite3_mprintf("file:%s?mw=1&mw_norebase=1&mw_mp=%d", esc, mp ? 1 : 0); + char *uri = sqlite3_mprintf("file:%s?mw=1&mw_norebase=1&mw_rbhelper=1&mw_mp=%d&mw_spec=%d", esc, mp ? 1 : 0, spec ? 1 : 0); // (the helper reads speculatively when the connection it replays for does) sqlite3_free(esc); return uri; } static int helper_open (mw_lane *lane) { if (lane->rb_db) return SQLITE_OK; - char *uri = uri_for(lane->db->path, lane->db->mp_req); + char *uri = uri_for(lane->db->path, lane->db->mp_req, lane->spec_on); if (!uri) return SQLITE_NOMEM; sqlite3 *h = NULL; int rc = sqlite3_open_v2(uri, &h, SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_PRIVATECACHE, MW_VFS_NAME); diff --git a/src/multiwriter_seglog.c b/src/multiwriter_seglog.c index d0ca0d5..ac5c271 100644 --- a/src/multiwriter_seglog.c +++ b/src/multiwriter_seglog.c @@ -494,6 +494,7 @@ int mw_seglog_sync (mw_db *db, uint32_t seg, uint64_t end) { for (;;) { if (atomic_load_explicit(&sh->sy_done, memory_order_acquire) >= target) return SQLITE_OK; if (atomic_load_explicit(&sh->sy_failed, memory_order_acquire)) return SQLITE_IOERR_FSYNC; + { static _Atomic int d = MW_KNOB_UNSET; int us = mw_knob_int(&d, "MW_TEST_SYNC_PRELEAD_US", 0); if (us > 0) usleep((useconds_t)us); } // (tests: a leader that finishes between our look at sy_done and our turn as the leader) int32_t exp = 0; if (atomic_compare_exchange_strong(&sh->sy_leader, &exp, me)) { // The leader: one fsync for every commit written so far, by any process (the processes share one active segment). @@ -505,8 +506,10 @@ int mw_seglog_sync (mw_db *db, uint32_t seg, uint64_t end) { uint32_t tseg = (uint32_t)MW_LOG_GEN(tpos); uint64_t tend = MW_LOG_END(tpos); if (tpos < target) { tseg = seg; tend = end; tpos = target; } - int frc = 0; - if (atomic_load_explicit(&sh->sy_done, memory_order_acquire) >= target) frc = 0; // (somebody finished while we were taking over) + int frc = 0; bool synced = false; + // (somebody finished while we were taking over: nothing is synced here, and sy_done must not move. It used to move to tpos all the same, and tpos, read after that, can be past + // records that other processes installed meanwhile and nobody synced: they were then acknowledged without an fsync. mw_syncwindow, about 1 run in 20 on a Linux of 4 CPUs) + if (atomic_load_explicit(&sh->sy_done, memory_order_acquire) >= target) frc = 0; else if (mw_fault_hit(MW_FAULT_LOG_SYNC_ERR)) frc = -1; else { segmap *m = map_acquire(sl, tseg); @@ -518,10 +521,11 @@ int mw_seglog_sync (mw_db *db, uint32_t seg, uint64_t end) { uint64_t to = (tend + (uint64_t)osp - 1) & ~((uint64_t)osp - 1); if (to > m->len) to = m->len; frc = to > from ? mw_io_msync(m->base + from, (size_t)(to - from), MS_SYNC) : 0; if (frc == 0) frc = mw_io_fsync(m->fd); + synced = frc == 0; map_release(m); } else frc = -1; } - if (frc == 0) { + if (synced) { // (only what this leader made durable) uint64_t cur = atomic_load(&sh->sy_done); while (cur < tpos && !atomic_compare_exchange_weak(&sh->sy_done, &cur, tpos)) {} atomic_fetch_add(&db->n_log_syncs, 1); diff --git a/src/multiwriter_shared.c b/src/multiwriter_shared.c index 1a52017..3dafcf3 100644 --- a/src/multiwriter_shared.c +++ b/src/multiwriter_shared.c @@ -293,7 +293,9 @@ int mw_shared_publish (mw_db *db, mw_lane *lane, const mw_validate *v, const uin mw_seglog_discard(db, atomic_load(&sh->pend_seg), atomic_load(&sh->pend_off)); atomic_store(&sh->sl_seg, atomic_load(&sh->pend_seg)); atomic_store_explicit(&sh->sl_end, atomic_load(&sh->pend_off), memory_order_release); atomic_store_explicit(&sh->pend_epoch, 0, memory_order_release); - if (n > 16) free(locs); ADOPT_FREE(); return SQLITE_FULL; + if (n > 16) free(locs); + ADOPT_FREE(); + return SQLITE_FULL; } MW_T1(MW_ST_SH_INSTALL, ti0); if (n > 16) free(locs); diff --git a/src/multiwriter_shidx.c b/src/multiwriter_shidx.c index 522c1c1..a811aef 100644 --- a/src/multiwriter_shidx.c +++ b/src/multiwriter_shidx.c @@ -91,8 +91,12 @@ shidx *shidx_open (const char *path, const shidx_params *params) { if (fstat(fd, &sb) != 0) { flock(fd, LOCK_UN); close(fd); return NULL; } if (sb.st_size == 0) { // first opener: lay the file out shidx_params p = { 24, 4u << 20, 4096, 0 }; - if (params) { if (params->max_pages_log2) p.max_pages_log2 = params->max_pages_log2; if (params->max_entries) p.max_entries = params->max_entries; - if (params->nslots) p.nslots = params->nslots; if (params->max_cands) p.max_cands = params->max_cands; } + if (params) { + if (params->max_pages_log2) p.max_pages_log2 = params->max_pages_log2; + if (params->max_entries) p.max_entries = params->max_entries; + if (params->nslots) p.nslots = params->nslots; + if (params->max_cands) p.max_cands = params->max_cands; + } if (!p.max_cands) p.max_cands = p.max_entries + 1; // (a page is queued once: never more candidates than versions) if (p.max_pages_log2 < BLOCK_BITS + 1 || p.max_pages_log2 > 32) { errno = EINVAL; flock(fd, LOCK_UN); close(fd); return NULL; } hdr h; @@ -251,6 +255,7 @@ void (*shidx_install_hook)(int done); // (tests: static int install_impl (shidx *ix, uint64_t epoch, uint32_t dbsize, bool with_size, int n, const uint32_t *pgnos, const uint64_t *locs) { hdr *h = ix->h; + if (n < 0) return -2; // (never: a count of pages; said so that the sizes of the allocations below cannot wrap) const int i0 = with_size ? -1 : 0; // (the size record is item -1) uint32_t need = (uint32_t)n + (with_size ? 1u : 0u); uint32_t room = h->n_free + (h->max_entries - h->arena_top); @@ -308,8 +313,8 @@ int shidx_install (shidx *ix, uint64_t epoch, uint32_t dbsize, int n, const uint // installed. The same call finishes a commit of which nothing was installed. int shidx_install_missing (shidx *ix, uint64_t epoch, uint32_t dbsize, int n, const uint32_t *pgnos, const uint64_t *locs) { const bool with_size = shidx_head_epoch(ix, 0) != epoch; - uint32_t pg_small[130]; uint64_t lc_small[130]; - uint32_t *pg = (size_t)n <= 130 ? pg_small : malloc((size_t)n * sizeof *pg); uint64_t *lc = (size_t)n <= 130 ? lc_small : malloc((size_t)n * sizeof *lc); + uint32_t pg_small[130] = {0}; uint64_t lc_small[130] = {0}; // (initialised, and calloc below: gcc cannot tell that install_impl reads only the m that are filled; this is the repair of a publisher that died, not a hot path) + uint32_t *pg = (size_t)n <= 130 ? pg_small : calloc((size_t)n, sizeof *pg); uint64_t *lc = (size_t)n <= 130 ? lc_small : calloc((size_t)n, sizeof *lc); if (!pg || !lc) { if (pg != pg_small) free(pg); if (lc != lc_small) free(lc); return -2; } int m = 0; for (int i = 0; i < n; i++) if (shidx_head_epoch(ix, pgnos[i]) != epoch) { pg[m] = pgnos[i]; lc[m] = locs[i]; m++; } diff --git a/src/multiwriter_tx.c b/src/multiwriter_tx.c index 9816dca..d80acb8 100644 --- a/src/multiwriter_tx.c +++ b/src/multiwriter_tx.c @@ -21,6 +21,42 @@ static int turn_slots (void) { static _Atomic int c = MW_KNOB_UNSET; int v = mw_ static inline bool db_mp_flag (mw_lane *lane) { return lane->db->mp; } +// Epochs are taken back (a record that could not be written, a recovery): their marks go first, then the generation is bumped (seq_mu held: no epoch is assigned meanwhile). +void mw_spec_forget (mw_db *db) { + for (int i = 0; i < MW_SPEC_RING; i++) atomic_store(&db->spec_inst[i], 0); + atomic_fetch_add(&db->spec_gen, 1); +} + +// The newest epoch up to which every epoch is installed (the top of a speculative snapshot taken now). +uint64_t mw_spec_top (mw_db *db) { + uint64_t s = mw_db_visible_epoch(db); + for (int k = 0; k < MW_SPEC_SCAN && atomic_load_explicit(&db->spec_inst[(s + 1) % MW_SPEC_RING], memory_order_acquire) == s + 1; k++) s++; + return s; +} + +bool mw_spec_on (void) { static _Atomic int c = MW_KNOB_UNSET; return !mw_knob_flag(&c, "MW_NO_SPEC"); } + +// The turn of a hot spot is given back as soon as the commit that holds it is installed (speculative snapshots): the next holder reads it at once, it does not wait for the fsync. +void mw_lane_turn_release (mw_lane *lane) { + if (!lane->holds_hot || lane->db->mp || lane->hot_shared) return; + lane->holds_hot = false; + atomic_fetch_sub(&lane->db->hot_held, 1); +} + +// A speculative snapshot that ends without a commit of its own (the write statement changed nothing, or the transaction was rolled back) may have shown the application rows of commits +// that are not durable yet: the transaction ends only once they are (or the database failed, or they were taken back). A commit needs none of this: it is acknowledged when its own record +// is durable, and the log is durable as a prefix. +void mw_lane_spec_settle (mw_lane *lane) { + if (!lane->spec) return; + lane->spec = false; + mw_db *db = lane->db; + const uint64_t s = lane->tx.snapshot_epoch; + for (unsigned i = 0; atomic_load_explicit(&db->epoch, memory_order_acquire) < s && !atomic_load(&db->failed) && atomic_load(&db->spec_gen) == lane->spec_gen; i++) { + if (i < 64) sched_yield(); + else { struct timespec ts = { 0, 20000 }; nanosleep(&ts, NULL); } + } +} + void mw_lane_init (mw_lane *lane, mw_db *db) { memset(lane, 0, sizeof(*lane)); lane->db = db; @@ -106,6 +142,13 @@ void mw_lane_snapshot_begin (mw_lane *lane) { for (;;) { sqlite3_mutex_enter(db->mu); lane->tx.snapshot_epoch = mw_db_visible_epoch(db); + lane->spec = false; + if ((lane->write_intent || lane->rb_helper) && !db->mp && !db->mp_req && lane->private_mode && !atomic_load(&db->failed) && lane->spec_on) { // (the helper of the rebase: its replay must read at least what the transaction it replays read, which may be speculative; it shows nothing to an application; a failed database has installed commits that will never be durable: the commit that recovers it must not have read them) + // (the generation first: if epochs are taken back after it was read, the commit of this snapshot is refused; if before, their marks were cleared before it was bumped) + uint64_t g = atomic_load(&db->spec_gen), s = mw_spec_top(db); + if (s > lane->tx.snapshot_epoch) { lane->tx.snapshot_epoch = s; lane->spec = true; lane->spec_gen = g; } + } + lane->write_intent = false; lane->next_active = db->active; lane->prev_active = NULL; if (db->active) db->active->prev_active = lane; @@ -154,6 +197,9 @@ void mw_lane_snapshot_begin (mw_lane *lane) { void mw_lane_snapshot_end (mw_lane *lane) { mw_db *db = lane->db; if (!lane->snapshot_held) return; + // (not after a commit: it waited for its own record; not after a refusal: the application was told that the transaction failed; not for the helper of the rebase: the transaction it replays is told the outcome of its own commit) + if (lane->spec && lane->tx.state == MW_TX_ACTIVE && !lane->rb_helper) mw_lane_spec_settle(lane); + lane->spec = false; sqlite3_mutex_enter(db->mu); if (lane->prev_active) lane->prev_active->next_active = lane->next_active; else db->active = lane->next_active; diff --git a/src/multiwriter_vfs.c b/src/multiwriter_vfs.c index 73b60f4..205c0b2 100644 --- a/src/multiwriter_vfs.c +++ b/src/multiwriter_vfs.c @@ -81,10 +81,24 @@ static bool mw_is_ddl_sql (const char *sql) { for (unsigned i = 0; i < sizeof(kw) / sizeof(kw[0]); i++) if (sqlite3_strnicmp(sql, kw[i], (int)strlen(kw[i])) == 0) return !mw_is_temp_ddl(sql); return false; } +// A statement that writes (sqlite3_stmt_readonly is true for BEGIN, which takes the snapshot when it is IMMEDIATE or EXCLUSIVE). +static bool mw_writes_stmt (sqlite3_stmt *st) { + if (!sqlite3_stmt_readonly(st)) return true; + const char *sql = sqlite3_sql(st); + if (!sql) return false; + char w[16]; const char *p = ddl_word(sql, w, sizeof w); + if (strcmp(w, "begin")) return false; + ddl_word(p, w, sizeof w); + return strcmp(w, "immediate") == 0 || strcmp(w, "exclusive") == 0; +} static int mw_trace_cb (unsigned type, void *ctx, void *p, void *x) { (void)x; if (type != SQLITE_TRACE_STMT && type != SQLITE_TRACE_PROFILE) return 0; sqlite3_stmt *st = (sqlite3_stmt *)p; + if (mw_writes_stmt(st)) { // (a write: the snapshot that it takes, if it takes one, may include commits that are not durable yet; see mw_spec_on) + int on = type == SQLITE_TRACE_STMT; + sqlite3_file_control(sqlite3_db_handle(st), "main", MW_FCNTL_WRITE_INTENT, &on); + } if (ctx) { // a mw_rebase=1 connection: what the transaction reads (mw_lane_reads_unchanged) mw_stmt_note n = { type == SQLITE_TRACE_PROFILE, sqlite3_get_autocommit(sqlite3_db_handle(st)), st }; sqlite3_file_control(sqlite3_db_handle(st), "main", MW_FCNTL_STMT, &n); @@ -309,6 +323,8 @@ static int mw_open (sqlite3_vfs *vfs, const char *name, sqlite3_file *pf, int fl if (small || sqlite3_uri_parameter(name, "mw_base_cache_mb")) { db->base_cache_bytes = (uint64_t)sqlite3_uri_int64(name, "mw_base_cache_mb", small ? 8 : 64) << 20; if (db->store) db->store->base_limit = db->base_cache_bytes; } if (small && !sqlite3_uri_parameter(name, "mw_log_max_mb")) db->log_max_bytes = 16ull << 20; lane->norebase = sqlite3_uri_boolean(name, "mw_norebase", 0) != 0; + lane->rb_helper = lane->norebase && sqlite3_uri_boolean(name, "mw_rbhelper", 0); // (internal: the helper connection of the rebase, see mw_lane_snapshot_begin) + lane->spec_on = sqlite3_uri_boolean(name, "mw_spec", mw_spec_on()) != 0; // (speculative snapshots of the writers: on unless the URI or MW_NO_SPEC says otherwise) lane->rebase_on = sqlite3_uri_boolean(name, "mw_rebase", 0) != 0 && !lane->norebase; lane->rb_nobackoff = !sqlite3_uri_boolean(name, "mw_rebase_backoff", 1); lane->noreloc = sqlite3_uri_boolean(name, "mw_noreloc", 0) != 0; diff --git a/test/mw_diskfull.c b/test/mw_diskfull.c index 283c750..ee757d3 100644 --- a/test/mw_diskfull.c +++ b/test/mw_diskfull.c @@ -21,7 +21,7 @@ static char img[256], mnt[256], ballast[300]; static bool vol_make (long mb) { - char cmd[900]; + char cmd[1600]; // (room for the longest command: three paths of up to 255 bytes each, a file system name and the fixed text) snprintf(img, sizeof img, "/tmp/mw_full_%d.img", (int)getpid()); snprintf(mnt, sizeof mnt, "/tmp/mw_full_mnt_%d", (int)getpid()); snprintf(ballast, sizeof ballast, "%s/ballast", mnt); #ifdef __APPLE__ diff --git a/test/mw_ioerr.c b/test/mw_ioerr.c index 796a4a6..d1ca6bd 100644 --- a/test/mw_ioerr.c +++ b/test/mw_ioerr.c @@ -95,7 +95,7 @@ static long run_once (const char *path, bool shared, const scenario *sc, long nt static void verify (const char *path, bool shared, int acked, const char *what, long nth) { sqlite3 *r; int rc = open_db(path, &r, shared); if (rc != SQLITE_OK) { printf("FAIL %s n=%ld: cannot open the database again (%d)\n", what, nth, rc); mw_failures++; return; } - int64_t sum; int rows; int bad = check_rows(r, &sum, &rows); + int64_t sum = 0; int rows = 0; int bad = check_rows(r, &sum, &rows); if (bad != 0 || rows != NROWS || (sum & 1) || sum < 2 * acked) { printf("FAIL %s n=%ld: %d rows (want %d), %d disagree with the metadata, sum(n)=%lld, acknowledged %d\n", what, nth, rows, NROWS, bad, (long long)sum, acked); mw_failures++; diff --git a/test/mw_multiproc.c b/test/mw_multiproc.c index 1e1c498..b6911d8 100644 --- a/test/mw_multiproc.c +++ b/test/mw_multiproc.c @@ -2,6 +2,8 @@ // Children are forked BEFORE the database is opened in the parent (a forked lane state is not shareable). #include #include +#include +#include #include #include "mw_test.h" #include "multiwriter.h" @@ -42,6 +44,7 @@ static void make_db (const char *path) { typedef struct { const char *path; int proc, thread, row, iters, kind; int64_t ok, retries; const char *extra; } job_t; static volatile int g_stop; +static int g_ack_fd = -1; // the victim of a kill (scenario 4): a byte for each of the first commits of each thread, so that it is killed after it has committed, not after a fixed time // kind 0: own row, disjoint pages; 1: shared counter (retry until committed); 2: unique inserts into a tracked table static void *worker (void *arg) { @@ -55,7 +58,7 @@ static void *worker (void *arg) { else snprintf(sql, sizeof sql, "INSERT INTO docs VALUES('p%d-t%d-%d',%d,'body %d')", j->proc, j->thread, i, j->proc, i); for (int a = 0; a < 5000; a++) { int rc = mw_exec(db, sql); - if (rc == SQLITE_OK) { j->ok++; break; } + if (rc == SQLITE_OK) { j->ok++; if (g_ack_fd >= 0 && j->ok <= 25) (void)!write(g_ack_fd, "x", 1); break; } if ((rc & 0xff) != SQLITE_BUSY) { fprintf(stderr, "proc %d thread %d iter %d: rc=%d ext=%d %s\n", j->proc, j->thread, i, rc, sqlite3_extended_errcode(db), sqlite3_errmsg(db)); break; } j->retries++; if (a == 4999) fprintf(stderr, "proc %d thread %d iter %d: gave up after 5000 retries, last rc=%d\n", j->proc, j->thread, i, sqlite3_extended_errcode(db)); @@ -82,6 +85,7 @@ static void child_main (int wfd, const char *path, int proc, int nthreads, int k static int spawn (int *rfd, const char *path, int proc, int nthreads, int kind, int iters, int row_base, const char *extra) { int pfd[2]; CHECK(pipe(pfd) == 0); + fflush(NULL); // (a child must not inherit what the parent has printed and not yet written: under ThreadSanitizer its _exit writes it again) pid_t pid = fork(); if (pid == 0) { close(pfd[0]); child_main(pfd[1], path, proc, nthreads, kind, iters, row_base, extra); } close(pfd[1]); @@ -149,9 +153,20 @@ int main (void) { // ---- 4. SIGKILL one process while the others keep writing mw_tmpdb(path, sizeof path, "mp4"); snprintf(lp, sizeof lp, "%s-mw", path); snprintf(mp, sizeof mp, "%s-mwlock", path); unlink(lp); unlink(mp); make_db(path); - for (int p = 0; p < 3; p++) pid[p] = spawn(&rfd[p], path, p, 4, 0, p == 0 ? 0 : 3000, 1 + p * 4, "&mw_compact_ms=5"); // proc 0 runs until killed - struct timespec ts = { 0, 150 * 1000000L }; nanosleep(&ts, NULL); + int ack[2]; CHECK(pipe(ack) == 0); + g_ack_fd = ack[1]; + for (int p = 0; p < 3; p++) { pid[p] = spawn(&rfd[p], path, p, 4, 0, p == 0 ? 0 : 3000, 1 + p * 4, "&mw_compact_ms=5"); g_ack_fd = -1; } // proc 0 runs until killed (only it acknowledges) + close(ack[1]); + { // killed once it has committed 50 updates (at most a minute): on a slow machine (ThreadSanitizer) a fixed 150 ms killed it before its first commit, and "killed > 0" failed + int got = 0; char buf[64]; + for (int waited = 0; got < 50 && waited < 60000; ) { + struct pollfd pf = { ack[0], POLLIN, 0 }; + if (poll(&pf, 1, 100) > 0) { ssize_t r = read(ack[0], buf, sizeof buf); if (r <= 0) break; got += (int)r; } else waited += 100; + } + if (got < 50) fprintf(stderr, "mw_multiproc: the process to kill had %d acknowledged commits (wanted 50)\n", got); + } kill(pid[0], SIGKILL); + close(ack[0]); int st; waitpid(pid[0], &st, 0); CHECK(WIFSIGNALED(st)); int64_t survivors = 0; for (int p = 1; p < 3; p++) { survivors += collect(rfd[p], NULL); waitpid(pid[p], &st, 0); CHECK(WIFEXITED(st) && WEXITSTATUS(st) == 0); } @@ -175,6 +190,7 @@ int main (void) { make_db(path); { int go[2], done[2]; CHECK(pipe(go) == 0 && pipe(done) == 0); + fflush(NULL); pid_t w = fork(); if (w == 0) { // writer process: waits for the go signal, commits 500 updates, exits char c; if (read(go[0], &c, 1) != 1) _exit(2); diff --git a/test/mw_reloc.c b/test/mw_reloc.c index 407d86c..d2789a3 100644 --- a/test/mw_reloc.c +++ b/test/mw_reloc.c @@ -135,7 +135,8 @@ int main (void) { CHECK_RC(mw_exec(a, "COMMIT"), SQLITE_OK); int rb = mw_exec(b, "COMMIT"), rc = mw_exec(c, "COMMIT"); printf("index test: commits rc=%d,%d relocations=%llu\n", rb, rc, (unsigned long long)stats(a).relocations); - if (rb) mw_exec(b, "ROLLBACK"); if (rc) mw_exec(c, "ROLLBACK"); + if (rb) mw_exec(b, "ROLLBACK"); + if (rc) mw_exec(c, "ROLLBACK"); int64_t expect = 1 + 401 + (rb == 0 ? 401 : 0) + (rc == 0 ? 401 : 0); CHECK(mw_scalar(a, "SELECT count(*) FROM t") == expect); CHECK(mw_scalar(a, "SELECT count(*) FROM t INDEXED BY tk") == expect); diff --git a/test/mw_relocprep.c b/test/mw_relocprep.c index c6b7159..f3b47d7 100644 --- a/test/mw_relocprep.c +++ b/test/mw_relocprep.c @@ -41,7 +41,8 @@ static void *worker (void *arg) { sqlite3_close(db); return NULL; } -static void run (const char *name, int delay_us, int hot, int need_rewrite) { +// Returns the number of prepared phases that were rewritten (the data checks are made in every run). +static uint64_t run (const char *name, int delay_us, int hot) { char path[256]; mw_tmpdb(path, sizeof path, "relocprep"); sqlite3 *s; CHECK_RC(sqlite3_open_v2(path, &s, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, MW_PLAIN_VFS), SQLITE_OK); CHECK_RC(mw_exec(s, "PRAGMA journal_mode=WAL; CREATE TABLE t(id INTEGER PRIMARY KEY, k TEXT, v BLOB); CREATE INDEX ik ON t(k); CREATE TABLE hot(id INTEGER PRIMARY KEY, n INTEGER); INSERT INTO hot VALUES(1, 0)"), SQLITE_OK); @@ -57,16 +58,20 @@ static void run (const char *name, int delay_us, int hot, int need_rewrite) { (unsigned long long)st.relocations, (unsigned long long)st.reloc_prep_used, (unsigned long long)st.reloc_prep_dropped, (unsigned long long)st.reloc_prep_rewrote); CHECK(rows == want_rows); CHECK(bytes == want_bytes); CHECK(idx == want_rows); CHECK(integrity_ok(obs)); CHECK(st.reloc_prep_used > 0); - if (need_rewrite) CHECK(st.reloc_prep_rewrote > 0); sqlite3_close(obs); { sqlite3 *r; CHECK_RC(open_mp(path, &r, 0), SQLITE_OK); CHECK(scalar(r, "SELECT count(*) FROM t") == want_rows); CHECK(integrity_ok(r)); sqlite3_close(r); } // (and after a reopen: the log replays what was published) mw_rmdb(path); + return st.reloc_prep_rewrote; } int main (void) { setvbuf(stdout, NULL, _IOLBF, 0); - run("1. the end of the file moves between the preparation and the lock", 400, 0, 1); - run("2. no delay", 0, 0, 0); - run("3. with a hot row next to the inserts", 200, 1, 0); + // 1. must rewrite prepared phases (that is what it is for): that needs commits that extend the file while another waits between its preparation and the lock, and on a slow machine + // (ThreadSanitizer on a runner of 4 CPUs: 5 relocations in a run, none rewritten) the threads may hardly overlap. Run again, up to three times, until it happens; the data are checked every time + uint64_t rewrote = 0; + for (int attempt = 0; attempt < 3 && rewrote == 0; attempt++) rewrote = run("1. the end of the file moves between the preparation and the lock", 400, 0); + CHECK(rewrote > 0); + run("2. no delay", 0, 0); + run("3. with a hot row next to the inserts", 200, 1); MW_DONE(); } diff --git a/test/mw_serial.c b/test/mw_serial.c index 24941d4..a3971ff 100644 --- a/test/mw_serial.c +++ b/test/mw_serial.c @@ -374,7 +374,10 @@ static void procs_run (const char *path, int keys, int nprocs, double secs, int g_procs_mode = 1; g_path = path; g_keys = keys; g_secs = secs; proc_h pid[32]; int gen[32]; struct timespec t0; clock_gettime(CLOCK_MONOTONIC, &t0); for (int i = 0; i < nprocs; i++) { gen[i] = 0; pid[i] = proc_start(i, 0); } - unsigned rng = 555u; int kills = 0, crashes = 0; double next_kill = (double)kill_ms / 1000.0; int sampled = 0; long long last_tot = -2; double last_move = 0, last_poll = 0; + unsigned rng = 555u; int kills = 0, crashes = 0; double next_kill = (double)kill_ms / 1000.0; +#ifndef _WIN32 + int sampled = 0; long long last_tot = -2; double last_move = 0, last_poll = 0; // (the sampling of a stall below: POSIX only) +#endif for (;;) { struct timespec t1; clock_gettime(CLOCK_MONOTONIC, &t1); double el = (double)(t1.tv_sec - t0.tv_sec) + (double)(t1.tv_nsec - t0.tv_nsec) / 1e9; diff --git a/test/mw_sharedwindow.c b/test/mw_sharedwindow.c index 070a1c7..20ac29e 100644 --- a/test/mw_sharedwindow.c +++ b/test/mw_sharedwindow.c @@ -34,9 +34,8 @@ int main (void) { if (pid == 0) { sqlite3 *b; if (open_mp(path, &b) != SQLITE_OK) _exit(2); mw_fault_arm(pts[p], nth); - int acked = 0; for (int i = 0; i < 20; i++) { - if (mw_exec(b, "UPDATE t SET n=n+1 WHERE id=1") == SQLITE_OK) { acked++; (void)!write(fd[1], "x", 1); } + if (mw_exec(b, "UPDATE t SET n=n+1 WHERE id=1") == SQLITE_OK) (void)!write(fd[1], "x", 1); // (the parent counts the acknowledgements from the pipe) } _exit(0); // (the fault point did not fire) } diff --git a/test/mw_spec.c b/test/mw_spec.c new file mode 100644 index 0000000..1ee4f6c --- /dev/null +++ b/test/mw_spec.c @@ -0,0 +1,192 @@ +// Speculative snapshots (one process). A write transaction reads at the newest installed epoch, which may include commits whose record is not durable yet; a reader that does not write +// reads only what is durable. Built with multiwriter_log.c compiled with -Dfsync=inject_fsync, so that the fsync of the log can be held or slowed. +// 1. While the fsync of commit A is held: a plain reader does not see A; a writer sees it (its rowid comes after A's) and is acknowledged only after the fsync; a write statement that +// changes nothing (it read A) ends only after the fsync too. +// 2. A commit whose record cannot be written is taken back: a writer that read it (speculatively) is refused, and its retry commits on the state without it. +// 4. A connection opened with mw_spec=0 does not read the commit whose fsync is held: its insert takes the same rowid as that commit. +// 3. Appends with SQLite's own rowids from several threads (each depends on the one before): every row is there once, and the commits share the fsyncs of the log (group commit). +#include +#include +#include +#include "mw_test.h" +#include "multiwriter.h" + +static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t cv = PTHREAD_COND_INITIALIZER; +static int armed, entered, released, slow_us; +int inject_fsync (int fd) { + pthread_mutex_lock(&mu); + if (armed) { armed = 0; entered = 1; pthread_cond_broadcast(&cv); while (!released) pthread_cond_wait(&cv, &mu); } + int us = slow_us; + pthread_mutex_unlock(&mu); + if (us) usleep((useconds_t)us); + return fsync(fd); +} + +static char g_path[300]; +static sqlite3 *open_mw_uri (const char *extra) { + char uri[400]; sqlite3 *db = NULL; + snprintf(uri, sizeof uri, "file:%s?vfs=multiwriter%s", g_path, extra); + if (sqlite3_open_v2(uri, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI, NULL) != SQLITE_OK) { printf("FAIL open\n"); exit(1); } + sqlite3_extended_result_codes(db, 1); + sqlite3_busy_timeout(db, 0); + return db; +} +static sqlite3 *open_mw (void) { return open_mw_uri(""); } +static void fresh (const char *tag) { + mw_tmpdb(g_path, sizeof g_path, tag); + sqlite3 *s; CHECK_RC(sqlite3_open_v2(g_path, &s, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, MW_PLAIN_VFS), SQLITE_OK); + CHECK_RC(mw_exec(s, "PRAGMA journal_mode=WAL; CREATE TABLE t(id INTEGER PRIMARY KEY, v TEXT); INSERT INTO t(v) VALUES ('seed')"), SQLITE_OK); + sqlite3_close(s); +} +static uint64_t now_ms (void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } + +typedef struct { sqlite3 *db; const char *sql; int rc; int64_t rowid; _Atomic int done; } job_t; +static void *run_job (void *a) { + job_t *j = a; + j->rc = mw_exec(j->db, j->sql); + j->rowid = sqlite3_last_insert_rowid(j->db); + atomic_store(&j->done, 1); + return NULL; +} + +static void case_held_fsync (void) { + fresh("spec1"); + sqlite3 *a = open_mw(), *r = open_mw(), *b = open_mw(), *c = open_mw(); + CHECK(mw_scalar(r, "SELECT count(*) FROM t") == 1); // (every connection has the database open: the store exists) + CHECK(mw_scalar(b, "SELECT count(*) FROM t") == 1); + CHECK(mw_scalar(c, "SELECT count(*) FROM t") == 1); + pthread_mutex_lock(&mu); armed = 1; entered = 0; released = 0; pthread_mutex_unlock(&mu); + job_t ja = { a, "INSERT INTO t(v) VALUES ('a')" }; + pthread_t ta; pthread_create(&ta, NULL, run_job, &ja); + pthread_mutex_lock(&mu); while (!entered) pthread_cond_wait(&cv, &mu); pthread_mutex_unlock(&mu); + // A is installed, its fsync is held + CHECK(mw_scalar(r, "SELECT count(*) FROM t") == 1); // a reader sees only what is durable + CHECK(mw_scalar(r, "SELECT count(*) FROM t WHERE v = 'a'") == 0); + job_t jb = { b, "INSERT INTO t(v) VALUES ('b')" }, jc = { c, "UPDATE t SET v = 'never' WHERE id = -5" }; + pthread_t tb, tc; pthread_create(&tb, NULL, run_job, &jb); pthread_create(&tc, NULL, run_job, &jc); + usleep(150000); + CHECK(!atomic_load(&ja.done)); + CHECK(!atomic_load(&jb.done)); // B committed on top of A: acknowledged only when durable + CHECK(!atomic_load(&jc.done)); // C changed nothing, and it read A: it ends when A is durable + CHECK(mw_scalar(r, "SELECT count(*) FROM t") == 1); + pthread_mutex_lock(&mu); released = 1; pthread_cond_broadcast(&cv); pthread_mutex_unlock(&mu); + pthread_join(ta, NULL); pthread_join(tb, NULL); pthread_join(tc, NULL); + CHECK_RC(ja.rc, SQLITE_OK); CHECK_RC(jb.rc, SQLITE_OK); CHECK_RC(jc.rc, SQLITE_OK); + CHECK(jb.rowid == ja.rowid + 1); // B's rowid was taken after A's: it read A before A was durable + CHECK(mw_scalar(r, "SELECT count(*) FROM t") == 3); + sqlite3_close(a); sqlite3_close(b); sqlite3_close(c); sqlite3_close(r); + mw_rmdb(g_path); +} + +static void case_taken_back (void) { + fresh("spec2"); + setenv("MW_FAULT_DELAY_US", "400000", 1); // the failing append of A waits 400 ms before it fails: B reads A meanwhile + sqlite3 *a = open_mw(), *b = open_mw(); + CHECK(mw_scalar(b, "SELECT count(*) FROM t") == 1); + mw_fault_arm(MW_FAULT_LOG_WRITE_ERR, 1); + job_t ja = { a, "INSERT INTO t(v) VALUES ('a')" }; + pthread_t ta; pthread_create(&ta, NULL, run_job, &ja); + usleep(100000); + CHECK_RC(mw_exec(b, "BEGIN"), SQLITE_OK); + CHECK_RC(mw_exec(b, "INSERT INTO t(v) VALUES ('b')"), SQLITE_OK); + int64_t spec_id = sqlite3_last_insert_rowid(b); + pthread_join(ta, NULL); + CHECK(ja.rc != SQLITE_OK); // A's record could not be written: A was taken back + CHECK(spec_id == 3); // B read A (seed = 1, A = 2) + int rc = mw_exec(b, "COMMIT"); + CHECK(rc != SQLITE_OK); // what B built on is gone: refused + mw_exec(b, "ROLLBACK"); + for (int i = 0; i < 100 && (rc = mw_exec(b, "INSERT INTO t(v) VALUES ('b')")) != SQLITE_OK; i++) usleep(10000); + CHECK_RC(rc, SQLITE_OK); + CHECK(sqlite3_last_insert_rowid(b) == 2); + CHECK(mw_scalar(b, "SELECT count(*) FROM t WHERE v = 'a'") == 0); + CHECK(mw_scalar(b, "SELECT count(*) FROM t") == 2); + sqlite3_close(a); sqlite3_close(b); + unsetenv("MW_FAULT_DELAY_US"); + char uri[400]; snprintf(uri, sizeof uri, "file:%s?vfs=multiwriter", g_path); + sqlite3 *v; CHECK_RC(sqlite3_open_v2(uri, &v, SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI, NULL), SQLITE_OK); + CHECK(mw_scalar(v, "SELECT count(*) FROM t") == 2); + CHECK(mw_scalar(v, "SELECT count(*) FROM t WHERE v = 'a'") == 0); + sqlite3_close(v); + mw_rmdb(g_path); +} + +enum { NT = 8, PER = 40, ROWS = 10 }; +static _Atomic int g_ok, g_retries; +static void *appender (void *arg) { + long id = (long)arg; sqlite3 *db = open_mw(); sqlite3_stmt *st; + sqlite3_prepare_v2(db, "INSERT INTO t(v) VALUES (?1)", -1, &st, NULL); + for (int k = 0; k < PER; k++) { + for (;;) { + int rc = mw_exec(db, "BEGIN"); + for (int i = 0; rc == SQLITE_OK && i < ROWS; i++) { + char v[40]; snprintf(v, sizeof v, "%ld:%d:%d", id, k, i); + sqlite3_bind_text(st, 1, v, -1, SQLITE_TRANSIENT); + rc = sqlite3_step(st); sqlite3_reset(st); + if (rc == SQLITE_DONE) rc = SQLITE_OK; + } + if (rc == SQLITE_OK) rc = mw_exec(db, "COMMIT"); + if (rc == SQLITE_OK) { g_ok++; break; } + mw_exec(db, "ROLLBACK"); + if ((rc & 0xff) != SQLITE_BUSY) { printf("FAIL appender rc %d\n", rc); mw_failures++; break; } + g_retries++; + } + } + sqlite3_finalize(st); sqlite3_close(db); + return NULL; +} +static void case_chain (void) { + fresh("spec3"); + sqlite3 *s = open_mw(); + CHECK(mw_scalar(s, "SELECT count(*) FROM t") == 1); + pthread_mutex_lock(&mu); slow_us = 3000; pthread_mutex_unlock(&mu); // a disk whose fsync takes 3 ms + mw_db_stats s0; memset(&s0, 0, sizeof s0); sqlite3_file_control(s, "main", MW_FCNTL_DBSTATS, &s0); + uint64_t t0 = now_ms(); + pthread_t th[NT]; + for (long i = 0; i < NT; i++) pthread_create(&th[i], NULL, appender, (void *)i); + for (int i = 0; i < NT; i++) pthread_join(th[i], NULL); + uint64_t ms = now_ms() - t0; + pthread_mutex_lock(&mu); slow_us = 0; pthread_mutex_unlock(&mu); + mw_db_stats s1; memset(&s1, 0, sizeof s1); sqlite3_file_control(s, "main", MW_FCNTL_DBSTATS, &s1); + uint64_t syncs = s1.log_syncs - s0.log_syncs; + printf("chain: %d commits, %d retries, %llu fsyncs, %llu ms\n", (int)g_ok, (int)g_retries, (unsigned long long)syncs, (unsigned long long)ms); + CHECK(g_ok == NT * PER); + CHECK(mw_scalar(s, "SELECT count(*) FROM t") == 1 + NT * PER * ROWS); + CHECK(mw_scalar(s, "SELECT count(DISTINCT v) FROM t") == 1 + NT * PER * ROWS); + CHECK(mw_scalar(s, "SELECT max(id) FROM t") == 1 + NT * PER * ROWS); // (no rowid was used twice or skipped: every commit took the ones after the one before) + CHECK(syncs * 2 < (uint64_t)g_ok); // the dependent commits shared the fsyncs (one each: as many fsyncs as commits) + sqlite3_stmt *st; sqlite3_prepare_v2(s, "PRAGMA integrity_check", -1, &st, NULL); + CHECK(sqlite3_step(st) == SQLITE_ROW && strcmp((const char *)sqlite3_column_text(st, 0), "ok") == 0); + sqlite3_finalize(st); + sqlite3_close(s); + mw_rmdb(g_path); +} + +static void case_spec_off (void) { + fresh("spec4"); + sqlite3 *a = open_mw(), *b = open_mw_uri("&mw_spec=0"); + CHECK(mw_scalar(b, "SELECT count(*) FROM t") == 1); + pthread_mutex_lock(&mu); armed = 1; entered = 0; released = 0; pthread_mutex_unlock(&mu); + job_t ja = { a, "INSERT INTO t(v) VALUES ('a')" }; + pthread_t ta; pthread_create(&ta, NULL, run_job, &ja); + pthread_mutex_lock(&mu); while (!entered) pthread_cond_wait(&cv, &mu); pthread_mutex_unlock(&mu); + CHECK_RC(mw_exec(b, "BEGIN"), SQLITE_OK); + CHECK_RC(mw_exec(b, "INSERT INTO t(v) VALUES ('b')"), SQLITE_OK); + CHECK(sqlite3_last_insert_rowid(b) == 2); // (seed = 1: it did not see A, which took 2 too) + mw_exec(b, "ROLLBACK"); // (a transaction that is not speculative ends at once) + pthread_mutex_lock(&mu); released = 1; pthread_cond_broadcast(&cv); pthread_mutex_unlock(&mu); + pthread_join(ta, NULL); + CHECK_RC(ja.rc, SQLITE_OK); + CHECK(ja.rowid == 2); + sqlite3_close(a); sqlite3_close(b); + mw_rmdb(g_path); +} + +int main (void) { + case_held_fsync(); + case_spec_off(); + case_taken_back(); + case_chain(); + MW_DONE(); +} diff --git a/test/mw_syncwindow.c b/test/mw_syncwindow.c index 53461d5..3aa7c58 100644 --- a/test/mw_syncwindow.c +++ b/test/mw_syncwindow.c @@ -2,11 +2,14 @@ // a sync of its own. So the point must be one where the log is complete and stays: it used to be taken from the append cursor (sl_seg and sl_end, two words), and // 1. while the log rolled to the next segment, a leader could see the new segment with the end of the old one (about a megabyte that was then taken for synced); // 2. a record that was appended and then taken out of the log (the install of its versions failed) was below the point that a leader had already declared durable, and the commit that -// took its place was acknowledged without a sync. +// took its place was acknowledged without a sync; +// 3. a leader that found its own record made durable by the leader before it (which finished between its look and its turn) synced nothing and still moved the durable point to the end of +// the log as it was after its delay: past records that others had installed meanwhile, which were then acknowledged without a sync. // Each commit is checked by the number of syncs of the log that were made while it ran (the I/O injection counts them): a commit with synchronous=FULL that returns with none was // covered by a sync that finished before its record was written. #include #include +#include #include "mw_test.h" #include "multiwriter.h" @@ -52,11 +55,25 @@ static void scenario (const char *label, const char *env, const char *val, const int main (void) { setenv("MW_SEG_MB", "1", 1); + { // 3. (first, in a child: the engine reads its knobs once per process) every committer waits 2 ms before it tries to be the leader, and the leader takes its look 3 ms late: another leader + // often finishes in between, and the one that takes over finds its own record durable already + fflush(NULL); + pid_t c = fork(); + if (c == 0) { + setenv("MW_TEST_SYNC_DELAY_US", "3000", 1); + scenario("leader after a leader", "MW_TEST_SYNC_PRELEAD_US", "2000", NULL, NULL, 0, 200); + fflush(NULL); + _exit(mw_failures ? 1 : 0); + } + int st = 0; waitpid(c, &st, 0); + CHECK(WIFEXITED(st) && WEXITSTATUS(st) == 0); + } // 1. segments of 1 MB (a roll every 120 commits); the roll takes 20 ms between its two words, and the leaders take their look 10 ms late setenv("MW_TEST_SYNC_DELAY_US", "10000", 1); scenario("roll", "MW_TEST_ROLL_DELAY_US", "20000", NULL, NULL, 0, 300); // 2. the install of the 60th commit fails after 30 ms, the leaders take their look 15 ms late setenv("MW_TEST_SYNC_DELAY_US", "15000", 1); scenario("install failure", "MW_FAULT_DELAY_US", "30000", NULL, NULL, 60, 200); + MW_DONE(); } diff --git a/test/sanitize.sh b/test/sanitize.sh index 7a5b64a..9ced93a 100755 --- a/test/sanitize.sh +++ b/test/sanitize.sh @@ -31,7 +31,7 @@ for t in $TESTS; do mw_stagednormal) "$CC" -w $CF -Dpwritev=inject_pwritev -c src/multiwriter_log.c -o $OUT/injected.o TEST_LIBS="${LIBS//$OUT\/multiwriter_log.o/} $OUT/injected.o";; - mw_holesync) + mw_holesync|mw_spec) "$CC" -w $CF -Dfsync=inject_fsync -c src/multiwriter_log.c -o $OUT/injected.o TEST_LIBS="${LIBS//$OUT\/multiwriter_log.o/} $OUT/injected.o";; mw_autoextfail)