mirror of
https://github.com/allankoechke/turso.git
synced 2026-12-01 17:43:08 +00:00
# Make the differential fuzzer reliable enough to run in CI, and run it in CI ## What's the differential fuzzer bro It runs generated SQL against Turso and SQLite, then compares the results and database state and expects them to match. ## The Problem ™️ We haven't been running the fuzzer in CI because it always fails somewhere. ## The Solution ©️ This PR fixes that in two ways: - **Fix Turso bugs.** Some differences are real Turso bugs. They are fixed here, each with a test. - **Make the fuzzer avoid SQL with more than one allowed answer.** Some SQL is allowed to give different results in different engines. Comparing those results tells us nothing, so the fuzzer stops generating them. ## Bonus features It also adds tooling: - Statement weight profiles, so CI covers several statement mixes instead of one. - Automatic minimization of failures: every failure now comes with a small reproduction script. - The SQLite TCL conformance runner now runs every test file in its own process, so one crashing file can't kill the whole run — and seven previously known-bad files now fully pass and are pinned green. --- ## Turso bugs fixed **A TEMP trigger stopped running after its table was renamed.** ```sql CREATE TABLE t(x); CREATE TEMP TRIGGER tr AFTER INSERT ON t BEGIN INSERT INTO log VALUES (1); END; ALTER TABLE t RENAME TO t2; INSERT INTO t2 VALUES (1); -- SQLite: trigger fires. Turso: trigger never fired again. ``` Turso updated the stored SQL but kept the trigger under the old table name in memory. The rename now updates both. **`DROP COLUMN` missed trigger references written as `alias.column`.** ```sql CREATE TABLE t(a, b); CREATE TRIGGER tr BEFORE UPDATE ON t WHEN t.b > 0 BEGIN SELECT 1; END; ALTER TABLE t DROP COLUMN b; -- SQLite: error "no such column: t.b". Turso: allowed the drop. ``` References spelled `t.b` or `main.t.b` were not checked. Such drops are now rejected. **A `BEFORE INSERT` trigger could make the outer insert pick a wrong automatic rowid.** ```sql CREATE TABLE t(id INTEGER PRIMARY KEY, v); CREATE TRIGGER tr BEFORE INSERT ON t BEGIN INSERT INTO t VALUES (100, 'x'); END; INSERT INTO t(v) VALUES ('a'), ('b'); ``` The outer insert chose its automatic rowid from a stale cursor position, as if the trigger's row didn't exist. Rowid lookup now seeks to the actual largest rowid first. **An unqualified TEMP trigger could forget which database its table came from.** ```sql CREATE TABLE t(x); -- in main CREATE TEMP TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END; CREATE TABLE aux.t(x); -- same name in aux DROP TABLE main.t; INSERT INTO aux.t VALUES (1); -- Turso: the temp trigger could fire on aux.t, or survive the drop of main.t. ``` Turso now remembers the correct database. **`UPDATE` skipped `NOT NULL` checks when the table's only trigger was `AFTER UPDATE`.** ```sql CREATE TABLE t(id INTEGER PRIMARY KEY, n TEXT NOT NULL); INSERT INTO t VALUES (1, 'keep'); CREATE TRIGGER tr AFTER UPDATE ON t BEGIN SELECT 1; END; UPDATE t SET n = NULL; -- SQLite: error "NOT NULL constraint failed". Turso: stored NULL. ``` The check is deferred so `BEFORE` triggers can run first. But it was skipped for *any* trigger and only re-added when a `BEFORE` trigger existed, so a table with only an `AFTER` trigger lost the check entirely. **`UPDATE OR FAIL` inside a trigger rolled back too much.** ```sql CREATE TABLE t(id INTEGER PRIMARY KEY); INSERT INTO t VALUES (-1); CREATE TRIGGER tr BEFORE INSERT ON t BEGIN UPDATE OR FAIL t SET id = 807742 WHERE (SELECT id FROM t LIMIT 1); END; INSERT INTO t VALUES (1), (2); -- Both engines report a UNIQUE error. -- SQLite table afterwards: {1, 807742}. Turso: {-1} — everything rolled back. ``` `OR FAIL` means: keep the rows already changed. That worked in a plain statement, but when the conflict happened inside a trigger, Turso applied the outer statement's rollback instead. SQLite keeps the earlier changes; now Turso does too. **`UPDATE ... RETURNING` showed values written by the `AFTER` trigger.** ```sql CREATE TABLE t(id INTEGER PRIMARY KEY, val INTEGER); INSERT INTO t VALUES (1, 10); CREATE TRIGGER tr AFTER UPDATE ON t BEGIN UPDATE t SET val = val + 100 WHERE id = NEW.id; END; UPDATE t SET val = 20 WHERE id = 1 RETURNING val; -- SQLite returns 20 (what the UPDATE wrote). Turso returned 120. -- The final table holds 120 in both engines. ``` Turso now fires `AFTER` triggers after RETURNING has captured the row. Two existing tests pinned the old behavior as intentional; they now expect SQLite's behavior. **`x IN ((SELECT ...))` returned NULL for an empty subquery.** ```sql SELECT 5 IN ((SELECT 1 WHERE 0)); -- SQLite: 0. Turso: NULL. ``` Turso parsed the double parentheses as a value list containing one scalar subquery, and an empty scalar subquery is NULL. SQLite reads it the same as `x IN (SELECT ...)`: an empty subquery means "not in", never NULL. **`OR REPLACE` stored a NULL default into a `NOT NULL` column.** ```sql CREATE TABLE t(id INTEGER PRIMARY KEY, c BLOB NOT NULL DEFAULT (NULL)); INSERT INTO t VALUES (1, X'AA'); UPDATE OR REPLACE t SET c = NULL; -- SQLite: error "NOT NULL constraint failed". Turso: stored NULL. ``` `OR REPLACE` fixes a `NOT NULL` violation by swapping in the column default — but the default can itself be NULL. Turso never re-checked the swapped-in value. Now it does. **`EXISTS` kept `ORDER BY` and `DISTINCT` that SQLite throws away.** `EXISTS` only asks whether a row comes back, so SQLite deletes `ORDER BY` and `DISTINCT` inside it. Turso kept them, which showed up in two ways: ```sql -- 1. An ORDER BY term that fails at runtime: SELECT EXISTS (SELECT x FROM t ORDER BY ABS(-9223372036854775807 - 1)); -- SQLite: 1 (the term is never evaluated). Turso: error "integer overflow". -- 2. DISTINCT changing what OFFSET counts (t has rows 1, 1, 2): SELECT EXISTS (SELECT DISTINCT x FROM t ORDER BY x LIMIT 5 OFFSET 2); -- SQLite: 1 (OFFSET skips 2 of 3 plain rows). Turso: 0 (OFFSET skipped both distinct rows). ``` Turso now drops both clauses in `EXISTS`. Name errors in the dropped clauses still surface, matching SQLite. **A backward scan with a text bound returned a phantom row from an empty table.** ```sql CREATE TABLE b(id INTEGER PRIMARY KEY); SELECT 1 FROM b WHERE id <= '' ORDER BY id DESC; -- SQLite: no rows. Turso: one row. The table is empty. ``` Every integer sorts before every text value, so `id <= ''` is true for all rows and the seek turns into "jump to the last row". On an empty table there is no last row, but Turso reported the seek as successful anyway, and the scan emitted one garbage row. Found by this PR's own CI setup: the `ddl` profile hit it, and the minimizer cut the failure down to a two-line reproduction on its own. **An index seek ignored a subquery's column type and compared an integer as text.** ```sql CREATE TABLE a(t TEXT UNIQUE); INSERT INTO a VALUES ('4x'); SELECT 1 FROM a WHERE t < (SELECT 602393 AS i); -- SQLite: no rows (the integer sorts before all text). -- Turso: one row ('4x' < '602393' compared as strings). ``` When both sides of a comparison have a type, and one is numeric, the comparison is numeric — so the integer keeps its type and sorts before the text. Turso's optimizer couldn't see the subquery's INTEGER type when building the index seek key, treated it as typeless, and let the TEXT column win: the seek converted the integer to text and string- compared. Only the index seek was wrong; a full table scan compared correctly. Also found by this PR's own CI setup: the `writes` profile hit it as a DELETE that removed a row SQLite kept, and the minimizer reduced it to five lines. **An aggregate over an outer column ran against the wrong table.** ```sql CREATE TABLE t(a); INSERT INTO t VALUES (1), (2), (3); SELECT (SELECT count(t.a)) FROM t; -- SQLite: one row, 3. Turso: three rows, 1 1 1. ``` An aggregate whose argument references a column from an outer query belongs to that outer query, not the subquery it is written in — the outer query becomes an aggregate query and collapses to one row. Turso bound every aggregate to the innermost query it was written in, so `count(t.a)` counted the subquery's own rows (a single correlated row) instead of the outer query's. The fix mirrors SQLite name resolution: when a subquery resolves an aggregate whose columns belong to the enclosing query, it moves the aggregate up to that query during resolution. Found by the `balanced` and `writes` profiles. **A CASE with no ELSE was treated as never producing NULL.** ```sql CREATE TABLE t(k INTEGER PRIMARY KEY, c REAL); INSERT INTO t VALUES (1, -47175.8); CREATE INDEX i ON t(c); SELECT 1 FROM t WHERE CASE WHEN '' THEN 1 END <= c; -- SQLite: no rows. Turso: one row. ``` An index range seek guards its seek key with an "is it NULL?" jump, because a NULL comparison is never true. Turso decided whether to emit that guard with a helper that wrongly reported a CASE with no ELSE as never-NULL — but such a CASE yields NULL when no WHEN matches. The seek then ran on a NULL key and returned rows. A CASE is non-null only when it has an ELSE and every branch is non-null. Found by the `balanced` profile. **A DELETE trigger inherited an outer `OR REPLACE` it should not have.** ```sql CREATE TABLE t(pk INTEGER PRIMARY KEY, x); CREATE TABLE t2(pk INTEGER PRIMARY KEY, y); INSERT INTO t VALUES(1,0); INSERT INTO t2 VALUES(1,0); CREATE TRIGGER t2_bd BEFORE DELETE ON t2 FOR EACH ROW BEGIN INSERT INTO t2(pk,y) VALUES(1,1),(1,2); END; CREATE TRIGGER t_au AFTER UPDATE ON t FOR EACH ROW BEGIN DELETE FROM t2 WHERE pk=1; END; UPDATE OR REPLACE t SET x=9; -- SQLite: UNIQUE constraint failed: t2.pk. Turso: silently succeeded. ``` A statement's `OR REPLACE` policy propagates into the triggers it fires, but a DELETE is an exception: it always fires its triggers with the default (ABORT) policy. Turso propagated the outer REPLACE through a delete-fired trigger, so a plain INSERT that duplicated a key was quietly resolved instead of raising the error SQLite raises. Found by the `triggers` profile; reduced from a three-trigger cascade to the two- trigger case above. **A trigger's `WHEN` reused a stale subquery result on every firing after the first.** ```sql CREATE TABLE tt (pk INTEGER PRIMARY KEY, d INTEGER); CREATE TRIGGER trg AFTER INSERT ON tt FOR EACH ROW WHEN EXISTS (SELECT 1 FROM tt WHERE EXISTS (SELECT 1 FROM tt WHERE d) IN (1)) BEGIN INSERT INTO tt (pk, d) VALUES (1, 0); END; INSERT INTO tt (pk, d) VALUES (1, 0), (2, 1), (3, 1); -- SQLite: UNIQUE constraint failed (the WHEN turns true at row 2, the body re-inserts pk=1). -- Turso: silently succeeded (the WHEN stayed false for every row). ``` A trigger body is inlined and re-run once per inserted row. An uncorrelated subquery is normally evaluated once and its result cached — but the cache is only valid within one run of the query. Turso kept the cache across trigger firings, so the inner `EXISTS` — false at the first firing, when no `d = 1` row exists yet — was reused as false forever, even after later rows made it true. The fix clears that "already evaluated" state at the start of each firing, so each firing re- evaluates against the current table. This matches SQLite, which gives every trigger firing a fresh start. It was not limited to `EXISTS`: a nested `IN (SELECT …)`, whose lookup table is also built once, went stale the same way. Found by the `triggers` profile; reduced from a large nested subquery to the five lines above. ## Harness fix 1: only run statements both engines can prepare, using EXPLAIN The flow is: 1. Generate a statement. 2. Run `EXPLAIN` in both engines. 3. If either engine rejects it, run it in neither. 4. Otherwise, run it in both and compare the results. 5. After writes, compare the database contents and schema, including triggers. Without this check, a statement accepted by only one engine could change only one database and spoil every later comparison. `EXPLAIN` checks acceptance without changing either database. - Skipped statements are reported separately from failures. - We may miss some real accept/reject bugs this way. That's a fair tradeoff: those can be tested elsewhere, while this fuzzer is most useful for comparing execution after both engines accept the same statement. ## Harness fix 2: avoid updates where row order decides the result ```sql CREATE TABLE t(id INTEGER PRIMARY KEY, value INTEGER UNIQUE); INSERT INTO t VALUES (1, 10), (2, 20); UPDATE OR IGNORE t SET value = 30; -- Whichever row is visited first gets 30. Both answers are allowed. ``` `UPDATE OR FAIL` has the same problem: it keeps the rows changed before the conflict, so the survivors depend on visit order. `UPDATE ... FROM` has a related one: ```sql UPDATE t SET v = s.val FROM s WHERE s.k = t.id; -- If several s rows match one t row, either engine may pick any of them. -- Turso often scans s through an index while SQLite scans the table, -- so they pick different rows. ``` What the generator does now: - `UPDATE OR IGNORE` and `UPDATE OR FAIL` are not generated. `UPDATE OR REPLACE`, `OR ABORT`, and `OR ROLLBACK` still are — their results don't depend on visit order. - `UPDATE ... FROM` is limited to one source table, and the generator writes `NOT INDEXED` on the target and the source. That forces a plain table scan in both engines, so they visit rows in the same order and pick the same matching row. - Joins and self-joins in `UPDATE ... FROM` are not generated. `NOT INDEXED` only controls how a table is scanned; Turso may still build a temporary index to run a join, and then the match order differs again. - Subquery sources are not generated either, because `NOT INDEXED` cannot be written on a subquery. This loses some random coverage. It is the price of a fuzzer that only flags real differences. These forms can still be covered by focused tests where the expected result is known. ## Harness fix 2b: make scalar subqueries pick a deterministic row A scalar subquery carries `LIMIT 1`, and both engines must pick the same row for the comparison to mean anything. Two generated shapes left the pick to engine scan order: ```sql -- Sort key can tie: rows with equal k are ordered by scan order. (SELECT v FROM t ORDER BY k DESC LIMIT 1) -- DISTINCT collapse: which duplicate's ORDER BY key survives is the -- engine's choice. (SELECT DISTINCT v FROM t ORDER BY k LIMIT 1) -- A constant ORDER BY term ties everything. (SELECT v FROM t ORDER BY REPLACE('a', 'b', 'c') LIMIT 1) ``` What the generator does now: - ORDER BY terms must reference a column; constant terms are replaced with a column reference. - Scalar subqueries get the table's primary key appended as a final ORDER BY tiebreaker. Grouped ones order by every GROUP BY expression instead — groups are distinct combinations of those, so that is already a total order. - Scalar subqueries no longer use DISTINCT; no tiebreaker can be added through the deduplication. ## Harness fix 2c: generate blob literals as valid UTF-8 ```sql SELECT HEX(CAST(X'96' AS TEXT)); -- SQLite: 96 (text is a plain byte string; the byte passes through). -- Turso: EFBFBD (text is a Rust string; the invalid byte becomes U+FFFD). ``` This is a real, documented Turso limitation (see the new Limitations section in COMPAT.md), not fuzzer noise: Turso's text type must be valid UTF-8, and blobs reach text through many doors — `CAST`, `UPPER`, `TRIM`, `REPLACE`, `||`. The fuzzer hit it as an UPDATE whose WHERE was `HEX(CAST(<blob> AS TEXT))`: the hex string starts with a digit in SQLite (truthy) and with 'E' in Turso (falsy), so one engine updated every row and the other none. The generator now produces blob bytes from printable ASCII, so every blob is valid UTF-8 and both engines see the same characters. Deciding whether Turso should store text as raw bytes like SQLite is a separate design question. ## Harness fix 3: use matching column types in compound queries ```sql WITH values_cte(x) AS ( SELECT real_column FROM real_table UNION ALL SELECT integer_column FROM integer_table ) SELECT x, typeof(x) FROM values_cte; -- SQLite may take the type from either arm: 7.0 as REAL or 7 as INTEGER. ``` The generator now uses matching declared types in every arm. This keeps `UNION`, `UNION ALL`, `INTERSECT`, and `EXCEPT` coverage while giving the fuzzer one answer to compare. ## Harness fix 4: don't rename tables or columns when SQLite would re- check the schema SQLite re-resolves *every* stored index and trigger during a table rename, column rename, or column drop. Turso does not, so it can accept a rename that SQLite rejects. Two schemas trigger this. **A trigger that uses a table that was dropped earlier.** SQLite allows dropping a table a trigger still uses: ```sql CREATE TRIGGER source_trigger AFTER INSERT ON source BEGIN INSERT INTO log VALUES (new.x); END; DROP TABLE log; -- fine in both engines; the trigger errors when it next runs ``` A later rename then fails in SQLite (it re-checks the now-broken trigger) but can succeed in Turso. - The fuzzer knows which table owns a trigger, but not every table used inside its body. - So it cannot tell whether an earlier drop broke a remaining trigger. **A TEMP table shadowing a permanent table of the same name.** SQLite resolves the shared name to the temp table, so re-checking an index on the permanent table fails against the temp table, which lacks the column: ```sql CREATE TABLE a(id INTEGER PRIMARY KEY, c INTEGER); CREATE UNIQUE INDEX ia ON a(c); CREATE TEMP TABLE a(x INTEGER PRIMARY KEY); -- shadows main.a, no column c CREATE TABLE b(z); ALTER TABLE b RENAME TO b2; -- unrelated rename -- SQLite: error "error in index ia after rename: no such column: c". Turso: succeeds. ``` What the generator does now: - It avoids table/column renames and column drops whenever any trigger exists, or any table name is shadowed across database scopes. `ADD COLUMN` stays enabled. - Focused tests still cover renames with valid schemas. ## Harness fix 5: don't generate `PRAGMA foreign_key_list('some_table')` before a table exists The fuzzer run would abort during SQL generation because there were no tables to choose from. ## Harness fix 6: skip statements over 64 KiB ```text Statement skipped because it is 367502 bytes; the limit is 65536 bytes ``` A generated expression can branch into several subqueries at each level, and occasionally the result is hundreds of kilobytes of SQL. Preparing that recurses deep enough to blow the process stack before either engine can return an error. Statements over 64 KiB are now skipped and counted separately. They add almost no coverage. The fuzzer also runs on a thread with a 256 MiB stack: debug-build parser frames are large enough that even a statement inside Turso's expression depth limit could overflow the default 8 MiB stack. Statements over the depth limit still get the parser's clean "expression tree is too large" error and are skipped. (The engine itself still can't prepare near-limit expressions on a default thread in debug builds; that needs its own parser fix.) ## Harness fix 7: print nested negation with a space ```sql SELECT --5; -- "--" starts a comment; the rest of the line is gone SELECT - -5; -- what the generator now prints ``` The SQL printer wrote nested minus as `--value`, silently turning the rest of the statement into a comment. ## New: statement weight profiles The fuzzer used one fixed mix of statement types, so every run stressed the same things. A new `--profile` flag picks a named mix: - `balanced` — the old default: mostly reads and writes, a little DDL - `ddl` — heavy table, index, and alter churn - `triggers` — heavy trigger creation, so triggers fire often - `writes` — heavy insert/update/delete, for constraint and conflict paths The profiles are fixed weight tables, not random, so a failing run reproduces with the same `--seed` and `--profile`. Most of the bugs above were found by the heavier mixes; the old default mix never hit them. ## New: failures come with a small reproduction When a comparison fails, the fuzzer now: 1. Writes `turso-state.sql` and `sqlite-state.sql` — scripts that recreate each engine's full state (all tables and rows, including temp and attached) plus the failing statement. 2. Shrinks the failing statement using the SQL parser: parse it, simplify one AST node — drop a clause (WHERE, LIMIT, an ORDER BY term, a select column, a CTE, a join), or replace an expression with `1`, `''`, or one of its own children — and print the tree back to SQL. Every candidate is valid SQL, so no time is wasted on candidates that don't parse. 3. Deletes every state line the shrunken statement doesn't need. 4. Writes the result to `minimized.sql`. A change is kept only if the same failure still happens — the same engine failing with the same error, or the same kind of result difference. That stops the shrinking from wandering onto a different bug. In practice this turns a 10 KB statement on top of 200 setup statements into a repro of a few lines. For example, the `EXISTS` bug above was found as a 10,610-byte subquery; shrinking it exposed the one load- bearing expression: ```sql -- before: 10,610 bytes of nested CASE/EXISTS/aggregate expressions -- after: SELECT EXISTS (SELECT x FROM t ORDER BY ABS(-9223372036854775807 - 1)); ``` ## Enable the differential fuzzer in CI The fuzzer runs as a matrix over the four profiles, but a random seed on every run would make it non-deterministic: a pull request could go red because of a newly generated statement unrelated to its change, and a green run wouldn't promise the next one passes. So CI runs it two ways: - **Pull requests** run a fixed set of seeds per profile. The generated SQL is identical every time, so a green run stays green and any failure blocks the merge and reproduces exactly: ```bash cargo run -p differential-fuzzer --bin differential_fuzzer -- \ --seed <seed> --profile <profile> -n 1000 ``` - **Pushes to main** additionally run random seeds, so new SQL keeps turning up divergences without gating unrelated pull requests: ```bash cargo run -p differential-fuzzer --bin differential_fuzzer -- \ --profile <profile> -n 1000 loop 10 ``` A failure prints its seed and profile, which reproduce it locally. The fixed seed set is a green baseline on this branch; it widens as more divergences are fixed. ## TCL conformance: crash-proof runner, seven files blessed The engine fixes above made previously-failing upstream SQLite tests pass, which surfaced two things in the TCL conformance suite. **Each test file now runs in its own process.** Before, `all.test` sourced every file into one tclsh process. A file that hard-crashed the engine — a segfault, a stack overflow, the OOM killer — took the whole run down with it: no summary, no hint of which file died or why. Now every file runs as a separate tclsh process, so: - A crash is contained to its own file. The runner reports `CRASH in <file>.test: killed by signal SIGSEGV` (the signal tells apart a stack overflow, a panic, and an OOM kill), keeps going, and still prints the full summary. - Test files can no longer leak state into each other, so each file's result reflects that file alone. **Seven known-bad files now fully pass and are blessed.** The suite marks each file `pass` (must stay green) or `fail` (known-bad, failures tolerated) — and it fails the run if a known-bad file goes fully green, so the known-bad list only ever shrinks. This branch tripped exactly that check: - `tkt3731` passes because of the engine fixes in this PR. - `rowvalue2`, `rowvalueA`, `tkt-c694113d5`, `tkt-d11f09d36e`, `tkt3992`, and `walbig` pass once files stop leaking state into each other. All seven are now marked `pass`, so any future failure in them fails CI. Closes #8115
TODO