#9426·turso

sync: MVCC pull fails when one remote transaction drops or redefines an indexed generated column

Author: LeMikaelFCreated Sep 30, 2026Updated Sep 30, 2026
Labelsmvccsync

Summary

In MVCC sync, a pull fails when one remote transaction drops or redefines a virtual generated column and the index on that column.

Example remote transactions:

sql
BEGIN;
DROP INDEX idx;
ALTER TABLE core DROP COLUMN search;
COMMIT;
sql
BEGIN;
DROP INDEX idx;
ALTER TABLE core DROP COLUMN search;
ALTER TABLE core ADD COLUMN search TEXT AS (UPPER(sort));
CREATE INDEX idx ON core(search);
COMMIT;

If the remote runs each statement in its own transaction, the pull works.

Current behavior on main

Both cases are already broken on main, in different ways:

  • Drop: the pull succeeds, but the local table keeps search. The replay reads local columns from pragma_table_info, which does not list virtual generated columns, so it never sees that search must go. The local schema then differs from the remote without any error.
  • Redefine: the pull fails with duplicate column name: search, for the same reason.

Behavior after "sync: fix table refresh replay for tables with generated columns"

That change reads local columns from the CREATE TABLE SQL in sqlite_schema. On a table refresh, it drops each local generated column that the remote removed or defined differently. For a generated column with an index, that DROP COLUMN now fails:

failed to execute DDL `ALTER TABLE core DROP COLUMN search`:
cannot drop column "search": it is referenced in the index idx

So after that change, both cases return an error instead of producing a wrong schema. They still don't work.

Cause

decode_recovery_ops_to_logical_txn (sync/engine/src/database_sync_operations.rs) combines the sqlite_schema changes of a transaction into one change per sqlite_schema rowid. append_schema_ops then emits them in rowid order, not in the order the statements ran. The table was created before its index, so the table has the lower rowid, and the replay applies the table refresh before the index drop. When the refresh runs DROP COLUMN search, the local index idx still exists.

Possible fix

Before the refresh drops a generated column, drop the local indexes that use that column. The index ops that come later in the same transaction then drop or re-create those indexes. Check first that replaying DROP INDEX works when the index is already gone.

Reproducer

Add to the tests module of sync/engine/src/database_tape.rs. Both tests fail on main and after the change above.

rust
#[test]
pub fn test_schema_refresh_drops_indexed_generated_column_before_its_index_drop() {
    let rows = replay_on_table_with_generated_columns(
        &[
            "CREATE TABLE core (id STRING PRIMARY KEY, sort TEXT, search TEXT AS (CAST (sort AS TEXT)))",
            "CREATE INDEX idx ON core (search)",
            "INSERT INTO core (id, sort) VALUES ('a', 'Hello')",
        ],
        vec![
            table_refresh("CREATE TABLE core (id STRING PRIMARY KEY, sort TEXT)"),
            DatabaseTapeOperation::SchemaReplay(DatabaseSchemaReplay::Drop {
                kind: DatabaseSchemaKind::Index,
                name: "idx".to_string(),
            }),
        ],
        "SELECT * FROM core",
    )
    .unwrap();
    assert_eq!(rows, vec![vec![text("a"), text("Hello")]]);
}

#[test]
pub fn test_schema_refresh_replaces_indexed_generated_column_before_its_index_refresh() {
    let rows = replay_on_table_with_generated_columns(
        &[
            "CREATE TABLE core (id STRING PRIMARY KEY, sort TEXT, search TEXT AS (CAST (sort AS TEXT)))",
            "CREATE INDEX idx ON core (search)",
            "INSERT INTO core (id, sort) VALUES ('a', 'Hello')",
        ],
        vec![
            table_refresh(
                "CREATE TABLE core (id STRING PRIMARY KEY, sort TEXT, search TEXT AS (UPPER (sort)))",
            ),
            DatabaseTapeOperation::SchemaReplay(DatabaseSchemaReplay::Drop {
                kind: DatabaseSchemaKind::Index,
                name: "idx".to_string(),
            }),
            DatabaseTapeOperation::SchemaReplay(DatabaseSchemaReplay::Create {
                sql: "CREATE INDEX idx ON core (search)".to_string(),
            }),
        ],
        "SELECT id, sort, search FROM core WHERE search = 'HELLO'",
    )
    .unwrap();
    assert_eq!(rows, vec![vec![text("a"), text("Hello"), text("HELLO")]]);
}

fn replay_on_table_with_generated_columns(
    setup: &[&str],
    operations: Vec<DatabaseTapeOperation>,
    query: &str,
) -> crate::Result<Vec<Vec<turso_core::Value>>> {
    let temp_file = NamedTempFile::new().unwrap();
    let db_path = temp_file.path().to_str().unwrap();
    let io: Arc<dyn turso_core::IO> = Arc::new(turso_core::PlatformIO::new().unwrap());
    let db = turso_core::Database::open(
        io.clone(),
        db_path,
        turso_core::OpenOptions::new(Arc::new(SqliteDialect))
            .db_opts(turso_core::DatabaseOpts::new().with_generated_columns(true)),
    )
    .unwrap();
    let db = Arc::new(DatabaseTape::new(db));
    let setup = setup.iter().map(|sql| sql.to_string()).collect::<Vec<_>>();
    let query = query.to_string();
    let mut gen = genawaiter::sync::Gen::new({
        let db = db.clone();
        |coro| async move {
            let coro: Coro<()> = coro.into();
            let conn = db.connect(&coro).await.unwrap();
            for sql in &setup {
                conn.execute(sql).unwrap();
            }
            let opts = DatabaseReplaySessionOpts {
                use_implicit_rowid: false,
            };
            let mut session = db.start_replay_session(&coro, opts).await.unwrap();
            for operation in operations {
                session.replay(&coro, operation).await?;
            }
            session.replay(&coro, DatabaseTapeOperation::Commit).await?;
            let mut stmt = conn.prepare(&query).unwrap();
            let mut rows = Vec::new();
            while let Some(row) = run_stmt_once(&coro, &mut stmt).await.unwrap() {
                rows.push(row.get_values().cloned().collect::<Vec<_>>());
            }
            Ok(rows)
        }
    });
    loop {
        match gen.resume_with(Ok(())) {
            genawaiter::GeneratorState::Yielded(..) => io.step().unwrap(),
            genawaiter::GeneratorState::Complete(result) => break result,
        }
    }
}

fn table_refresh(sql: &str) -> DatabaseTapeOperation {
    DatabaseTapeOperation::SchemaReplay(DatabaseSchemaReplay::Refresh {
        kind: DatabaseSchemaKind::Table,
        name: "core".to_string(),
        sql: sql.to_string(),
    })
}

fn text(value: &str) -> turso_core::Value {
    turso_core::Value::from_text(value.to_string())
}

The tests build the op list by hand, in the order append_schema_ops emits it (table refresh first, because the table has the lower sqlite_schema rowid). They do not decode a real remote MVCC log.