An Antithesis stress run (WAL mode, two threads sharing one database, no
disk faults) failed PRAGMA integrity_check with index entries missing
from their tables and two pages that no B-tree used. Committed writes
were partly lost: one INSERT kept its table row but lost its index
entry, another kept its index entry but lost its table row.
The damage was done by a FULL checkpoint. It reported every frame of the
WAL as copied (log=23 checkpointed=23), but the database file it left
behind still had the old content of every page whose newest version was
in WAL frames 1 to 6. Every page with a newer frame had been copied. The
next WAL restart then discarded frames 1 to 6, so the committed changes
in them were gone from both the WAL and the database file.
The checkpoint reads nbackfills from a WAL snapshot taken before it
acquires the checkpoint locks, and copies frames starting from
nbackfills + 1. The upper end of the range, the maximum safe frame, is
read after the locks are held. If, between the two reads, another
connection copies the whole WAL, restarts it and commits new frames, the
checkpoint copies frames old_nbackfills + 1 to new_max_frame of the new
WAL generation. It skips the first old_nbackfills frames of the new
generation without an error and then publishes nbackfills as
new_max_frame, so from then on those frames count as copied.
In the failing run, one thread published nbackfills = 6 with a PASSIVE
checkpoint and then started a FULL checkpoint, which read nbackfills =
6. Before the thread took the checkpoint locks, the other thread
checkpointed the WAL, restarted it and committed 23 new frames. The FULL
checkpoint then copied frames 7 to 23 only.
The mismatch was introduced by commit 7c027fed8c ("Keep
should_checkpoint logic for now until greater checkpointing is fixed"),
which set the first frame to copy to nbackfills + 1 using the value read
before the checkpoint lock was taken, while the maximum safe frame was
read after it. Later changes to the checkpoint kept that order.
Fix this by reading nbackfills after the checkpoint locks are acquired,
so both ends of the copy range come from the same state. The check
before the locks that decides whether there is anything to copy still
uses the earlier read.
Closes#9384
An Antithesis stress run (WAL mode, two threads sharing one database, no
disk faults) failed PRAGMA integrity_check with index entries missing
from their tables and two pages that no B-tree used. Committed writes
were partly lost: one INSERT kept its table row but lost its index
entry, another kept its index entry but lost its table row.
The damage was done by a FULL checkpoint. It reported every frame of
the WAL as copied (log=23 checkpointed=23), but the database file it
left behind still had the old content of every page whose newest
version was in WAL frames 1 to 6. Every page with a newer frame had
been copied. The next WAL restart then discarded frames 1 to 6, so the
committed changes in them were gone from both the WAL and the database
file.
The checkpoint reads nbackfills from a WAL snapshot taken before it
acquires the checkpoint locks, and copies frames starting from
nbackfills + 1. The upper end of the range, the maximum safe frame, is
read after the locks are held. If, between the two reads, another
connection copies the whole WAL, restarts it and commits new frames,
the checkpoint copies frames old_nbackfills + 1 to new_max_frame of the
new WAL generation. It skips the first old_nbackfills frames of the new
generation without an error and then publishes nbackfills as
new_max_frame, so from then on those frames count as copied.
In the failing run, one thread published nbackfills = 6 with a PASSIVE
checkpoint and then started a FULL checkpoint, which read
nbackfills = 6. Before the thread took the checkpoint locks, the other
thread checkpointed the WAL, restarted it and committed 23 new frames.
The FULL checkpoint then copied frames 7 to 23 only.
The mismatch was introduced by commit 7c027fed8c ("Keep
should_checkpoint logic for now until greater checkpointing is fixed"),
which set the first frame to copy to nbackfills + 1 using the value
read before the checkpoint lock was taken, while the maximum safe frame
was read after it. Later changes to the checkpoint kept that order.
Fix this by reading nbackfills after the checkpoint locks are acquired,
so both ends of the copy range come from the same state. The check
before the locks that decides whether there is anything to copy still
uses the earlier read.
This is a follow up from
https://github.com/tursodatabase/turso/pull/8945 When doing integrity
checks, if we get busy, we roll back the txn and let the stresser
continue.
Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Closes#9319
`Database::connect` refreshed the connection's ANALYZE stats by running
`SELECT ... FROM sqlite_stat1` through `run_with_row_callback`, a
blocking loop that pumps `io.step()` until the statement finishes. The
same loop ran after every ANALYZE from `Statement::finish_step`.
That is only correct when whatever the statement waits for can make
progress on its own. When the `sqlite_stat1` scan speculatively read a
version whose writer was still `Preparing`, its end-of-statement commit
parked in `WaitForDependencies` with an explicit yield: a request to run
*other* connections. In a host that schedules every connection
cooperatively on one thread (turso-server), `io.step()` never does that,
so `connect` spun at 100% CPU inside the host's event loop and every
connection froze. The turso-server's simulator (internal project) hit
this on redeploy, when fresh connections raced a concurrent ANALYZE
commit that was itself parked on S3 uploads.
Turn both refreshes into resumable state machines built on the existing
`refresh_analyze_stats_nonblock`:
- `Database::connect_async` / `connect_with_encryption_async` take a
`ConnectAsyncState` and return `IOResult::IO` for every wait, to be
driven like `open_async`. `connect` keeps its blocking behaviour for
embedded callers; connection construction is split out into
`new_connection` so the blocking refresh is a caller decision.
- After ANALYZE reaches `Done`, `Statement::step` keeps returning
IO/Yield while the refresh waits and reports `Done` once it has
finished, instead of pumping IO itself. `reset` abandons an in-flight
refresh.
Add a regression test that parks an ANALYZE commit in `Preparing` with
the yield injector and checks that `connect_async` hands the dependency
wait back to the caller and completes once the commit finishes.
Reviewed-by: Jussi Saurio <jussi.saurio@gmail.com>
Closes#9320
I tried to make the hash join selection algorithm a little more
readable. It was one big flat procedure, so I tried to make its
structure more explicit by extracting two functions and moving
conditions to closures. Now we have this in the code:
```rs
// we should not use a hash join if...
!both_sides_have_rowid()
|| not_full_outer_join_and_both_tables_are_the_same_table()
|| has_indexed_by_directives()
|| any_side_is_semi_or_build_side_is_anti()
|| build_table_is_null_row()
|| is_using_or_natural_join()
|| some_correlated_subqueries_reference_the_joined_tables()
```
Reviewed-by: Jussi Saurio <jussi.saurio@gmail.com>
Closes#9136
a subquery's FROM could bind a table name to an outer alias, so a DELETE
aliased to another table's name read the target and emptied it. FROM now
sees only CTE names.
```sql
CREATE TABLE t(a INT);
CREATE TABLE u(a INT);
INSERT INTO t VALUES(1),(2),(3);
INSERT INTO u VALUES(2);
DELETE FROM t AS u WHERE a IN (SELECT a FROM u);
SELECT COUNT(*) FROM t;
-- turso: 0
-- sqlite: 2
CREATE TABLE w(a INT);
INSERT INTO w VALUES(5),(6);
WITH w(a) AS (SELECT 9) UPDATE w SET a = (SELECT a FROM w);
SELECT a FROM w;
-- turso: 5 5
-- sqlite: 9 9
```
closes#8709
Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Reviewed-by: Pere Diaz Bou <pere-altea@homail.com>
Closes#9191
`Database::connect` refreshed the connection's ANALYZE stats by running
`SELECT ... FROM sqlite_stat1` through `run_with_row_callback`, a blocking
loop that pumps `io.step()` until the statement finishes. The same loop ran
after every ANALYZE from `Statement::finish_step`.
That is only correct when whatever the statement waits for can make progress
on its own. When the `sqlite_stat1` scan speculatively read a version whose
writer was still `Preparing`, its end-of-statement commit parked in
`WaitForDependencies` with an explicit yield: a request to run *other*
connections. In a host that schedules every connection cooperatively on one
thread (turso-server), `io.step()` never does that, so `connect` spun at
100% CPU inside the host's event loop and every connection froze. The
server's simulator hit this on redeploy, when fresh connections raced a
concurrent ANALYZE commit that was itself parked on S3 uploads.
Turn both refreshes into resumable state machines built on the existing
`refresh_analyze_stats_nonblock`:
- `Database::connect_async` / `connect_with_encryption_async` take a
`ConnectAsyncState` and return `IOResult::IO` for every wait, to be driven
like `open_async`. `connect` keeps its blocking behaviour for embedded
callers; connection construction is split out into `new_connection` so the
blocking refresh is a caller decision.
- After ANALYZE reaches `Done`, `Statement::step` keeps returning IO/Yield
while the refresh waits and reports `Done` once it has finished, instead of
pumping IO itself. `reset` abandons an in-flight refresh.
- The blocking `refresh_analyze_stats` now drives the non-blocking state
machine to completion instead of carrying its own scanner, so the two
cannot diverge; the duplicate blocking scanner is removed.
Add regression tests: one parks an ANALYZE commit in `Preparing` with the
yield injector and checks that `connect_async` hands the dependency wait back
to the caller and completes once the commit finishes; one drops a connect
state while its scan is parked and checks nothing blocks.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Read the source row before passing its values to an index method. Keep
table access and index-method predicate evaluation separate when the
search needs values from that row or from a later join table.
- The source can be a table scan, a primary-key lookup, or a covering-
index scan.
- A separate index-method cursor searches with the captured arguments
and checks whether its results contain the source row.
- Existing expression table masks prevent an index search from supplying
rows that its own arguments need first.
This uses the existing index-method query patterns and bytecode
instructions. It does not add an FTS-specific runtime instruction or
change scalar function implementations. Matching predicates use the
index method instead of scalar fallback, including when the normal table
access plan uses a different index.
## Plain-English explanation and example
This fix stops Turso from starting an indexed text search before it
reads the row that supplies the search text.
For example, this query uses each row's text as its own search query:
```sql
CREATE TABLE d(id INTEGER PRIMARY KEY, body);
CREATE INDEX fx ON d USING fts(body);
INSERT INTO d VALUES
(1, 'database'),
(2, 'sql'),
(3, 'database sql');
SELECT id FROM d WHERE fts_match(body, body) ORDER BY id;
```
Before this fix, the query returned no rows because Turso tried to read
the search text before it selected a row.
After this fix, Turso reads each row and passes its `body` to the index
method, which returns:
```text
1
2
3
```
Turso now checks whether the search text is available before it chooses
an index search.
If the text comes from another table, Turso can read that table first
and repeat the indexed search for each row.
If the index search cannot supply the source rows, a separate source
cursor reads them first.
The index cursor does not move the source cursor, and the result
includes each source row only if the index search matches it.
## Bytecode before and after
Captured from the baseline and fixed CLI builds, using the fixture above
and this query without `ORDER BY`:
```sql
EXPLAIN SELECT id FROM d WHERE fts_match(body, body);
```
The diff shows the changed instructions and the surrounding row loop.
The columns are instruction address, opcode, P1, P2, P3, P4, and P5.
Setup and shutdown instructions are omitted.
```diff
1 OpenRead 0 2 0 k(2,B,B) 0
-2 OpenRead 1 0 0 0
-3 Integer 4 2 0 0
-4 Column 0 1 3 0
-5 IndexMethodQuery 0 1 2 0
-6 DeferredSeek 1 0 0 0
-7 IdxRowId 1 1 0 0
-8 ResultRow 1 1 0 0
-9 Next 1 6 0 0
+2 Rewind 0 17 0 0
+3 Once 5 0 0 0
+4 OpenRead 1 0 0 0
+5 RowId 0 2 0 0
+6 IsNull 2 16 0 0
+7 Integer 4 3 0 0
+8 Column 0 1 4 0
+9 IndexMethodQuery 0 1 3 0
+10 IdxRowId 1 5 0 0
+11 Eq 2 5 14 0
+12 Next 1 10 0 0
+13 Goto 0 16 0 0
+14 RowId 0 1 0 0
+15 ResultRow 1 1 0 0
+16 Next 0 3 0 1
```
Cursor 0 reads table `d`, and cursor 1 searches index `fx`.
Before the fix, `Column` reads `d.body` before any instruction positions
the table cursor on a row.
After the fix, `Rewind` positions the source cursor first, and `Column`
supplies that row's `body` to `IndexMethodQuery`.
`Once` opens the independent index cursor once per statement, while
`IndexMethodQuery` runs for every source row.
`Eq` checks whether the index result belongs to the source row, and the
two `Next` instructions advance the cursors separately.
There is no scalar `Function fts_match` instruction in this query.
IndexMethodQuery evaluates arguments before positioning its own table.
On the clean main baseline, `fts_match(body, body)` returned no rows and
`fts_match(body, coalesce(body, 'database'))` returned only rows 1 and 3
instead of 1, 2, 3. Searches referencing a later join table also
returned no rows.
Regressions cover both own-row forms, forced and reorderable joins,
changing outer queries, covering-index sources, primary-key lookups,
correlated arguments, limits, NULL values, and independent searches
using the same index. They also cover left and hash joins, updates,
deletes, and MVCC. `AND` and `NOT` queries distinguish indexed matching
from scalar fallback, and EXPLAIN assertions require `IndexMethodQuery`
with no scalar `fts_match` call.
The shared sparse-vector test still checks that a row-dependent search
vector cannot drive its own row's index scan. This PR does not add new
index-method patterns or change unrelated scalar-function policy. Per-
row predicate evaluation can repeat a broad index search for each source
row, so it can cost more than one index-driven scan.
Implemented independently from freshly fetched origin/main at https://gi
thub.com/tursodatabase/turso/commit/acc5a8808e47e374f4ce6eb004003b0a4f57
98c3; no PR #9182 or scalar-policy patches imported.
## Validation
- Regression-first runs: four dependency regressions failed on the
original baseline, then three indexed-predicate regressions failed
against the initial scalar-fallback implementation.
- `cargo test -p core_tester --test integration_tests index_method:: --
--nocapture` — 129 passed, including all seven dependency tests.
- `cargo test -p core_tester --test integration_tests` — 1,136 passed
and 9 ignored.
- From `sqlite/conformance`: `../../target/debug/sqltest run turso-
sqltests/fts.sqltest --backend cli --binary ../../target/debug/tursodb
--snapshot-filter __never__` — 68 passed, including the new own-row and
join regressions.
- `cargo clippy -p core_tester --test integration_tests --
--deny=warnings` — passed.
- `cargo fmt --check` and `git diff --check` — passed.
- CLI reproductions and EXPLAIN checked. Full workspace tests were not
run.
Amp implemented the fix, added and ran regressions before changing
engine code, and performed the targeted verification described above.
Implementation thread:
https://ampcode.com/threads/T-01a0c9d1-6ce7-735b-9d2b-2139e237f6b5
Reviewed-by: Jussi Saurio <jussi.saurio@gmail.com>
Closes#9292
A server that opens and drops many databases can keep using more heap
memory, even after all handles to each database are dropped. This PR
fixes a completion-group reference cycle and adds CI checks for memory
retained across repeated database lifecycles.
### Fix
A completion group waits for its child I/O completions, then calls its
callback. The old ownership links formed a cycle:
```text
GroupCompletionInner.self_completion
└──strong──> CompletionInner
└──strong──> GroupCompletionInner
```
Because each side held the other strongly, neither was freed after the
group finished. Every group could leak, including groups used for WAL
commits, checkpoints, and sorter spills.
The fix removes `self_completion`. While a child is pending, its
`parent` field holds the group's completion strongly. When the child
finishes, it takes and releases that reference, then reports its result
to the group:
```text
pending child.parent = Some(group completion)
child finishes:
parent = child.parent.take()
parent reports the child's result
```
This keeps the group alive if its caller drops the group handle while
children are pending. When the last child finishes, the group callback
and any parent-group notification still run. Finished child handles do
not keep the group alive.
### Accepted retention
- `DATABASE_MANAGER` keeps an entry for each unique database file
opened. Its `Weak<Database>` retains the `Database` allocation (about
470 bytes per file identity). The leak test calculates this expected
cost and includes it in its per-cycle budget.
- MVCC skiplist memory uses crossbeam-epoch deferred reclamation. The
leak test drains the epoch collector before measuring retained memory.
### CI automation
- `tests/leak/mod.rs` adds a separate `leak_tests` binary with a
counting global allocator. It runs 20 warmup and 100 measured
open/workload/drop cycles per journal mode (WAL and MVCC). Each cycle
uses a distinct database file. It fails if growth exceeds 128 bytes per
cycle beyond the calculated registry allowance. The completion-group
leak exceeds this budget.
- `tests/integration/database_leak.rs` checks that `Weak<Database>` and
`Weak<MvStore>` cannot be upgraded after all MVCC database handles are
dropped.
- `.github/workflows/rust.yml` runs the leak check explicitly. The test
target also runs in the workspace nextest job.
## Test plan
- `cargo test -p core_tester --test leak_tests`: about 470 bytes per
cycle, including registry retention, against a 640-byte budget in both
modes. With the completion-group leak restored, measured growth is about
750 bytes per cycle.
- `cargo test -p turso_core --lib` (1954 tests), `cargo test -p
core_tester --test integration_tests` (934 tests), shuttle tests single-
threaded (71 tests), clippy with `--deny=warnings`, and `cargo check -p
turso_core --target wasm32-wasip1-threads` all passed when this test
plan was run.
The `simulator (Faultless)` CI failure also occurred on main at the PR's
original base commit (`e773cdd5`) and was unrelated to this change.
https://claude.ai/code/session_0171ou6qAsxxvCtaWDKFk9s
Reviewed-by: Pere Diaz Bou <pere-altea@homail.com>
Closes#7447
ALTER TABLE ADD COLUMN and DROP COLUMN rebuild the stored CREATE TABLE
text from the parsed table. The code that rebuilds a FOREIGN KEY clause
always wrapped the parent column list in parentheses. When a foreign key
names no parent columns (REFERENCES p, meaning the parent's primary
key), it wrote REFERENCES p(). That is not valid SQL, so neither Turso
nor SQLite could open the database again.
Write the parentheses only when there is at least one parent column. The
clause then comes back as REFERENCES p, as SQLite stores it.
Tests: sqlite/conformance/sqlite-sqltests/alter-table-fk-without-parent-
columns.sqltest
Fixes#8701Closes#9314
Split from #8796. Numbers are Callgrind instructions per operation from
the MVCC benchmark in #8796 (each workload runs at 200 and 2,200
iterations; the difference is divided by 2,000), measured on #8796 when
each change was made. "Before" is #8796 just before the change.
Two commits.
**1. Box the checkpoint state machine in commit state.**
`CommitState::Checkpoint` stored the `CheckpointStateMachine` inline, so
every `CommitStateMachine` was 4,344 bytes. `commit_tx` built it on the
stack and copied it into its box, and each state change moved the whole
enum. That copy was the largest single cost of a read-only autocommit
statement. Boxing it makes `CommitStateMachine` 352 bytes; only a commit
that starts an automatic checkpoint allocates the box.
| Scenario | Before | After | Change |
|---|---:|---:|---:|
| `point_read` | 17,965 | 16,011 | -10.9% |
| `point_update_commit` | 44,144 | 39,210 | -11.2% |
| `index_read` | 40,568 | 38,544 | -5.0% |
| `insert_commit` | 106,520 | 101,355 | -4.8% |
**2. Hold the committing transaction's entry for the whole commit.**
Each commit state (`Initial`, `Commit`, `WaitForDependencies`, the
logical-log states, `CommitEnd`, `RewriteLiveVersions`,
`FinalizeCommit`) searched `txs` for the committing transaction again,
mostly to fail if it had been removed: 13 skip-map lookups per commit.
The state machine now takes the transaction's reference-counted skip-
list entry once, when it is built, and keeps it until the state machine
is dropped. Each state checks `Entry::is_removed()` where it checked for
a missing entry, and returns the same error. A removed node is never
returned by `get` and transaction IDs are never reused, so the check
gives the same answer as the search.
The entry's lifetime is extended to `'static` the same way as
`static_iterator_hack!`. The state machine owns the `Arc<MvStore>` whose
map the entry borrows, and the entry field is declared first, so it is
dropped first. The entry is never changed after construction. That is
what keeps the `&Transaction` references from `committing_tx` valid for
a whole step: they are tied to the step's store borrow, not to `self`.
The SAFETY comment in `CommitStateMachine::new` lists these rules.
| Scenario | Before | After | Change |
|---|---:|---:|---:|
| `point_update_commit` | 36,936 | 35,447 | -4.0% |
| `delete_commit` | 63,758 | 62,615 | -1.8% |
| `insert_commit` | 99,441 | 98,116 | -1.3% |
| `point_read` | 14,443 | 14,676 | +1.6% |
| `index_read` | 29,114 | 29,353 | +0.8% |
**Unexplained:** after commit 2, read-only statements do one lookup as
before, yet cost about 230 more instructions. The difference is in
glibc's allocator slow path (`_int_malloc`, `unlink_chunk`), not in MVCC
code. A likely cause is that the state machine grew by 16 bytes and its
per-commit box moved to another allocator size class; this was not
confirmed.
No behavior change; covered by the existing MVCC commit and checkpoint
tests.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-by: Avinash Sajjanshetty (@avinassh)
Closes#9303
In a group commit the leader writes the log records of every queued
transaction, but it chose whether to sync the log using only its own
sync mode. With a synchronous=OFF or NORMAL leader, a synchronous=FULL
waiter in the same group was marked durable and its COMMIT returned
success even though the log was never synced, so a crash could lose a
transaction that turso reported as durable.
Each queued commit now records its connection's sync mode. When the
leader writes a FULL record, the commit coordinator remembers that
ticket as the highest written ticket that needs a FULL sync. The sync
steps (SyncLogicalLog and SyncGroupPrefix) sync the log when the leader
uses FULL or when a FULL record is written but not yet durable. This
makes the group use the strictest sync mode of the records it writes.
The prefix sync case also covers FULL records written by an earlier
leader that stopped before syncing.
Tests: cargo test -p turso_core --lib
full_waiter_is_synced_when_group_leader_uses_sync_off
Fixes#9237
Reviewed-by: Pere Diaz Bou <pere-altea@homail.com>
Closes#9308
ALTER TABLE ADD COLUMN and DROP COLUMN rebuild the stored CREATE TABLE
text from the parsed table. The code that rebuilds a FOREIGN KEY clause
always wrapped the parent column list in parentheses. When a foreign key
names no parent columns (REFERENCES p, meaning the parent's primary key),
it wrote REFERENCES p(). That is not valid SQL, so neither Turso nor
SQLite could open the database again.
Write the parentheses only when there is at least one parent column. The
clause then comes back as REFERENCES p, as SQLite stores it.
Tests: sqlite/conformance/sqlite-sqltests/alter-table-fk-without-parent-columns.sqltest
Fixes#8701
Each commit state searched the transaction map for the committing
transaction again, mostly to fail if it had been removed: 13 skip-map
lookups for a one-row commit. Take the transaction's reference-counted
skip-list entry when the commit starts, release it when the commit finishes,
and check Entry::is_removed() where each state checked for a missing entry,
returning the same error. Removed nodes are never returned by get and
transaction IDs are never reused, so the check gives the same answer.
The entry's lifetime is extended to 'static like static_iterator_hack!: the
state machine owns the Arc<MvStore> whose map the entry borrows and drops
the entry before it.
Callgrind, 200/2,200 iterations: point_update_commit 36,936 -> 35,447
(-4.0%); delete_commit 63,758 -> 62,615 (-1.8%); insert_commit 99,441 ->
98,116 (-1.3%). Read-only statements rose about 230 instructions in glibc's
allocator slow path; the cause is not established.
Tests: cargo test -p turso_core --lib; cargo test -p core_tester --test
integration_tests mvcc; make -C sqlite/conformance run-rust MVCC=1;
turso_whopper --enable-mvcc seeds 1-20
ALTER TABLE ADD COLUMN and DROP COLUMN rewrite sqlite_schema.sql using
BTreeTable::to_sql(), which printed PRIMARY KEY without the column's
sort order. For `a INTEGER PRIMARY KEY DESC` this is worse than
cosmetic: the DESC form is not a rowid alias and owns an automatic
index, while the rewritten `a INTEGER PRIMARY KEY` is a rowid alias that
owns no index. The old index then stays in sqlite_schema with no key to
belong to, so reopening the file panics tursodb and sqlite3 reports a
malformed schema.
to_sql() now prints DESC after an inline PRIMARY KEY whose stored sort
order is descending, and after each descending column of a table-level
PRIMARY KEY (...). It skips DESC for an inline key that is a rowid
alias. That case only comes from a table-level `PRIMARY KEY(a DESC)` on
an INTEGER column, which SQLite treats as a rowid alias. Printing DESC
inline there would turn it into a non-alias key.
Fixes#8699Closes#9313
ALTER TABLE ADD COLUMN and DROP COLUMN rewrite sqlite_schema.sql using
BTreeTable::to_sql(), which printed PRIMARY KEY without the column's sort
order. For `a INTEGER PRIMARY KEY DESC` this is worse than cosmetic:
the DESC form is not a rowid alias and owns an automatic index, while the
rewritten `a INTEGER PRIMARY KEY` is a rowid alias that owns no index.
The old index then stays in sqlite_schema with no key to belong to, so
reopening the file panics tursodb and sqlite3 reports a malformed schema.
to_sql() now prints DESC after an inline PRIMARY KEY whose stored sort
order is descending, and after each descending column of a table-level
PRIMARY KEY (...). It skips DESC for an inline key that is a rowid
alias. That case only comes from a table-level `PRIMARY KEY(a DESC)` on an
INTEGER column, which SQLite treats as a rowid alias. Printing DESC inline
there would turn it into a non-alias key.
Fixes#8699
ALTER TABLE ADD COLUMN and DROP COLUMN rewrite sqlite_schema.sql using
BTreeTable::to_sql(). That function printed NOT NULL, UNIQUE, PRIMARY
KEY and table-level UNIQUE constraints without their ON CONFLICT clause,
even though the parsed schema keeps it. After such an ALTER, any
connection that reloads the schema enforced ABORT where the user asked
for ROLLBACK (or IGNORE/REPLACE/FAIL), so a transaction that relied on
ROLLBACK could end up with its earlier rows committed.
to_sql() now adds the stored clause after each constraint: the column's
NOT NULL clause, the matching single-column unique set for inline
UNIQUE, the primary key unique set (or the saved clause for an INTEGER
PRIMARY KEY rowid alias, whose unique set is removed during parsing) for
PRIMARY KEY, and each table-level UNIQUE set's own clause.
Tests: sqlite-sqltests/alter-table-keeps-on-conflict-clause.sqltest
Fixes#8703
Reviewed-by: Jussi Saurio <jussi.saurio@gmail.com>
Closes#9298
## What changed
- Write one register directly when `Null` or `BeginSubrtn` has no end
register.
- For `Copy` with `extra_amount == 0`, skip the range loop. Copy NULL
and numeric values by value.
- Return from `MustBeInt` immediately when the register already holds an
integer.
- Inline the `Column` opcode handler in non-test builds.
- Check `MakeRecord` register overlap with one unsigned comparison.
- Compare record payload bytes directly when checking whether an update
changed a row.
- Increment row-change counters with relaxed load/store. `wrapping_add`
preserves wraparound at `i64::MAX`.
## Source
Extracted from #9187. The source PR measured separate workloads; this
extracted bundle has not been measured as a whole.
## Tests
- `cargo test -p turso_core --lib vdbe::execute -- --test-threads=1`
- `cargo test -p turso_core --lib
vdbe::statement_lifecycle_tests::test_mvcc_completed_writer_changes --
--test-threads=1`
- `cargo test -p turso_core --lib
change_count_increment_matches_atomic_wraparound`
- `cargo clippy -p turso_core --all-features --all-targets --
--deny=warnings`
- `cargo fmt --all -- --check`
Closes#9255
## Problem
The optimizer checks possible ways to read each table while it prepares
a query. It did extra work for two multi-index cases:
- **multi-index intersection**: It analyzed a multi-index intersection
when the table had fewer than two local conditions. An intersection
needs at least two conditions.
- **multi-index union:** It checked outer-join rules for a condition
before it checked whether the condition was an `OR`. Only `OR`
conditions can use a multi-index union.
## Change
The optimizer now counts distinct, unconsumed local conditions before it
analyzes a multi-index intersection.
```sql
CREATE TABLE items(a INTEGER, b INTEGER);
CREATE INDEX items_a ON items(a);
CREATE INDEX items_b ON items(b);
-- One local condition cannot use both indexes. Skip intersection analysis.
SELECT * FROM items WHERE a = 1;
-- Two local conditions allow the optimizer to consider both indexes.
SELECT * FROM items WHERE a = 1 AND b = 2;
```
For multi-index unions, the optimizer now checks that a condition is an
`OR` before it checks the outer-join rules. A condition such as `a = 1`
cannot use a union. A condition such as `a = 1 OR b = 2` still reaches
the existing analysis.
This PR does not change join rewrites, table constraints, row estimates,
cost values, or execution code. The existing cost comparison still
decides which valid plan to use.
## Result
In a local TPC-H Q21 preparation test, the median time decreased from
`73.3 µs` to `64.2 µs` over 100 samples. Allocations decreased from
`1,290` to `1,227` per preparation. These numbers measure query
preparation, not query execution.
All 23 TPC-H plan snapshots stayed unchanged. The SQL tests, including
snapshots and matrix cases, passed in CI. All six deterministic
differential-fuzzer profiles passed in CI.
## Description of AI usage
Codex helped inspect the optimizer, measure query preparation, and
review the change.
Closes#9155
This branch builds on
[#9262](https://github.com/tursodatabase/turso/pull/9262):
- Read one-byte serial types directly. Longer values still use the
varint reader.
- When a reused register has enough capacity, copy TEXT values up to 64
bytes and check for ASCII in the same pass. This extends the existing
copy-and-fold helper.
Extracted from
[#9188](https://github.com/tursodatabase/turso/pull/9188). The one-byte
serial-type change also appeared in
[#9187](https://github.com/tursodatabase/turso/pull/9187).
## Source measurements
The source PR's callgrind results were:
- One-byte serial types: 3.67% fewer instructions on a two-column scan
and 2.01% fewer on `SELECT * FROM users`. No listed workload regressed.
- Combined copy and ASCII check: 2.00% fewer instructions on `SELECT *
FROM users`; other listed workloads changed by at most 0.11%.
These are source-branch results. This extracted branch has not been
benchmarked again.
## Tests
- Before rebase: `cargo test -p turso_core --lib vdbe:: -- --test-
threads=1` (281 passed).
- After rebase: `cargo test -p turso_core --lib vdbe::tests::text_decode
-- --test-threads=1` (4 passed).
- After rebase: `cargo fmt --all -- --check` and `git diff --check`
passed.
- Clippy stops on an unmatched lint expectation in unchanged
`core/json/cache.rs:107`.
Codex helped split and review the changes, audit the buffer handling,
and run tests. The maintainer is responsible for reviewing the result.
Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Closes#9263
When a reused register has enough space, copy TEXT values up to 64 bytes
while checking whether all bytes are ASCII. ASCII needs no second UTF-8
check. For valid non-ASCII text, validate the bytes and keep the first copy.
For invalid text, return an error before restoring the string length. Values
over 64 bytes use the existing UTF-8 check and copy path.
Callgrind instruction counts for `SELECT * FROM users` fell from 19,462,290
to 19,072,189 (-2.00%). Other measured workloads moved by at most 0.11%.
Tests: reused TEXT and BLOB registers at every length from 0 to 80, valid
multi-byte UTF-8, and invalid UTF-8 below and above the 16-byte short-copy
limit.
Most record serial types fit in one byte. The old path called `read_varint`
and then advanced the header by the returned byte count for every value.
- If the first byte is below 128, return it and advance by one byte.
- Otherwise, keep using `read_varint` for the longer value.
For example, serial type 13 uses the one-byte path. Serial type 413 still
uses the two-byte varint path.
Callgrind instruction counts:
- Two-column scan: 11,116,116 to 10,708,116 (-3.67%).
- Full scan: 19,861,619 to 19,462,290 (-2.01%).
- No measured workload regressed.
Tests: decode a 200-byte TEXT value, then a short TEXT value in the same
register.
When a record decoder reuses a TEXT register, copy short values into its
existing buffer if it has enough capacity. Use the copied bytes to check
for ASCII. Validate non-ASCII values as UTF-8 before restoring the
string length.
Extracted from
[#9188](https://github.com/tursodatabase/turso/pull/9188).
## Source measurements
The source PR's callgrind results were:
- `SELECT * FROM users`: 5.76% fewer instructions.
- Two-column scan: 0.94% fewer instructions.
- Grouped scan: 0.20% fewer instructions.
- Point lookup: 0.23% more instructions.
These are source-branch results. This extracted branch has not been
benchmarked again.
## Tests
- Before rebase: `cargo test -p turso_core --lib vdbe:: -- --test-
threads=1` (280 passed).
- After rebase on the stack tip: `cargo test -p turso_core --lib
vdbe::tests::text_decode -- --test-threads=1` (4 passed).
- After rebase: `cargo fmt --all -- --check` and `git diff --check`
passed.
- Clippy stops on an unmatched lint expectation in unchanged
`core/json/cache.rs:107`.
Codex helped split and review the changes, audit the buffer handling,
and run tests. The maintainer is responsible for reviewing the result.
Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Closes#9262
VACUUM INTO copies the source header's schema cookie, user_version and
application_id into the new database. When the source uses MVCC, the
target is also an MVCC database and these values are written into the
target's MVCC header.
The MVCC checkpoint does not write the header's schema cookie to page 1.
It writes the connection's in-memory `Schema::schema_version` instead.
VACUUM INTO only updated the header, so the final TRUNCATE checkpoint
replaced the copied cookie with the target's own schema version, and
`PRAGMA schema_version` on the new database returned the wrong value.
Fix: when the target is MVCC, also set the target connection's
`schema_version` to the copied cookie. This matches what `SetCookie`
already does when a statement changes the schema version. `user_version`
and `application_id` were not affected because the checkpoint reads them
from the header.
Tests:
`vacuum_db_header_meta_schema_cookie_survives_mvcc_target_checkpoint` in
`core/vdbe/vacuum.rs` fails without the fix and passes with it. New MVCC
integration tests in
`tests/integration/query_processing/test_vacuum_into_mvcc.rs`.
Fixes#4929
Reviewed-by: Avinash Sajjanshetty (@avinassh)
Closes#9230
In a group commit the leader writes the log records of every queued
transaction, but it chose whether to sync the log using only its own
sync mode. With a synchronous=OFF or NORMAL leader, a synchronous=FULL
waiter in the same group was marked durable and its COMMIT returned
success even though the log was never synced, so a crash could lose a
transaction that turso reported as durable.
Each queued commit now records its connection's sync mode. When the
leader writes a FULL record, the commit coordinator remembers that
ticket as the highest written ticket that needs a FULL sync. The sync
steps (SyncLogicalLog and SyncGroupPrefix) sync the log when the leader
uses FULL or when a FULL record is written but not yet durable. This
makes the group use the strictest sync mode of the records it writes.
The prefix sync case also covers FULL records written by an earlier
leader that stopped before syncing.
Tests: cargo test -p turso_core --lib full_waiter_is_synced_when_group_leader_uses_sync_off
Fixes#9237
Build final table constraints once after join rewrites and implied equalities. Reuse base row estimates, and reject impossible multi-index candidates before full analysis.
This reduces TPC-H Q21 preparation allocations without changing its plan or runtime counters.
Tests: cargo test -p turso_core --lib -- --test-threads=1; cargo clippy -p turso_core --lib -- -A unfulfilled-lint-expectations -D warnings; normal and MVCC SQL conformance; all TPC-H plan snapshots
Add a dedicated leak_tests binary (separate target because it installs
a counting #[global_allocator]) that models a server creating and
dropping many databases: repeated open/workload/drop cycles in one
process — a fresh database file each cycle — in both WAL and MVCC
journal modes, failing if the heap grows beyond a computed budget.
The budget pre-computes accepted retention: the database registry keeps
a dead entry (whose Weak pins the Database allocation) per unique file
identity, sized via size_of::<Database>() so struct growth doesn't
require retuning; MVCC is granted two entries per cycle. crossbeam-epoch
garbage from the MVCC skiplists is drained before measuring so deferred
reclamation is not mistaken for a leak. The completion-group leak blows
through this budget on every platform.
Also add a reference-retention regression test: after dropping every
handle to an MVCC database, Weak handles to the Database and MvStore
must fail to upgrade.
The leak tests run in the workspace nextest job and as an explicit
named step in the Rust workflow.
https://claude.ai/code/session_0171ou6qAsxxvCtaWDKFk9sK
CompletionGroup::build stored the group's own Completion in
GroupCompletionInner::self_completion — an Arc cycle (CompletionInner ->
GroupCompletionInner -> Completion -> same CompletionInner) that leaked
every completion group ever built (~280 bytes per WAL checkpoint /
commit batch / sorter spill), i.e. continuous heap growth proportional
to write traffic, surviving even after the database is dropped.
Invert the ownership instead: each child completion's parent now holds
the group's Completion strongly, so the group lives exactly as long as
it has unfinished children. self_completion is deleted entirely — no
cycle and no extra lock — and dropped-handle semantics are preserved:
the group callback and grandparent notification still run when the last
child finishes, even if the caller dropped its handle to the group.
Tests: leak_tests measures 0 unaccounted bytes per database lifecycle
after this change (~280 before).
https://claude.ai/code/session_0171ou6qAsxxvCtaWDKFk9sK
CommitState::Checkpoint stored the 4 KB CheckpointStateMachine inline, so
every commit, including read-only autocommit statements, built a 4,344-byte
CommitStateMachine on the stack, copied it into a box, and moved the full
enum on state changes. Only commits that start an automatic checkpoint need
that state, so allocate it there. CommitStateMachine is now 352 bytes.
Callgrind, 200/2,200 iterations: point_read 17,965 -> 16,011 (-10.9%);
index_read 40,568 -> 38,544 (-5.0%); point_update_commit 44,144 -> 39,210
(-11.2%); insert_commit 106,520 -> 101,355 (-4.8%).
Tests: cargo test -p turso_core --lib mvcc::
For a short TEXT value, the old path validated the record bytes and then
copied them into a reused register. ASCII values were read twice.
- Copy values shorter than 16 bytes into an owned register buffer when it
has enough space.
- Use the copied words to check whether every byte is ASCII.
- If any high bit is set, validate UTF-8 before restoring the string length.
Keep the first copy if validation succeeds.
- Use the existing validate-then-copy path when the buffer cannot be reused.
Callgrind instruction counts:
- Full scan: 21,251,617 to 20,027,063 (-5.76%).
- Two-column scan: 11,233,455 to 11,128,114 (-0.94%).
- Point lookup: 7,786 to 7,804 (+0.23%), because reset registers start as
NULL and need the cold initialization path.
Tests: reused text buffers at lengths 0 to 40, multi-byte UTF-8, and invalid
UTF-8 that must leave the register usable.
VACUUM INTO copies the source header's schema cookie, user_version and
application_id into the new database. When the source uses MVCC, the
target is also an MVCC database and these values are written into the
target's MVCC header.
The MVCC checkpoint does not write the header's schema cookie to page 1.
It writes the connection's in-memory `Schema::schema_version` instead.
VACUUM INTO only updated the header, so the final TRUNCATE checkpoint
replaced the copied cookie with the target's own schema version, and
`PRAGMA schema_version` on the new database returned the wrong value.
Fix: when the target is MVCC, also set the target connection's
`schema_version` to the copied cookie. This matches what `SetCookie`
already does when a statement changes the schema version. `user_version`
and `application_id` were not affected because the checkpoint reads them
from the header.
Tests: `vacuum_db_header_meta_schema_cookie_survives_mvcc_target_checkpoint`
in `core/vdbe/vacuum.rs` fails without the fix and passes with it. New
MVCC integration tests in
`tests/integration/query_processing/test_vacuum_into_mvcc.rs`.
Fixes#4929
ALTER TABLE ADD COLUMN and DROP COLUMN rewrite sqlite_schema.sql using
BTreeTable::to_sql(). That function printed NOT NULL, UNIQUE, PRIMARY KEY
and table-level UNIQUE constraints without their ON CONFLICT clause, even
though the parsed schema keeps it. After such an ALTER, any connection
that reloads the schema enforced ABORT where the user asked for ROLLBACK
(or IGNORE/REPLACE/FAIL), so a transaction that relied on ROLLBACK could
end up with its earlier rows committed.
to_sql() now adds the stored clause after each constraint: the column's
NOT NULL clause, the matching single-column unique set for inline UNIQUE,
the primary key unique set (or the saved clause for an INTEGER PRIMARY KEY
rowid alias, whose unique set is removed during parsing) for PRIMARY KEY,
and each table-level UNIQUE set's own clause.
Tests: sqlite-sqltests/alter-table-keeps-on-conflict-clause.sqltest
Fixes#8703
Keep WHERE-term dispatch separate from the index cursor setup and result-matching loop.
Tests: 129 index-method integration tests and 68 FTS SQL tests pass. The own-row example emits identical bytecode before and after the extraction.
Amp-Thread-ID: https://ampcode.com/threads/T-01a0c9d1-6ce7-735b-9d2b-2139e237f6b5
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
Exercise own-row arguments, covering-index and primary-key sources, and both forced join orders with changing queries. Include NOT syntax so scalar fallback cannot satisfy the expected indexed results.
Tests: all 68 cases in turso-sqltests/fts.sqltest pass with the CLI backend.
Amp-Thread-ID: https://ampcode.com/threads/T-01a0c9d1-6ce7-735b-9d2b-2139e237f6b5
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
Third of three stacked PRs; depends on #9166, which depends on #9165.
Integrate the converted FTS allocations with Whopper using
`#[turso_macros::allocation_site(...)]`. Register
`FtsAllocationSite::CaptureBuffer` and `AtomicMetadata` with
deterministic IDs 37 and 38, leaving existing IDs unchanged. Whopper can
now inject faults at these sites through its allocation backend.
Preserve `LimboError::OutOfMemory` through Tantivy build and merge
failures so Whopper treats them as recoverable. Some Tantivy buffered
serializers erase the I/O error kind; the private build directory
records allocation failures so classification does not depend on error
text.
Add a test-only, per-database allocator that fails each allocation in
turn during inserts and merges in WAL and MVCC mode. Require the exact
OutOfMemory error, verify base-table and FTS results after rollback, and
retry on the same connection. Directory tests verify exact macro site
labels, metadata preservation, and no partial-file publication. Whopper
tests verify site IDs, injection, and NoFaultInjection suppression.
Validation:
- `cargo test -p turso_core --features fts,allocation_metric --lib
index_method::fts` — 25 stable / 28 nightly passed.
- `cargo test -p turso_whopper --lib allocation_fault::tests` — 9 stable
/ 10 nightly passed.
- Nightly uses 2025-12-17 with `RUSTFLAGS="--cfg nightly"`.
- `cargo fmt --all --check` and `git diff --check` pass.
- The earlier allocator suite passed 29 stable / 35 nightly tests.
The full workspace suite and a randomized Whopper workload run were not
run.
Closes#9167