#1544·litestream

BUG: litestream-vfs write mode leaks global txid counter across multiple replicas in one process

Author: benlauCreated Oct 1, 2026Updated Oct 1, 2026
Labelsbug

Bug Description

Since version 0.5.17, litestream-vfs introduced thread-safe replica URLs to support accessing multiple databases within a single process.

However, while connection creation and concurrent reads/writes are thread-safe, the internal write path state inside litestream-vfs still maintains a process-global transaction ID counter rather than scoping the counter tracking per database handle or replica URL.

When a process writes to a new database after writing to a previous one, the VFS emits a remote .ltx transaction log file starting at txid > 1 (e.g., txid=2 or txid=3). Because txid=1 is never generated on remote storage for subsequent replicas, opening them later for read operations hangs indefinitely inside the extension shared library (.so).

Environment

Litestream version:

  • Version: 0.5.17

Operating system & version:

  • OS: Debian 13 running inside python:3.14.5-slim docker image

Installation method: pip install

Storage backend: S3 / Minio

Steps to Reproduce

  1. In a single process, load the VFS extension: loader.load_extension(VFS_PATH, entrypoint="sqlite3_litestreamvfs_init").
  2. Connect to db1 with vfs=litestream&write_enabled=true, execute a write, commit, and close the connection.
  3. Connect to db2 (a distinct replica URL) in the same process with write_enabled=true, execute a write, commit, and close the connection.
  4. Connect to db3 (a distinct replica URL) in the same process, execute a write, commit, and close the connection.
  5. Inspect the generated .ltx files in the remote S3 bucket prefix.
  6. Open read-only connections (write_enabled omitted) for db1, db2, and db3 sequentially and query the inserted rows.

Expected behavior: Every distinct database replica initializes its remote transaction log sequence at txid = 1:

  • /litestream-vfs-bug/db1/0000/0000000000000001-0000000000000001.ltx
  • /litestream-vfs-bug/db2/0000/0000000000000001-0000000000000001.ltx
  • /litestream-vfs-bug/db3/0000/0000000000000001-0000000000000001.ltx

Every replica read completes successfully, returning its respective record.

Actual behavior:

/litestream-vfs-bug/db1/0000/0000000000000001-0000000000000001.ltx
/litestream-vfs-bug/db2/0000/0000000000000002-0000000000000002.ltx
/litestream-vfs-bug/db3/0000/0000000000000003-0000000000000003.ltx

Read failure on corrupted replicas:

db1: first txid=1 (ok), read='record-from-db1' (ok) db2: first txid=2 (EXPECTED 1), read='HANG' (EXPECTED 'record-from-db2') db3: first txid=3 (EXPECTED 1), read='HANG' (EXPECTED 'record-from-db3')

Example Code

python
from __future__ import annotations

import os
import re
import sqlite3
import sys
import tempfile
import threading
from typing import Any, Callable
from urllib.parse import quote

import boto3

PREFIX = "litestream-vfs-bug"
DB_NAMES = ["db1", "db2", "db3"]
THREAD_TIMEOUT_SECONDS = 15.0
VFS_PATH = os.environ.get("LITESTREAM_VFS_PATH", "/usr/local/lib/litestream-vfs.so")


def _require_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        sys.exit(f"missing required environment variable {name}")
    return value


BUCKET = _require_env("S3_BUCKET")
ACCESS_KEY_ID = _require_env("S3_ACCESS_KEY_ID")
SECRET_ACCESS_KEY = _require_env("S3_SECRET_ACCESS_KEY")
ENDPOINT_URL = os.environ.get("S3_ENDPOINT_URL")


def reexec_with_credentials() -> None:
    """litestream-vfs only sees the process's initial environment, so re-exec once."""
    wanted = {
        "LITESTREAM_ACCESS_KEY_ID": ACCESS_KEY_ID,
        "LITESTREAM_SECRET_ACCESS_KEY": SECRET_ACCESS_KEY,
    }
    if all(os.environ.get(k) == v for k, v in wanted.items()):
        return
    os.environ.update(wanted)
    os.execv(sys.executable, [sys.executable, *sys.orig_argv[1:]])


def s3_client() -> Any:
    return boto3.client(
        "s3",
        endpoint_url=ENDPOINT_URL,
        aws_access_key_id=ACCESS_KEY_ID,
        aws_secret_access_key=SECRET_ACCESS_KEY,
        region_name="us-east-1",
    )


def list_files(s3: Any) -> list[str]:
    paginator = s3.get_paginator("list_objects_v2")
    keys = [
        obj["Key"]
        for page in paginator.paginate(Bucket=BUCKET, Prefix=f"{PREFIX}/")
        for obj in page.get("Contents", [])
    ]
    return sorted(keys)


def clear_prefix(s3: Any) -> None:
    keys = list_files(s3)
    for i in range(0, len(keys), 1000):
        s3.delete_objects(
            Bucket=BUCKET,
            Delete={"Objects": [{"Key": k} for k in keys[i : i + 1000]]},
        )
    print(f"cleared {len(keys)} object(s)")


def report(s3: Any, label: str) -> None:
    keys = list_files(s3)
    print(f"\n[{label}] files under /{PREFIX}/ ({len(keys)}):")
    for key in keys:
        print(f"  /{key}")


def first_txid(s3: Any, db: str) -> int | None:
    """Lowest txid among the LTX files of one replica (healthy replicas start at 1)."""
    txids = []
    for key in list_files(s3):
        if key.startswith(f"{PREFIX}/{db}/"):
            m = re.search(r"/([0-9a-f]{16})-([0-9a-f]{16})\.ltx$", key)
            if m:
                txids.append(int(m.group(1), 16))
    return min(txids) if txids else None


def replica_url(db: str) -> str:
    url = f"s3://{BUCKET}/{PREFIX}/{db}"
    return f"{url}?endpoint={ENDPOINT_URL}" if ENDPOINT_URL else url


def load_vfs() -> None:
    loader = sqlite3.connect(":memory:")
    try:
        loader.enable_load_extension(True)
        loader.load_extension(VFS_PATH, entrypoint="sqlite3_litestreamvfs_init")
    finally:
        loader.close()


def connect(db: str, write_dir: str | None) -> sqlite3.Connection:
    uri = f"file:{db}.db?vfs=litestream&replica_url={quote(replica_url(db), safe='')}"
    if write_dir is not None:
        buffer_path = os.path.join(write_dir, f"{db}-buffer.db")
        uri += f"&write_enabled=true&buffer_path={quote(buffer_path, safe='')}"
    return sqlite3.connect(uri, uri=True, check_same_thread=False)


def run_in_thread(fn: Callable[[], str]) -> str:
    """Run ``fn`` in a daemon thread; return its result, 'ERROR: ...' or 'HANG'.

    A broken replica can hang inside the .so, and nothing in sqlite3 can time that out.
    """
    result: list[str] = []

    def work() -> None:
        try:
            result.append(fn())
        except Exception as e:  # noqa: BLE001
            result.append(f"ERROR: {e}")

    thread = threading.Thread(target=work, daemon=True)
    thread.start()
    thread.join(THREAD_TIMEOUT_SECONDS)
    return result[0] if result else "HANG"


def write_record(db: str) -> str:
    """Create the table and one record in write mode; returns 'ok'."""
    with tempfile.TemporaryDirectory() as tmp_dir:
        conn = connect(db, tmp_dir)
        try:
            conn.execute(
                "CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, v TEXT)"
            )
            conn.execute("INSERT INTO t (v) VALUES (?)", (f"record-from-{db}",))
            conn.commit()
        finally:
            conn.close()
    return "ok"


def read_record(db: str) -> str:
    """Read the first record back; returns its value."""
    conn = connect(db, None)
    try:
        row = conn.execute("SELECT v FROM t ORDER BY id LIMIT 1").fetchone()
        return row[0] if row else "ERROR: no rows"
    finally:
        conn.close()


def main() -> int:
    reexec_with_credentials()
    s3 = s3_client()
    print(f"bucket={BUCKET} endpoint={ENDPOINT_URL} vfs={VFS_PATH} pid={os.getpid()}")

    clear_prefix(s3)
    report(s3, "after clear")
    load_vfs()
    problems: list[str] = []

    for db in DB_NAMES:
        outcome = run_in_thread(lambda db=db: write_record(db))
        print(f"\nwrite {db}: {outcome}")
        if outcome != "ok":
            problems.append(f"{db} write -> {outcome!r}")
        report(s3, f"after write {db}")

    print("\nread back:")
    for db in DB_NAMES:
        first = first_txid(s3, db)
        value = run_in_thread(lambda db=db: read_record(db))
        expected = f"record-from-{db}"
        ok_txid = first == 1
        ok_read = value == expected
        print(
            f"  {db}: first txid={first} ({'ok' if ok_txid else 'EXPECTED 1'}), "
            f"read={value!r} ({'ok' if ok_read else f'EXPECTED {expected!r}'})"
        )
        if not ok_txid:
            problems.append(f"{db} starts at txid {first}")
        if not ok_read:
            problems.append(f"{db} read -> {value!r}")

    if problems:
        print("\nBUG REPRODUCED: " + "; ".join(problems))
        return 1
    print("\nOK: every replica starts at txid 1 and reads back its own record")
    return 0


if __name__ == "__main__":
    code = main()
    sys.stdout.flush()
    os._exit(code)  # a hung read thread (inside the .so) must not block exit

Logs

Log output
leared 3 object(s)

[after clear] files under /litestream-vfs-bug/ (0):
time=2026-10-01T05:31:18.592Z level=INFO msg="no existing database found, creating new database" vfs=true name=db1.db
time=2026-10-01T05:31:18.601Z level=INFO msg="synced to remote" vfs=true name=db1.db txid=0000000000000001 pages=2 size=366

write db1: ok

[after write db1] files under /litestream-vfs-bug/ (1):
  /litestream-vfs-bug/db1/0000/0000000000000001-0000000000000001.ltx
time=2026-10-01T05:31:18.610Z level=INFO msg="no existing database found, creating new database" vfs=true name=db2.db
time=2026-10-01T05:31:18.627Z level=INFO msg="synced to remote" vfs=true name=db2.db txid=0000000000000002 pages=2 size=366

write db2: ok

[after write db2] files under /litestream-vfs-bug/ (2):
  /litestream-vfs-bug/db1/0000/0000000000000001-0000000000000001.ltx
  /litestream-vfs-bug/db2/0000/0000000000000002-0000000000000002.ltx
time=2026-10-01T05:31:18.635Z level=INFO msg="no existing database found, creating new database" vfs=true name=db3.db
time=2026-10-01T05:31:18.644Z level=INFO msg="synced to remote" vfs=true name=db3.db txid=0000000000000003 pages=2 size=366

write db3: ok

[after write db3] files under /litestream-vfs-bug/ (3):
  /litestream-vfs-bug/db1/0000/0000000000000001-0000000000000001.ltx
  /litestream-vfs-bug/db2/0000/0000000000000002-0000000000000002.ltx
  /litestream-vfs-bug/db3/0000/0000000000000003-0000000000000003.ltx

read back:
  db1: first txid=1 (ok), read='record-from-db1' (ok)
  db2: first txid=2 (EXPECTED 1), read='HANG' (EXPECTED 'record-from-db2')
  db3: first txid=3 (EXPECTED 1), read='HANG' (EXPECTED 'record-from-db3')

BUG REPRODUCED: db2 starts at txid 2; db2 read -> 'HANG'; db3 starts at txid 3; db3 read -> 'HANG'