Commit Graph

22 Commits

Author SHA1 Message Date
Glauber Costa
e6f0981b43 simulator: correct MVCC rowid assumptions and validation
Under MVCC, implicit rowid allocation behaves like a sequence: the next
value comes from a high-water mark that a rollback does not lower, so an
aborted insert consumes its rowid for good and the next insert skips
past it. This is deliberate — we do not guarantee that a rolled-back
allocation is handed back, matching PostgreSQL sequences, where nextval
is never rolled back and aborted transactions leave permanent gaps.
(AUTOINCREMENT already behaved this way; the same rule now covers plain
INTEGER PRIMARY KEY rowids.) WAL mode, like SQLite, reuses the freed
value.

The simulator makes exact-row assertions, and it cannot predict a
post-rollback rowid without modeling that watermark. Rather than model
it, generate explicit integer primary keys in MVCC INSERT and UPSERT
workloads, so the assertions no longer assume rolled-back allocations
come back. WAL mode keeps generating implicit keys.

Check MVCC integrity with Turso, which can read the logical-log state
SQLite cannot, and keep the SQLite integrity check for WAL. Export the
logical log from the in-memory I/O so a retained failure artifact
includes committed state.

Tests: 21 generator tests, the MVCC profile regression, and
deterministic integrity and export regressions pass.
2026-10-12 19:56:09 -05:00
Pekka Enberg
4de24b0c62 core: Pass connection settings to Database::connect as ConnectOpts
Database had five public ways to open a connection: connect,
connect_with_encryption, connect_with_page_codec, connect_async and
connect_with_encryption_async. Every new connection setting needs more
variants, and the async path doubles them again.

Database::connect and Database::connect_async now take a ConnectOpts
that holds the encryption key and the page codec, and the other three
variants are removed. ConnectOpts has no Default, so every caller goes
through ConnectOpts::new() and a required argument added there later
makes the compiler find every call site.
2026-10-12 10:05:12 +03:00
Glauber Costa
c340222f60 sqlite/parser: keep GENERATED ALWAYS in rendered schema text
Turso stores schema SQL by re-rendering the statement from the AST, and
the AST did not record whether the user wrote GENERATED ALWAYS AS or the
bare AS form, so the keywords vanished from sqlite_master. SQLite keeps
the original spelling, and tools that round-trip schema text depend on
it.

Record the spelling on the generated-column constraint, emit it from
both renderers (the AST token stream used by RENAME, and the column
metadata renderer used by ADD COLUMN), and only where the user actually
wrote it — bare AS stays bare.

Tests: spelling round-trip coverage through CREATE and the ALTER paths
in gencol.sqltest.

Fixes #6155

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-16 15:15:48 +00:00
Pavan Nambi
5cefb9dc05 simulator: inject power loss and retry interrupted fsync queries
Use the memory backend's crash boundary for POWER_LOSS and FsyncNoWait.
Recreate connections through their normal setup and retry an fsync query
only when power loss actually interrupted it.

Enable eligible WAL memory simulations while keeping power loss out of
MVCC and comparison modes. Reject plan conversion when the destination
test harness cannot reproduce the crash semantics.
2026-09-08 18:15:24 +05:30
Jussi Saurio
643ea2752c simulator: model per-row UNIQUE checks in UPDATE shadow
SQLite and Turso apply an UPDATE row by row in rowid order with an
immediate uniqueness check per row, so a new value that collides with
the old value of a later, not-yet-updated row aborts the statement even
when the final row set would be unique. The shadow model checked
uniqueness set-wise, excluding all updated rows' old values, so it
accepted such statements and flagged a false "Turso rejected with
constraint error but shadow would accept" divergence. Unique virtual
generated columns made the collision likely because overflow-clamping
operators collapse values onto 0/i64::MIN/i64::MAX.

Tests: new shadow unit tests (fail without the fix); sim seed
2271740788807898754 with `--maximum-tests 1000 --min-tick 10
--max-tick 50 --io-backend=memory` now succeeds.
2026-07-20 14:51:16 +03:00
Pekka Enberg
9b10c496db core: add Dialect trait and route schema loading through it
Introduce the Dialect trait as the boundary between the engine and the
SQL dialect a frontend speaks. The engine hardcodes SQLite behavior in
many places; the trait is the seam where a frontend substitutes its own
surface, growing one hook per behavior that moves behind it, with
SqliteDialect in core/dialect/sqlite.rs as the SQLite implementation.

The first hook is schema loading: every path that parses a
sqlite_schema table row back into a table definition now goes through
Dialect::parse_table_sql instead of calling BTreeTable::from_sql
directly. Rows written by internal engine paths (sequence backing
tables, sqlite_sequence) are plain SQLite text with no frontend marker,
so every dialect falls back to SQLite parsing for text it does not
recognize as its own.

The dialect is a mandatory, explicit argument on every database
constructor — open_file, open, open_new, from_uri, and the async and
bypass-registry variants — with no defaulting convenience wrappers:
SQLite-compatible callers state Arc::new(SqliteDialect) at the call
site, so the dialect a database runs under is always visible where it
is opened. It is fixed at open time because the schema is parsed during
open itself; a dialect installed later could never see rows stored by
another frontend. The process-wide database registry rejects an open
whose dialect name differs from the already-open instance, and
engine-initiated secondary opens (ATTACH) propagate the parent
database's dialect instead of assuming SQLite.
2026-07-16 10:36:39 +03:00
PThorpe92
7ba74ada0b sim: only rollback shadowed connections that were rolled back by the engine due to I/O fault 2026-07-03 13:49:01 -07:00
Glauber Costa
b9503e7d0b feat: add PostgreSQL-style sequences and MVCC-safe AUTOINCREMENT
Add CREATE SEQUENCE / DROP SEQUENCE / nextval() / setval() / currval()
as first-class schema objects, and reimplement AUTOINCREMENT on top of
the same infrastructure so it works correctly under MVCC.

Sequences are the standard mechanism for generating monotonically
increasing (or decreasing) identifiers. This commit adds full support
for user-created sequences (CREATE SEQUENCE name [INCREMENT BY n]
[MINVALUE n] [MAXVALUE n] [START n] [CYCLE | NO CYCLE]) and the
functions nextval(), setval(), and currval(). AUTOINCREMENT tables now
implicitly create a sequence named __turso_internal_autoincrement_<table>
so high-water-mark logic is unified across both features.

Design: disk is the source of truth
-----------------------------------

Every sequence is backed by a hidden B-tree table:

    CREATE TABLE "__turso_internal_seq_<name>"(
        value INTEGER PRIMARY KEY,    -- rowid alias = the sequence value
        is_called INTEGER,
        start INTEGER, inc INTEGER,
        min INTEGER, max INTEGER, cycle INTEGER)

`value` is INTEGER PRIMARY KEY (the rowid alias). The B-tree is keyed
by the sequence value, so MIN(value) / MAX(value) is an O(1) seek to
the first/last leaf -- the B-tree *is* the watermark.

The in-memory `Sequence` is pure schema data -- start, increment, min,
max, cycle. No AtomicI64, no is_called flag, no dirty bit, no
in-process current-value cache. This is a deliberate change from an
earlier in-memory-atomic design which couldn't be made safe across
processes (multiple workers on the same disk would each maintain their
own atomic and diverge). Reading from disk on every call is the only
design that survives multiprocess WAL, MVCC, and crash-recovery
uniformly.

nextval execution
-----------------

At compile time, nextval() emits `begin_write_on_database`, making the
statement a write transaction. At runtime the translator emits an RMW
sequence (see core/translate/sequence.rs::emit_disk_read_nextval):

1. SequenceBeginInnerTx -- under MVCC, open an autonomous inner
   Concurrent tx scoped to this RMW. The outer tx (if any) is saved
   off. Under WAL or when the outer tx is exclusive, this is a no-op
   -- the RMW runs in the outer tx; the single-writer WAL lock
   provides the same serialization the inner tx provides under MVCC.
2. Cursor RMW: Rewind/Last on the backing table -> read the single
   watermark row -> SequenceComputeNext opcode computes the next value
   from (current, is_called, start, inc, min, max, cycle) baked into
   the program -> Insert the new row keyed by the new value (since
   `value` is INTEGER PRIMARY KEY, distinct nextvals land on distinct
   B-tree keys and never key-conflict).
3. Inline backing-table compaction: a small loop emitted right after
   the insert deletes every row except the new watermark. After every
   successful nextval the backing table holds exactly one row. (This
   used to run at commit time via flush_dirty_sequences, but the
   implementation issued nested prepare_internal() calls that drove
   pager.io.step() synchronously and broke the vdbe async contract --
   the outer Statement::step() would block instead of returning
   StepResult::IO. Moving the compaction inline fixed that.)
4. For AUTOINCREMENT-backing sequences, mirror the watermark into
   sqlite_sequence in the same inner tx so SQLite-compat readers see
   the high-water mark without needing a checkpoint.
5. SequenceCommitInnerTx -- commit the inner tx. On WriteWriteConflict
   (against another nextval racing on the same backing table),
   op_sequence_commit_inner_tx retries the whole RMW with a bounded
   budget (ProgramState::sequence_inner_retry_count); when the budget
   is exhausted it surfaces LimboError::Busy so the caller can retry
   at their level. The outer tx (if any) is restored.

Why an inner tx under MVCC: a nextval that aborts because its outer tx
rolls back must still leave its watermark advance durable on disk --
otherwise a parallel reader could observe the same value twice (the
first reader sees the in-memory state, the rolled-back tx releases its
disk write, the next reader recomputes and lands on the same value).
The autonomous inner tx commits the backing-table write independent of
the outer tx, so a rolled-back nextval still "consumed" the value.
This is the standard PostgreSQL semantics (rollback does not reclaim
nextval'd values; gaps are expected).

setval
------

setval(seq, value) can place the watermark anywhere, which cannot be
expressed as a conflict-free append (two concurrent setval(s, 5)
followed by setval(s, 3) are not commutative). It requires an
exclusive write transaction and is rejected inside BEGIN CONCURRENT.

currval
-------

currval(seq) is per-connection. It returns the value most recently
emitted by nextval or setval on this connection. It's a register
lookup populated by the SetSequenceCurrval opcode at the tail of
every nextval/setval; it does not touch disk.

Restart / recovery
------------------

On database open, sequences are initialized from disk:
- User sequences: read the single watermark row from each
  __turso_internal_seq_* backing table.
- AUTOINCREMENT: read sqlite_sequence and seed the implicit sequence
  to that value.

If a crash occurs after a nextval committed but before its compaction
loop deleted the prior row, the backing table may briefly contain
multiple rows. The compaction always re-runs on the next nextval, and
the open-time read uses MAX(value) for ascending or MIN(value) for
descending sequences, so multi-row state is recovered cleanly.

The MVCC checkpoint state machine also rewrites sqlite_sequence from
the in-schema sequence list during checkpoint, ensuring the on-disk
autoinc state is clean after every checkpoint cycle.

Testing
-------

- Integration tests covering all sequence operations, concurrent
  nextval from multiple connections, AUTOINCREMENT interaction, ATTACH
  database sequences, transaction rollback semantics, descending and
  CYCLE sequences, and restart-recovery scenarios.
- Simulator (limbo_sim): sequence-aware query generation
  (CREATE/DROP SEQUENCE, nextval, setval) and a SequenceMonotonicity
  property -- creates a fresh sequence in a reserved namespace, runs N
  nextvals, asserts the engine returned start + k*increment (or
  correct CYCLE wrap).
- Concurrent simulator (whopper): dedicated sequence workloads
  testing MVCC concurrent nextval, setval exclusivity, in-flight
  setval that survives worker death, autocommit and in-tx nextval
  interleavings, CYCLE wrap-aware duplicate / wrong-direction
  tracking, and cross-checkpoint persistence. Coverage includes
  InsertSeqDefault (INSERT into table with DEFAULT (nextval('s'))) and
  tracker handling for sequences advanced through that opaque path.
- SQL tests (sqltest): sequence.sqltest, mvcc_sequence.sqltest, and
  attach/sequence.sqltest covering the full feature surface.

Closes #5688
2026-06-08 15:25:05 -04:00
Claude
b2635b4ba5 simulator: add virtual generated columns support to the simulator
Extend SQL generation and simulator models to produce and validate
tables with VIRTUAL generated columns.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-18 13:28:25 -04:00
webhop123
28666bb1b7 simulator: add savepoint rollback DST coverage 2026-04-30 00:42:11 +01:00
Pekka Enberg
5b8d84888f Rename remaining experimental_mvcc references to mvcc
Update VDBE comment, docs, simulator, and integration tests to use
the new mvcc pragma name.
2026-03-02 10:44:02 +02:00
Eren Türkoğlu
5af96886a4 Merge branch 'main' into rename-mvcc-pragma 2026-02-28 09:00:04 +01:00
Glauber Costa
3114781455 feat: per-database MVCC transactions for attached databases
Each attached database now gets its own independent MvStore with its own
.db-log file when the main database uses MVCC mode. This enables full
MVCC isolation across all databases in a session.

Key changes:
- Split MVCC transaction storage: mv_tx for main DB (hot path),
  attached_mv_txs SmallVec for attached DBs (cold path)
- op_open_read/op_open_write/op_transaction use per-DB MvStore lookup
- commit_txn_mvcc iterates all databases with active MVCC transactions
- rollback handles attached MVCC transactions before clearing state
- Removed hardcoded MVCC block in ATTACH translation
- Removed @skip-file-if mvcc from ATTACH test files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 09:03:40 -06:00
Eren Turkoglu
366e3572a7 Rename experimental_mvcc to mvcc 2026-02-27 14:12:38 +01:00
Glauber Costa
75d0128905 fix: clean up db-log and fix WAL extension for attached DBs in simulator
The simulator clear() and new() methods were missing cleanup for MVCC
.db-log files, causing corrupt database errors when the simulator
reopened the database after a simulated crash. Additionally, the WAL
extension for attached databases used with_extension(format!) which
produced doubled names like test.aux.aux.db-wal instead of the correct
test.aux.db-wal.

Reproduces with: cargo run --bin limbo_sim -- --seed 867 --experimental-mvcc true

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 14:23:56 -06:00
Glauber Costa
b49254116f feat: add ATTACH database infrastructure to deterministic simulator
Add full infrastructure for testing ATTACH databases in the simulator:
- SimulatorEnv tracks attached databases with path helpers and cleanup
- Selective per-file fault injection via inject_fault_selective() on SimIO
- CREATE TABLE redirect to attached DBs (30% probability) in plan generation
- Proper QualifiedName/DoublyQualified handling for dotted table names in
  sql_generation (FROM clauses, column references, result columns)
- Re-ATTACH on database reopen with DatabaseOpts::with_attach(true)
- Fix core/connection.rs attach_database() to reuse parent DB IO instead
  of creating a new PlatformIO (enables simulator fault injection)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 12:08:51 -05:00
Mikaël Francoeur
45abf9b0cf Reapply "Merge 'Use new Antithesis assertions' from Mikaël Francoeur" 2026-02-18 08:44:50 -05:00
Pekka Enberg
80db011182 Revert "Merge 'Use new Antithesis assertions' from Mikaël Francoeur"
This reverts commit 73d48edeb4, reversing
changes made to 6acfa563ab because it breaks
the Antithesis Docker build.
2026-02-17 08:57:12 +02:00
Mikaël Francoeur
01e70f7fc0 Instrument codebase with turso_assert macros 2026-02-16 15:37:36 -05:00
Pavan-Nambi
20ba0dfe21 sim:support upsert in shadow 2026-02-10 05:22:55 +05:30
Pavan-Nambi
ad38fe9e73 simulator: add StatementAtomicity property
simulator: improve error handling in execution

simulator: add WriteStress profile
2026-01-27 19:11:44 +05:30
pedrocarlo
68701b1011 move simulator and docker runner to testing/simulator 2026-01-20 12:24:03 -03:00